text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix app files test on windows
package cf_test import ( . "cf" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "path/filepath" "path" ) var _ = Describe("AppFiles", func() { fixturePath := filepath.Join("..", "fixtures", "applications") Describe("AppFilesInDir", func() { It("all files have '/' path separators", func() { files, err := AppFilesInDir(fixturePath) Expect(err).ShouldNot(HaveOccurred()) for _, afile := range files { Expect(afile.Path).Should(Equal(filepath.ToSlash(afile.Path))) } }) It("excludes files based on the .cfignore file", func() { appPath := filepath.Join(fixturePath, "app-with-cfignore") files, err := AppFilesInDir(appPath) Expect(err).ShouldNot(HaveOccurred()) paths := []string{} for _, file := range files { paths = append(paths, file.Path) } Expect(paths).To(Equal([]string{ path.Join("dir1", "child-dir", "file3.txt"), path.Join("dir1", "file1.txt"), })) }) }) })
package cf_test import ( . "cf" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "path/filepath" ) var _ = Describe("AppFiles", func() { fixturePath := filepath.Join("..", "fixtures", "applications") Describe("AppFilesInDir", func() { It("all files have '/' path separators", func() { files, err := AppFilesInDir(fixturePath) Expect(err).ShouldNot(HaveOccurred()) for _, afile := range files { Expect(afile.Path).Should(Equal(filepath.ToSlash(afile.Path))) } }) It("excludes files based on the .cfignore file", func() { appPath := filepath.Join(fixturePath, "app-with-cfignore") files, err := AppFilesInDir(appPath) Expect(err).ShouldNot(HaveOccurred()) paths := []string{} for _, file := range files { paths = append(paths, file.Path) } Expect(paths).To(Equal([]string{ filepath.Join("dir1", "child-dir", "file3.txt"), filepath.Join("dir1", "file1.txt"), })) }) }) })
Convert for use with Django
from django.conf import settings import re import sys class DisposableEmailChecker(): """ Check if an email is from a disposable email service """ def __init__(self): self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)] def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable(self, email): for email_group in self.chunk(self.emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False
#!/usr/bin/env python import re import sys def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable_email(email): emails = [line.strip() for line in open('domain-list.txt')] """ Chunk it! Regex parser doesn't deal with hundreds of groups """ for email_group in chunk(emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write("You must supply at least 1 email\n") for email in sys.argv[1:]: if is_disposable_email(email): sys.stderr.write("{email} appears to be a disposable address\n".format(email=email))
Use 'template ...' for the SchemaTemplate verbose_name*
from django.db import models from django.utils import six from django.utils.functional import lazy from boardinghouse.base import SharedSchemaMixin from boardinghouse.schema import activate_schema, deactivate_schema, get_schema_model def verbose_name_plural(): return u'template {}'.format(get_schema_model()._meta.verbose_name_plural) def verbose_name(): return u'template {}'.format(get_schema_model()._meta.verbose_name) @six.python_2_unicode_compatible class SchemaTemplate(SharedSchemaMixin, models.Model): """ A ``boardinghouse.contrib.template.models.SchemaTemplate`` can be used for creating a new schema complete with some initial data. """ template_schema_id = models.AutoField(primary_key=True) name = models.CharField(max_length=128, unique=True) is_active = models.BooleanField(default=True) description = models.TextField(null=True, blank=True) class Meta: default_permissions = ('add', 'change', 'delete', 'view', 'activate', 'clone') verbose_name = lazy(verbose_name, six.text_type)() verbose_name_plural = lazy(verbose_name_plural, six.text_type)() def __str__(self): return self.name @property def schema(self): return '__template_{}'.format(self.pk) def activate(self): activate_schema(self.schema) def deactivate(self): deactivate_schema()
from django.db import models from django.utils import six from boardinghouse.base import SharedSchemaMixin from boardinghouse.schema import activate_schema, deactivate_schema @six.python_2_unicode_compatible class SchemaTemplate(SharedSchemaMixin, models.Model): """ A ``boardinghouse.contrib.template.models.SchemaTemplate`` can be used for creating a new schema complete with some initial data. """ template_schema_id = models.AutoField(primary_key=True) name = models.CharField(max_length=128, unique=True) is_active = models.BooleanField(default=True) description = models.TextField(null=True, blank=True) class Meta: default_permissions = ('add', 'change', 'delete', 'view', 'activate', 'clone') verbose_name_plural = u'template schemata' def __str__(self): return self.name @property def schema(self): return '__template_{}'.format(self.pk) def activate(self): activate_schema(self.schema) def deactivate(self): deactivate_schema()
Increase the number of backill_meta_created iterations
#!/usr/bin/env python # Copyright (C) 2019 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. import logging logger = logging.getLogger(__name__) def run_backfill_meta_created(script, opts, args): if script.config.cluster.role != 'master': logger.info('Not running backfill_meta_created in slave mode') return query = """ WITH meta_created AS ( SELECT meta_id, min(created) AS created FROM track_meta WHERE meta_id IN (SELECT id FROM meta WHERE created IS NULL LIMIT 10000) GROUP BY meta_id ) UPDATE meta SET created = meta_created.created FROM meta_created WHERE meta.id = meta_created.meta_id AND meta.created IS NULL """ for i in range(100): with script.context() as ctx: fingerprint_db = ctx.db.get_fingerprint_db() fingerprint_db.execute(query) ctx.db.session.commit()
#!/usr/bin/env python # Copyright (C) 2019 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. import logging logger = logging.getLogger(__name__) def run_backfill_meta_created(script, opts, args): if script.config.cluster.role != 'master': logger.info('Not running backfill_meta_created in slave mode') return query = """ WITH meta_created AS ( SELECT meta_id, min(created) AS created FROM track_meta WHERE meta_id IN (SELECT id FROM meta WHERE created IS NULL LIMIT 10000) GROUP BY meta_id ) UPDATE meta SET created = meta_created.created FROM meta_created WHERE meta.id = meta_created.meta_id AND meta.created IS NULL """ for i in range(10): with script.context() as ctx: fingerprint_db = ctx.db.get_fingerprint_db() fingerprint_db.execute(query) ctx.db.session.commit()
Fix javascript file ordering in manifest
//= require jquery //= require jquery.ui.all //= require jquery_ujs //= require jquery-fileupload //= require twitter/bootstrap //= require select2 //= require shadowbox //= require mousetrap //= require ckeditor/init //= require_tree .//ckeditor //= require handlebars.runtime //= require underscore //= require backbone //= require georgia/backbone-relational //= require georgia/panels //= require_tree ./../../templates/ //= require_tree .//models //= require_tree .//collections //= require_tree .//views //= require_tree .//routers //= require georgia/bootstrap //= require georgia/featured-image //= require georgia/form-actions //= require georgia/jquery.mjs.nestedSortable //= require georgia/jquery.ui.touch-punch //= require georgia/keybindings //= require georgia/media //= require georgia/pages //= require georgia/tags
//= require jquery //= require jquery.ui.all //= require jquery_ujs //= require jquery-fileupload //= require twitter/bootstrap //= require select2 //= require shadowbox //= require mousetrap //= require ckeditor/init //= require_tree .//ckeditor //= require handlebars.runtime //= require underscore //= require backbone //= require_tree ./../../templates/ //= require_tree .//models //= require_tree .//collections //= require_tree .//views //= require_tree .//routers //= require .//backbone-relational //= require .//bootstrap //= require .//featured-image //= require .//form-actions //= require .//jquery.mjs.nestedSortable //= require .//jquery.ui.touch-punch //= require .//keybindings //= require .//media //= require .//pages //= require .//panels //= require .//tags
Fix import error by calling prepare_env first
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. import logging from awx import __version__ as tower_version # Prepare the AWX environment. from awx import prepare_env prepare_env() from django.core.wsgi import get_wsgi_application """ WSGI config for AWX project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ logger = logging.getLogger('awx.main.models.jobs') try: fd = open("/var/lib/awx/.tower_version", "r") if fd.read().strip() != tower_version: raise Exception() except Exception: logger.error("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.") raise Exception("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.") # Return the default Django WSGI application. application = get_wsgi_application()
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. import logging from django.core.wsgi import get_wsgi_application from awx import prepare_env from awx import __version__ as tower_version """ WSGI config for AWX project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ # Prepare the AWX environment. prepare_env() logger = logging.getLogger('awx.main.models.jobs') try: fd = open("/var/lib/awx/.tower_version", "r") if fd.read().strip() != tower_version: raise Exception() except Exception: logger.error("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.") raise Exception("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.") # Return the default Django WSGI application. application = get_wsgi_application()
Fix typeof check for allowed globals
var allowedGlobals = require('./allowed-globals'), UNDEF = 'undefined', cache; /** * Get global object based on what is available * @private */ module.exports = function () { if (typeof global !== UNDEF && global !== null && global.Array) { return global; } if (typeof window !== UNDEF && window !== null && window.Array) { return window; } // now that the global and window is not present, we load them by creating functions // since that is expensive, we cache it if (cache) { return cache; } cache = {}; allowedGlobals.forEach(function (prop) { var value = Function('return (typeof ' + // eslint-disable-line no-new-func prop + ' !== "undefined") ? ' + prop + ' : undefined')(); value && (cache[prop] = value); }); return cache; };
var allowedGlobals = require('./allowed-globals'), UNDEF = 'undefined', cache; /** * Get global object based on what is available * @private */ module.exports = function () { if (typeof global !== UNDEF && global !== null && global.Array) { return global; } if (typeof window !== UNDEF && window !== null && window.Array) { return window; } // now that the global and window is not present, we load them by creating functions // since that is expensive, we cache it if (cache) { return cache; } cache = {}; allowedGlobals.forEach(function (prop) { var value = Function('return (typeof ' + // eslint-disable-line no-new-func prop + ' !== "undefined") && ' + prop + ' || undefined')(); value && (cache[prop] = value); }); return cache; };
Add color log in the world generator
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const log = require('./log'); var worldDB = 'labyrinth'; if (require.main === module) { program .version('0.0.1') .option('-n, --dbname', 'Name of world database') .option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015}) .option('-t, --test <n>', 'Create n Corals', parseInt) .parse(process.argv); rethinkDB.connect( {host: 'localhost', port: program.port}, function(err, conn) { if (err) throw err; rethinkDB .dbCreate(program.dbname) .run(conn, (err, res) => { if (err) { log.error(`The world is exist. ` + `If you really want create a new world, ` + `delete the database "${program.dbname}".`); throw err; } }); }); }
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const log = require('./log'); var worldDB = 'labyrinth'; if (require.main === module) { program .version('0.0.1') .option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015}) .option('-t, --test <n>', 'Create n Corals', parseInt) .parse(process.argv); rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; rethinkDB .dbCreate(worldDB) .run(conn, (err, res) => { if (err) { log.error(`The world is exist. ` + `If you really want create a new world, ` + `delete the database "${worldDB}".`); throw err; } }); }); }
Make deployment script work from anywhere.
import logging import os import yaml from fabric.api import lcd, env, task, local from fabric.contrib.project import rsync_project logging.basicConfig(level=logging.DEBUG) log = logging.getLogger() repo_root = local('git rev-parse --show-toplevel', capture=True) try: conf = yaml.load(open(os.path.join(repo_root, 'deploy.yaml'), 'rb').read()) except: log.exception('error: unable to read deply.yaml config file:') env.user = conf['user'] env.hosts = ['{}@{}:22'.format(env.user, host) for host in conf['hosts']] def deploy_project(local_dir, remote_dir, exclusions=[]): """Deploy the entire project at local_dir to remote_dir, excluding the given paths.""" with lcd(repo_root): with lcd(local_dir): rsync_project(remote_dir=remote_dir, local_dir='.', exclude=exclusions) rsync_project(remote_dir=remote_dir, local_dir='resources', exclude=exclusions, delete=True) @task def deploy(): """Deploys web and script to remote server.""" deploy_project('web', conf['web_remote_dir'], ['.git', 'fabfile.py', 'cache', 'config', 'template']) deploy_project('script', conf['script_remote_dir'], ['.git', 'fabfile.py', 'cache', 'js', 'image'])
import logging import yaml from fabric.api import lcd, env, task from fabric.contrib.project import rsync_project logging.basicConfig(level=logging.DEBUG) log = logging.getLogger() try: conf = yaml.load(open('deploy.yaml', 'rb').read()) except: log.exception('error: unable to read deply.yaml config file:') env.user = conf['user'] env.hosts = ['{}@{}:22'.format(env.user, host) for host in conf['hosts']] def deploy_project(local_dir, remote_dir, exclusions=[]): """Deploy the entire project at local_dir to remote_dir, excluding the given paths.""" with lcd(local_dir): rsync_project(remote_dir=remote_dir, local_dir='.', exclude=exclusions) rsync_project(remote_dir=remote_dir, local_dir='resources', exclude=exclusions, delete=True) @task def deploy(): """Deploys web and script to remote server.""" deploy_project('web', conf['web_remote_dir'], ['.git', 'fabfile.py', 'cache', 'config', 'template']) deploy_project('script', conf['script_remote_dir'], ['.git', 'fabfile.py', 'cache', 'js', 'image'])
Remove legacy/deprecated code and cleanup.
package org.metaborg.meta.lang.spt.testrunner.cmd; import org.metaborg.core.editor.IEditorRegistry; import org.metaborg.core.editor.NullEditorRegistry; import org.metaborg.core.project.IProjectService; import org.metaborg.core.project.ISimpleProjectService; import org.metaborg.core.project.SimpleProjectService; import org.metaborg.spoofax.core.SpoofaxModule; import org.metaborg.spoofax.meta.spt.testrunner.core.TestRunner; import com.google.inject.Singleton; public class Module extends SpoofaxModule { @Override protected void configure() { super.configure(); bind(TestRunner.class).in(Singleton.class); bind(Runner.class).in(Singleton.class); } @Override protected void bindProject() { bind(SimpleProjectService.class).in(Singleton.class); bind(IProjectService.class).to(SimpleProjectService.class); bind(ISimpleProjectService.class).to(SimpleProjectService.class); } @Override protected void bindEditor() { bind(IEditorRegistry.class).to(NullEditorRegistry.class).in(Singleton.class); } }
package org.metaborg.meta.lang.spt.testrunner.cmd; import org.metaborg.core.editor.IEditorRegistry; import org.metaborg.core.editor.NullEditorRegistry; import org.metaborg.core.project.IProjectService; import org.metaborg.core.project.ISimpleProjectService; import org.metaborg.core.project.SimpleProjectService; import org.metaborg.spoofax.core.SpoofaxModule; import org.metaborg.spoofax.core.project.ILegacyMavenProjectService; import org.metaborg.spoofax.core.project.NullLegacyMavenProjectService; import org.metaborg.spoofax.meta.spt.testrunner.core.TestRunner; import com.google.inject.Singleton; public class Module extends SpoofaxModule { @Override protected void configure() { super.configure(); bind(TestRunner.class).in(Singleton.class); bind(Runner.class).in(Singleton.class); } @Override protected void bindProject() { bind(SimpleProjectService.class).in(Singleton.class); bind(IProjectService.class).to(SimpleProjectService.class).in(Singleton.class); bind(ISimpleProjectService.class).to(SimpleProjectService.class).in(Singleton.class); } @Override protected void bindMavenProject() { bind(ILegacyMavenProjectService.class).to(NullLegacyMavenProjectService.class).in(Singleton.class); } @Override protected void bindEditor() { bind(IEditorRegistry.class).to(NullEditorRegistry.class).in(Singleton.class); } }
Troubleshoot script for displaying getting the counts of tickets assigned to each user.
/* global SW:true */ $(document).ready(function(){ 'use strict'; console.log( 'Doing SW things!' ); var card = new SW.Card(); var helpdesk = card.services('helpdesk'); var assignmentCount = {}; helpdesk .request('tickets') .then( function(data){ console.log( 'got data!' ); $.each(data.tickets, function(index, ticket){ console.log( ticket.assignee.id ); if (assignmentCount[ticket.assignee.id]){ assignmentCount[ticket.assignee.id] += 1; } else { assignmentCount[ticket.assignee.id] = 1; } console.log( 'assignmentCount object' ); console.log( assignmentCount ); }); console.log( assignmentCount + 'final' ); var ticketTotal = 0; for (var property in assignmentCount) { ticketTotal += assignmentCount[property]; } var unassignedTickets = data.tickets.length - ticketTotal; console.log('unassignedTickets'); console.log(unassignedTickets); }); });
/* global SW:true */ $(document).ready(function(){ 'use strict'; console.log( 'Doing SW things!' ); var card = new SW.Card(); var helpdesk = card.services('helpdesk'); helpdesk .request('tickets') .then( function(data){ console.log( 'got data!' ); var ticketCount = {}; $.each(data.tickets, function(index, ticket){ console.log( index ); if (ticketCount[ticket.assignee.id]){ ticketCount[ticket.assignee.id] += 1; } else { ticketCount[ticket.assignee.id] = 1; } console.log( 'ticketCount object' ); console.log( ticketCount ); }); }); });
HOTFIX: Replace Object.values with old-node friendly code
var locationGraph = require('../assets/data/dummy-picker-data-2.json') function isCanonicalNode (node) { return node.meta.canonical } function presentableName (node, locale) { var requestedName = node['names'][locale] var fallback = Object.keys(node['names']).map(k => node['names'][k])[0] return requestedName || fallback } var locationReverseMap = (preferredLocale) => Object.keys(locationGraph) .reduce((revMap, curie) => { var node = locationGraph[curie] Object.keys(node.names).forEach(locale => { var name = node.names[locale] // HACK to prevent overriding for example Antarctica, // where the en-GB and cy names are identical, and we want // en-GB to stay on top. var isntDefinedOrLocaleIsEnGb = !revMap[name] || locale === preferredLocale if (isntDefinedOrLocaleIsEnGb) { revMap[name] = { node, locale } } }) return revMap }, {}) var canonicalLocationList = (preferredLocale) => Object.keys(locationGraph) .reduce((list, curie) => { var node = locationGraph[curie] return isCanonicalNode(node) ? list.concat([presentableName(node, preferredLocale)]) : list }, []) .sort() module.exports = { canonicalLocationList: canonicalLocationList, locationGraph: locationGraph, locationReverseMap: locationReverseMap }
var locationGraph = require('../assets/data/dummy-picker-data-2.json') function isCanonicalNode (node) { return node.meta.canonical } function presentableName (node, locale) { var requestedName = node['names'][locale] var fallback = Object.values(node['names'])[0] return requestedName || fallback } var locationReverseMap = (preferredLocale) => Object.keys(locationGraph) .reduce((revMap, curie) => { var node = locationGraph[curie] Object.keys(node.names).forEach(locale => { var name = node.names[locale] // HACK to prevent overriding for example Antarctica, // where the en-GB and cy names are identical, and we want // en-GB to stay on top. var isntDefinedOrLocaleIsEnGb = !revMap[name] || locale === preferredLocale if (isntDefinedOrLocaleIsEnGb) { revMap[name] = { node, locale } } }) return revMap }, {}) var canonicalLocationList = (preferredLocale) => Object.keys(locationGraph) .reduce((list, curie) => { var node = locationGraph[curie] return isCanonicalNode(node) ? list.concat([presentableName(node, preferredLocale)]) : list }, []) .sort() module.exports = { canonicalLocationList: canonicalLocationList, locationGraph: locationGraph, locationReverseMap: locationReverseMap }
Disable inline sourcemaps in postcss
/* eslint-env node */ 'use strict' const EmberApp = require('ember-cli/lib/broccoli/ember-app') const cssnext = require('postcss-cssnext') module.exports = function(defaults) { let app = new EmberApp(defaults, { postcssOptions: { compile: { enabled: false }, filter: { enabled: true, map: { inline: false }, plugins: [ { module: cssnext, options: { browsers: [ '> 1%', 'last 3 versions', 'Firefox ESR' ] } } ] } } }) app.import('bower_components/xss/dist/xss.js') return app.toTree() }
/* eslint-env node */ 'use strict' const EmberApp = require('ember-cli/lib/broccoli/ember-app') const cssnext = require('postcss-cssnext') module.exports = function(defaults) { let app = new EmberApp(defaults, { postcssOptions: { compile: { enabled: false }, filter: { enabled: true, plugins: [ { module: cssnext, options: { browsers: [ '> 1%', 'last 3 versions', 'Firefox ESR' ] } } ] } } }) app.import('bower_components/xss/dist/xss.js') return app.toTree() }
Add second argument to parse()
"use strict"; var renderNull = function () { return 'NULL' } , parser parser = require('editorsnotes-markup-parser')({ projectBaseURL: '/', resolveItemText: renderNull, makeBibliographyEntry: renderNull, makeInlineCitation: function(citations) { return { citations: citations.map(renderNull) } } }); function getENReferences(nodeArray, items) { items = items || {}; return nodeArray.reduce(function (acc, node) { if (node.meta && node.meta.enItemType) { let itemType = node.meta.enItemType , itemID = node.meta.enItemID if (!acc.hasOwnProperty(itemType)) acc[itemType] = []; if (acc[itemType].indexOf(itemID) === -1) acc[itemType].push(itemID); } return node.children ? getENReferences(node.children, acc) : acc; }, items) } module.exports = function (text) { return getENReferences(parser.parse(text, {})) }
"use strict"; var renderNull = function () { return 'NULL' } , parser parser = require('editorsnotes-markup-parser')({ projectBaseURL: '/', resolveItemText: renderNull, makeBibliographyEntry: renderNull, makeInlineCitation: function(citations) { return { citations: citations.map(renderNull) } } }); function getENReferences(nodeArray, items) { items = items || {}; return nodeArray.reduce(function (acc, node) { if (node.meta && node.meta.enItemType) { let itemType = node.meta.enItemType , itemID = node.meta.enItemID if (!acc.hasOwnProperty(itemType)) acc[itemType] = []; if (acc[itemType].indexOf(itemID) === -1) acc[itemType].push(itemID); } return node.children ? getENReferences(node.children, acc) : acc; }, items) } module.exports = function (text) { return getENReferences(parser.parse(text)) }
Remove trailing slashes from requests in frontend
import axios from 'axios'; export function getRestaurants ({ commit }) { return new Promise((resolve, reject) => { axios .get('/api/restaurant') .then((response) => { commit('updateRestaurants', response.data.restaurants); resolve(response); }) .catch((err) => { reject(err); }); }); } export function getRestaurant ({ commit }, identifier) { return new Promise((resolve, reject) => { axios .get('/api/restaurant' + identifier) .then((response) => { resolve(response); }) .catch((err) => { reject(err); }); }); } export function setShowSolna ({ commit }, status) { commit('updateSolna', status); } export function setShowUppsala ({ commit }, status) { commit('updateUppsala', status); } export function setOnlyFavourites ({ commit }, status) { commit('updateOnlyFavourites', status); } // expects payload to be {'restaurant': name, 'favourite': state} export function setFavourite ({ commit }, payload) { commit('updateFavourite', payload); }
import axios from 'axios'; export function getRestaurants ({ commit }) { return new Promise((resolve, reject) => { axios .get('/api/restaurant/') .then((response) => { commit('updateRestaurants', response.data.restaurants); resolve(response); }) .catch((err) => { reject(err); }); }); } export function getRestaurant ({ commit }, identifier) { return new Promise((resolve, reject) => { axios .get('/api/restaurant/' + identifier) .then((response) => { resolve(response); }) .catch((err) => { reject(err); }); }); } export function setShowSolna ({ commit }, status) { commit('updateSolna', status); } export function setShowUppsala ({ commit }, status) { commit('updateUppsala', status); } export function setOnlyFavourites ({ commit }, status) { commit('updateOnlyFavourites', status); } // expects payload to be {'restaurant': name, 'favourite': state} export function setFavourite ({ commit }, payload) { commit('updateFavourite', payload); }
Fix testHarness call for Windows
from SCons.Script import * import shlex def run_tests(env): import shlex import subprocess import sys cmd = shlex.split(env.get('TEST_COMMAND')) print('Executing:', cmd) sys.exit(subprocess.call(cmd)) def generate(env): import os import distutils.spawn python = distutils.spawn.find_executable('python3') if not python: python = distutils.spawn.find_executable('python') if not python: python = distutils.spawn.find_executable('python2') if not python: python = 'python' if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\') cmd = [python, 'tests/testHarness', '-C', 'tests', '--diff-failed', '--view-failed', '--view-unfiltered', '--save-failed', '--build'] cmd = shlex.join(cmd) env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd)) if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests) def exists(): return 1
from SCons.Script import * import inspect def run_tests(env): import shlex import subprocess import sys cmd = shlex.split(env.get('TEST_COMMAND')) print('Executing:', cmd) sys.exit(subprocess.call(cmd)) def generate(env): import os import distutils.spawn python = distutils.spawn.find_executable('python3') if not python: python = distutils.spawn.find_executable('python') if not python: python = distutils.spawn.find_executable('python2') if not python: python = 'python' if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\') path = inspect.getfile(inspect.currentframe()) home = os.path.dirname(os.path.abspath(path)) + '/../..' cmd = python + ' ' + home + '/tests/testHarness -C tests --diff-failed ' \ '--view-failed --view-unfiltered --save-failed --build' if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color' env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd)) if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests) def exists(): return 1
Update match-id to equal that used in compd.
#!/usr/bin/env python import os import sys import yaml import score MATCH_ID = 'match-{0}' def usage(): print "Usage: score-match.py MATCH_NUMBER" print " Scores the match file at matches/MATCH_NUMBER.yaml" print " Outputs scoring format suitable for piping at compd" if len(sys.argv) is not 2: usage() exit(1) match_num = sys.argv[1] match_file = "matches/{0}.yaml".format(match_num) if not os.path.exists(match_file): print "Match file '{0}' doesn't exist. Have you created it?".format(match_file) usage() exit(2) scores = yaml.load(open(match_file).read()) scorer = score.StrangeGameScorer(scores) scorer.compute_cell_winners() match_id = MATCH_ID.format(match_num) for tla in scores.keys(): this_score = scorer.compute_game_score(tla) print 'set-score {0} {1} {2}'.format(match_id, tla, this_score) print 'calc-league-points {0}'.format(match_id)
#!/usr/bin/env python import os import sys import yaml import score def usage(): print "Usage: score-match.py MATCH_NUMBER" print " Scores the match file at matches/MATCH_NUMBER.yaml" print " Outputs scoring format suitable for piping at compd" if len(sys.argv) is not 2: usage() exit(1) match_num = sys.argv[1] match_file = "matches/{0}.yaml".format(match_num) if not os.path.exists(match_file): print "Match file '{0}' doesn't exist. Have you created it?".format(match_file) usage() exit(2) scores = yaml.load(open(match_file).read()) scorer = score.StrangeGameScorer(scores) scorer.compute_cell_winners() for tla in scores.keys(): this_score = scorer.compute_game_score(tla) print 'set-score {0} {1} {2}'.format(match_num, tla, this_score) print 'calc-league-points {0}'.format(match_num)
Fix typo for js file.
const {resolve} = require('path'); const webpack =require('webpack'); module.exports = { entry: [ './index.tsx' ], output:{ filename: 'bundle.js', path: resolve(__dirname, 'static'), publicPath: '' }, resolve:{ extensions: ['.js', '.jsx', '.ts', '.tsx', '.css'] }, context: resolve(__dirname, 'src'), devtool: 'inline-source-map', devServer:{ hot: true, contentBase: resolve(__dirname, 'static'), publicPath: '' }, module: { rules:[{ test: /\.(ts|tsx)$/, use: ['awesome-typescript-loader'] },{ test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, plugins: [] };
const {resolve} = require('path'); const webpack =require('webpack'); module.exports = { entry: [ './index.tsx' ], output:{ filename: 'bundle.js', path: resolve(__dirname, 'static'), publicPath: '' }, resolve:{ extensions: ['js', '.jsx', '.ts', '.tsx', '.css'] }, context: resolve(__dirname, 'src'), devtool: 'inline-source-map', devServer:{ hot: true, contentBase: resolve(__dirname, 'static'), publicPath: '' }, module: { rules:[{ test: /\.(ts|tsx)$/, use: ['awesome-typescript-loader'] },{ test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, plugins: [] }
Update endpoint to remote api
package com.sanchez.fmf.service; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.OkHttpClient; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.converter.GsonConverter; /** * Created by dakota on 9/2/15. */ public class RestClient { private static final String BASE_URL = "http://138.197.218.95"; private MarketService marketService; public RestClient() { Gson gson = new Gson(); RestAdapter retrofit = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.NONE) .setEndpoint(BASE_URL) .setClient(new OkClient(new OkHttpClient())) .setConverter(new GsonConverter(gson)) .build(); marketService = retrofit.create(MarketService.class); } public MarketService getMarketService() { return marketService; } }
package com.sanchez.fmf.service; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.OkHttpClient; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.converter.GsonConverter; /** * Created by dakota on 9/2/15. */ public class RestClient { private static final String BASE_URL = "http://10.0.2.2:5000"; private MarketService marketService; public RestClient() { Gson gson = new Gson(); RestAdapter retrofit = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.NONE) .setEndpoint(BASE_URL) .setClient(new OkClient(new OkHttpClient())) .setConverter(new GsonConverter(gson)) .build(); marketService = retrofit.create(MarketService.class); } public MarketService getMarketService() { return marketService; } }
Add bin to package.json and move rc-loading to plugin.js
import postcss from "postcss" import fs from "fs" import gs from "glob-stream" import { Transform } from "stream" import plugin from "./plugin" export default function ({ files, config } = {}) { const linter = new Transform({ objectMode: true }) linter._transform = function (chunk, enc, callback) { if (files) { const filepath = chunk.path fs.readFile(filepath, "utf8", (err, css) => { if (err) { linter.emit("error", err) } lint({ css, filepath: filepath }, callback) }) } else { lint({ css: chunk }, callback) } } function lint({ css, filepath }, callback) { const processOptions = {} if (filepath) { processOptions.from = filepath } postcss() .use(plugin(config)) .process(css, processOptions) .then(result => { callback(null, result) }) .catch(err => { linter.emit("error", new Error(err)) }) } if (files) { const fileStream = gs.create(files) return fileStream.pipe(linter) } return linter }
import postcss from "postcss" import fs from "fs" import gs from "glob-stream" import rcLoader from "rc-loader" import { Transform } from "stream" import plugin from "./plugin" export default function ({ files, config } = {}) { const stylelintConfig = config || rcLoader("stylelint") if (!stylelintConfig) { throw new Error("No stylelint config found") } const linter = new Transform({ objectMode: true }) linter._transform = function (chunk, enc, callback) { if (files) { const filepath = chunk.path fs.readFile(filepath, "utf8", (err, css) => { if (err) { linter.emit("error", err) } lint({ css, filepath: filepath }, callback) }) } else { lint({ css: chunk }, callback) } } function lint({ css, filepath }, callback) { const processOptions = {} if (filepath) { processOptions.from = filepath } postcss() .use(plugin(stylelintConfig)) .process(css, processOptions) .then(result => { callback(null, result) }) .catch(err => { linter.emit("error", new Error(err)) }) } if (files) { const fileStream = gs.create(files) return fileStream.pipe(linter) } return linter }
Make engine available in app.
#!/usr/bin/env python # coding=utf8 from flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import model import defaults from views.frontend import frontend, oid def create_app(config_filename): app = Flask(__name__) app.config.from_object(defaults) app.config.from_pyfile(config_filename) # init db connection app.engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], encoding = 'utf8', echo = app.config['SQLALCHEMY_ECHO']) app.session = scoped_session(sessionmaker(bind = app.engine)) @app.after_request def shutdown_session(response): app.session.remove() return response app.storage = model.FileStorage(app.config['FILE_STORAGE']) app.oid = oid app.oid.init_app(app) # load modules app.register_module(frontend) return app
#!/usr/bin/env python # coding=utf8 from flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import model import defaults from views.frontend import frontend, oid def create_app(config_filename): app = Flask(__name__) app.config.from_object(defaults) app.config.from_pyfile(config_filename) # init db connection engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], encoding = 'utf8', echo = app.config['SQLALCHEMY_ECHO']) app.session = scoped_session(sessionmaker(bind = engine)) @app.after_request def shutdown_session(response): app.session.remove() return response app.storage = model.FileStorage(app.config['FILE_STORAGE']) app.oid = oid app.oid.init_app(app) # load modules app.register_module(frontend) return app
Add template fields to wcloud config.
package main import ( "time" ) // Deployment describes a deployment type Deployment struct { ID string `json:"id"` CreatedAt time.Time `json:"created_at"` ImageName string `json:"image_name"` Version string `json:"version"` Priority int `json:"priority"` State string `json:"status"` } // Config for the deployment system for a user. type Config struct { RepoURL string `json:"repo_url" yaml:"repo_url"` RepoPath string `json:"repo_path" yaml:"repo_path"` RepoKey string `json:"repo_key" yaml:"repo_key"` KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"` Notifications []NotificationConfig `json:"notifications" yaml:"notifications"` // Globs of files not to change, relative to the route of the repo ConfigFileBlackList []string `json:"config_file_black_list" yaml:"config_file_black_list"` CommitMessageTemplate string `json:"commit_message_template" yaml:"commit_message_template"` // See https://golang.org/pkg/text/template/ } // NotificationConfig describes how to send notifications type NotificationConfig struct { SlackWebhookURL string `json:"slack_webhook_url" yaml:"slack_webhook_url"` SlackUsername string `json:"slack_username" yaml:"slack_username"` MessageTemplate string `json:"message_template" yaml:"message_template"` }
package main import ( "time" ) // Deployment describes a deployment type Deployment struct { ID string `json:"id"` CreatedAt time.Time `json:"created_at"` ImageName string `json:"image_name"` Version string `json:"version"` Priority int `json:"priority"` State string `json:"status"` LogKey string `json:"-"` } // Config for the deployment system for a user. type Config struct { RepoURL string `json:"repo_url" yaml:"repo_url"` RepoPath string `json:"repo_path" yaml:"repo_path"` RepoKey string `json:"repo_key" yaml:"repo_key"` KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"` Notifications []NotificationConfig `json:"notifications" yaml:"notifications"` // Globs of files not to change, relative to the route of the repo ConfigFileBlackList []string `json:"config_file_black_list" yaml:"config_file_black_list"` } // NotificationConfig describes how to send notifications type NotificationConfig struct { SlackWebhookURL string `json:"slack_webhook_url" yaml:"slack_webhook_url"` SlackUsername string `json:"slack_username" yaml:"slack_username"` }
Fix old Safari by using `dispatchEvent` from `Element` rather than `EventTarget`.
/** @license Copyright (c) 2016 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ 'use strict'; export let appendChild = Element.prototype.appendChild; export let insertBefore = Element.prototype.insertBefore; export let removeChild = Element.prototype.removeChild; export let setAttribute = Element.prototype.setAttribute; export let removeAttribute = Element.prototype.removeAttribute; export let cloneNode = Element.prototype.cloneNode; export let importNode = Document.prototype.importNode; export let addEventListener = Element.prototype.addEventListener; export let removeEventListener = Element.prototype.removeEventListener; export let dispatchEvent = Element.prototype.dispatchEvent;
/** @license Copyright (c) 2016 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ 'use strict'; export let appendChild = Element.prototype.appendChild; export let insertBefore = Element.prototype.insertBefore; export let removeChild = Element.prototype.removeChild; export let setAttribute = Element.prototype.setAttribute; export let removeAttribute = Element.prototype.removeAttribute; export let cloneNode = Element.prototype.cloneNode; export let importNode = Document.prototype.importNode; export let addEventListener = Element.prototype.addEventListener; export let removeEventListener = Element.prototype.removeEventListener;
Refactor env in run command
'use strict' var path = require('path') var async = require('async') var config = require('./config') var child_process = require('child_process') var assign = require('object-assign') function runCmd (cwd, argv) { var scripts = argv._.slice(1) var pkg = require(path.join(cwd, 'package.json')) if (!scripts.length) { var availableScripts = Object.keys(pkg.scripts || []) console.log('Available scripts: ' + availableScripts.join(', ')) return } var env = assign({}, process.env, { PATH: [ path.join(cwd, 'node_modules/.bin'), process.env.PATH ].join(path.delimiter) }) async.mapSeries(scripts, function execScript (scriptName, cb) { var scriptCmd = pkg.scripts[scriptName] if (!scriptCmd) return cb(null, null) var childProcess = child_process.spawn(config.sh, [config.shFlag, scriptCmd], { env: env, stdio: 'inherit' }) childProcess.on('close', cb.bind(null, null)) childProcess.on('error', cb) }, function (err, statuses) { if (err) throw err var info = scripts.map(function (script, i) { return script + ' exited with status ' + statuses[i] }).join('\n') console.log(info) var success = statuses.every(function (code) { return code === 0 }) process.exit(success | 0) }) } module.exports = runCmd
'use strict' var path = require('path') var async = require('async') var config = require('./config') var child_process = require('child_process') function runCmd (cwd, argv) { var scripts = argv._.slice(1) var pkg = require(path.join(cwd, 'package.json')) if (!scripts.length) { var availableScripts = Object.keys(pkg.scripts || []) console.log('Available scripts: ' + availableScripts.join(', ')) return } var env = Object.create(process.env) env.PATH = [path.join(cwd, 'node_modules/.bin'), process.env.PATH].join(path.delimiter) async.mapSeries(scripts, function execScript (scriptName, cb) { var scriptCmd = pkg.scripts[scriptName] if (!scriptCmd) return cb(null, null) var childProcess = child_process.spawn(config.sh, [config.shFlag, scriptCmd], { env: env, stdio: 'inherit' }) childProcess.on('close', cb.bind(null, null)) childProcess.on('error', cb) }, function (err, statuses) { if (err) throw err var info = scripts.map(function (script, i) { return script + ' exited with status ' + statuses[i] }).join('\n') console.log(info) var success = statuses.every(function (code) { return code === 0 }) process.exit(success | 0) }) } module.exports = runCmd
Join channel and register on reconnect
var chat = angular.module('chat', ['btford.socket-io']); var channel = new Channel('hellas'); var me = null; chat.factory('chatServer', function (socketFactory) { var url = '/'; if (location.port != '') { url = ':' + location.port + '/'; } return socketFactory({ioSocket: io.connect(url)}) }); chat.controller('MessagesCtrl', MessagesCtrl); chat.controller('NicklistCtrl', NicklistCtrl); chat.run(function(chatServer) { var nickname; if (!localStorage['nickname']) { nickname = prompt('Πληκτρολόγησε το όνομά σου:'); localStorage['nickname'] = nickname; } else { nickname = localStorage['nickname']; } me = new User(nickname); $('#chat').show(); chatServer.on('connect', function() { chatServer.emit('register', me); chatServer.emit('join', channel); }); });
var chat = angular.module('chat', ['btford.socket-io']); var channel = new Channel('hellas'); var me = null; chat.factory('chatServer', function (socketFactory) { var url = '/'; if (location.port != '') { url = ':' + location.port + '/'; } return socketFactory({ioSocket: io.connect(url)}) }); chat.controller('MessagesCtrl', MessagesCtrl); chat.controller('NicklistCtrl', NicklistCtrl); chat.run(function(chatServer) { var nickname; if (!localStorage['nickname']) { nickname = prompt('Πληκτρολόγησε το όνομά σου:'); localStorage['nickname'] = nickname; } else { nickname = localStorage['nickname']; } me = new User(nickname); $('#chat').show(); chatServer.emit('register', me); chatServer.emit('join', channel); });
Fix error if column has empty string
<?php namespace Maphper\DataSource; //Replaces dates in an object graph with \DateTime instances class DateInjector { private $processCache; public function replaceDates($obj, $reset = true) { //prevent infinite recursion, only process each object once if ($reset) $this->processCache = new \SplObjectStorage(); if (is_object($obj) && $this->processCache->contains($obj)) return $obj; else if (is_object($obj)) $this->processCache->attach($obj, true); if (is_array($obj) || (is_object($obj) && (!$obj instanceof \Iterator))) foreach ($obj as &$o) $o = $this->replaceDates($o, false); if (is_string($obj) && isset($obj[0]) && is_numeric($obj[0]) && strlen($obj) <= 20) { try { $date = new \DateTime($obj); if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20)) $obj = $date; } catch (\Exception $e) { //Doesn't need to do anything as the try/catch is working out whether $obj is a date } } return $obj; } }
<?php namespace Maphper\DataSource; //Replaces dates in an object graph with \DateTime instances class DateInjector { private $processCache; public function replaceDates($obj, $reset = true) { //prevent infinite recursion, only process each object once if ($reset) $this->processCache = new \SplObjectStorage(); if (is_object($obj) && $this->processCache->contains($obj)) return $obj; else if (is_object($obj)) $this->processCache->attach($obj, true); if (is_array($obj) || (is_object($obj) && (!$obj instanceof \Iterator))) foreach ($obj as &$o) $o = $this->replaceDates($o, false); if (is_string($obj) && is_numeric($obj[0]) && strlen($obj) <= 20) { try { $date = new \DateTime($obj); if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20)) $obj = $date; } catch (\Exception $e) { //Doesn't need to do anything as the try/catch is working out whether $obj is a date } } return $obj; } }
Include LICENSE.txt in the package tarball
from distutils.core import setup VERSION='0.3.1' setup( name = 'sdnotify', packages = ['sdnotify'], version = VERSION, description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)', author = 'Brett Bethke', author_email = 'bbethke@gmail.com', url = 'https://github.com/bb4242/sdnotify', download_url = 'https://github.com/bb4242/sdnotify/tarball/v{}'.format(VERSION), keywords = ['systemd'], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Topic :: Software Development :: Libraries :: Python Modules", ], data_files = [("", ["LICENSE.txt"])], long_description = """\ systemd Service Notification This is a pure Python implementation of the systemd sd_notify protocol. This protocol can be used to inform systemd about service start-up completion, watchdog events, and other service status changes. Thus, this package can be used to write system services in Python that play nicely with systemd. sdnotify is compatible with both Python 2 and Python 3. """ )
from distutils.core import setup setup( name = 'sdnotify', packages = ['sdnotify'], version = '0.3.0', description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)', author = 'Brett Bethke', author_email = 'bbethke@gmail.com', url = 'https://github.com/bb4242/sdnotify', download_url = 'https://github.com/bb4242/sdnotify/tarball/v0.3.0', keywords = ['systemd'], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Topic :: Software Development :: Libraries :: Python Modules", ], long_description = """\ systemd Service Notification This is a pure Python implementation of the systemd sd_notify protocol. This protocol can be used to inform systemd about service start-up completion, watchdog events, and other service status changes. Thus, this package can be used to write system services in Python that play nicely with systemd. sdnotify is compatible with both Python 2 and Python 3. """ )
Change import InviteForm from private.forms to accounts.forms
from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from accounts.forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form })
from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from .forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form })
Handle TZ change in iso8601 >=0.1.12 The iso8601 lib introduced a change such that if running on python 3.2 or later it internally uses the python timezone information instead of its own implementation. This does not change direct date handling, but when converting this value there is a slight difference where now python 2.x will show UTC times as "UTC", but on python 3 they will end up with "UTC+00:00". The to_primitive call for DateTime fields was doing an exact match on "UTC" to determine whether to include "Z" in the resulting string. This updates that handling to recognize either of the new values. Change-Id: I71b58e8fd8fee8a57ee275ff3e0b77f165eca836 Closes-bug: #1744160
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # 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. """Utilities and helper functions.""" # ISO 8601 extended time format without microseconds _ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S' def isotime(at): """Stringify time in ISO 8601 format.""" st = at.strftime(_ISO8601_TIME_FORMAT) tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC' # Need to handle either iso8601 or python UTC format st += ('Z' if tz in ['UTC', 'UTC+00:00'] else tz) return st
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # 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. """Utilities and helper functions.""" # ISO 8601 extended time format without microseconds _ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S' def isotime(at): """Stringify time in ISO 8601 format.""" st = at.strftime(_ISO8601_TIME_FORMAT) tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC' st += ('Z' if tz == 'UTC' else tz) return st
Improve phonenumber formats for nl_NL
<?php namespace Faker\Provider\nl_NL; class PhoneNumber extends \Faker\Provider\PhoneNumber { protected static $formats = array( '06 ########', '06-########', '+316-########', '+31(0)6-########', '+316 ########', '+31(0)6 ########', '01# #######', '(01#) #######', '+311# #######', '02# #######', '(02#) #######', '+312# #######', '03# #######', '(03#) #######', '+313# #######', '04# #######', '(04#) #######', '+314# #######', '05# #######', '(05#) #######', '+315# #######', '07# #######', '(07#) #######', '+317# #######', '0800 ######', '+31800 ######', '088 #######', '+3188 #######', '0900 ######', '+31900 ######', ); }
<?php namespace Faker\Provider\nl_NL; class PhoneNumber extends \Faker\Provider\PhoneNumber { protected static $formats = array( '+31(0)#########', '+31(0)### ######', '+31(0)## #######', '+31(0)6 ########', '+31#########', '+31### ######', '+31## #######', '+316 ########', '0#########', '0### ######', '0## #######', '06 ########', '(0###) ######', '(0##) #######', '+31(0)###-######', '+31(0)##-#######', '+31(0)6-########', '+31###-######', '+31##-#######', '+316-########', '0###-######', '0##-#######', '06-########', '(0###)-######', '(0##)-#######', ); }
Allow mutation commands from the test client.
#!/usr/bin/env python """ Binary memcached test client. Copyright (c) 2007 Dustin Sallings <dustin@spy.net> """ import sys import socket import random import struct from testServer import REQ_MAGIC_BYTE, PKT_FMT, MIN_RECV_PACKET, EXTRA_HDR_FMTS from testServer import CMD_SET, CMD_ADD, CMD_REPLACE if __name__ == '__main__': s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) rv = s.connect_ex(('127.0.0.1', 11211)) cmd, key, val = sys.argv[1:4] cmd = int(cmd) if cmd in EXTRA_HDR_FMTS: flags, exp=[int(x) for x in sys.argv[4:]] myopaque=random.Random().randint(0, 2**32) extraHeader='' if cmd in EXTRA_HDR_FMTS: extraHeader = struct.pack(">II", flags, exp) msg=struct.pack(PKT_FMT, REQ_MAGIC_BYTE, cmd, len(key), myopaque, len(key) + len(extraHeader) + len(val)) s.send(msg + extraHeader + key + val) response=s.recv(MIN_RECV_PACKET) assert len(response) == MIN_RECV_PACKET magic, cmd, errcode, opaque, remaining=struct.unpack(PKT_FMT, response) assert magic == REQ_MAGIC_BYTE assert opaque == myopaque print "Error code: ", errcode print `s.recv(remaining)`
#!/usr/bin/env python """ Binary memcached test client. Copyright (c) 2007 Dustin Sallings <dustin@spy.net> """ import sys import socket import random import struct from testServer import REQ_MAGIC_BYTE, PKT_FMT, MIN_RECV_PACKET if __name__ == '__main__': s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) rv = s.connect_ex(('127.0.0.1', 11211)) cmd, key, val = sys.argv[1:] myopaque=random.Random().randint(0, 2**32) s.send(struct.pack(PKT_FMT, REQ_MAGIC_BYTE, int(cmd), len(key), myopaque, len(val)) + key + val) response=s.recv(MIN_RECV_PACKET) assert len(response) == MIN_RECV_PACKET magic, cmd, errcode, opaque, remaining=struct.unpack(PKT_FMT, response) assert magic == REQ_MAGIC_BYTE assert opaque == myopaque print "Error code: ", errcode print s.recv(remaining)
Remove usage of ember jquery integration in tests Note, the ember-jquery addon re-enables usage of this.$() within components without a depreciation warning. https://deprecations.emberjs.com/v3.x/#toc_jquery-apis
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import $ from 'jquery'; module('Integration | Component | froala-content', function(hooks) { setupRenderingTest(hooks); test('.fr-view class is applied', async function(assert) { await render(hbs`{{froala-content elementId="editor"}}`); assert.ok($('#editor', this.element).hasClass('fr-view')); }); test("'content' is output inside the block", async function(assert) { await render(hbs`{{froala-content content="foobar"}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); test("positional param 'content' is output inside the block", async function(assert) { await render(hbs`{{froala-content "foobar"}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); test("block content is properly yield'ed", async function(assert) { await render(hbs`{{#froala-content}}foobar{{/froala-content}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); });
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | froala-content', function(hooks) { setupRenderingTest(hooks); test('.fr-view class is applied', async function(assert) { await render(hbs`{{froala-content elementId="editor"}}`); assert.ok(this.$('#editor').hasClass('fr-view')); }); test("'content' is output inside the block", async function(assert) { await render(hbs`{{froala-content content="foobar"}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); test("positional param 'content' is output inside the block", async function(assert) { await render(hbs`{{froala-content "foobar"}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); test("block content is properly yield'ed", async function(assert) { await render(hbs`{{#froala-content}}foobar{{/froala-content}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); });
Remove redundant ws accept replies It's only relevent on connection
from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.create(user=user, reply_channel=message.reply_channel) message.reply_channel.send({"accept": True}) @channel_session_user def ws_message(message): """They sent us a websocket message! We just update the ChannelSubscription lastseen time..""" user = message.user if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) @channel_session_user def ws_disconnect(message): """The user has disconnected so we remove all their ChannelSubscriptions""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete()
from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.create(user=user, reply_channel=message.reply_channel) message.reply_channel.send({"accept": True}) @channel_session_user def ws_message(message): """They sent us a websocket message! We just update the ChannelSubscription lastseen time..""" user = message.user if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) message.reply_channel.send({"accept": True}) @channel_session_user def ws_disconnect(message): """The user has disconnected so we remove all their ChannelSubscriptions""" user = message.user if not user.is_anonymous(): ChannelSubscription.objects.filter(user=user, reply_channel=message.reply_channel).delete() message.reply_channel.send({"accept": True})
Add COLOR as an available field type
/* * Copyright 2008-2013 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 org.broadleafcommerce.common.presentation.client; /** * * @author jfischer * */ public enum SupportedFieldType { UNKNOWN, ID, BOOLEAN, DATE, INTEGER, DECIMAL, STRING, PASSWORD, PASSWORD_CONFIRM, EMAIL, FOREIGN_KEY, ADDITIONAL_FOREIGN_KEY, MONEY, BROADLEAF_ENUMERATION, EXPLICIT_ENUMERATION, EMPTY_ENUMERATION, DATA_DRIVEN_ENUMERATION, HTML, HTML_BASIC, UPLOAD, HIDDEN, ASSET_URL, ASSET_LOOKUP, MEDIA, RULE_SIMPLE, RULE_WITH_QUANTITY, STRING_LIST, IMAGE, COLOR }
/* * Copyright 2008-2013 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 org.broadleafcommerce.common.presentation.client; /** * * @author jfischer * */ public enum SupportedFieldType { UNKNOWN, ID, BOOLEAN, DATE, INTEGER, DECIMAL, STRING, PASSWORD, PASSWORD_CONFIRM, EMAIL, FOREIGN_KEY, ADDITIONAL_FOREIGN_KEY, MONEY, BROADLEAF_ENUMERATION, EXPLICIT_ENUMERATION, EMPTY_ENUMERATION, DATA_DRIVEN_ENUMERATION, HTML, HTML_BASIC, UPLOAD, HIDDEN, ASSET_URL, ASSET_LOOKUP, MEDIA, RULE_SIMPLE, RULE_WITH_QUANTITY, STRING_LIST, IMAGE }
Add documentation menu to the front page. svn commit r1956
<?php require_once 'DemoPage.php'; /** * The front page of the demo application * * This page displays a quick introduction to the Swat Demo Application * * @package SwatDemo * @copyright 2005 silverorange * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 */ class FrontPage extends DemoPage { public function init() { $this->start_time = microtime(true); $this->demo = 'FrontPage'; $this->ui = new SwatUI(); $this->ui->loadFromXML('../include/pages/'.strtolower($this->demo).'.xml'); $this->initUI(); $this->ui->init(); $this->navbar->createEntry($this->app->title); $this->documentation_menu = $this->getDocumentationMenu(); } public function initUI() { $content = $this->ui->getWidget('content'); $content->content = "Welcome to the Swat Widget Gallery. ". "Here you will find a number of examples of the different widgets ". "Swat provides."; } public function process() { } public function build() { parent::build(); $this->layout->title = $this->app->title; } protected function createLayout() { return new SwatLayout('../layouts/no_source.php'); } } ?>
<?php require_once 'DemoPage.php'; /** * The front page of the demo application * * This page displays a quick introduction to the Swat Demo Application * * @package SwatDemo * @copyright 2005 silverorange * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 */ class FrontPage extends DemoPage { public function init() { $this->start_time = microtime(true); $this->demo = 'FrontPage'; $this->ui = new SwatUI(); $this->ui->loadFromXML('../include/pages/'.strtolower($this->demo).'.xml'); $this->initUI(); $this->ui->init(); $this->navbar->createEntry($this->app->title); } public function initUI() { $content = $this->ui->getWidget('content'); $content->content = "Welcome to the Swat Widget Gallery. ". "Here you will find a number of examples of the different widgets ". "Swat provides."; } public function process() { } public function build() { parent::build(); $this->layout->title = $this->app->title; } protected function createLayout() { return new SwatLayout('../layouts/no_source.php'); } } ?>
Make abstract test case class abstract
<?php /* * This file is part of Laravel Algolia. * * (c) Vincent Klaiber <hello@vinkla.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vinkla\Tests\Algolia; use GrahamCampbell\TestBench\AbstractPackageTestCase; /** * This is the abstract test case class. * * @author Vincent Klaiber <hello@vinkla.com> */ abstract class AbstractTestCase extends AbstractPackageTestCase { /** * Get the service provider class. * * @param \Illuminate\Contracts\Foundation\Application $app * * @return string */ protected function getServiceProviderClass($app) { return 'Vinkla\Algolia\AlgoliaServiceProvider'; } }
<?php /* * This file is part of Laravel Algolia. * * (c) Vincent Klaiber <hello@vinkla.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vinkla\Tests\Algolia; use GrahamCampbell\TestBench\AbstractPackageTestCase; /** * This is the abstract test case class. * * @author Vincent Klaiber <hello@vinkla.com> */ class AbstractTestCase extends AbstractPackageTestCase { /** * Get the service provider class. * * @param \Illuminate\Contracts\Foundation\Application $app * * @return string */ protected function getServiceProviderClass($app) { return 'Vinkla\Algolia\AlgoliaServiceProvider'; } }
Use commit URL to get repo name
<?php declare(strict_types=1); namespace ApiClients\Client\Github\Resource\Async\Repository; use ApiClients\Client\Github\CommandBus\Command\Repository\DetailedCommitCommand; use ApiClients\Client\Github\Resource\Repository\Branch as BaseBranch; use React\Promise\PromiseInterface; class Branch extends BaseBranch { public function refresh(): Branch { throw new \Exception('TODO: create refresh method!'); } public function detailedCommit(): PromiseInterface { return $this->handleCommand(new DetailedCommitCommand( \str_replace('/commits/' . $this->commit->sha(), '', \explode('/repos/', $this->commit->url())[1]), $this->commit->sha() )); } }
<?php declare(strict_types=1); namespace ApiClients\Client\Github\Resource\Async\Repository; use ApiClients\Client\Github\CommandBus\Command\Repository\DetailedCommitCommand; use ApiClients\Client\Github\Resource\Repository\Branch as BaseBranch; use React\Promise\PromiseInterface; class Branch extends BaseBranch { public function refresh(): Branch { throw new \Exception('TODO: create refresh method!'); } public function detailedCommit(): PromiseInterface { return $this->handleCommand(new DetailedCommitCommand( \str_replace('/branches/' . $this->name . '/protection', '', \explode('/repos/', $this->protection_url)[1]), $this->commit->sha() )); } }
Add two more fields to StatsBase
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class SchoolYear(models.Model): name = models.CharField(max_length=9) def __str__(self): return self.name @python_2_unicode_compatible class StatsBase(models.Model): """ An abstract model representing stats commonly tracked across all entities in TEA data. Meant to be the base used by other apps for establishing their stats models. Example: class CampusStats(StatsBase): ... """ # Student counts all_students_count = models.IntegerField('Number of students') african_american_count = models.IntegerField( 'Number of African American students') asian_count = models.IntegerField('Number of Asian students') hispanic_count = models.IntegerField('Number of Hispanic students') pacific_islander_count = models.IntegerField( 'Number of Pacific Islander students') two_or_more_races_count = models.IntegerField( 'Number of Two or More Races students') white_count = models.IntegerField('Number of White students') class Meta: abstract = True
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class SchoolYear(models.Model): name = models.CharField(max_length=9) def __str__(self): return self.name @python_2_unicode_compatible class StatsBase(models.Model): """ An abstract model representing stats commonly tracked across all entities in TEA data. Meant to be the base used by other apps for establishing their stats models. Example: class CampusStats(StatsBase): ... """ # Student counts all_students_count = models.IntegerField('Number of students') asian_count = models.IntegerField('Number of Asian students') hispanic_count = models.IntegerField('Number of Hispanic students') pacific_islander_count = models.IntegerField( 'Number of Pacific Islander students') white_count = models.IntegerField('Number of White students') class Meta: abstract = True
Add a short description to NodeIterator
// A DOM node iterator. // // Has the ability to replace nodes on the fly and continue // the iteration. var NodeIterator = (function() { var NodeIterator = function(root) { this.root = root; this.current = this.next = this.root; }; NodeIterator.prototype.getNextTextNode = function() { var next; while ( (next = this.getNext()) ) { if (next.nodeType === 3 && next.data !== '') { return next; } } }, NodeIterator.prototype.getNext = function() { var child, n; n = this.current = this.next; child = this.next = undefined; if (this.current) { child = n.firstChild; if (child) { this.next = child; } else { while ((n !== this.root) && !(this.next = n.nextSibling)) { n = n.parentNode; } } } return this.current; }; NodeIterator.prototype.replaceCurrent = function(replacement) { this.current = replacement; this.next = undefined; var n = this.current; while ((n !== this.root) && !(this.next = n.nextSibling)) { n = n.parentNode; } }; return NodeIterator; })();
var NodeIterator = (function() { var NodeIterator = function(root) { this.root = root; this.current = this.next = this.root; }; NodeIterator.prototype.getNextTextNode = function() { var next; while ( (next = this.getNext()) ) { if (next.nodeType === 3 && next.data !== '') { return next; } } }, NodeIterator.prototype.getNext = function() { var child, n; n = this.current = this.next; child = this.next = undefined; if (this.current) { child = n.firstChild; if (child) { this.next = child; } else { while ((n !== this.root) && !(this.next = n.nextSibling)) { n = n.parentNode; } } } return this.current; }; NodeIterator.prototype.replaceCurrent = function(replacement) { this.current = replacement; this.next = undefined; var n = this.current; while ((n !== this.root) && !(this.next = n.nextSibling)) { n = n.parentNode; } }; return NodeIterator; })();
Change Camel-Mail example to - not create 2 SMTP servers. - use an integer instead of an integer-shaped string.
/* * #%L * Wildfly Swarm :: Examples :: Camel Mail * %% * Copyright (C) 2016 RedHat * %% * 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. * #L% */ package org.wildfly.swarm.examples.camel.mail; import org.wildfly.swarm.Swarm; import org.wildfly.swarm.mail.MailFraction; public class Main { public static void main(String... args) throws Exception { Swarm swarm = new Swarm(); // Configure mock mail server SMTP session swarm.fraction(new MailFraction().smtpServer("greenmail", s -> s.host("localhost").port(10110).username("user1@localhost").password("password"))); // Deploy mock mail server swarm.start(true); swarm.deploy(Swarm.artifact("com.icegreen:greenmail-webapp:war:1.4.1")); swarm.deploy(); } }
/* * #%L * Wildfly Swarm :: Examples :: Camel Mail * %% * Copyright (C) 2016 RedHat * %% * 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. * #L% */ package org.wildfly.swarm.examples.camel.mail; import org.wildfly.swarm.Swarm; import org.wildfly.swarm.mail.MailFraction; public class Main { public static void main(String... args) throws Exception { MailFraction fraction = MailFraction.defaultFraction(); Swarm swarm = new Swarm(); // Configure mock mail server SMTP session swarm.fraction(fraction.smtpServer("greenmail", s -> s.host("localhost").port("10110").username("user1@localhost").password("password"))); // Deploy mock mail server swarm.start(true); swarm.deploy(Swarm.artifact("com.icegreen:greenmail-webapp:war:1.4.1")); swarm.deploy(); } }
Add link to release notes (to motivate myself write them)
import * as utils from 'base/utils'; import Dialog from '../_dialog'; import Vzb from 'vizabi'; /* * Size dialog */ var About = Dialog.extend({ /** * Initializes the dialog component * @param config component configuration * @param context component context (parent) */ init: function(config, parent) { this.name = 'about'; this._super(config, parent); }, readyOnce: function(){ var version = Vzb._version; var updated = new Date(parseInt(Vzb._build)); this.element = d3.select(this.element); this.element.select(".vzb-about-text0") .html("Vizabi, a project") this.element.select(".vzb-about-text1") .html("by <a href='http://gapminder.org'>Gapminder Foundation</a>") this.element.select(".vzb-about-version") .html("<a href='https://github.com/Gapminder/vizabi/releases/tag/v"+version+"'>Version: "+version+"</a>"); this.element.select(".vzb-about-updated") .html("Build: " + d3.time.format("%Y-%m-%d at %H:%M")(updated)); this.element.select(".vzb-about-text2") .html("Pre-alpha, don't expect too much!"); this.element.select(".vzb-about-credits") .html("<a href='https://github.com/Gapminder/vizabi/graphs/contributors'>Contributors</a>"); } }); export default About;
import * as utils from 'base/utils'; import Dialog from '../_dialog'; import Vzb from 'vizabi'; /* * Size dialog */ var About = Dialog.extend({ /** * Initializes the dialog component * @param config component configuration * @param context component context (parent) */ init: function(config, parent) { this.name = 'about'; this._super(config, parent); }, readyOnce: function(){ var version = Vzb._version; var updated = new Date(parseInt(Vzb._build)); this.element = d3.select(this.element); this.element.select(".vzb-about-text0") .text("Vizabi, a project") this.element.select(".vzb-about-text1") .html("by <a href='http://gapminder.org'>Gapminder Foundation</a>") this.element.select(".vzb-about-version") .text("Version: " + version); this.element.select(".vzb-about-updated") .text("Build: " + d3.time.format("%Y-%m-%d at %H:%M")(updated)); this.element.select(".vzb-about-text2") .text("Pre-alpha, don't expect too much!"); this.element.select(".vzb-about-credits") .html("<a href='https://github.com/Gapminder/vizabi/graphs/contributors'>Contributors</a>"); } }); export default About;
Test the actual get_zone call
import os from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def setUp(self): configure_services('cloudflare', ['cloudflare'], conf.common) self.cloudflare = CloudFlareService() def test_get_all_zones(self): zones = self.cloudflare.get_zones() self.assertIsInstance(zones, list) def test_get_zone(self): zone_id = self.cloudflare.get_zones()[0]['id'] zone = self.cloudflare.get_zone(zone_id) self.assertIsInstance(zone, dict)
import os from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def setUp(self): configure_services('cloudflare', ['cloudflare'], conf.common) self.cloudflare = CloudFlareService() def test_get_all_zones(self): zones = self.cloudflare.get_zones() self.assertIsInstance(zones, list) def test_get_zone(self): zone = self.cloudflare.get_zones()[0] self.assertIsInstance(zone, dict)
Use let instead of var
import Shogi from '../src/shogi'; import * as CONST from '../constants/actionTypes'; const InitialState = { board: Shogi.Board, isHoldingPiece: undefined }; const ShogiReducer = (state = InitialState, action) => { switch (action.type) { case CONST.HOLD_PIECE: if (action.piece.type == '*') { return state; } else { let newBoard = state.board.enhanceMovablePoint(action.piece); return Object.assign({}, { board: newBoard, isHoldingPiece: action.piece }); } case CONST.MOVE_PIECE: // if same piece click, release piece. if (state.isHoldingPiece) { let newBoard = state.board.movePiece(state.isHoldingPiece, action.piece); return Object.assign({}, { board: newBoard }, { isHoldingPiece: undefined }); } else { return Object.assign({}, state, { isHoldingPiece: action.piece }); } default: return state; } }; export default ShogiReducer;
import Shogi from '../src/shogi'; import * as CONST from '../constants/actionTypes'; const InitialState = { board: Shogi.Board, isHoldingPiece: undefined }; const ShogiReducer = (state = InitialState, action) => { switch (action.type) { case CONST.HOLD_PIECE: if (action.piece.type == '*') { return state; } else { let newBoard = state.board.enhanceMovablePoint(action.piece); return Object.assign({}, { board: newBoard, isHoldingPiece: action.piece }); } case CONST.MOVE_PIECE: // if same piece click, release piece. if (state.isHoldingPiece) { var newBoard = state.board.movePiece(state.isHoldingPiece, action.piece); return Object.assign({}, { board: newBoard }, { isHoldingPiece: undefined }); } else { return Object.assign({}, state, { isHoldingPiece: action.piece }); } default: return state; } }; export default ShogiReducer;
Add try…catch block to track
import { addCallback } from 'meteor/vulcan:core'; export const initFunctions = []; export const trackFunctions = []; export const addInitFunction = f => { initFunctions.push(f); // execute init function as soon as possible f(); }; export const addTrackFunction = f => { trackFunctions.push(f); }; export const track = async (eventName, eventProperties, currentUser) => { for (let f of trackFunctions) { try { await f(eventName, eventProperties, currentUser); } catch (error) { // eslint-disable-next-line no-console console.log(`// ${f.name} track error`); // eslint-disable-next-line no-console console.log(error); } } }; export const addUserFunction = f => { addCallback('users.new.async', f); }; export const addIdentifyFunction = f => { addCallback('events.identify', f); }; export const addPageFunction = f => { const f2 = (empty, route) => f(route); // rename f2 to same name as f // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty const descriptor = Object.create(null); // no inherited properties descriptor.value = f.name; Object.defineProperty(f2, 'name', descriptor); addCallback('router.onUpdate', f2); };
import { addCallback } from 'meteor/vulcan:core'; export const initFunctions = []; export const trackFunctions = []; export const addInitFunction = f => { initFunctions.push(f); // execute init function as soon as possible f(); }; export const addTrackFunction = f => { trackFunctions.push(f); }; export const track = async (eventName, eventProperties, currentUser) => { for (let f of trackFunctions) { await f(eventName, eventProperties, currentUser); } }; export const addUserFunction = f => { addCallback('users.new.async', f); }; export const addIdentifyFunction = f => { addCallback('events.identify', f); }; export const addPageFunction = f => { const f2 = (empty, route) => f(route); // rename f2 to same name as f // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty const descriptor = Object.create(null); // no inherited properties descriptor.value = f.name; Object.defineProperty(f2, 'name', descriptor); addCallback('router.onUpdate', f2); };
Add the instructor toggle functionality
var AdminPanel = function() { var self = this; $('.admin_toggle').change(function() { self.togglePrivileges(this, $(this).data('url'), 'admin', this.checked); }); $('.instructor_toggle').change(function() { self.togglePrivileges(this, $(this).data('url'), 'instructor', this.checked); }); this.togglePrivileges = function(element, url, role, privilege) { $.ajax({ url: url, type: 'POST', data: {toggle_to: privilege}, success: function(data) { console.log(data); }, error: function(err) { console.log('errror'); console.log(err); } }); } }; $(document).ready(AdminPanel); $(document).on('page:load', AdminPanel);
var AdminPanel = function() { var self = this; $('.admin_toggle').change(function() { self.togglePrivileges(this, $(this).data('url'), 'admin', this.checked); }); $('.instructor_toggle').change(function() { console.log('stub'); }); this.togglePrivileges = function(element, url, role, privilege) { $.ajax({ url: url, type: 'POST', data: {toggle_to: privilege}, success: function(data) { console.log(data); }, error: function(err) { console.log('errror'); console.log(err); } }); } }; $(document).ready(AdminPanel); $(document).on('page:load', AdminPanel);
Add "long" package to webpack externals
import path from 'path'; export default { module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }] }, output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', libraryTarget: 'commonjs2' }, resolve: { extensions: ['', '.js', '.jsx', '.json'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] }, plugins: [ ], externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) 'pokemon-go-node-api', 'long' ] };
import path from 'path'; export default { module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }] }, output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', libraryTarget: 'commonjs2' }, resolve: { extensions: ['', '.js', '.jsx', '.json'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] }, plugins: [ ], externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) 'pokemon-go-node-api' ] };
Use `canOpen` in GPIO `open` function
import Promise from "bluebird"; import gpio from "rpi-gpio"; import _ from "underscore"; class RpiGpioOpener { constructor(config) { gpio.setMode(gpio.MODE_BCM); this.pins = config.pins; this.opening = {}; } canOpen(doorId) { return !_.isUndefined(this.pins[doorId]); } open(doorId, time) { if (!this.canOpen(doorId) || this.opening[doorId]) return; this.opening[doorId] = true; this.writePin(doorId, true) .delay(time) .then(() => this.writePin(doorId, false)) .catch(console.error) .finally(() => this.opening[doorId] = false); } writePin(doorId, value) { const pin = this.pins[doorId]; const gpioSetup = Promise.promisify(gpio.setup, { context: gpio }); const gpioWrite = Promise.promisify(gpio.write, { context: gpio }); return gpioSetup(pin, gpio.DIR_OUT, gpio.EDGE_NONE) .tap(() => console.log(`Writing '${value}' to pin ${pin}`)) .then(() => gpioWrite(pin, value)); } } export default RpiGpioOpener;
import Promise from "bluebird"; import gpio from "rpi-gpio"; import _ from "underscore"; class RpiGpioOpener { constructor(config) { gpio.setMode(gpio.MODE_BCM); this.pins = config.pins; this.opening = {}; } canOpen(doorId) { return !_.isUndefined(this.pins[doorId]); } open(doorId, time) { if (_.isUndefined(this.pins[doorId]) || this.opening[doorId]) return; this.opening[doorId] = true; this.writePin(doorId, true) .delay(time) .then(() => this.writePin(doorId, false)) .catch(console.error) .finally(() => this.opening[doorId] = false); } writePin(doorId, value) { const pin = this.pins[doorId]; const gpioSetup = Promise.promisify(gpio.setup, { context: gpio }); const gpioWrite = Promise.promisify(gpio.write, { context: gpio }); return gpioSetup(pin, gpio.DIR_OUT, gpio.EDGE_NONE) .tap(() => console.log(`Writing '${value}' to pin ${pin}`)) .then(() => gpioWrite(pin, value)); } } export default RpiGpioOpener;
:art: Apply colored image when you hover the link Not just the image itself (there's padding on the link).
import React, { Component, PropTypes } from 'react'; import './SocialLink.css'; class SocialLink extends Component { static propTypes = { name: PropTypes.string.isRequired, url: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, iconHover: PropTypes.string.isRequired, }; state = { isHovering: false, }; handleMouseOver() { this.setState({ isHovering: true }); } handleMouseOut() { this.setState({ isHovering: false }); } render() { const { isHovering } = this.state; const { name, url, icon, iconHover } = this.props; return ( <li className="social-link"> <a className="social-link" href={url} onMouseOver={() => this.handleMouseOver()} onMouseOut={() => this.handleMouseOut()} > <img className="social-icon" src={isHovering ? iconHover : icon} alt={name} /> </a> </li> ); } } export default SocialLink;
import React, { Component, PropTypes } from 'react'; import './SocialLink.css'; class SocialLink extends Component { static propTypes = { name: PropTypes.string.isRequired, url: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, iconHover: PropTypes.string.isRequired, }; state = { isHovering: false, }; handleMouseOver() { this.setState({ isHovering: true }); } handleMouseOut() { this.setState({ isHovering: false }); } render() { const { isHovering } = this.state; const { name, url, icon, iconHover } = this.props; return ( <li className="social-link"> <a className="social-link" href={url}> <img className="social-icon" src={isHovering ? iconHover : icon} alt={name} onMouseOver={() => this.handleMouseOver()} onMouseOut={() => this.handleMouseOut()} /> </a> </li> ); } } export default SocialLink;
Include an override to the default manager to allow geospatial querying.
from django.conf import settings from django.contrib.gis.db import models class Campground(models.Model): campground_code = models.CharField(max_length=64) name = models.CharField(max_length=128) campground_type = models.CharField(max_length=128) phone = models.CharField(max_length=128) comments = models.TextField() sites = models.CharField(max_length=128) elevation = models.CharField(max_length=128) hookups = models.CharField(max_length=128) amenities = models.TextField() point = models.PointField(srid=4326) objects = models.GeoManager() def locator_point(self): return self.point def __unicode__(self): return self.name # integrate with the django-locator app for easy geo lookups if it's installed if 'locator.objects' in settings.INSTALLED_APPS: from locator.objects.models import create_locator_object models.signals.post_save.connect(create_locator_object, sender=Campground)
from django.conf import settings from django.contrib.gis.db import models class Campground(models.Model): campground_code = models.CharField(max_length=64) name = models.CharField(max_length=128) campground_type = models.CharField(max_length=128) phone = models.CharField(max_length=128) comments = models.TextField() sites = models.CharField(max_length=128) elevation = models.CharField(max_length=128) hookups = models.CharField(max_length=128) amenities = models.TextField() point = models.PointField(srid=4326) def locator_point(self): return self.point def __unicode__(self): return self.name # integrate with the django-locator app for easy geo lookups if it's installed if 'locator.objects' in settings.INSTALLED_APPS: from locator.objects.models import create_locator_object models.signals.post_save.connect(create_locator_object, sender=Campground)
Fix protocol join group including the assigner metadata
const Encoder = require('../../../encoder') const { JoinGroup: apiKey } = require('../../apiKeys') /** * JoinGroup Request (Version: 0) => group_id session_timeout member_id protocol_type [group_protocols] * group_id => STRING * session_timeout => INT32 * member_id => STRING * protocol_type => STRING * group_protocols => protocol_name protocol_metadata * protocol_name => STRING * protocol_metadata => BYTES */ module.exports = ({ groupId, sessionTimeout, memberId, protocolType, groupProtocols }) => ({ apiKey, apiVersion: 0, apiName: 'JoinGroup', encode: async () => { return new Encoder() .writeString(groupId) .writeInt32(sessionTimeout) .writeString(memberId) .writeString(protocolType) .writeArray(groupProtocols.map(encodeGroupProtocols)) }, }) const encodeGroupProtocols = ({ name, metadata = '' }) => { return new Encoder().writeString(name).writeBytes(metadata) }
const Encoder = require('../../../encoder') const { JoinGroup: apiKey } = require('../../apiKeys') /** * JoinGroup Request (Version: 0) => group_id session_timeout member_id protocol_type [group_protocols] * group_id => STRING * session_timeout => INT32 * member_id => STRING * protocol_type => STRING * group_protocols => protocol_name protocol_metadata * protocol_name => STRING * protocol_metadata => BYTES */ module.exports = ({ groupId, sessionTimeout, memberId, protocolType, groupProtocols }) => ({ apiKey, apiVersion: 0, apiName: 'JoinGroup', encode: async () => { return new Encoder() .writeString(groupId) .writeInt32(sessionTimeout) .writeString(memberId) .writeString(protocolType) .writeArray(groupProtocols.map(encodeGroupProtocols)) }, }) const encodeGroupProtocols = ({ name, metadata = {} }) => { const protocolMetadata = new Encoder().writeInt16(metadata.version || 0) return new Encoder().writeString(name).writeBytes(protocolMetadata.buffer) }
Fix old variable STACK_START name (not used anymore)
# State identifiers (begin and end). NO_STATE = -1 BIND_START = 0 BIND_END = BIND_START + 1 INTER_SSH_START = 10 INTER_SSH_END = INTER_SSH_START + 1 GIT_SETUP_START = 20 GIT_SETUP_END = GIT_SETUP_START + 1 UPLOAD_REPO_START = 30 UPLOAD_REPO_END = UPLOAD_REPO_START + 1 INSTALL_PKG_START = 40 INSTALL_PKG_END = INSTALL_PKG_START + 1 CLONE_STACK_START = 50 CLONE_STACK_END = CLONE_STACK_START + 1 PATCH_STACK_START = 60 PATCH_STACK_END = PATCH_STACK_START + 1 UPLOAD_EXTRAS_START = 70 UPLOAD_EXTRAS_END = UPLOAD_EXTRAS_START + 1 CREATE_LOCAL_START = 80 CREATE_LOCAL_END = CREATE_LOCAL_START + 1 STACK_SH_START = 100 STACK_SH_END = STACK_SH_START + 1
# State identifiers (begin and end). NO_STATE = -1 BIND_START = 0 BIND_END = BIND_START + 1 INTER_SSH_START = 10 INTER_SSH_END = INTER_SSH_START + 1 GIT_SETUP_START = 20 GIT_SETUP_END = GIT_SETUP_START + 1 UPLOAD_REPO_START = 30 UPLOAD_REPO_END = UPLOAD_REPO_START + 1 INSTALL_PKG_START = 40 INSTALL_PKG_END = INSTALL_PKG_START + 1 CLONE_STACK_START = 50 CLONE_STACK_END = CLONE_STACK_START + 1 PATCH_STACK_START = 60 PATCH_STACK_END = PATCH_STACK_START + 1 UPLOAD_EXTRAS_START = 70 UPLOAD_EXTRAS_END = UPLOAD_EXTRAS_START + 1 CREATE_LOCAL_START = 80 CREATE_LOCAL_END = CREATE_LOCAL_START + 1 STACK_SH_START = 100 STACK_SH_END = STACK_START + 1
Use process.exit(0) if none found
'use strict' var fs = require('fs') var miss = require('mississippi') var config = require('../config') function filterJobsList (jobs) { var list = [] jobs.forEach(function (job) { if (job.indexOf('.json') > -1) { list.push(job) } }) return list } var getNextJob = miss.through(function (chunck, encoding, callback) { var jobs = filterJobsList(fs.readdirSync(config.JOB_DIRECTORY_PATH)) var item console.log('get-next-job') if (jobs.length > 0) { item = fs.readFileSync(config.JOB_DIRECTORY_PATH + '/' + jobs[0]) return callback(null, item.toString()) } else { console.log('No jobs in queue') process.exit(0) } }) module.exports = getNextJob
'use strict' var fs = require('fs') var miss = require('mississippi') var config = require('../config') function filterJobsList (jobs) { var list = [] jobs.forEach(function (job) { if (job.indexOf('.json') > -1) { list.push(job) } }) return list } var getNextJob = miss.through(function (chunck, encoding, callback) { var jobs = filterJobsList(fs.readdirSync(config.JOB_DIRECTORY_PATH)) var item console.log('get-next-job') if (jobs.length > 0) { item = fs.readFileSync(config.JOB_DIRECTORY_PATH + '/' + jobs[0]) return callback(null, item.toString()) } else { return callback(new Error('No jobs in queue'), null) } }) module.exports = getNextJob
Copy identities from context to event model
var Promise = require('bluebird'); var deepExtend = require('deep-extend'); var AnalyticsContext = require('./AnalyticsContext'); var AnalyticsEventModel = require('./AnalyticsEventModel'); var AnalyticsDispatcher = require('./AnalyticsDispatcher'); var createEventModel = function(eventName, context){ var eventModel = new AnalyticsEventModel(); eventModel.Name = eventName; eventModel.Scope = context.Scopes.join("_"); deepExtend(eventModel.ExtraData, context.ExtraData); deepExtend(eventModel.MetaData, context.MetaData); deepExtend(eventModel.Identities, context.Identities); return context.Filters.reduce(function(cur, next) { return cur.then( function(){ return next(eventModel); }); }, Promise.resolve()) .then(function() { return eventModel; }); }; module.exports = function(eventModelWriter, rootContext) { return new AnalyticsDispatcher(function(name, context) { return Promise.resolve() .then(function () { return createEventModel(name,context); }) .then(function (eventModel){ return eventModelWriter(eventModel); }); }, rootContext); };
var Promise = require('bluebird'); var deepExtend = require('deep-extend'); var AnalyticsContext = require('./AnalyticsContext'); var AnalyticsEventModel = require('./AnalyticsEventModel'); var AnalyticsDispatcher = require('./AnalyticsDispatcher'); var createEventModel = function(eventName, context){ var eventModel = new AnalyticsEventModel(); eventModel.Name = eventName; eventModel.Scope = context.Scopes.join("_"); deepExtend(eventModel.ExtraData, context.ExtraData); deepExtend(eventModel.MetaData, context.MetaData); return context.Filters.reduce(function(cur, next) { return cur.then( function(){ return next(eventModel); }); }, Promise.resolve()) .then(function() { return eventModel; }); }; module.exports = function(eventModelWriter, rootContext) { return new AnalyticsDispatcher(function(name, context) { return Promise.resolve() .then(function () { return createEventModel(name,context); }) .then(function (eventModel){ return eventModelWriter(eventModel); }); }, rootContext); };
Add ResizerObserver shim for tests.
import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; global.requestAnimationFrame = function(callback) { setTimeout(callback, 0); }; try { require('canvas'); } catch(err) { global.HAS_CANVAS = false; global.HTMLCanvasElement = function() {}; global.HTMLCanvasElement.prototype.getContext = () => { return {}; }; } window.ResizeObserver = jest.fn().mockImplementation(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn() })); // add an i18n setup i18n .use(initReactI18next) .init({ keySeparator: false, lng: 'dev', resources: { dev: { translation: {} }, }, interpolation: { escapeValue: false, }, });
import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; global.requestAnimationFrame = function(callback) { setTimeout(callback, 0); }; try { require('canvas'); } catch(err) { global.HAS_CANVAS = false; global.HTMLCanvasElement = function() {}; global.HTMLCanvasElement.prototype.getContext = () => { return {}; }; } // add an i18n setup i18n .use(initReactI18next) .init({ keySeparator: false, lng: 'dev', resources: { dev: { translation: {} }, }, interpolation: { escapeValue: false, }, });
Remove unnecessary call to promisify
const command = { command: "console", description: "Run a console with contract abstractions and commands available", builder: {}, help: { usage: "truffle console [--network <name>] [--verbose-rpc]", options: [ { option: "--network <name>", description: "Specify the network to use. Network name must exist in the configuration." }, { option: "--verbose-rpc", description: "Log communication between Truffle and the Ethereum client." } ] }, run: async function (options) { const Config = require("@truffle/config"); const Console = require("../console"); const { Environment } = require("@truffle/environment"); const config = Config.detect(options); // This require a smell? const commands = require("./index"); const excluded = new Set(["console", "init", "watch", "develop"]); const consoleCommands = Object.keys(commands).reduce((acc, name) => { return !excluded.has(name) ? Object.assign(acc, {[name]: commands[name]}) : acc; }, {}); await Environment.detect(config); const c = new Console(consoleCommands, config.with({noAliases: true})); return await c.start(); } }; module.exports = command;
const { promisify } = require("util"); const command = { command: "console", description: "Run a console with contract abstractions and commands available", builder: {}, help: { usage: "truffle console [--network <name>] [--verbose-rpc]", options: [ { option: "--network <name>", description: "Specify the network to use. Network name must exist in the configuration." }, { option: "--verbose-rpc", description: "Log communication between Truffle and the Ethereum client." } ] }, run: async function (options) { const Config = require("@truffle/config"); const Console = require("../console"); const { Environment } = require("@truffle/environment"); const config = Config.detect(options); // This require a smell? const commands = require("./index"); const excluded = new Set(["console", "init", "watch", "develop"]); const consoleCommands = Object.keys(commands).reduce((acc, name) => { return !excluded.has(name) ? Object.assign(acc, {[name]: commands[name]}) : acc; }, {}); await Environment.detect(config); const c = new Console(consoleCommands, config.with({noAliases: true})); return await promisify(c.start).bind(c.start)(); } }; module.exports = command;
Make sure to update correct load balancer
#!/usr/bin/env python3 import argparse import subprocess import json import sys parser = argparse.ArgumentParser() args = parser.parse_args() def info(msg): sys.stdout.write('* {}\n'.format(msg)) sys.stdout.flush() info('Determining current production details...') output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode( 'utf-8') data = json.loads(output) linked_service = data['linked_to_service'][0]['name'] info('Currently linked service is \'{}\''.format(linked_service)) if linked_service == 'muzhack-green': link_to = 'muzhack-blue' else: assert linked_service == 'muzhack-blue' link_to = 'muzhack-green' info('Redeploying service \'{}\'...'.format(link_to)) subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE) info('Linking to service \'{}\'...'.format(link_to)) subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to), '--sync', 'lb.muzhack-staging'], stdout=subprocess.PIPE) info('Successfully switched production service to {}'.format(link_to))
#!/usr/bin/env python3 import argparse import subprocess import json import sys parser = argparse.ArgumentParser() args = parser.parse_args() def info(msg): sys.stdout.write('* {}\n'.format(msg)) sys.stdout.flush() info('Determining current production details...') output = subprocess.check_output(['tutum', 'service', 'inspect', 'lb.muzhack-staging']).decode( 'utf-8') data = json.loads(output) linked_service = data['linked_to_service'][0]['name'] info('Currently linked service is \'{}\''.format(linked_service)) if linked_service == 'muzhack-green': link_to = 'muzhack-blue' else: assert linked_service == 'muzhack-blue' link_to = 'muzhack-green' info('Redeploying service \'{}\'...'.format(link_to)) subprocess.check_call(['tutum', 'service', 'redeploy', '--sync', link_to], stdout=subprocess.PIPE) info('Linking to service \'{}\'...'.format(link_to)) subprocess.check_call(['tutum', 'service', 'set', '--link-service', '{0}:{0}'.format(link_to), '--sync', 'lb'], stdout=subprocess.PIPE) info('Successfully switched production service to {}'.format(link_to))
Indent with tabs in generated xml
'use strict'; const neatCsv = require('neat-csv'); const pify = require('pify'); const Promise = require('pinkie-promise'); const redent = require('redent'); const trimNewlines = require('trim-newlines'); module.exports = (str, opts) => { opts = opts || {}; opts.attributes = opts.attributes || {}; if (typeof str !== 'string') { return Promise.reject(new TypeError('Expected a string')); } function getAttributes() { const keys = Object.keys(opts.attributes); return keys.map(el => `${el}="${String(opts.attributes[el])}"`).join(' ').trim(); } return pify(neatCsv, Promise)(str, opts).then(data => { return data.map(el => { const attrs = getAttributes() ? ` ${getAttributes()}` : ''; const keys = Object.keys(el); const tags = keys.map(key => { const tag = key === 'to' ? `${key}${attrs}` : key; if (!el[key]) { return null; } if (key === 'from' && opts.strict) { el[key] = `^${el[key].trim()}$`; } return ` <${tag}>${el[key].trim()}</${key}>`; }).filter(Boolean).join('\n'); return redent(trimNewlines(`<rule>\n${tags}\n</rule>`)); }); }); };
'use strict'; const neatCsv = require('neat-csv'); const pify = require('pify'); const Promise = require('pinkie-promise'); const redent = require('redent'); const trimNewlines = require('trim-newlines'); module.exports = (str, opts) => { opts = opts || {}; opts.attributes = opts.attributes || {}; if (typeof str !== 'string') { return Promise.reject(new TypeError('Expected a string')); } function getAttributes() { const keys = Object.keys(opts.attributes); return keys.map(el => `${el}="${String(opts.attributes[el])}"`).join(' ').trim(); } return pify(neatCsv, Promise)(str, opts).then(data => { return data.map(el => { const attrs = getAttributes() ? ` ${getAttributes()}` : ''; const keys = Object.keys(el); const tags = keys.map(key => { const tag = key === 'to' ? `${key}${attrs}` : key; if (!el[key]) { return null; } if (key === 'from' && opts.strict) { el[key] = `^${el[key].trim()}$`; } return ` <${tag}>${el[key].trim()}</${key}>`; }).filter(Boolean).join('\n'); return redent(trimNewlines(`<rule>\n${tags}\n</rule>`)); }); }); };
Prepare for config and command line arguments
#!/usr/bin/env python3 # Pianette # A command-line emulator of a PS2 Game Pad Controller # that asynchronously listens to GPIO EDGE_RISING # inputs from sensors and sends Serial commands to # an ATMEGA328P acting as a fake SPI Slave for the Console. # Written in Python 3. import pianette.config import sys from pianette.GPIOController import GPIOController from pianette.Pianette import Pianette from pianette.utils import Debug Debug.println("INFO", " ") Debug.println("INFO", " ################################## ") Debug.println("INFO", " | PIANETTE | ") Debug.println("INFO", " ################################## ") Debug.println("INFO", " ") # FIX ME - introduce sys.argv[1] to choose player AND game? configobj = pianette.config.get_configobj('street-fighter-alpha-3', 'player1') # Instanciate the global Pianette # Its responsibility is to translate Piano actions to Console actions pianette = Pianette(configobj=configobj) # Instanciate the global GPIO Controller # Its responsibility is to feed the Pianette based on GPIO inputs gpio_controller = GPIOController(configobj=configobj, pianette=pianette) # Make the Pianette object listen to GPIO inputs pianette.enable_source("gpio") # Run the main loop of interactive Pianette Debug.println("NOTICE", "Entering main loop") pianette.cmd.cmdloop()
#!/usr/bin/env python3 # Pianette # A command-line emulator of a PS2 Game Pad Controller # that asynchronously listens to GPIO EDGE_RISING # inputs from sensors and sends Serial commands to # an ATMEGA328P acting as a fake SPI Slave for the Console. # Written in Python 3. import pianette.config import sys from pianette.GPIOController import GPIOController from pianette.Pianette import Pianette from pianette.utils import Debug Debug.println("INFO", " ") Debug.println("INFO", " ################################## ") Debug.println("INFO", " | PIANETTE | ") Debug.println("INFO", " ################################## ") Debug.println("INFO", " ") configobj = pianette.config.get_configobj('street-fighter-alpha-3', 'player1') # Instanciate the global Pianette # Its responsibility is to translate Piano actions to Console actions pianette = Pianette(configobj=configobj) # Instanciate the global GPIO Controller # Its responsibility is to feed the Pianette based on GPIO inputs gpio_controller = GPIOController(configobj=configobj, pianette=pianette) # Make the Pianette object listen to GPIO inputs pianette.enable_source("gpio") # Run the main loop of interactive Pianette Debug.println("NOTICE", "Entering main loop") pianette.cmd.cmdloop()
Use the right comment style for jsdoc
// @flow /** * Transform a Promise-returning function into a function that can optionally * take a callback as the last parameter instead. * * @param {Function} fn a function that returns a Promise * @param {Object} self (optional) `this` to be used when applying fn * @return {Function} a function that can take callbacks as well. */ function optionalCallback(fn, self) { return function() { if (!self) { self = this; } var last = arguments[arguments.length - 1]; if (typeof last === 'function') { return fn.apply(self, arguments).then(function(){ last.apply(self, arguments); }).catch(function(err){ last(err); }); } else { return fn.apply(self, arguments); } }; } module.exports = optionalCallback;
// @flow /* Transform a Promise-returning function into a function that can optionally * take a callback as the last parameter instead. * * @param {Function} fn a function that returns a Promise * @param {Object} self (optional) `this` to be used when applying fn * @return {Function} a function that can take callbacks as well. */ function optionalCallback(fn, self) { return function() { if (!self) { self = this; } var last = arguments[arguments.length - 1]; if (typeof last === 'function') { return fn.apply(self, arguments).then(function(){ last.apply(self, arguments); }).catch(function(err){ last(err); }); } else { return fn.apply(self, arguments); } }; } module.exports = optionalCallback;
Refactor slash-unpickiness as a function and redecorate
import projects from flask import Flask, render_template, abort app = Flask(__name__) def route(*a, **kw): kw['strict_slashes'] = kw.get('strict_slashes', False) return app.route(*a, **kw) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @route('/blog') def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @route('/<project>') def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True)
import projects from flask import Flask, render_template, abort app = Flask(__name__) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @app.route('/blog', strict_slashes=False) def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @app.route('/<project>', strict_slashes=False) def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True)
Use includes to make code simplier
export function getInterfaceLanguage() { if (!!navigator && !!navigator.language) { return navigator.language; } else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) { return navigator.languages[0]; } else if (!!navigator && !!navigator.userLanguage) { return navigator.userLanguage; } else if (!!navigator && !!navigator.browserLanguage) { return navigator.browserLanguage; } return 'en-US'; } export function validateProps(props) { const reservedNames = [ '_interfaceLanguage', '_language', '_defaultLanguage', '_defaultLanguageFirstLevelKeys', '_props', ]; Object.keys(props).forEach(key => { if (reservedNames.includes(key)) throw new Error(`${key} cannot be used as a key. It is a reserved word.`) }); }
export function getInterfaceLanguage() { if (!!navigator && !!navigator.language) { return navigator.language; } else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) { return navigator.languages[0]; } else if (!!navigator && !!navigator.userLanguage) { return navigator.userLanguage; } else if (!!navigator && !!navigator.browserLanguage) { return navigator.browserLanguage; } return 'en-US'; } export function validateProps(props) { const reservedNames = [ '_interfaceLanguage', '_language', '_defaultLanguage', '_defaultLanguageFirstLevelKeys', '_props', ]; Object.keys(props).forEach(key => { if (reservedNames.indexOf(key)>=0) throw new Error(`${key} cannot be used as a key. It is a reserved word.`) }); }
Add more verbose error to reporte on Travis parserXML.py
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): element=root.findall('.//FatalError')[0] eprint("Error detected") print(infile) print(element.text) sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") print(infile) sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
Substitute console logs with proper asserts
/* jshint mocha: true */ 'use strict'; const assert = require('assert'); const jenkins = require('../lib/jenkins'); describe('jenkins', function() { describe('getComputers()', function() { it('returns all nodes', function(done) { this.timeout(10000); jenkins.getComputers(function(err, nodes) { assert.ifError(err); assert.equal(nodes.length, 68); done(); }); }); }); describe('getOffline()', function() { it('returns offline nodes', function(done) { this.timeout(10000); jenkins.getOffline(function(err, offline) { assert.ifError(err); assert.equal(offline.length, 5); done(); }); }); }); });
/* jshint mocha: true */ 'use strict'; const assert = require('assert'); const jenkins = require('../lib/jenkins'); describe('jenkins', function() { describe('getComputers()', function() { it('returns all nodes', function(done) { this.timeout(10000); jenkins.getComputers(function(err, nodes) { assert.ifError(err); console.log(nodes); console.log(nodes.length); done(); }); }); }); describe('getOffline()', function() { it('returns offline nodes', function(done) { this.timeout(10000); jenkins.getOffline(function(err, offline) { assert.ifError(err); console.log(offline); done(); }); }); }); });
Remove useless mock side effect
import pytest from unittest import TestCase, mock import core.config import core.widget import modules.contrib.publicip def build_module(): config = core.config.Config([]) return modules.contrib.publicip.Module(config=config, theme=None) def widget(module): return module.widgets()[0] class PublicIPTest(TestCase): def test_load_module(self): __import__("modules.contrib.publicip") @mock.patch('util.location.public_ip') def test_public_ip(self, public_ip_mock): public_ip_mock.return_value = '5.12.220.2' module = build_module() module.update() assert widget(module).full_text() == '5.12.220.2' @mock.patch('util.location.public_ip') def test_public_ip_with_exception(self, public_ip_mock): public_ip_mock.side_effect = Exception module = build_module() module.update() assert widget(module).full_text() == 'n/a' def test_interval_seconds(self): module = build_module() assert module.parameter('interval') == 3600
import pytest from unittest import TestCase, mock import core.config import core.widget import modules.contrib.publicip def build_module(): config = core.config.Config([]) return modules.contrib.publicip.Module(config=config, theme=None) def widget(module): return module.widgets()[0] class PublicIPTest(TestCase): def test_load_module(self): __import__("modules.contrib.publicip") @mock.patch('util.location.public_ip') def test_public_ip(self, public_ip_mock): public_ip_mock.return_value = '5.12.220.2' module = build_module() module.update() assert widget(module).full_text() == '5.12.220.2' @mock.patch('util.location.public_ip') def test_public_ip_with_exception(self, public_ip_mock): public_ip_mock.side_effect = Exception module = build_module() module.update() assert widget(module).full_text() == 'n/a' @mock.patch('util.location.public_ip') def test_interval_seconds(self, public_ip_mock): public_ip_mock.side_effect = Exception module = build_module() assert module.parameter('interval') == 3600
Modify test worker unit test Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
import sys import os sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine')) from worker import Worker from worker_queue import WorkerQueue from job import Job class TestWorker(object): def setup(self): self.worker = Worker() def test_init(self): assert isinstance(self.worker.worker_queue, WorkerQueue) is True def test_execute_simple_cmd(self): job = Job(service_id="12345", command="echo 'HELLO'") updated_job = self.worker.execute_cmd(job) assert updated_job.output == "HELLO\n" assert updated_job.completed() is True assert updated_job.passed() is False def test_execute_cmd_trigger_timeout(self): timeout_time = 1 sleep_time = timeout_time + 1 job = Job(service_id="12345", command="sleep " + str(sleep_time)) updated_job = self.worker.execute_cmd(job, timeout_time) assert updated_job.output is None assert updated_job.reason == "Command Timed Out" assert updated_job.passed() is False assert updated_job.completed() is True
import sys import os sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine')) from worker import Worker from worker_queue import WorkerQueue from job import Job class TestWorker(object): def test_init(self): worker = Worker() assert isinstance(worker.worker_queue, WorkerQueue) is True def test_execute_simple_cmd(self): worker = Worker() job = Job(service_id="12345", command="echo 'HELLO'") updated_job = worker.execute_cmd(job) assert updated_job.output == "HELLO\n" assert updated_job.completed() is True assert updated_job.passed() is False def test_execute_cmd_trigger_timeout(self): worker = Worker() timeout_time = 1 sleep_time = timeout_time + 1 job = Job(service_id="12345", command="sleep " + str(sleep_time)) updated_job = worker.execute_cmd(job, timeout_time) assert updated_job.output is None assert updated_job.reason == "Command Timed Out" assert updated_job.passed() is False assert updated_job.completed() is True
Make sure random values are random across processes
import logging import random import os from unittest import TestLoader, TestSuite import unittest.util from exchangelib.util import PrettyXmlHandler class RandomTestSuite(TestSuite): def __iter__(self): tests = list(super().__iter__()) random.shuffle(tests) return iter(tests) # Execute test classes in random order TestLoader.suiteClass = RandomTestSuite # Execute test methods in random order within each test class TestLoader.sortTestMethodsUsing = lambda _, x, y: random.choice((1, -1)) # Make sure we're also random in multiprocess test runners random.seed() # Always show full repr() output for object instances in unittest error messages unittest.util._MAX_LENGTH = 2000 if os.environ.get('DEBUG', '').lower() in ('1', 'yes', 'true'): logging.basicConfig(level=logging.DEBUG, handlers=[PrettyXmlHandler()]) else: logging.basicConfig(level=logging.CRITICAL)
import logging import random import os from unittest import TestLoader, TestSuite import unittest.util from exchangelib.util import PrettyXmlHandler class RandomTestSuite(TestSuite): def __iter__(self): tests = list(super().__iter__()) random.shuffle(tests) return iter(tests) # Execute test classes in random order TestLoader.suiteClass = RandomTestSuite # Execute test methods in random order within each test class TestLoader.sortTestMethodsUsing = lambda _, x, y: random.choice((1, -1)) # Always show full repr() output for object instances in unittest error messages unittest.util._MAX_LENGTH = 2000 if os.environ.get('DEBUG', '').lower() in ('1', 'yes', 'true'): logging.basicConfig(level=logging.DEBUG, handlers=[PrettyXmlHandler()]) else: logging.basicConfig(level=logging.CRITICAL)
Delete useless param $response in redirect()
<?php namespace Rudolf\Framework\Controller; use Rudolf\Component\Http\Response; abstract class BaseController { protected $request; public function __construct($request) { $this->request = $request; if (method_exists($this, 'init')) { $this->init(); } } /** * Redirect to `up`, if curent page is 1. * * @param int $page * @param int $code * * @return int|redirection */ protected function firstPageRedirect($page, $code = 301, $location = '..') { if (1 == $page) { $this->redirect($location, $code); } elseif (0 === $page) { return 1; } return $page; } protected function redirect($path = DIR, $code = 301) { $response = new Response('', $code); $response->setHeader(['Location', $path]); $response->send(); exit; } public function redirectTo($path) { $this->redirect($path); } }
<?php namespace Rudolf\Framework\Controller; use Rudolf\Component\Http\Response; abstract class BaseController { protected $request; public function __construct($request) { $this->request = $request; if (method_exists($this, 'init')) { $this->init(); } } /** * Redirect to `up`, if curent page is 1. * * @param int $page * @param int $code * * @return int|redirection */ protected function firstPageRedirect($page, $code = 301, $location = '..') { if (1 == $page) { $this->redirect($location, $code); } elseif (0 === $page) { return 1; } return $page; } protected function redirect($path = DIR, $code = 301, $response = '') { $response = new Response($response, $code); $response->setHeader(['Location', $path]); $response->send(); exit; } public function redirectTo($path) { $this->redirect($path); } }
Return new object instead of modifying input objects
var angular = require('angular') require('../app').directive('previewPictures', /* @ngInject */function () { return { restrict: 'EA', templateUrl: '/views/directives/previewpictures.html', scope: { pictures: '=' }, bindToController: true, link: function ($scope, $element, $attrs, $ctrl) { $element.on('click', $ctrl.preview) }, controller: /* @ngInject */function ($filter, Lightbox) { var $ctrl = this var authurl = $filter('authurl') $ctrl.preview = function (event) { event.preventDefault() event.stopImmediatePropagation() Lightbox.openModal($ctrl.pictures.map(function (picture) { return angular.extend({}, picture, { url: authurl(picture.url) }) }), 0) } }, controllerAs: '$ctrl' } })
require('../app').directive('previewPictures', /* @ngInject */function () { return { restrict: 'EA', templateUrl: '/views/directives/previewpictures.html', scope: { pictures: '=' }, bindToController: true, link: function ($scope, $element, $attrs, $ctrl) { $element.on('click', $ctrl.preview) }, controller: /* @ngInject */function ($filter, Lightbox) { var $ctrl = this var authurl = $filter('authurl') $ctrl.preview = function (event) { event.preventDefault() event.stopImmediatePropagation() Lightbox.openModal($ctrl.pictures.map(function (picture) { picture.url = authurl(picture.url) return picture }), 0) } }, controllerAs: '$ctrl' } })
Make the propTypes removal explicit. See: https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types#with-comment-annotation
import React, { Fragment } from 'react' import PropTypes from 'prop-types' import styled, { css } from 'styled-components' const createHelpers = '##CREATEHELPERS##' const width = '##WIDTH##' const height = '##HEIGHT##' const viewBox = '##VIEWBOX##' const { getDimensions, getCss, propsToCss, sanitizeSizes } = createHelpers(width, height, css) const sizes = sanitizeSizes('##SIZES##') const Image = styled.svg`${propsToCss}` const children = ( <Fragment> ##SVG## </Fragment> ) const defaultProps = { children, viewBox, fillColor: null, fillColorRule: '&&& path, &&& use, &&& g', sizes, size: null } Image.propTypes /* remove-proptypes */ = { fillColor: PropTypes.string, fillColorRule: PropTypes.string, viewBox: PropTypes.string.isRequired, children: PropTypes.node.isRequired, size: PropTypes.oneOfType([ PropTypes.string, PropTypes.shape({ height: PropTypes.number.isRequired, width: PropTypes.number.isRequired }) ]), sizes: PropTypes.shape({ height: PropTypes.number, width: PropTypes.number }) } export default Object.assign(Image, { getDimensions, getCss, defaultProps, displayName: '##NAME##' })
import React, { Fragment } from 'react' import PropTypes from 'prop-types' import styled, { css } from 'styled-components' const createHelpers = '##CREATEHELPERS##' const width = '##WIDTH##' const height = '##HEIGHT##' const viewBox = '##VIEWBOX##' const { getDimensions, getCss, propsToCss, sanitizeSizes } = createHelpers(width, height, css) const sizes = sanitizeSizes('##SIZES##') const Image = styled.svg`${propsToCss}` const children = ( <Fragment> ##SVG## </Fragment> ) const defaultProps = { children, viewBox, fillColor: null, fillColorRule: '&&& path, &&& use, &&& g', sizes, size: null } Image.propTypes = { fillColor: PropTypes.string, fillColorRule: PropTypes.string, viewBox: PropTypes.string.isRequired, children: PropTypes.node.isRequired, size: PropTypes.oneOfType([ PropTypes.string, PropTypes.shape({ height: PropTypes.number.isRequired, width: PropTypes.number.isRequired }) ]), sizes: PropTypes.shape({ height: PropTypes.number, width: PropTypes.number }) } export default Object.assign(Image, { getDimensions, getCss, defaultProps, displayName: '##NAME##' })
Remove simplejson as a dependency for python 2.6+ Python 2.6 introduced the ``json`` module into the core language and so ``simplejson`` is only required in python versions prior to python 2.6. This fix ensures that pip will only install simplejson if the version of python being run is less than 2.6. This stops the un-needed installation of a library that wont ever actually get used by authy if a newer version of python is running.
from authy import __version__ from setuptools import setup, find_packages # to install authy type the following command: # python setup.py install with open('README.md') as f: long_description = f.read() setup( name="authy", version=__version__, description="Authy API Client", author="Authy Inc", author_email="dev-support@authy.com", url="http://github.com/authy/authy-python", keywords=["authy", "two factor", "authentication"], install_requires=[ "requests>=2.2.1", "six>=1.8.0", "simplejson>=3.4.0;python_version<'2.6'" ] packages=find_packages(), classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Security" ], long_description=long_description, long_description_content_type='text/markdown' )
from authy import __version__ from setuptools import setup, find_packages # to install authy type the following command: # python setup.py install with open('README.md') as f: long_description = f.read() setup( name="authy", version=__version__, description="Authy API Client", author="Authy Inc", author_email="dev-support@authy.com", url="http://github.com/authy/authy-python", keywords=["authy", "two factor", "authentication"], install_requires=["requests>=2.2.1", "simplejson>=3.4.0", "six>=1.8.0"], packages=find_packages(), classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Security" ], long_description=long_description, long_description_content_type='text/markdown' )
Use $sections instead of sections As the variable is a JQuery object, give it a $name instead of a name
(function() { "use strict"; window.GOVUK = window.GOVUK || {}; function CollapsibleCollection(options){ this.collapsibles = {}; this.$sections = options.el.find('section'); this.$sections.each($.proxy(this.initCollapsible, this)); this.closeAll(); } CollapsibleCollection.prototype.initCollapsible = function initCollapsible(sectionIndex){ var $section = $(this.sections[sectionIndex]); var collapsible = new GOVUK.Collapsible($section); this.collapsibles[$section.attr('data-section-id')] = collapsible; } CollapsibleCollection.prototype.closeAll = function closeAll(){ for (var sectionId in this.collapsibles) { this.collapsibles[sectionId].close(); } } CollapsibleCollection.prototype.openAll = function openAll(){ for (var sectionId in this.collapsibles) { this.collapsibles[sectionId].open(); } } GOVUK.CollapsibleCollection = CollapsibleCollection; }());
(function() { "use strict"; window.GOVUK = window.GOVUK || {}; function CollapsibleCollection(options){ this.collapsibles = {}; this.sections = options.el.find('section'); this.sections.each($.proxy(this.initCollapsible, this)); this.closeAll(); } CollapsibleCollection.prototype.initCollapsible = function initCollapsible(sectionIndex){ var $section = $(this.sections[sectionIndex]); var collapsible = new GOVUK.Collapsible($section); this.collapsibles[$section.attr('data-section-id')] = collapsible; } CollapsibleCollection.prototype.closeAll = function closeAll(){ for (var section in this.collapsibles) { this.collapsibles[section].close(); } } CollapsibleCollection.prototype.openAll = function openAll(){ for (var section in this.collapsibles) { this.collapsibles[section].open(); } } GOVUK.CollapsibleCollection = CollapsibleCollection; }());
Update docblocks to return the model after calling save on the repository.
<?php namespace Enzyme\Axiom\Repositories; use Enzyme\Axiom\Models\ModelInterface; use Enzyme\Axiom\Atoms\AtomInterface; /** * Manages a collection of models. */ interface RepositoryInterface { /** * Get a collection of all models for this type. * * @return array */ public function getAll(); /** * Get a model with the given id. * * @param AtomInterface $id * * @return \Enzyme\Axiom\Models\ModelInterface */ public function getById(AtomInterface $id); /** * Save the given model to the underlying persistence layer * and return the model with any new properties set (such as ID). * * @param ModelInterface $model * * @return \Enzyme\Axiom\Models\ModelInterface */ public function save(ModelInterface $model); }
<?php namespace Enzyme\Axiom\Repositories; use Enzyme\Axiom\Models\ModelInterface; use Enzyme\Axiom\Atoms\AtomInterface; /** * Manages a collection of models. */ interface RepositoryInterface { /** * Get a collection of all models for this type. * * @return array */ public function getAll(); /** * Get a model with the given id. * * @param AtomInterface $id * * @return \Enzyme\Axiom\Models\ModelInterface */ public function getById(AtomInterface $id); /** * Save the given model to the underlying persistence layer. * * @param ModelInterface $model * * @return void */ public function save(ModelInterface $model); }
Improve English for checkbox label
<?php namespace MarkMx\SkelBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\Validator\Constraints\NotBlank; class ResetDbType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('confirm', 'checkbox', array( 'label' => 'Confirm current DB data will be destroyed and replaced with fixtures data.', 'required' => true, 'constraints' => array( new NotBlank(array( 'message' => 'Confirm box must be checked to reset the DB.' )) ), )); } public function getName() { return 'reset_db'; } }
<?php namespace MarkMx\SkelBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\Validator\Constraints\NotBlank; class ResetDbType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('confirm', 'checkbox', array( 'label' => 'Confirm reset the demo DB to default fixtures losing all current data.', 'required' => true, 'constraints' => array( new NotBlank(array( 'message' => 'Confirm box must be checked to reset the DB.' )) ), )); } public function getName() { return 'reset_db'; } }
Change @bench to return a list, because there will never be more than 1 key in the dict
from functools import wraps from inspect import getcallargs from timer import Timer def bench(f): """Times a function given specific arguments.""" timer = Timer(tick_now=False) @wraps(f) def wrapped(*args, **kwargs): timer.start() f(*args, **kwargs) timer.stop() res = [call_signature(f, *args, **kwargs), timer.get_times()['real']] # TODO penser a quel temps garder return res return wrapped def call_signature(f, *args, **kwargs): """Return a string representation of a function call.""" call_args = getcallargs(f, *args, **kwargs) return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()]) @bench def lala(a, b, c="default c", d="default d"): print("lala est appelee") if __name__ == '__main__': print(lala("cest a", "cest b", d="change d"))
from functools import wraps from inspect import getcallargs from timer import Timer def bench(f): """Times a function given specific arguments.""" timer = Timer(tick_now=False) @wraps(f) def wrapped(*args, **kwargs): timer.start() f(*args, **kwargs) timer.stop() res = {call_signature(f, *args, **kwargs): timer.get_times()['real']} # TODO penser a quel temps garder return res return wrapped def call_signature(f, *args, **kwargs): """Return a string representation of a function call.""" call_args = getcallargs(f, *args, **kwargs) return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()]) @bench def lala(a, b, c="default c", d="default d"): print("lala est appelee") if __name__ == '__main__': print(lala("cest a", "cest b", d="change d"))
Use correct background & icon colors according to design
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import Icon from '../icon'; import { IconTeamMediumOutline, IconTeamSmallOutline } from '@teamleader/ui-icons'; class AvatarTeam extends PureComponent { render() { const { size } = this.props; return ( <Box alignItems="center" backgroundColor="neutral" backgroundTint="darkest" className={cx(theme['avatar'], theme['avatar-team'])} data-teamleader-ui="avatar-team" display="flex" justifyContent="center" > <Icon color="neutral" tint="light"> {size === 'tiny' || size === 'small' ? <IconTeamSmallOutline /> : <IconTeamMediumOutline />} </Icon> </Box> ); } } AvatarTeam.propTypes = { /** The size of the avatar. */ size: PropTypes.oneOf(['tiny', 'small', 'medium', 'large', 'hero']), }; export default AvatarTeam;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import Icon from '../icon'; import { IconTeamMediumOutline, IconTeamSmallOutline } from '@teamleader/ui-icons'; class AvatarTeam extends PureComponent { render() { const { size } = this.props; return ( <Box alignItems="center" backgroundColor="neutral" backgroundTint="normal" className={cx(theme['avatar'], theme['avatar-team'])} data-teamleader-ui="avatar-team" display="flex" justifyContent="center" > <Icon color="neutral" tint="darkest"> {size === 'tiny' || size === 'small' ? <IconTeamSmallOutline /> : <IconTeamMediumOutline />} </Icon> </Box> ); } } AvatarTeam.propTypes = { /** The size of the avatar. */ size: PropTypes.oneOf(['tiny', 'small', 'medium', 'large', 'hero']), }; export default AvatarTeam;
Add gulp serve no build task
/* ************************************ */ /* Server */ /* ************************************ */ 'use strict'; var path = require('path'); var gulp = require('gulp'); var conf = require('./conf'); var $ = require('gulp-load-plugins')({ pattern: ['browser-*'] }); var proxyMiddleware = require('http-proxy-middleware'); function browserSyncInit(baseDir, browser) { browser = browser === undefined ? 'default' : browser; var routes = null; routes = { '/bower_components': 'bower_components', '/dist': 'dist', '/assets': 'workspace/assets' }; var server = { baseDir: baseDir, routes: routes }; $.browserSync.instance = $.browserSync.init({ port: 7001, startPath: '/', server: server, browser: browser, ui: { port: 7002 } }); } $.browserSync.use($.browserSyncSpa({ selector: '[ng-app]'// Only needed for angular apps })); gulp.task('serve', ['workspace', 'watch'], function () { browserSyncInit(conf.paths.workspace); }); // If rebuilding the library on every change is using too much cpu, // or you want to manually build. gulp.task('serve:noreload', ['workspace'], function () { browserSyncInit(conf.paths.workspace); }); gulp.task('serve:nobuild', function () { browserSyncInit(conf.paths.workspace); });
/* ************************************ */ /* Server */ /* ************************************ */ 'use strict'; var path = require('path'); var gulp = require('gulp'); var conf = require('./conf'); var $ = require('gulp-load-plugins')({ pattern: ['browser-*'] }); var proxyMiddleware = require('http-proxy-middleware'); function browserSyncInit(baseDir, browser) { browser = browser === undefined ? 'default' : browser; var routes = null; routes = { '/bower_components': 'bower_components', '/dist': 'dist', '/assets': 'workspace/assets' }; var server = { baseDir: baseDir, routes: routes }; $.browserSync.instance = $.browserSync.init({ port: 7001, startPath: '/', server: server, browser: browser, ui: { port: 7002 } }); } $.browserSync.use($.browserSyncSpa({ selector: '[ng-app]'// Only needed for angular apps })); gulp.task('serve', ['workspace', 'watch'], function () { browserSyncInit(conf.paths.workspace); }); // If rebuilding the library on every change is using too much cpu, // or you want to manually build. gulp.task('serve:noreload', ['workspace'], function () { browserSyncInit(conf.paths.workspace); });
HG-1871: Fix missing tools package install
from setuptools import setup import subprocess, os version = open('pymoku/version.txt').read().strip() setup( name='pymoku', version=version, author='Ben Nizette', author_email='ben.nizette@liquidinstruments.com', packages=['pymoku', 'pymoku.tools'], package_dir={'pymoku': 'pymoku/'}, package_data={ 'pymoku' : ['version.txt', '*.capnp', 'bin/*'] }, license='MIT', long_description="Python scripting interface to the Liquid Instruments Moku:Lab", url="https://github.com/liquidinstruments/pymoku", download_url="https://github.com/liquidinstruments/pymoku/archive/%s.tar.gz" % version, keywords=['moku', 'liquid instruments', 'test', 'measurement', 'lab', 'equipment'], entry_points={ 'console_scripts' : [ 'moku=pymoku.tools.moku:main', 'moku_convert=pymoku.tools.moku_convert:main', ] }, install_requires=[ 'future', 'pyzmq>=15.3.0', 'six', 'urllib3', 'pyzmq', 'rfc6266', 'requests', ], zip_safe=False, # This isn't strictly true, but makes debugging easier on the device )
from setuptools import setup import subprocess, os version = open('pymoku/version.txt').read().strip() setup( name='pymoku', version=version, author='Ben Nizette', author_email='ben.nizette@liquidinstruments.com', packages=['pymoku'], package_dir={'pymoku': 'pymoku/'}, package_data={ 'pymoku' : ['version.txt', '*.capnp', 'bin/*'] }, license='MIT', long_description="Python scripting interface to the Liquid Instruments Moku:Lab", url="https://github.com/liquidinstruments/pymoku", download_url="https://github.com/liquidinstruments/pymoku/archive/%s.tar.gz" % version, keywords=['moku', 'liquid instruments', 'test', 'measurement', 'lab', 'equipment'], entry_points={ 'console_scripts' : [ 'moku=pymoku.tools.moku:main', 'moku_convert=pymoku.tools.moku_convert:main', ] }, install_requires=[ 'future', 'pyzmq>=15.3.0', 'six', 'urllib3', 'pyzmq', 'rfc6266', 'requests', ], )
Add .isEmpty() on slate value container
import toSlate from './conversion/toSlate' import fromSlate from './conversion/fromSlate' export default class SlateValueContainer { static deserialize(value, context) { const state = toSlate(value || [], context) return new SlateValueContainer(state, context) } constructor(state, context) { this.state = state this.context = context } validate() { } patch(patch) { let nextState if (patch.type === 'localState') { nextState = patch.value } else { throw new Error(`Unknown patch type for block editor ${patch.type}`) } return (nextState === this.state) ? this : new SlateValueContainer(nextState, this.context) } isEmpty() { return this.state.document.length === 0 } serialize() { return fromSlate(this.state, this.context) } }
import toSlate from './conversion/toSlate' import fromSlate from './conversion/fromSlate' export default class SlateValueContainer { static deserialize(value, context) { const state = toSlate(value || [], context) return new SlateValueContainer(state, context) } constructor(state, context) { this.state = state this.context = context } validate() { } patch(patch) { let nextState if (patch.type === 'localState') { nextState = patch.value } else { throw new Error(`Unknown patch type for block editor ${patch.type}`) } return (nextState === this.state) ? this : new SlateValueContainer(nextState, this.context) } serialize() { return fromSlate(this.state, this.context) } }
Fix bug in relationships via REST API.
'use strict'; var DataCollection = require('data-collection'), _ = require('lodash'); /** * Given a array of relationship data and the HTTP query, filters it * @param {Array} data Array of data coming from a relationship * @param {Object} httpQuery * @return {Array} */ module.exports = function filterRelationship(data, httpQuery) { if(!_.isArray(data)) { return data; } if(httpQuery.limit || httpQuery.offset || httpQuery.orderby || httpQuery.order) { var collection = new DataCollection(data), query = collection.query(); if(httpQuery.orderby) { httpQuery.order = httpQuery.order || 'asc'; query = query.order(httpQuery.orderby, httpQuery.order === 'desc'); } if(httpQuery.limit || httpQuery.offset) { httpQuery.offset = httpQuery.offset || 0; query = query.limit(httpQuery.offset, httpQuery.limit); } return query.values(); } return data; };
'use strict'; var DataCollection = require('data-collection'); /** * Given a array of relationship data and the HTTP query, filters it * @param {Array} data Array of data coming from a relationship * @param {Object} httpQuery * @return {Array} */ module.exports = function filterRelationship(data, httpQuery) { if(httpQuery.limit || httpQuery.offset || httpQuery.orderby || httpQuery.order) { var collection = new DataCollection(data), query = collection.query(); if(httpQuery.orderby) { httpQuery.order = httpQuery.order || 'asc'; query = query.order(httpQuery.orderby, httpQuery.order === 'desc'); } if(httpQuery.limit || httpQuery.offset) { httpQuery.offset = httpQuery.offset || 0; query = query.limit(httpQuery.offset, httpQuery.limit); } return query.values(); } return data; };
Fix 'global is not defined' error
const path = require('path'); function resolvePath(pathToResolve) { return path.resolve(__dirname, pathToResolve); } module.exports = { lintOnSave: false, pages: { 'index': { entry: 'src/main.js', chunks: ['chunk-vendors', 'chunk-common', 'index', 'preload'], }, 'options/options': { entry: 'src/options/options.js', }, }, pluginOptions: { browserExtension: { components: { background: true, options: true, standalone: true, }, api: 'browser', usePolyfill: true, autoImportPolyfill: true, componentOptions: { background: { entry: 'src/browser/background.js', }, }, }, }, chainWebpack: (config) => { config.resolve.alias.set('styles', resolvePath('src/styles')); config.entry('preload').add(resolvePath('src/styles/preload.scss')); }, configureWebpack: { node: { global: true, }, }, };
const path = require('path'); function resolvePath(pathToResolve) { return path.resolve(__dirname, pathToResolve); } module.exports = { lintOnSave: false, pages: { 'index': { entry: 'src/main.js', chunks: ['chunk-vendors', 'chunk-common', 'index', 'preload'], }, 'options/options': { entry: 'src/options/options.js', }, }, pluginOptions: { browserExtension: { components: { background: true, options: true, standalone: true, }, api: 'browser', usePolyfill: true, autoImportPolyfill: true, componentOptions: { background: { entry: 'src/browser/background.js', }, }, }, }, chainWebpack: (config) => { config.resolve.alias.set('styles', resolvePath('src/styles')); config.entry('preload').add(resolvePath('src/styles/preload.scss')); }, };
Handle patterns as String or RegExp.
'use strict'; var EventEmitter = require('events').EventEmitter; var mixin = require('merge-descriptors'); function Command() { this.actions = []; this.token; mixin(this, EventEmitter.prototype, false); } Command.prototype.setToken = function (token) { this.token = token; } Command.prototype._checkToken = function(data) { if(!this.token) { console.warn('Without a validation token anyone can execute your command.'); } else { if(data.token !== this.token) throw 'Invalid token'; } } Command.prototype._findAction = function (text) { var action; for(var i = 0; i < this.actions.length; i++) { action = this.actions[i]; console.log(action, action.pattern.test(text)); if(action.pattern.test(text)) { return action; } } }; Command.prototype.action = function (pattern, callback) { if(typeof pattern !== RegExp) pattern = new RegExp(pattern); this.actions.push({pattern: pattern, callback: callback}); }; Command.prototype.execute = function (data) { try { this._checkToken(data); var text = data.text.trim(); var action = this._findAction(text); if(action) { this.emit('success', action.callback(data, action.pattern.exec(text))); } else { this.emit('error', 'No matching action found to handle ' + text); } } catch(e) { this.emit('error', e); } }; exports.Command = Command;
'use strict'; var EventEmitter = require('events').EventEmitter; var mixin = require('merge-descriptors'); function Command() { this.actions = []; this.token; mixin(this, EventEmitter.prototype, false); } Command.prototype.setToken = function (token) { this.token = token; } Command.prototype._checkToken = function(data) { if(!this.token) { console.warn('Without a validation token anyone can execute your command.'); } else { if(data.token !== this.token) throw 'Invalid token'; } } Command.prototype._findAction = function (text) { var action; for(var i = 0; i < this.actions.length; i++) { action = this.actions[i]; if(action.pattern.test(text)) { return action; } } }; Command.prototype.action = function (pattern, callback) { this.actions.push({pattern: new RegExp(pattern), callback: callback}); }; Command.prototype.execute = function (data) { try { this._checkToken(data); var text = data.text; var action = this._findAction(text); if(action) { this.emit('success', action.callback(data, action.pattern.exec(text))); } else { this.emit('error', 'No matching action found to handle ' + text); } } catch(e) { this.emit('error', e); } }; exports.Command = Command;
Add space to separate arguments.
package executors; public class CommandCreator { public String createCommand(String userCommand) { String[] tokens = userCommand.split("\\s+"); switch(tokens[0]) { case "security": switch (tokens[1]) { case "tls": return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2]; case "ecrypt2lvl": return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2]; case "open_ports": return "nmap " + tokens[2]; default : return null; } default : return null; } } }
package executors; public class CommandCreator { public String createCommand(String userCommand) { String[] tokens = userCommand.split("\\s+"); switch(tokens[0]) { case "security": switch (tokens[1]) { case "tls": return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2]; case "ecrypt2lvl": return "nmap --script ssl-enum-ciphers -p 443" + tokens[2]; case "open_ports": return "nmap " + tokens[2]; default : return null; } default : return null; } } }
Add sphinx autosection label plugin.
from datetime import date import guzzle_sphinx_theme from pyinfra import __version__ copyright = 'Nick Barrett {0} — pyinfra v{1}'.format( date.today().year, __version__, ) extensions = [ # Official 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.autosectionlabel', ] autosectionlabel_prefix_document = True extensions.append('guzzle_sphinx_theme') source_suffix = ['.rst', '.md'] source_parsers = { '.md': 'recommonmark.parser.CommonMarkParser', } master_doc = 'index' project = 'pyinfra' author = 'Fizzadar' version = 'develop' pygments_style = 'sphinx' # Theme style override html_short_title = 'Home' html_theme = 'guzzle_sphinx_theme' html_theme_path = guzzle_sphinx_theme.html_theme_path() html_static_path = ['static'] templates_path = ['templates'] html_favicon = 'static/logo_small.png' html_sidebars = { '**': ['pyinfra_sidebar.html', 'searchbox.html'], }
from datetime import date import guzzle_sphinx_theme from pyinfra import __version__ copyright = 'Nick Barrett {0} — pyinfra v{1}'.format( date.today().year, __version__, ) extensions = [ # Official 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', ] extensions.append('guzzle_sphinx_theme') source_suffix = ['.rst', '.md'] source_parsers = { '.md': 'recommonmark.parser.CommonMarkParser', } master_doc = 'index' project = 'pyinfra' author = 'Fizzadar' version = 'develop' pygments_style = 'sphinx' # Theme style override html_short_title = 'Home' html_theme = 'guzzle_sphinx_theme' html_theme_path = guzzle_sphinx_theme.html_theme_path() html_static_path = ['static'] templates_path = ['templates'] html_favicon = 'static/logo_small.png' html_sidebars = { '**': ['pyinfra_sidebar.html', 'searchbox.html'], }
Remove process.exit(0) when windows is closed
/* ---------- Electron init ------------------------------------------------- */ import { app, BrowserWindow } from 'electron' /* ---------- Requires ------------------------------------------------------ */ import { host, port } from '../scripts/config' import { isDev } from '../scripts/env' import path from 'path' /* ---------- Refs for garbage collection ----------------------------------- */ let window /* -------------------------------------------------------------------------- */ if (isDev()) require('electron-reload')(__dirname) function createBrowserWindow () { // Init Window window = new BrowserWindow({ width: 1024, height: 700, frame: true, }) // Load template file window.loadURL(`http://${host}:${port}`) // Open the DevTools. if (isDev()) window.webContents.openDevTools() // Emitted when the window is closed. window.on('closed', () => { window = null }) } app.on('ready', createBrowserWindow) // Quit when all windows are closed. app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (window === null) { createBrowserWindow() } })
/* ---------- Electron init ------------------------------------------------- */ import { app, BrowserWindow } from 'electron' /* ---------- Requires ------------------------------------------------------ */ import { host, port } from '../scripts/config' import { isDev } from '../scripts/env' import path from 'path' /* ---------- Refs for garbage collection ----------------------------------- */ let window /* -------------------------------------------------------------------------- */ if (isDev()) require('electron-reload')(__dirname) function createBrowserWindow () { // Init Window window = new BrowserWindow({ width: 1024, height: 700, frame: true, }) // Load template file window.loadURL(`http://${host}:${port}`) // Open the DevTools. if (isDev()) window.webContents.openDevTools() // Emitted when the window is closed. window.on('closed', () => { process.exit(0) window = null }) } app.on('ready', createBrowserWindow) // Quit when all windows are closed. app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (window === null) { createBrowserWindow() } })
Set default value for event stream module
/* * 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.rakam.plugin.stream; import io.airlift.configuration.Config; public class EventStreamConfig { private boolean enabled = false; @Config("event.stream.enabled") public void setEventStreamEnabled(boolean enabled) { this.enabled = enabled; } public boolean getEventStreamEnabled() { return enabled; } }
/* * 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.rakam.plugin.stream; import io.airlift.configuration.Config; public class EventStreamConfig { private boolean enabled = true; @Config("event.stream.enabled") public void setEventStreamEnabled(boolean enabled) { this.enabled = enabled; } public boolean getEventStreamEnabled() { return enabled; } }
Change response status type from string to bool
package handlers import ( "encoding/json" "log" "net/http" ) //ReturnInternalServerError returns an Internal Server Error func ReturnInternalServerError(w http.ResponseWriter, message string) { log.Println(message) response := make(map[string]interface{}) response["status"] = false w.WriteHeader(http.StatusInternalServerError) json.NewEncoder(w).Encode(response) } //ReturnStatusBadRequest returns a Bad Request Error func ReturnStatusBadRequest(w http.ResponseWriter, message string) { log.Println(message) response := make(map[string]interface{}) response["status"] = false w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(response) } //ReturnUnauthorized returns a Unauthorized Error func ReturnUnauthorized(w http.ResponseWriter, message string) { log.Println(message) response := make(map[string]interface{}) response["Status"] = false w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(response) }
package handlers import ( "encoding/json" "log" "net/http" ) //ReturnInternalServerError returns an Internal Server Error func ReturnInternalServerError(w http.ResponseWriter, message string) { log.Println(message) response := make(map[string]string) response["status"] = "false" w.WriteHeader(http.StatusInternalServerError) json.NewEncoder(w).Encode(response) } //ReturnStatusBadRequest returns a Bad Request Error func ReturnStatusBadRequest(w http.ResponseWriter, message string) { log.Println(message) response := make(map[string]string) response["status"] = "false" w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(response) } //ReturnUnauthorized returns a Unauthorized Error func ReturnUnauthorized(w http.ResponseWriter, message string) { log.Println(message) response := make(map[string]string) response["Status"] = "false" w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(response) }
Make sure ESLint covers all JS unit tests
/* 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/. */ /* global __dirname, require */ var gulp = require('gulp'); var karma = require('karma'); var eslint = require('gulp-eslint'); var lintPaths = [ 'media/js/**/*.js', '!media/js/libs/*.js', 'tests/unit/spec/**/*.js', 'gulpfile.js' ]; gulp.task('test', function(done) { new karma.Server({ configFile: __dirname + '/tests/unit/karma.conf.js', singleRun: true }, done).start(); }); gulp.task('lint', function() { return gulp.src(lintPaths) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); });
/* 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/. */ /* global __dirname, require */ var gulp = require('gulp'); var karma = require('karma'); var eslint = require('gulp-eslint'); var lintPaths = [ 'media/js/**/*.js', '!media/js/libs/*.js', 'tests/unit/spec/*.js', 'gulpfile.js' ]; gulp.task('test', function(done) { new karma.Server({ configFile: __dirname + '/tests/unit/karma.conf.js', singleRun: true }, done).start(); }); gulp.task('lint', function() { return gulp.src(lintPaths) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); });
Fix LCD display of the first line.
"use strict"; const env = require('../../env'); if (env.lcd.enable) { let Lcd; if (env.inDevMode) { Lcd = require('gpio-peripherals-test').lcd; } else { Lcd = require('lcd'); } let lcd = new Lcd({ cols: env.lcd.cols, rows: env.lcd.rows, rs: env.lcd.rs, e: env.lcd.e, data: env.lcd.data }); let printLcd = function (data) { lcd.clear(); lcd.setCursor(0, 0); lcd.print('I: '+ (" " + data.inside.temperature.toFixed(1)).slice(-5) + '°C ' + (" " + data.inside.humidity).slice(-3) + '%', () => { lcd.setCursor(0, 1); lcd.print('O: '+ (" " + data.outside.temperature.toFixed(1)).slice(-5) + '°C ' + (" " + data.outside.humidity).slice(-3) + '%'); } ); }; const ambientalConditions = require('./ambientalConditions'); let data = ambientalConditions.get(); printLcd(data); ambientalConditions.evts.on('change', function (data) { printLcd(data); }); }
"use strict"; const env = require('../../env'); if (env.lcd.enable) { let Lcd; if (env.inDevMode) { Lcd = require('gpio-peripherals-test').lcd; } else { Lcd = require('lcd'); } let lcd = new Lcd({ cols: env.lcd.cols, rows: env.lcd.rows, rs: env.lcd.rs, e: env.lcd.e, data: env.lcd.data }); let printLcd = function (data) { lcd.clear(); console.log(typeof data.inside.temperature); lcd.print('I: '+ (" " + data.inside.temperature.toFixed(1)).slice(-5) + '°C ' + (" " + data.inside.humidity).slice(-3) + '%', () => { lcd.setCursor(0, 1); console.log(typeof data.outside.temperature); lcd.print('O: '+ (" " + data.outside.temperature.toFixed(1)).slice(-5) + '°C ' + (" " + data.outside.humidity).slice(-3) + '%'); } ); }; const ambientalConditions = require('./ambientalConditions'); let data = ambientalConditions.get(); printLcd(data); ambientalConditions.evts.on('change', function (data) { printLcd(data); }); }
Update oslo log messages with translation domains Update the incubator code to use different domains for log messages at different levels. Update the import exceptions setting for hacking to allow multiple functions to be imported from gettextutils on one line. bp log-messages-translation-domain Change-Id: I6ce0f4a59438612ce74c46b3ee9398bef24c0c19
# Copyright (c) 2013 NEC Corporation # All Rights Reserved. # # 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. """Middleware that provides high-level error handling. It catches all exceptions from subsequent applications in WSGI pipeline to hide internal errors from API response. """ import webob.dec import webob.exc from openstack.common.gettextutils import _LE from openstack.common import log as logging from openstack.common.middleware import base LOG = logging.getLogger(__name__) class CatchErrorsMiddleware(base.Middleware): @webob.dec.wsgify def __call__(self, req): try: response = req.get_response(self.application) except Exception: LOG.exception(_LE('An error occurred during ' 'processing the request: %s')) response = webob.exc.HTTPInternalServerError() return response
# Copyright (c) 2013 NEC Corporation # All Rights Reserved. # # 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. """Middleware that provides high-level error handling. It catches all exceptions from subsequent applications in WSGI pipeline to hide internal errors from API response. """ import webob.dec import webob.exc from openstack.common.gettextutils import _ # noqa from openstack.common import log as logging from openstack.common.middleware import base LOG = logging.getLogger(__name__) class CatchErrorsMiddleware(base.Middleware): @webob.dec.wsgify def __call__(self, req): try: response = req.get_response(self.application) except Exception: LOG.exception(_('An error occurred during ' 'processing the request: %s')) response = webob.exc.HTTPInternalServerError() return response
Make Lisk counters patch more robust Summary: We need to revert this patch and we will need to re-apply it later. We can't drop the table and delete these rows as we need to run both versions for a temporary period. Test Plan: Applied it. Reviewers: epriestley, nh Reviewed By: epriestley CC: aran, Korvin Differential Revision: https://secure.phabricator.com/D3924
<?php // Switch PhabricatorWorkerActiveTask from autoincrement IDs to counter IDs. // Set the initial counter ID to be larger than any known task ID. $active_table = new PhabricatorWorkerActiveTask(); $archive_table = new PhabricatorWorkerArchiveTask(); $conn_w = $active_table->establishConnection('w'); $active_auto = head(queryfx_one( $conn_w, 'SELECT auto_increment FROM information_schema.tables WHERE table_name = %s AND table_schema = DATABASE()', $active_table->getTableName())); $active_max = head(queryfx_one( $conn_w, 'SELECT MAX(id) FROM %T', $active_table->getTableName())); $archive_max = head(queryfx_one( $conn_w, 'SELECT MAX(id) FROM %T', $archive_table->getTableName())); $initial_counter = max((int)$active_auto, (int)$active_max, (int)$archive_max); queryfx( $conn_w, 'INSERT INTO %T (counterName, counterValue) VALUES (%s, %d) ON DUPLICATE KEY UPDATE counterValue = %d', LiskDAO::COUNTER_TABLE_NAME, $active_table->getTableName(), $initial_counter + 1, $initial_counter + 1); // Drop AUTO_INCREMENT from the ID column. queryfx( $conn_w, 'ALTER TABLE %T CHANGE id id INT UNSIGNED NOT NULL', $active_table->getTableName());
<?php // Switch PhabricatorWorkerActiveTask from autoincrement IDs to counter IDs. // Set the initial counter ID to be larger than any known task ID. $active_table = new PhabricatorWorkerActiveTask(); $archive_table = new PhabricatorWorkerArchiveTask(); $conn_w = $active_table->establishConnection('w'); $active_auto = head(queryfx_one( $conn_w, 'SELECT auto_increment FROM information_schema.tables WHERE table_name = %s AND table_schema = DATABASE()', $active_table->getTableName())); $active_max = head(queryfx_one( $conn_w, 'SELECT MAX(id) FROM %T', $active_table->getTableName())); $archive_max = head(queryfx_one( $conn_w, 'SELECT MAX(id) FROM %T', $archive_table->getTableName())); $initial_counter = max((int)$active_auto, (int)$active_max, (int)$archive_max); queryfx( $conn_w, 'INSERT IGNORE INTO %T (counterName, counterValue) VALUES (%s, %d)', LiskDAO::COUNTER_TABLE_NAME, $active_table->getTableName(), $initial_counter + 1); // Drop AUTO_INCREMENT from the ID column. queryfx( $conn_w, 'ALTER TABLE %T CHANGE id id INT UNSIGNED NOT NULL', $active_table->getTableName());
Add 4,000Mbps plan to VPCRouter
// Copyright 2016-2019 The Libsacloud 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 // VPCRouterPlans VPCルータのプラン var VPCRouterPlans = struct { // Standard スタンダードプラン シングル構成/最大スループット 80Mbps/一部機能は利用不可 Standard ID // Premium プレミアムプラン 冗長構成/最大スループット400Mbps Premium ID // HighSpec ハイスペックプラン 冗長構成/最大スループット1,600Mbps HighSpec ID // HighSpec ハイスペックプラン 冗長構成/最大スループット4,000Mbps HighSpec4000 ID }{ Standard: ID(1), Premium: ID(2), HighSpec: ID(3), HighSpec4000: ID(4), }
// Copyright 2016-2019 The Libsacloud 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 // VPCRouterPlans VPCルータのプラン var VPCRouterPlans = struct { // Standard スタンダードプラン シングル構成/最大スループット 80Mbps/一部機能は利用不可 Standard ID // Premium プレミアムプラン 冗長構成/最大スループット400Mbps Premium ID // HighSpec ハイスペックプラン 冗長構成/最大スループット1,200Mbps HighSpec ID }{ Standard: ID(1), Premium: ID(2), HighSpec: ID(3), }
Remove nginx as a directly supported option.
'use strict'; var _ = require('lodash'); var prompts = [ { type: 'input', name: 'projectName', message: 'Machine-name of your project?', // Name of the parent directory. default: _.last(process.cwd().split('/')), validate: function (input) { return (input.search(' ') === -1) ? true : 'No spaces allowed.'; } }, { type: 'list', name: 'webserver', message: 'Choose your webserver:', choices: [ 'apache', 'custom' ], default: 'apache' }, { name: 'webImage', message: 'Specify your webserver Docker image:', default: 'phase2/apache24php55', when: function(answers) { return answers.webserver == 'custom'; }, validate: function(input) { if (_.isString(input)) { return true; } return 'A validate docker image identifier is required.'; } }, { type: 'list', name: 'cacheInternal', message: 'Choose a cache backend:', default: 'memcache', choices: [ 'memcache', 'database' ] } ]; module.exports = prompts;
'use strict'; var _ = require('lodash'); var prompts = [ { type: 'input', name: 'projectName', message: 'Machine-name of your project?', // Name of the parent directory. default: _.last(process.cwd().split('/')), validate: function (input) { return (input.search(' ') === -1) ? true : 'No spaces allowed.'; } }, { type: 'list', name: 'webserver', message: 'Choose your webserver:', choices: [ 'apache', 'nginx', 'custom' ], default: 'apache' }, { name: 'webImage', message: 'Specify your webserver Docker image:', default: 'phase2/apache24php55', when: function(answers) { return answers.webserver == 'custom'; }, validate: function(input) { if (_.isString(input)) { return true; } return 'A validate docker image identifier is required.'; } }, { type: 'list', name: 'cacheInternal', message: 'Choose a cache backend:', default: 'memcache', choices: [ 'memcache', 'database' ] } ]; module.exports = prompts;
Fix Wishlist add button on Spree 4.1
(function() { Spree.ready(function($) { $('#new_wished_product').on('submit', function() { var cart_quantity, selected_variant_id; selected_variant_id = $('#product-variants input[type=radio]:checked').val(); if (selected_variant_id) { $('#wished_product_variant_id').val(selected_variant_id); } cart_quantity = $('#quantity').val(); if (cart_quantity) { return $('#wished_product_quantity').val(cart_quantity); } }); $('form#change_wishlist_accessibility').on('submit', function() { $.post($(this).prop('action'), $(this).serialize(), null, 'script'); return false; }); return $('form#change_wishlist_accessibility input[type=radio]').on('click', function() { return $(this).parent().submit(); }); }); }).call(this);
(function() { Spree.ready(function($) { $('#new_wished_product').on('submit', function() { var cart_quantity, selected_variant_id; selected_variant_id = $('#product-variants input[type=radio]:checked').val(); if (selected_variant_id) { $('#wished_product_variant_id').val(selected_variant_id); } cart_quantity = $('.add-to-cart #quantity').val(); if (cart_quantity) { return $('#wished_product_quantity').val(cart_quantity); } }); $('form#change_wishlist_accessibility').on('submit', function() { $.post($(this).prop('action'), $(this).serialize(), null, 'script'); return false; }); return $('form#change_wishlist_accessibility input[type=radio]').on('click', function() { return $(this).parent().submit(); }); }); }).call(this);
Refresh widget when config changes
import BoardView from 'app/components/serverboard/board' import store from 'app/utils/store' import { serverboards_widget_list, serverboard_update_widget_catalog, board_update_now } from 'app/actions/serverboard' const Board = store.connect({ state: (state) => ({ widgets: state.serverboard.widgets, widget_catalog: state.serverboard.widget_catalog }), handlers: (dispatch, prop) => ({ updateDaterangeNow: () => dispatch( board_update_now() ) }), subscriptions: (state, props) => { return [ `serverboard.widget.added[${props.serverboard}]`, `serverboard.widget.removed[${props.serverboard}]`, `serverboard.widget.updated[${props.serverboard}]` ] }, // Update catalog on entry store_enter: (props) => [ () => serverboards_widget_list(props.serverboard.current), () => serverboard_update_widget_catalog(props.serverboard.current) ], store_exit: (props) => [ () => serverboards_widget_list(null), () => serverboard_update_widget_catalog(null), ], watch: ['serverboard'], // Watch this prop loading(state){ if (!state.serverboard.widget_catalog) return "Widget catalog" return false } }, BoardView) export default Board
import BoardView from 'app/components/serverboard/board' import store from 'app/utils/store' import { serverboards_widget_list, serverboard_update_widget_catalog, board_update_now } from 'app/actions/serverboard' const Board = store.connect({ state: (state) => ({ widgets: state.serverboard.widgets, widget_catalog: state.serverboard.widget_catalog }), handlers: (dispatch, prop) => ({ updateDaterangeNow: () => dispatch( board_update_now() ) }), subscribe: (props) => [ `serverboard.widget.added[${props.serverboard}]`, `serverboard.widget.removed[${props.serverboard}]`, `serverboard.widget.updated[${props.serverboard}]` ], // Update catalog on entry store_enter: (props) => [ () => serverboards_widget_list(props.serverboard.current), () => serverboard_update_widget_catalog(props.serverboard.current) ], store_exit: (props) => [ () => serverboards_widget_list(null), () => serverboard_update_widget_catalog(null), ], watch: ['serverboard'], // Watch this prop loading(state){ if (!state.serverboard.widget_catalog) return "Widget catalog" return false } }, BoardView) export default Board
Use Setext strategy in GitHub built in Collector
""" File that initializes a Collector object designed for GitHub style markdown files. """ from anchorhub.collector import Collector from anchorhub.builtin.github.cstrategies import \ MarkdownATXCollectorStrategy, MarkdownSetextCollectorStrategy import anchorhub.builtin.github.converter as converter import anchorhub.builtin.github.switches as ghswitches def make_github_markdown_collector(opts): """ Creates a Collector object used for parsing Markdown files with a GitHub style anchor transformation :param opts: Namespace object of options for the AnchorHub program. Usually created from command-line arguments. It must contain a 'wrapper_regex' attribute :return: a Collector object designed for collecting tag/anchor pairs from Markdown files using GitHub style anchors """ assert hasattr(opts, 'wrapper_regex') atx = MarkdownATXCollectorStrategy(opts) setext = MarkdownSetextCollectorStrategy(opts) code_block_switch = ghswitches.code_block_switch strategies = [atx, setext] switches = [code_block_switch] return Collector(converter.create_anchor_from_header, strategies, switches=switches)
""" File that initializes a Collector object designed for GitHub style markdown files. """ from anchorhub.collector import Collector from anchorhub.builtin.github.cstrategies import MarkdownATXCollectorStrategy import anchorhub.builtin.github.converter as converter import anchorhub.builtin.github.switches as ghswitches def make_github_markdown_collector(opts): """ Creates a Collector object used for parsing Markdown files with a GitHub style anchor transformation :param opts: Namespace object of options for the AnchorHub program. Usually created from command-line arguments. It must contain a 'wrapper_regex' attribute :return: a Collector object designed for collecting tag/anchor pairs from Markdown files using GitHub style anchors """ assert hasattr(opts, 'wrapper_regex') atx = MarkdownATXCollectorStrategy(opts) code_block_switch = ghswitches.code_block_switch strategies = [atx] switches = [code_block_switch] return Collector(converter.create_anchor_from_header, strategies, switches=switches)
Use io.open for py2/py3 compat
import os import io import json from setuptools import setup with io.open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding="utf-8") as f: readme = f.read() with io.open(os.path.join(os.path.dirname(__file__), 'package.json'), encoding="utf-8") as f: package = json.loads(f.read()) setup( name=package['name'], version=package['version'], description=package['description'], long_description=readme, long_description_content_type='text/markdown', author=package['author']['name'], author_email=package['author']['email'], url=package['homepage'], packages=['s3direct'], include_package_data=True, install_requires=['django>=1.8'], zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
import os import json from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding="utf-8") as f: readme = f.read() with open(os.path.join(os.path.dirname(__file__), 'package.json'), encoding="utf-8") as f: package = json.loads(f.read()) setup( name=package['name'], version=package['version'], description=package['description'], long_description=readme, long_description_content_type='text/markdown', author=package['author']['name'], author_email=package['author']['email'], url=package['homepage'], packages=['s3direct'], include_package_data=True, install_requires=['django>=1.8'], zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
Set the target of zombies spawned by the Zombie curse
/* * Copyright (c) 2014 Wyatt Childers. * * All Rights Reserved */ package com.skelril.aurora.prayer.PrayerFX; import com.skelril.aurora.prayer.PrayerType; import org.bukkit.entity.Player; import org.bukkit.entity.Zombie; /** * Author: Turtle9598 */ public class ZombieFX extends AbstractEffect { @Override public PrayerType getType() { return PrayerType.ZOMBIE; } @Override public void add(Player player) { if (player.getWorld().getEntitiesByClass(Zombie.class).size() < 1000) { player.getWorld().spawn(player.getLocation(), Zombie.class).setTarget(player); } } @Override public void clean(Player player) { // Nothing to do here } }
/* * Copyright (c) 2014 Wyatt Childers. * * All Rights Reserved */ package com.skelril.aurora.prayer.PrayerFX; import com.skelril.aurora.prayer.PrayerType; import org.bukkit.entity.Player; import org.bukkit.entity.Zombie; /** * Author: Turtle9598 */ public class ZombieFX extends AbstractEffect { @Override public PrayerType getType() { return PrayerType.ZOMBIE; } @Override public void add(Player player) { if (player.getWorld().getEntitiesByClass(Zombie.class).size() < 1000) { player.getWorld().spawn(player.getLocation(), Zombie.class); } } @Override public void clean(Player player) { // Nothing to do here } }
Add delegated credential to remove operation git-svn-id: bdb5f82b9b83a1400e05d69d262344b821646179@1376 e217846f-e12e-0410-a4e5-89ccaea66ff7
package edu.usc.glidein.service.impl; import java.rmi.RemoteException; import org.apache.axis.message.addressing.EndpointReferenceType; import org.globus.wsrf.ResourceContext; import edu.usc.glidein.stubs.RemoveRequest; import edu.usc.glidein.stubs.types.EmptyObject; import edu.usc.glidein.stubs.types.Site; public class SiteService { private SiteResource getResource() throws RemoteException { try { return (SiteResource) ResourceContext.getResourceContext().getResource(); } catch (Exception e) { throw new RemoteException("Unable to find site resource", e); } } public Site getSite(EmptyObject empty) throws RemoteException { return getResource().getSite(); } public EmptyObject submit(EndpointReferenceType credential) throws RemoteException { getResource().submit(credential); return new EmptyObject(); } public EmptyObject remove(RemoveRequest request) throws RemoteException { boolean force = request.isForce(); EndpointReferenceType credential = request.getCredential(); getResource().remove(force,credential); return new EmptyObject(); } }
package edu.usc.glidein.service.impl; import java.rmi.RemoteException; import org.apache.axis.message.addressing.EndpointReferenceType; import org.globus.wsrf.ResourceContext; import edu.usc.glidein.stubs.types.EmptyObject; import edu.usc.glidein.stubs.types.Site; public class SiteService { private SiteResource getResource() throws RemoteException { try { return (SiteResource) ResourceContext.getResourceContext().getResource(); } catch (Exception e) { throw new RemoteException("Unable to find site resource", e); } } public Site getSite(EmptyObject empty) throws RemoteException { return getResource().getSite(); } public EmptyObject submit(EndpointReferenceType credential) throws RemoteException { getResource().submit(credential); return new EmptyObject(); } public EmptyObject remove(boolean force) throws RemoteException { getResource().remove(force); return new EmptyObject(); } }
Use object attributes; adjust appearance
Template.homeResidentActivityLevelTrend.rendered = function () { // Get reference to template instance var instance = this; instance.autorun(function () { // Get reference to Route var router = Router.current(); // Get current Home ID var homeId = router.params.homeId; // Get data for trend line chart var data = ReactiveMethod.call("getHomeActivityCountTrend", homeId); if (data) { MG.data_graphic({ title: "Count of residents per activity level for each of last seven days", description: "Daily count of residents with inactive, semi-active, and active status.", data: data, x_axis: true, y_accessor: ['inactive', 'semiActive', 'active'], interpolate: 'basic', full_width: true, height: 333, right: 49, target: '#trend-chart', legend: ['Inactive','Semi-active','Active'], colors: ['red', 'gold', 'green'], aggregate_rollover: true }); } }); }
Template.homeResidentActivityLevelTrend.rendered = function () { // Get reference to template instance var instance = this; instance.autorun(function () { // Get reference to Route var router = Router.current(); // Get current Home ID var homeId = router.params.homeId; // Get data for trend line chart var data = ReactiveMethod.call("getHomeActivityCountTrend", homeId); if (data) { MG.data_graphic({ title: "Count of residents per activity level for each of last seven days", description: "Daily count of residents with inactive, semi-active, and active status.", data: [data[0], data[1], data[2]], x_axis: false, interpolate: 'basic', full_width: true, height: 200, right: 40, target: '#trend-chart', legend: ['Inactive','Semi-active','Active'], legend_target: '.legend', colors: ['red', 'gold', 'green'], aggregate_rollover: true }); } }); }
Use sets to define allowed regions for plugins
from django import forms from django.contrib import admin from django.db import models from content_editor.admin import ContentEditor, ContentEditorInline from .models import Article, Download, RichText, Thing class RichTextarea(forms.Textarea): def __init__(self, attrs=None): default_attrs = {"class": "richtext"} if attrs: # pragma: no cover default_attrs.update(attrs) super(RichTextarea, self).__init__(default_attrs) class RichTextInline(ContentEditorInline): model = RichText formfield_overrides = {models.TextField: {"widget": RichTextarea}} fieldsets = [(None, {"fields": ("text", "region", "ordering")})] regions = {"main"} class Media: js = ("//cdn.ckeditor.com/4.5.6/standard/ckeditor.js", "app/plugin_ckeditor.js") class ThingInline(admin.TabularInline): model = Thing admin.site.register( Article, ContentEditor, inlines=[ RichTextInline, ContentEditorInline.create( model=Download, regions=lambda self, regions: regions - {"sidebar"} ), ThingInline, ], )
from django import forms from django.contrib import admin from django.db import models from content_editor.admin import ContentEditor, ContentEditorInline from .models import Article, Download, RichText, Thing class RichTextarea(forms.Textarea): def __init__(self, attrs=None): default_attrs = {"class": "richtext"} if attrs: # pragma: no cover default_attrs.update(attrs) super(RichTextarea, self).__init__(default_attrs) class RichTextInline(ContentEditorInline): model = RichText formfield_overrides = {models.TextField: {"widget": RichTextarea}} fieldsets = [(None, {"fields": ("text", "region", "ordering")})] regions = ("main",) class Media: js = ("//cdn.ckeditor.com/4.5.6/standard/ckeditor.js", "app/plugin_ckeditor.js") class ThingInline(admin.TabularInline): model = Thing admin.site.register( Article, ContentEditor, inlines=[ RichTextInline, ContentEditorInline.create( model=Download, regions=lambda inline, regions: regions - {"sidebar"} ), ThingInline, ], )