text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Sort choices by ID. Send choice ID to view.
var uuidV4 = require('uuid/v4'); var models = require('../models'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { var promise; if (req.session.uuid) { promise = models.Guest.find({ where: { sessionId: req.session.uuid } }) } else { req.session.uuid = uuidV4(); promise = models.Guest.create({ sessionId: req.session.uuid }); } promise.then(function(guest) { return models.Question.find({ include: [{ model: models.Choice }], order: [ [ models.sequelize.fn('RANDOM') ] ] }) }) .then(function(question) { var choices = question.Choices; // TODO: Sort in query instead of here choices.sort(function(a, b) { return a.id - b.id; }); return { title: question.title, choices: choices.map(function(choice) { return { id: choice.id, text: choice.text }; }) }; }) .then(function(question) { res.render('index', { question: question }); }); }); module.exports = router;
var uuidV4 = require('uuid/v4'); var models = require('../models'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { var promise; if (req.session.uuid) { promise = models.Guest.find({ where: { sessionId: req.session.uuid } }) } else { req.session.uuid = uuidV4(); promise = models.Guest.create({ sessionId: req.session.uuid }); } promise.then(function(guest) { return models.Question.find({ include: [{ model: models.Choice }], order: [ [ models.sequelize.fn('RANDOM') ] ] }) }) .then(function(question) { return { title: question.title, choices: question.Choices.map(function(choice) { return { text: choice.text }; }) }; }) .then(function(question) { res.render('index', { question: question }); }); }); module.exports = router;
Bugfix: Allow integer ports in split_address.
from .validation import valid_hostname, valid_port def resolve(path_or_address=None, address=None, *ignored): """Returns (path, address) based on consecutive optional arguments, [path] [address].""" if path_or_address is None or address is not None: return path_or_address, address path = None if split_address(path_or_address)[1] is not None: address = path_or_address else: path = path_or_address return path, address def split_address(address): """Returns (host, port) with an integer port from the specified address string. (None, None) is returned if the address is invalid.""" invalid = None, None if not address: return invalid components = str(address).split(':') if len(components) > 2 or not valid_hostname(components[0]): return invalid if len(components) == 2 and not valid_port(components[1]): return invalid if len(components) == 1: components.insert(0 if valid_port(components[0]) else 1, None) host, port = components port = int(port) if port else None return host, port
from .validation import valid_hostname, valid_port def resolve(path_or_address=None, address=None, *ignored): """Returns (path, address) based on consecutive optional arguments, [path] [address].""" if path_or_address is None or address is not None: return path_or_address, address path = None if split_address(path_or_address)[1] is not None: address = path_or_address else: path = path_or_address return path, address def split_address(address): """Returns (host, port) with an integer port from the specified address string. (None, None) is returned if the address is invalid.""" invalid = None, None if not address: return invalid components = address.split(':') if len(components) > 2 or not valid_hostname(components[0]): return invalid if len(components) == 2 and not valid_port(components[1]): return invalid if len(components) == 1: components.insert(0 if valid_port(components[0]) else 1, None) host, port = components port = int(port) if port else None return host, port
Add more tests for sneeze.
import os from tempfile import mkdtemp from shutil import rmtree from nipy.testing import * from sneeze import find_pkg, run_nose import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit", "from nipype.interfaces import afni", "import nipype.interfaces.afni", "from nipype.interfaces import afni as af"] def test_imports(): dname = mkdtemp() fname = os.path.join(dname, 'test_afni.py') for impt in import_strings: fp = open(fname, 'w') fp.write(impt) fp.close() cover_pkg, module = find_pkg(fname) cmd = run_nose(cover_pkg, fname, dry_run=True) cmdlst = cmd.split() cmd = ' '.join(cmdlst[:4]) # strip off temporary directory path yield assert_equal, cmd, \ 'nosetests -sv --with-coverage --cover-package=nipype.interfaces.afni' if os.path.exists(dname): rmtree(dname)
import os from tempfile import mkdtemp from shutil import rmtree from nipy.testing import * from sneeze import find_pkg, run_nose import_strings = ["from nipype.interfaces.afni import To3d", "from nipype.interfaces import afni", "import nipype.interfaces.afni"] def test_from_namespace(): dname = mkdtemp() fname = os.path.join(dname, 'test_afni.py') fp = open(fname, 'w') fp.write('from nipype.interfaces.afni import To3d') fp.close() cover_pkg, module = find_pkg(fname) cmd = run_nose(cover_pkg, fname, dry_run=True) cmdlst = cmd.split() cmd = ' '.join(cmdlst[:4]) # strip off temporary directory path #print cmd assert_equal(cmd, 'nosetests -sv --with-coverage --cover-package=nipype.interfaces.afni') if os.path.exists(dname): rmtree(dname)
Make countcontainer members public for now
package io.sigpipe.sing.graph; import java.io.IOException; import io.sigpipe.sing.serialization.SerializationInputStream; import io.sigpipe.sing.serialization.SerializationOutputStream; public class CountContainer extends DataContainer { public long a; public long b; public CountContainer() { } public CountContainer(long a, long b) { this.a = a; this.b = b; } public void merge(DataContainer container) { CountContainer cc = (CountContainer) container; this.a += cc.a; this.b += cc.b; } public void clear() { this.a = 0; this.b = 0; } @Deserialize public CountContainer(SerializationInputStream in) throws IOException { this.a = in.readLong(); this.b = in.readLong(); } @Override public void serialize(SerializationOutputStream out) throws IOException { out.writeLong(a); out.writeLong(b); } }
package io.sigpipe.sing.graph; import java.io.IOException; import io.sigpipe.sing.serialization.SerializationInputStream; import io.sigpipe.sing.serialization.SerializationOutputStream; public class CountContainer extends DataContainer { long a; long b; public CountContainer() { } public CountContainer(long a, long b) { this.a = a; this.b = b; } public void merge(DataContainer container) { CountContainer cc = (CountContainer) container; this.a += cc.a; this.b += cc.b; } public void clear() { this.a = 0; this.b = 0; } @Deserialize public CountContainer(SerializationInputStream in) throws IOException { this.a = in.readLong(); this.b = in.readLong(); } @Override public void serialize(SerializationOutputStream out) throws IOException { out.writeLong(a); out.writeLong(b); } }
Fix: Use instanceof instead of is_a()
<?php namespace TomPHP\ContainerConfigurator; use TomPHP\ContainerConfigurator\Exception\UnknownContainerException; final class ContainerAdapterFactory { /** * @var array */ private $config; public function __construct(array $config) { $this->config = $config; } /** * @param object $container * * @throws UnknownContainerException * * @return void */ public function create($container) { $class = ''; foreach ($this->config as $containerClass => $configuratorClass) { if ($container instanceof $containerClass) { $class = $configuratorClass; break; } } if (!$class) { throw UnknownContainerException::fromContainerName( get_class($container), array_keys($this->config) ); } $instance = new $class(); $instance->setContainer($container); return $instance; } }
<?php namespace TomPHP\ContainerConfigurator; use TomPHP\ContainerConfigurator\Exception\UnknownContainerException; final class ContainerAdapterFactory { /** * @var array */ private $config; public function __construct(array $config) { $this->config = $config; } /** * @param object $container * * @throws UnknownContainerException * * @return void */ public function create($container) { $class = ''; foreach ($this->config as $containerClass => $configuratorClass) { if (is_a($container, $containerClass)) { $class = $configuratorClass; break; } } if (!$class) { throw UnknownContainerException::fromContainerName( get_class($container), array_keys($this->config) ); } $instance = new $class(); $instance->setContainer($container); return $instance; } }
Add error handling to reduce dependency on pypi
import xmlrpclib from socket import gaierror, error VERSION_OK = "0.6.0" try: pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') VERSION_OK = pypi.package_releases('ricecooker')[0] except (gaierror, error): pass VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date." VERSION_SOFT_WARNING = "0.5.6" VERSION_SOFT_WARNING_MESSAGE = "You are using Ricecooker v{}, however v{} is available. You should consider upgrading your Ricecooker." VERSION_HARD_WARNING = "0.3.13" VERSION_HARD_WARNING_MESSAGE = "Ricecooker v{} is deprecated. Any channels created with this version will be unlinked with any future upgrades. You are strongly recommended to upgrade to v{}." VERSION_ERROR = None VERSION_ERROR_MESSAGE = "Ricecooker v{} is no longer compatible. You must upgrade to v{} to continue."
import xmlrpclib from socket import gaierror VERSION_OK = "0.5.13" try: pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') VERSION_OK = pypi.package_releases('ricecooker')[0] except gaierror: pass VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date." VERSION_SOFT_WARNING = "0.5.6" VERSION_SOFT_WARNING_MESSAGE = "You are using Ricecooker v{}, however v{} is available. You should consider upgrading your Ricecooker." VERSION_HARD_WARNING = "0.3.13" VERSION_HARD_WARNING_MESSAGE = "Ricecooker v{} is deprecated. Any channels created with this version will be unlinked with any future upgrades. You are strongly recommended to upgrade to v{}." VERSION_ERROR = None VERSION_ERROR_MESSAGE = "Ricecooker v{} is no longer compatible. You must upgrade to v{} to continue."
Add a globalflag to disable audit logs audit logs may contains some sensitive information: - Requester IP - Token subject - Token ID If you want to disable audit log, you can use env `export FEDERATED_ACCESS_DISABLE_AUDIT_LOG=true` PiperOrigin-RevId: 294515600 Change-Id: Ifb5f2023b0903a01d7a3ce21f9b27045588a3063
// Copyright 2019 Google LLC // // 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 globalflags contains global flags of binary, eg. Experimental. package globalflags import ( "os" ) var ( // Experimental is a global flag determining if experimental features should be enabled. // Set from env var: `export FEDERATED_ACCESS_ENABLE_EXPERIMENTAL=true` Experimental = os.Getenv("FEDERATED_ACCESS_ENABLE_EXPERIMENTAL") == "true" // DisableAuditLog is a global flag determining if you want to disable audit log. // Set from env var: `export FEDERATED_ACCESS_DISABLE_AUDIT_LOG=true` DisableAuditLog = os.Getenv("FEDERATED_ACCESS_DISABLE_AUDIT_LOG") == "true" )
// Copyright 2019 Google LLC // // 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 globalflags contains global flags of binary, eg. Experimental. package globalflags import ( "os" ) var ( // Experimental is a global flag determining if experimental features should be enabled. // Set from env var: `export FEDERATED_ACCESS_ENABLE_EXPERIMENTAL=true` Experimental = os.Getenv("FEDERATED_ACCESS_ENABLE_EXPERIMENTAL") == "true" )
Remove the admin url mapping
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views import project urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
Set global asset path for Css
<!doctype html> <html lang="de"> <head> <link href='https://fonts.googleapis.com/css?family=Catamaran:400,700|Cambay:400,700' rel='stylesheet' type='text/css'> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>backstage</title> <link href="{{ asset('bower_components/normalize-css/normalize.css') }}" rel="stylesheet"> <link rel="stylesheet" href="{{ asset('dist/frontend-global.css') }}"> </head> <body> <div class="page-wrapper"> @yield('content') </div> <script src="{{ asset('bower_components/jquery/dist/jquery.min.js') }}"></script> <script src="{{ asset('src/scripts/custom.js') }}"></script> </body> </html>
<!doctype html> <html lang="de"> <head> <link href='https://fonts.googleapis.com/css?family=Catamaran:400,700|Cambay:400,700' rel='stylesheet' type='text/css'> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>backstage</title> <link href="{{ asset('bower_components/normalize-css/normalize.css') }}" rel="stylesheet"> <link rel="stylesheet" href="dist/frontend-global.css"> </head> <body> <div class="page-wrapper"> @yield('content') </div> <script src="{{ asset('bower_components/jquery/dist/jquery.min.js') }}"></script> <script src="{{ asset('src/scripts/custom.js') }}"></script> </body> </html>
Make $id property be concepts key
'use strict'; module.exports = /*@ngInject*/ function GrammarActivitiesEditCmsCtrl ( $scope, GrammarActivity, $state, _, ConceptsFBService ) { $scope.grammarActivity = {}; $scope.grammarActivity.concepts = []; GrammarActivity.getOneByIdFromFB($state.params.id).then(function (ga) { $scope.grammarActivity = ga; $scope.grammarActivity.concepts = _.map($scope.grammarActivity.concepts, function(c, k) { c.$id = k; ConceptsFBService.getById(k).then(function (cfb) { if (cfb) { c.concept_level_2 = cfb.concept_level_2; c.concept_level_1 = cfb.concept_level_1; c.concept_level_0 = cfb.concept_level_0; } }); return c; }); }); $scope.processGrammarActivityForm = function () { }; };
'use strict'; module.exports = /*@ngInject*/ function GrammarActivitiesEditCmsCtrl ( $scope, GrammarActivity, $state, _, ConceptsFBService ) { $scope.grammarActivity = {}; $scope.grammarActivity.concepts = []; GrammarActivity.getOneByIdFromFB($state.params.id).then(function (ga) { $scope.grammarActivity = ga; $scope.grammarActivity.concepts = _.map($scope.grammarActivity.concepts, function(c, k) { c.fb_concept_key = k; ConceptsFBService.getById(k).then(function (cfb) { if (cfb) { c.concept_level_2 = cfb.concept_level_2; c.concept_level_1 = cfb.concept_level_1; c.concept_level_0 = cfb.concept_level_0; } }); return c; }); }); $scope.processGrammarActivityForm = function () { }; };
Update PageSpeed test to match API
<?php /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class PageSpeedTest extends BaseTest { public $service; public function __construct() { parent::__construct(); $this->service = new Google_Service_Pagespeedonline($this->getClient()); } public function testPageSpeed() { $this->checkToken(); $psapi = $this->service->pagespeedapi; $result = $psapi->runpagespeed('http://code.google.com'); $this->assertArrayHasKey('kind', $result); $this->assertArrayHasKey('id', $result); $this->assertArrayHasKey('responseCode', $result); $this->assertArrayHasKey('title', $result); $this->assertArrayHasKey('score', $result->ruleGroups['SPEED']); $this->assertInstanceOf('Google_Service_Pagespeedonline_ResultPageStats', $result->pageStats); $this->assertArrayHasKey('minor', $result['version']); } }
<?php /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class PageSpeedTest extends BaseTest { public $service; public function __construct() { parent::__construct(); $this->service = new Google_Service_Pagespeedonline($this->getClient()); } public function testPageSpeed() { $this->checkToken(); $psapi = $this->service->pagespeedapi; $result = $psapi->runpagespeed('http://code.google.com'); $this->assertArrayHasKey('kind', $result); $this->assertArrayHasKey('id', $result); $this->assertArrayHasKey('responseCode', $result); $this->assertArrayHasKey('title', $result); $this->assertArrayHasKey('score', $result); $this->assertInstanceOf('Google_Service_Pagespeedonline_ResultPageStats', $result->pageStats); $this->assertArrayHasKey('minor', $result['version']); } }
Fix reference to class attribute
import asyncio import esipy from discord.ext import commands from requests.adapters import DEFAULT_POOLSIZE from utils.log import get_logger ESI_SWAGGER_JSON = 'https://esi.evetech.net/dev/swagger.json' class EsiCog: _esi_app_task: asyncio.Task = None _semaphore = asyncio.Semaphore(DEFAULT_POOLSIZE) def __init__(self, bot: commands.Bot): logger = get_logger(__name__, bot) if EsiCog._esi_app_task is None: logger.info("Creating esipy App...") EsiCog._esi_app_task = bot.loop.run_in_executor( None, self._create_esi_app) EsiCog._esi_app_task.add_done_callback( lambda f: logger.info("esipy App created")) async def get_esi_app(self) -> asyncio.Task: return await self._esi_app_task def _create_esi_app(self): return esipy.App.create(url=ESI_SWAGGER_JSON) async def esi_request(self, loop, client, operation): async with self._semaphore: return await loop.run_in_executor(None, client.request, operation)
import asyncio import esipy from discord.ext import commands from requests.adapters import DEFAULT_POOLSIZE from utils.log import get_logger ESI_SWAGGER_JSON = 'https://esi.evetech.net/dev/swagger.json' class EsiCog: _esi_app_task: asyncio.Task = None _semaphore = asyncio.Semaphore(DEFAULT_POOLSIZE) def __init__(self, bot: commands.Bot): logger = get_logger(__name__, bot) if self._esi_app_task is None: logger.info("Creating esipy App...") self._esi_app_task = bot.loop.run_in_executor( None, self._create_esi_app) self._esi_app_task.add_done_callback( lambda f: logger.info("esipy App created")) def __unload(self): self._esi_app_task.cancel() async def get_esi_app(self) -> asyncio.Task: return await self._esi_app_task def _create_esi_app(self): return esipy.App.create(url=ESI_SWAGGER_JSON) async def esi_request(self, loop, client, operation): async with self._semaphore: return await loop.run_in_executor(None, client.request, operation)
Add with_statement import for python2.5. See http://www.python.org/dev/peps/pep-0343/ which describes the with statement. Review URL: http://codereview.chromium.org/5690003
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that .so files that are order only dependencies are specified by their install location rather than by their alias. """ # Python 2.5 needs this for the with statement. from __future__ import with_statement import os import TestGyp test = TestGyp.TestGyp(formats=['make']) test.run_gyp('shared_dependency.gyp', chdir='src') test.relocate('src', 'relocate/src') test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src') with open('relocate/src/Makefile') as makefile: make_contents = makefile.read() # If we remove the code to generate lib1, Make should still be able # to build lib2 since lib1.so already exists. make_contents = make_contents.replace('include lib1.target.mk', '') with open('relocate/src/Makefile', 'w') as makefile: makefile.write(make_contents) test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src') test.pass_test()
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that .so files that are order only dependencies are specified by their install location rather than by their alias. """ import os import TestGyp test = TestGyp.TestGyp(formats=['make']) test.run_gyp('shared_dependency.gyp', chdir='src') test.relocate('src', 'relocate/src') test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src') with open('relocate/src/Makefile') as makefile: make_contents = makefile.read() # If we remove the code to generate lib1, Make should still be able # to build lib2 since lib1.so already exists. make_contents = make_contents.replace('include lib1.target.mk', '') with open('relocate/src/Makefile', 'w') as makefile: makefile.write(make_contents) test.build('shared_dependency.gyp', test.ALL, chdir='relocate/src') test.pass_test()
Replace broken cookstr with random-recipes.com Resolve #1
/* Require modules */ var nodeTelegramBot = require('node-telegram-bot') , config = require('./config.json') , request = require("request") , cheerio = require("cheerio"); /* Functions */ /** * Uses the request module to return the body of a web page * @param {string} url * @param {callback} callback * @return {string} */ function getWebContent(url, callback){ request({ uri: url, }, function(error, response, body) { callback(body); }); } /* Logic */ var recipeURL = 'http://www.random-recipes.com/index.php?page=index&filter=true'; var bot = new nodeTelegramBot({ token: config.token }) .on('message', function (message) { /* Process "/dinner" command */ if (message.text == "/dinner" || message.text == "/dinner@" + config.botname) { console.log(message); getWebContent(recipeURL, function(data){ // Parse DOM and recipe informations var $ = cheerio.load(data) , recipeName = $(".recipe-name-title").text() , recipeURL = 'http://www.random-recipes.com/' + $(".recipe-name").attr('href'); // Send bot reply bot.sendMessage({ chat_id: message.chat.id, text: 'What about "' + recipeName + '"? ' + recipeURL }); }); } }) .start();
/* Require modules */ var nodeTelegramBot = require('node-telegram-bot') , config = require('./config.json') , request = require("request") , cheerio = require("cheerio"); /* Functions */ /** * Uses the request module to return the body of a web page * @param {string} url * @param {callback} callback * @return {string} */ function getWebContent(url, callback){ request({ uri: url, }, function(error, response, body) { callback(body); }); } /* Logic */ var recipeURL = 'http://www.cookstr.com/searches/surprise'; var bot = new nodeTelegramBot({ token: config.token }) .on('message', function (message) { /* Process "/dinner" command */ if (message.text == "/dinner" || message.text == "/dinner@" + config.botname) { console.log(message); getWebContent(recipeURL, function(data){ // Parse DOM and recipe informations var $ = cheerio.load(data) , recipeName = $("meta[property='og:title']").attr('content') , recipeURL = $("meta[property='og:url']").attr('content'); // Send bot reply bot.sendMessage({ chat_id: message.chat.id, text: 'What about "' + recipeName + '"? ' + recipeURL }); }); } }) .start();
Use WebserviceTestCase as parent for details organismsWithTrait test
<?php namespace Test\AppBundle\API\Details; use AppBundle\API\Details\OrganismsWithTrait; use Symfony\Component\HttpFoundation\ParameterBag; use Tests\AppBundle\API\WebserviceTestCase; class OrganismsWithTraitTest extends WebserviceTestCase { public function testExecute() { $default_db = $this->default_db; $service = $this->webservice->factory('details', 'organismsWithTrait'); //Test for the correct number of elements in the returned array $results = $service->execute(new ParameterBag(array( 'dbversion' => $default_db, 'trait_type_id' => 1)), null ); $this->assertEquals(OrganismsWithTrait::DEFAULT_LIMIT, count($results)); $results = $service->execute( new ParameterBag(array( 'dbversion' => $default_db, 'trait_type_id' => 1, 'limit' => 10 )), null ); $this->assertEquals(10, count($results)); } }
<?php namespace Test\AppBundle\API\Details; use AppBundle\API\Details\OrganismsWithTrait; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\HttpFoundation\ParameterBag; class OrganismsWithTraitTest extends WebTestCase { public function testExecute() { $container = static::createClient()->getContainer(); $default_db = $container->getParameter('default_db'); $service = $container->get('app.api.webservice')->factory('details', 'organismsWithTrait'); //Test for the correct number of elements in the returned array $results = $service->execute(new ParameterBag(array( 'dbversion' => $default_db, 'trait_type_id' => 1)), null ); $this->assertEquals(OrganismsWithTrait::DEFAULT_LIMIT, count($results)); $results = $service->execute( new ParameterBag(array( 'dbversion' => $default_db, 'trait_type_id' => 1, 'limit' => 10 )), null ); $this->assertEquals(10, count($results)); } }
Make example auth always true.
"""This is your typical app, demonstrating usage.""" import os from flask_jsondash.charts_builder import charts from flask import ( Flask, session, ) app = Flask(__name__) app.config['SECRET_KEY'] = 'NOTSECURELOL' app.config.update( JSONDASH_FILTERUSERS=True, JSONDASH_GLOBALDASH=True, JSONDASH_GLOBAL_USER='global', ) app.debug = True app.register_blueprint(charts) def _can_delete(): return True def _can_clone(): return True def _get_username(): return 'anonymous' # Config examples. app.config['JSONDASH'] = dict( metadata=dict( created_by=_get_username, username=_get_username, ), auth=dict( clone=_can_clone, delete=_can_delete, ) ) @app.route('/', methods=['GET']) def index(): """Sample index.""" return '<a href="/charts">Visit the charts blueprint.</a>' if __name__ == '__main__': PORT = int(os.getenv('PORT', 5002)) app.run(debug=True, port=PORT)
"""This is your typical app, demonstrating usage.""" import os from flask_jsondash.charts_builder import charts from flask import ( Flask, session, ) app = Flask(__name__) app.config['SECRET_KEY'] = 'NOTSECURELOL' app.config.update( JSONDASH_FILTERUSERS=True, JSONDASH_GLOBALDASH=True, JSONDASH_GLOBAL_USER='global', ) app.debug = True app.register_blueprint(charts) def _can_delete(): return False def _can_clone(): return True def _get_username(): return 'anonymous' # Config examples. app.config['JSONDASH'] = dict( metadata=dict( created_by=_get_username, username=_get_username, ), auth=dict( clone=_can_clone, delete=_can_delete, ) ) @app.route('/', methods=['GET']) def index(): """Sample index.""" return '<a href="/charts">Visit the charts blueprint.</a>' if __name__ == '__main__': PORT = int(os.getenv('PORT', 5002)) app.run(debug=True, port=PORT)
Remove manual env injection and uglify plugin. webpacks `-p` argument handles this.
const path = require('path') const webpack = require('webpack') const ENV = process.env.NODE_ENV || 'development' const appendIf = (cond, ...items) => cond ? items : [] const plugins = [ ...appendIf(ENV !== 'production', new webpack.HotModuleReplacementPlugin()) ] module.exports = { entry: [ 'react-hot-loader/patch', './src/index.js' ], output: { path: path.resolve(__dirname, 'static'), filename: 'bundle.js' }, resolve: { extensions: ['.js', '.jsx'] }, plugins: plugins, module: { rules: [{ test: /\.jsx?$/, exclude: /node_modules/, loaders: [ 'react-hot-loader/webpack', 'babel-loader' ], }] }, devServer: { hot: true, contentBase: path.join(__dirname, 'static'), publicPath: '/' } }
const path = require('path') const webpack = require('webpack') const ENV = process.env.NODE_ENV || 'development' const appendIf = (cond, ...items) => cond ? items : [] const plugins = [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(ENV) } }), ...appendIf(ENV === 'production', new webpack.optimize.UglifyJsPlugin()), ...appendIf(ENV !== 'production', new webpack.HotModuleReplacementPlugin()) ] module.exports = { entry: [ 'react-hot-loader/patch', './src/index.js' ], output: { path: path.resolve(__dirname, 'static'), filename: 'bundle.js' }, resolve: { extensions: ['.js', '.jsx'] }, plugins: plugins, module: { rules: [{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot-loader/webpack', 'babel-loader'], }] }, devServer: { hot: true, contentBase: path.join(__dirname, 'static'), publicPath: '/' } }
Add mock as a dep
#!/usr/bin/env python # Copyright 2009-2014 Eucalyptus Systems, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup setup(name='deploymentmanager', version='0.1', description='Eucalyptus Deployment and Configuration Management tools', url='https://github.com/eucalyptus/DeploymentManager.git', license='Apache License 2.0', packages=find_packages(), install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock', 'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'], test_suite="nose.collector", zip_safe=False, classifiers=[ "Development Status :: 1 - Alpha", "Topic :: Utilities", "Environment :: Console", ], )
#!/usr/bin/env python # Copyright 2009-2014 Eucalyptus Systems, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup setup(name='deploymentmanager', version='0.1', description='Eucalyptus Deployment and Configuration Management tools', url='https://github.com/eucalyptus/DeploymentManager.git', license='Apache License 2.0', packages=find_packages(), install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'], test_suite="nose.collector", zip_safe=False, classifiers=[ "Development Status :: 1 - Alpha", "Topic :: Utilities", "Environment :: Console", ], )
Fix ordering of latest models on the leader board.
import glob import numpy as np import pandas as pd def load_df(file_name): model_id = file_name.split('/')[4] df = pd.read_csv(file_name) df.rename(columns={'Unnamed: 0': 'split'}, inplace=True) df['model_id'] = model_id if 'auc' not in df.columns: df['auc'] = np.nan df = df[['model_id', 'split', 'loss', 'error', 'auc']] return df files = sorted(glob.glob('data/working/single-notes-2000/models/*/evaluation/final_metrics.csv')) df = pd.concat([load_df(f) for f in files]) df_valid = df[df['split'] == 'valid'] df_valid.set_index('model_id', inplace=True) print('Ranking on the validation split metrics.\n') print('Lowest error:') print(df_valid.sort_values('error', ascending=True)[:5]) print('\nHighest AUC:') print(df_valid.sort_values('auc', ascending=False)[:5]) print('\nRank of the last few models by error, total:', len(df_valid)) print(df_valid.rank()['error'].astype(int).iloc[-5:])
import glob import numpy as np import pandas as pd def load_df(file_name): model_id = file_name.split('/')[4] df = pd.read_csv(file_name) df.rename(columns={'Unnamed: 0': 'split'}, inplace=True) df['model_id'] = model_id if 'auc' not in df.columns: df['auc'] = np.nan df = df[['model_id', 'split', 'loss', 'error', 'auc']] return df files = glob.glob('data/working/single-notes-2000/models/*/evaluation/final_metrics.csv') df = pd.concat([load_df(f) for f in files]) df_valid = df[df['split'] == 'valid'] df_valid.set_index('model_id', inplace=True) print('Ranking on the validation split metrics.\n') print('Lowest error:') print(df_valid.sort_values('error', ascending=True)[:5]) print('\nHighest AUC:') print(df_valid.sort_values('auc', ascending=False)[:5]) print('\nRank of the last few models by error, total:', len(df_valid)) print(df_valid.rank()['error'].astype(int).iloc[-5:])
Increase chrome driver start timeout
import test from 'ava'; import electronPath from 'electron'; import { Application } from 'spectron'; import path from 'path'; const appPath = path.join(__dirname, '..'); test.beforeEach(async t => { t.context.app = new Application({ // eslint-disable-line no-param-reassign path: electronPath, args: [appPath], startTimeout: 60000, }); await t.context.app.start(); }); test.afterEach.always(async t => { await t.context.app.stop(); }); test('Launch', async t => { const { app } = t.context; await app.client.waitUntilWindowLoaded(); const win = app.browserWindow; t.is(await app.client.getWindowCount(), 1); t.false(await win.isMinimized()); t.false(await win.isDevToolsOpened()); t.true(await win.isVisible()); const { width, height } = await win.getBounds(); t.true(width > 0); t.true(height > 0); });
import test from 'ava'; import electronPath from 'electron'; import { Application } from 'spectron'; import path from 'path'; const appPath = path.join(__dirname, '..'); test.beforeEach(async t => { t.context.app = new Application({ // eslint-disable-line no-param-reassign path: electronPath, args: [appPath], }); await t.context.app.start(); }); test.afterEach.always(async t => { await t.context.app.stop(); }); test('Launch', async t => { const { app } = t.context; await app.client.waitUntilWindowLoaded(); const win = app.browserWindow; t.is(await app.client.getWindowCount(), 1); t.false(await win.isMinimized()); t.false(await win.isDevToolsOpened()); t.true(await win.isVisible()); const { width, height } = await win.getBounds(); t.true(width > 0); t.true(height > 0); });
Format volume and snapshot size quota using filesize filter [WAL-813].
// @ngInject export function quotaName($filter) { var names = { floating_ip_count: gettext('Floating IP count'), vcpu: gettext('vCPU count'), ram: gettext('RAM'), storage: gettext('Storage'), vm_count: gettext('Virtual machines count'), instances: gettext('Instances count'), volumes: gettext('Volumes count'), snapshots: gettext('Snapshots count'), cost: gettext('Monthly cost'), }; return function(name) { if (names[name]) { return names[name]; } name = name.replace(/_/g, ' '); return $filter('titleCase')(name); }; } // @ngInject export function quotaValue($filter) { var filters = { ram: 'filesize', storage: 'filesize', volumes_size: 'filesize', snapshots_size: 'filesize', backup_storage: 'filesize', cost: 'defaultCurrency', }; return function(value, name) { if (value == -1) { return '∞'; } var filter = filters[name]; if (filter) { return $filter(filter)(value); } else { return value; } }; }
// @ngInject export function quotaName($filter) { var names = { floating_ip_count: gettext('Floating IP count'), vcpu: gettext('vCPU count'), ram: gettext('RAM'), storage: gettext('Storage'), vm_count: gettext('Virtual machines count'), instances: gettext('Instances count'), volumes: gettext('Volumes count'), snapshots: gettext('Snapshots count'), cost: gettext('Monthly cost'), }; return function(name) { if (names[name]) { return names[name]; } name = name.replace(/_/g, ' '); return $filter('titleCase')(name); }; } // @ngInject export function quotaValue($filter) { var filters = { ram: 'filesize', storage: 'filesize', backup_storage: 'filesize', cost: 'defaultCurrency', }; return function(value, name) { if (value == -1) { return '∞'; } var filter = filters[name]; if (filter) { return $filter(filter)(value); } else { return value; } }; }
Update unmarshal test for User context
package config import ( "reflect" "testing" "github.com/lifesum/configsum/pkg/errors" ) func TestLocationInvalidLocale(t *testing.T) { var ( input = []byte(`{"locale": "foobarz"}`) l = location{} ) err := l.UnmarshalJSON(input) if have, want := errors.Cause(err), errors.ErrInvalidPayload; have != want { t.Errorf("have %v, want %v", have, want) } } func TestUnmarshalUserContext(t *testing.T) { var ( input = []byte(`{ "age": 27, "registered": "2017-12-04T23:11:38Z", "subscription": 2 }`) u = userInfo{} ) err := u.UnmarshalJSON(input) if err != nil { t.Fatal(err) } have := u want := userInfo{ Age: 27, Registered: "2017-12-04T23:11:38Z", Subscription: 2, } if !reflect.DeepEqual(have, want) { t.Errorf("have %v, want %v", have, want) } }
package config import ( "github.com/lifesum/configsum/pkg/errors" "testing" ) func TestLocationInvalidLocale(t *testing.T) { var ( input = []byte(`{"locale": "foobarz"}`) l = location{} ) err := l.UnmarshalJSON(input) if have, want := errors.Cause(err), errors.ErrInvalidPayload; have != want { t.Errorf("have %v, want %v", have, want) } } func TestUnmarshalUserContext(t *testing.T) { var ( input = []byte(`{ "age": 27, "registered": "2017-12-04T23:11:38Z", "subscription": 2 }`) u = userInfo{} ) err := u.UnmarshalJSON(input) if err != nil { t.Fatal(err) } }
Allow delimeter to be specified
<?php /** * LICENSE: This source code is subject to the license that is available * in the LICENSE file distributed along with this package. * * @package Penelope * @author Matthew Caruana Galizia <mcg@karwana.com> * @copyright Karwana Ltd * @since File available since Release 1.0.0 */ use Karwana\Penelope\Node; use Karwana\Penelope\NodeSchema; use Karwana\Penelope\Scripts\NodePropertyMapper; function split_node_property(NodeSchema $node_schema, $property_name, $delimeter) { $mapper = new NodePropertyMapper($node_schema, $property_name, function(Node $node) use (&$mapper, $delimeter) { return $mapper->split($node, $delimeter); }); $mapper->run(); } if (empty($argv[1])) { throw new \InvalidArgumentException('Missing initialization script path.'); } if (empty($argv[2])) { throw new \InvalidArgumentException('Missing schema name.'); } if (empty($argv[3])) { throw new \InvalidArgumentException('Missing property name.'); } if (empty($argv[4])) { throw new \InvalidArgumentException('Missing delimeter.'); } require_once __DIR__ . '/Penelope/NodePropertyMapper.php'; require_once $argv[1]; if (!isset($schema)) { $schema = $penelope->getSchema(); } split_node_property($schema->getNode($argv[2]), $argv[3], $argv[4]);
<?php /** * LICENSE: This source code is subject to the license that is available * in the LICENSE file distributed along with this package. * * @package Penelope * @author Matthew Caruana Galizia <mcg@karwana.com> * @copyright Karwana Ltd * @since File available since Release 1.0.0 */ use Karwana\Penelope\Node; use Karwana\Penelope\NodeSchema; use Karwana\Penelope\Scripts\NodePropertyMapper; function split_node_property(NodeSchema $node_schema, $property_name) { $mapper = new NodePropertyMapper($node_schema, $property_name, function(Node $node) use (&$mapper) { return $mapper->split($node); }); $mapper->run(); } if (empty($argv[1])) { throw new \InvalidArgumentException('Missing initialization script path.'); } if (empty($argv[2])) { throw new \InvalidArgumentException('Missing schema name.'); } if (empty($argv[3])) { throw new \InvalidArgumentException('Missing property name.'); } require_once __DIR__ . '/Penelope/NodePropertyMapper.php'; require_once $argv[1]; if (!isset($schema)) { $schema = $penelope->getSchema(); } split_node_property($schema->getNode($argv[2]), $argv[3]);
Add an additional description for 'token_ttl' The unit of 'token_ttl' is not clear in the help text in nova/conf/consoleauth.py. So add the unit (in seconds) in the help text. TrivialFix Change-Id: Id6506b7462c303223bac8586e664e187cb52abd6
# Copyright (c) 2016 Intel, Inc. # Copyright (c) 2013 OpenStack Foundation # 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. from oslo_config import cfg consoleauth_group = cfg.OptGroup( name='consoleauth', title='Console auth options') consoleauth_opts = [ cfg.IntOpt('token_ttl', default=600, min=0, deprecated_name='console_token_ttl', deprecated_group='DEFAULT', help=""" The lifetime of a console auth token (in seconds). A console auth token is used in authorizing console access for a user. Once the auth token time to live count has elapsed, the token is considered expired. Expired tokens are then deleted. """) ] def register_opts(conf): conf.register_group(consoleauth_group) conf.register_opts(consoleauth_opts, group=consoleauth_group) def list_opts(): return {consoleauth_group: consoleauth_opts}
# Copyright (c) 2016 Intel, Inc. # Copyright (c) 2013 OpenStack Foundation # 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. from oslo_config import cfg consoleauth_group = cfg.OptGroup( name='consoleauth', title='Console auth options') consoleauth_opts = [ cfg.IntOpt('token_ttl', default=600, min=0, deprecated_name='console_token_ttl', deprecated_group='DEFAULT', help=""" The lifetime of a console auth token. A console auth token is used in authorizing console access for a user. Once the auth token time to live count has elapsed, the token is considered expired. Expired tokens are then deleted. """) ] def register_opts(conf): conf.register_group(consoleauth_group) conf.register_opts(consoleauth_opts, group=consoleauth_group) def list_opts(): return {consoleauth_group: consoleauth_opts}
Add animation on button press
--- layout: null sitemap: exclude: 'yes' --- $(document).ready(function () { $('a.about-button').click(function (e) { if ($('.panel-cover').hasClass('panel-cover--collapsed')) return currentWidth = $('.panel-cover').width() if (currentWidth < 960) { $('.panel-cover').addClass('panel-cover--collapsed') $('.content-wrapper').addClass('animated slideInRight') } else { $('.panel-cover').css('max-width', currentWidth) $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {}) } }) if (window.location.hash && window.location.hash == '#about') { $('.panel-cover').addClass('panel-cover--collapsed') } /* if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') { $('.panel-cover').addClass('panel-cover--collapsed') } */ $('.btn-mobile-menu').click(function () { $('.navigation-wrapper').toggleClass('visible animated bounceInDown') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn') }) $('.navigation-wrapper .about-button').click(function () { $('.navigation-wrapper').toggleClass('visible') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn') }) })
--- layout: null sitemap: exclude: 'yes' --- $(document).ready(function () { $('a.about-button').click(function (e) { if ($('.panel-cover').hasClass('panel-cover--collapsed')) return currentWidth = $('.panel-cover').width() if (currentWidth < 960) { $('.panel-cover').addClass('panel-cover--collapsed') $('.content-wrapper').addClass('animated slideInRight') } else { $('.panel-cover').css('max-width', currentWidth) $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {}) } }) if (window.location.hash && window.location.hash == '#about') { $('.panel-cover').addClass('panel-cover--collapsed') } /* if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') { $('.panel-cover').addClass('panel-cover--collapsed') } $('.btn-mobile-menu').click(function () { $('.navigation-wrapper').toggleClass('visible animated bounceInDown') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn') }) $('.navigation-wrapper .about-button').click(function () { $('.navigation-wrapper').toggleClass('visible') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn') }) */ })
Use history fallback on development
/* eslint-disable no-var */ var webpack = require('webpack') var Config = require('webpack-config').default module.exports = new Config().extend('webpack/config/base.config.js').merge({ devtool: 'cheap-module-eval-source-map', devServer: { port: process.env.PORT || 8080, historyApiFallback: true, }, output: { publicPath: '/', }, module: { preLoaders: [ { test: /\.jsx?$/, loader: 'eslint', exclude: /node_modules/, }, ], loaders: [ { test: /\.s(c|a)ss$/, loaders: ['style', 'css', 'sass?sourceMap=true'], }, ], }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development'), }), ], })
/* eslint-disable no-var */ var webpack = require('webpack') var Config = require('webpack-config').default module.exports = new Config().extend('webpack/config/base.config.js').merge({ devtool: 'cheap-module-eval-source-map', devServer: { port: process.env.PORT || 8080, }, output: { publicPath: '/', }, module: { preLoaders: [ { test: /\.jsx?$/, loader: 'eslint', exclude: /node_modules/, }, ], loaders: [ { test: /\.s(c|a)ss$/, loaders: ['style', 'css', 'sass?sourceMap=true'], }, ], }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development'), }), ], })
Fix an issue with redirects
import './main.sass' import 'babel-core/polyfill' import React from 'react' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { Router } from 'react-router' import createBrowserHistory from 'history/lib/createBrowserHistory' import { createStore, applyMiddleware, combineReducers } from 'redux' import { Provider } from 'react-redux' import * as reducers from './reducers' import { analytics, uploader, requester } from './middleware' import App from './containers/App' const logger = createLogger({ collapsed: true }) const createStoreWithMiddleware = applyMiddleware(thunk, uploader, requester, analytics, logger)(createStore) const reducer = combineReducers(reducers) const store = createStoreWithMiddleware(reducer) function createRedirect(from, to) { return { path: from, onEnter(nextState, replaceState) { replaceState(nextState, to) }, } } const rootRoute = { path: '/', component: App, childRoutes: [ createRedirect('onboarding', '/onboarding/communities'), require('./routes/Onboarding'), ], } const element = ( <Provider store={store}> {() => <Router history={createBrowserHistory()} routes={rootRoute} /> } </Provider> ) React.render(element, document.getElementById('root'))
import './main.sass' import 'babel-core/polyfill' import React from 'react' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { Router } from 'react-router' import createBrowserHistory from 'history/lib/createBrowserHistory' import { createStore, applyMiddleware, combineReducers } from 'redux' import { Provider } from 'react-redux' import * as reducers from './reducers' import { analytics, uploader, requester } from './middleware' import App from './containers/App' const logger = createLogger({ collapsed: true }) const createStoreWithMiddleware = applyMiddleware(thunk, uploader, requester, analytics, logger)(createStore) const reducer = combineReducers(reducers) const store = createStoreWithMiddleware(reducer) function createRedirect(from, to) { return { path: from, onEnter(nextState, transition) { transition.to(to) }, } } const rootRoute = { path: '/', component: App, childRoutes: [ createRedirect('onboarding', '/onboarding/communities'), require('./routes/Onboarding'), ], } const element = ( <Provider store={store}> {() => <Router history={createBrowserHistory()} routes={rootRoute} /> } </Provider> ) React.render(element, document.getElementById('root'))
Update example to account for object merging PR #1331 introduces new behavior that merges a passed object with the defaults.
var path = require('path'); var HtmlWebpackPlugin = require('../..'); var webpackMajorVersion = require('webpack/package.json').version.split('.')[0]; module.exports = { context: __dirname, entry: './example.js', output: { path: path.join(__dirname, 'dist/webpack-' + webpackMajorVersion), publicPath: '', filename: 'bundle.js' }, plugins: [ new HtmlWebpackPlugin({ // If you pass a plain object, it will be merged with the default values // (New in version 4) templateParameters: { 'foo': 'bar' }, // Or if you want full control, pass a function // templateParameters: (compilation, assets, assetTags, options) => { // return { // compilation, // webpackConfig: compilation.options, // htmlWebpackPlugin: { // tags: assetTags, // files: assets, // options // }, // 'foo': 'bar' // }; // }, template: 'index.ejs' }) ] };
var path = require('path'); var HtmlWebpackPlugin = require('../..'); var webpackMajorVersion = require('webpack/package.json').version.split('.')[0]; module.exports = { context: __dirname, entry: './example.js', output: { path: path.join(__dirname, 'dist/webpack-' + webpackMajorVersion), publicPath: '', filename: 'bundle.js' }, plugins: [ new HtmlWebpackPlugin({ // NOTE if you pass plain object it will be passed as is. no default values there, so be aware! // for implementation detail, please see index.js and search for "userOptions" variable templateParameters: (compilation, assets, assetTags, options) => { return { compilation, webpackConfig: compilation.options, htmlWebpackPlugin: { tags: assetTags, files: assets, options }, 'foo': 'bar' }; }, template: 'index.ejs' }) ] };
Update requirement neo4j-driver to <1.5.0
from setuptools import setup, find_packages version = '1.0.17' requires = [ 'neo4j-driver<1.5,0', 'six>=1.10.0', ] testing_requires = [ 'nose', 'coverage', 'nosexcover', ] setup( name='norduniclient', version=version, url='https://github.com/NORDUnet/python-norduniclient', license='Apache License, Version 2.0', author='Johan Lundberg', author_email='lundberg@nordu.net', description='Neo4j (>=3.2.2) database client using bolt for NORDUnet network inventory', packages=find_packages(), zip_safe=False, install_requires=requires, tests_require=testing_requires, test_suite='nose.collector', extras_require={ 'testing': testing_requires } )
from setuptools import setup, find_packages version = '1.0.17' requires = [ 'neo4j-driver<1.2.0', 'six>=1.10.0', ] testing_requires = [ 'nose', 'coverage', 'nosexcover', ] setup( name='norduniclient', version=version, url='https://github.com/NORDUnet/python-norduniclient', license='Apache License, Version 2.0', author='Johan Lundberg', author_email='lundberg@nordu.net', description='Neo4j (>=3.2.2) database client using bolt for NORDUnet network inventory', packages=find_packages(), zip_safe=False, install_requires=requires, tests_require=testing_requires, test_suite='nose.collector', extras_require={ 'testing': testing_requires } )
Add comment_required to category simple serializer
from .models import Category, Keyword, Subcategory from rest_framework import serializers class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') class CategorySerializer(serializers.ModelSerializer): subcategories = SubcategoryListSerializer(many=True, source='subcategory_set') class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required', 'subcategories') class CategorySimpleSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required')
from .models import Category, Keyword, Subcategory from rest_framework import serializers class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') class CategorySerializer(serializers.ModelSerializer): subcategories = SubcategoryListSerializer(many=True, source='subcategory_set') class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required', 'subcategories') class CategorySimpleSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('pk', 'name', 'weight')
Move sluggable transliterator to content bundle.
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\UtilsBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class DarvinUtilsExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { // $configuration = new Configuration(); // $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('cloner.yml'); $loader->load('flash.yml'); $loader->load('mapping.yml'); $loader->load('security.yml'); $loader->load('stringifier.yml'); $loader->load('transliterator.yml'); } }
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\UtilsBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class DarvinUtilsExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { // $configuration = new Configuration(); // $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('cloner.yml'); $loader->load('flash.yml'); $loader->load('mapping.yml'); $loader->load('security.yml'); $loader->load('sluggable.yml'); $loader->load('stringifier.yml'); $loader->load('transliterator.yml'); } }
Fix bad casing in import
import isPlainObject from 'lodash/isPlainObject' function arrayify(fn) { return (...args) => { const ret = fn(...args) return Array.isArray(ret) ? ret : ret == null ? [] : [ret] } } export default function createRoute(pattern, ...rest) { let options, children if (isPlainObject(rest[0]) || typeof rest[0] === 'string') { [options, children] = rest if (typeof options === 'string') { options = {activeKey: options} } } else { options = {} children = rest[0] } if (!pattern.includes(':')) { // throw new Error(`A route must include at least one unique parameter. Please check the route "${pattern}"`) } return { pattern, options: options || {}, children: arrayify(typeof children === 'function' ? children : () => children) } }
import isPlainObject from 'lodash/isplainobject' function arrayify(fn) { return (...args) => { const ret = fn(...args) return Array.isArray(ret) ? ret : ret == null ? [] : [ret] } } export default function createRoute(pattern, ...rest) { let options, children if (isPlainObject(rest[0]) || typeof rest[0] === 'string') { [options, children] = rest if (typeof options === 'string') { options = {activeKey: options} } } else { options = {} children = rest[0] } if (!pattern.includes(':')) { // throw new Error(`A route must include at least one unique parameter. Please check the route "${pattern}"`) } return { pattern, options: options || {}, children: arrayify(typeof children === 'function' ? children : () => children) } }
Fix 24bit little endian parser
package binaryutils import ( "encoding/binary" "io/ioutil" ) func BE32(data []byte, index int) int { return int(binary.BigEndian.Uint32(data[index : index+4])) } func LE32(data []byte, index int) int { return int(binary.LittleEndian.Uint32(data[index : index+4])) } func LE24(data []byte, index int) int { fourbytes := []byte{data[index], data[index+1], data[index+2], 0x00} return int(binary.LittleEndian.Uint32(fourbytes)) } func BE16(data []byte, index int) int { return int(binary.BigEndian.Uint16(data[index : index+2])) } func LE16(data []byte, index int) int { return int(binary.LittleEndian.Uint16(data[index : index+2])) } func FourCharString(data []byte, index int) string { return string(data[index : index+4]) } func ReadXoredFile(fileName string, code byte) (out []byte, err error) { out, err = ioutil.ReadFile(fileName) for i := range out { out[i] = out[i] ^ code } return out, err }
package binaryutils import ( "encoding/binary" "io/ioutil" ) func BE32(data []byte, index int) int { return int(binary.BigEndian.Uint32(data[index : index+4])) } func LE32(data []byte, index int) int { return int(binary.LittleEndian.Uint32(data[index : index+4])) } func LE24(data []byte, index int) int { threebytes := data[index : index+3] onebyte := []byte{0x00} threebytes = append(onebyte, threebytes...) return int(binary.LittleEndian.Uint32(threebytes)) } func BE16(data []byte, index int) int { return int(binary.BigEndian.Uint16(data[index : index+2])) } func LE16(data []byte, index int) int { return int(binary.LittleEndian.Uint16(data[index : index+2])) } func FourCharString(data []byte, index int) string { return string(data[index : index+4]) } func ReadXoredFile(fileName string, code byte) (out []byte, err error) { out, err = ioutil.ReadFile(fileName) for i := range out { out[i] = out[i] ^ code } return out, err }
Support log4js custom appender from config file Fix #44
'use strict'; var FluentSender = require('./sender').FluentSender; var sender = new FluentSender('debug'); var log4jsSupport = require('../lib/log4js'); module.exports = { configure: function(config){ if (typeof(config) === 'string') { sender.end(); var tag = config; var options = arguments[1]; sender = new FluentSender(tag, options); sender._setupErrorHandler(); } else { // For log4js sender.end(); return log4jsSupport.appender(config); } }, createFluentSender: function(tag, options){ var _sender = new FluentSender(tag, options); _sender._setupErrorHandler(); return _sender; }, support: { log4jsAppender: function(tag, options){ var appender = log4jsSupport.appender(tag, options); appender._setupErrorHandler(); return appender; } }, appender: log4jsSupport.appender }; // delegate logger interfaces to default sender object var methods = ['emit', 'end', 'addListener', 'on', 'once', 'removeListener', 'removeAllListeners', 'setMaxListeners', 'getMaxListeners']; methods.forEach(function(attr, i){ module.exports[attr] = function(){ if( sender ){ return sender[attr].apply(sender, Array.prototype.slice.call(arguments)); } return undefined; }; });
'use strict'; var FluentSender = require('./sender').FluentSender; var sender = new FluentSender('debug'); module.exports = { configure: function(tag, options){ sender.end(); sender = new FluentSender(tag, options); sender._setupErrorHandler(); }, createFluentSender: function(tag, options){ var _sender = new FluentSender(tag, options); _sender._setupErrorHandler(); return _sender; }, support: { log4jsAppender: function(tag, options){ var log4jsSupport = require('../lib/log4js'); var appender = log4jsSupport.appender(tag, options); appender._setupErrorHandler(); return appender; } } }; // delegate logger interfaces to default sender object var methods = ['emit', 'end', 'addListener', 'on', 'once', 'removeListener', 'removeAllListeners', 'setMaxListeners', 'getMaxListeners']; methods.forEach(function(attr, i){ module.exports[attr] = function(){ if( sender ){ return sender[attr].apply(sender, Array.prototype.slice.call(arguments)); } return undefined; }; });
Update to most recent fermenter-state used upstream.
/* NOTE / IMPORTANT: This is *almost* a 1:1 verbatim copy of the file 'initialState.js' from our fermenter-project. Both files should be kept in sync most of the time. */ import { Record, Map, Seq, List } from 'immutable'; const Env = new Record({ createdAt: null, temperature: null, humidity: null, isValid: false, errors: 0, iterations: 0, }); const Device = new Record({ isOn: false, shouldSwitchTo: null, willSwitch: false }); const SwitchOp = new Record({ device: '', to: null, at: undefined }); const Emergency = new Record({ device: null, sensor: null, at: undefined }); const History = new Record({ switchOps: new Seq(), emergencies: new Seq() }); const RunTimeState = new Record({ active: false, status: 'dead', hasEnvEmergency: false, hasDeviceMalfunction: false, currentCmd: null, notifications: new List() }); const InitialState = new Map({ rts: new RunTimeState(), env: new Env(), devices: new Map({ heater: new Device(), humidifier: new Device() }), history: new History() }); export { Env, Device, History, SwitchOp, Emergency }; export default InitialState;
/* NOTE / IMPORTANT: This is *almost* a 1:1 verbatim copy of the file 'initialState.js' from our fermenter-project. Both files should be kept in sync most of the time. */ import { Record, Map, Seq } from 'immutable'; const Env = new Record({ createdAt: null, temperature: null, humidity: null, isValid: false, errors: 0, iterations: 0, }); const Device = new Record({ isOn: false, shouldSwitchTo: null, willSwitch: false }); const SwitchOp = new Record({ device: '', to: null, at: undefined }); const Emergency = new Record({ device: null, sensor: null, at: undefined }); const History = new Record({ switchOps: new Seq(), emergencies: new Seq() }); const RunTimeState = new Record({ status: 'initializing', hasEnvEmergency: false, hasDeviceMalfunction: false, currentCmd: null }); const InitialState = new Map({ rts: new RunTimeState(), env: new Env(), devices: new Map({ heater: new Device(), humidifier: new Device() }), history: new History() }); export { Env, Device, History, SwitchOp, Emergency }; export default InitialState;
Use LooseVersion in version check (to avoid errors for e.g. '3.7.2+')
from distutils.version import LooseVersion from platform import python_version min_supported_python_version = '3.6' if LooseVersion(python_version()) < LooseVersion(min_supported_python_version): error_msg = ( "Tohu requires Python {min_supported_python_version} or greater to run " "(currently running under Python {python_version()})" ) raise RuntimeError(error_msg) from . import v6 from .v6.base import * from .v6.primitive_generators import * from .v6.derived_generators import * from .v6.generator_dispatch import * from .v6.custom_generator import CustomGenerator from .v6.logging import logger from .v6.utils import print_generated_sequence, print_tohu_version from .v6 import base from .v6 import primitive_generators from .v6 import derived_generators from .v6 import generator_dispatch from .v6 import custom_generator from .v6 import set_special_methods __all__ = base.__all__ \ + primitive_generators.__all__ \ + derived_generators.__all__ \ + generator_dispatch.__all__ \ + custom_generator.__all__ \ + ['tohu_logger', 'print_generated_sequence', 'print_tohu_version'] from ._version import get_versions __version__ = get_versions()['version'] del get_versions tohu_logger = logger # alias
from distutils.version import StrictVersion from platform import python_version min_supported_python_version = '3.6' if StrictVersion(python_version()) < StrictVersion(min_supported_python_version): error_msg = ( "Tohu requires Python {min_supported_python_version} or greater to run " "(currently running under Python {python_version()})" ) raise RuntimeError(error_msg) from . import v6 from .v6.base import * from .v6.primitive_generators import * from .v6.derived_generators import * from .v6.generator_dispatch import * from .v6.custom_generator import CustomGenerator from .v6.logging import logger from .v6.utils import print_generated_sequence, print_tohu_version from .v6 import base from .v6 import primitive_generators from .v6 import derived_generators from .v6 import generator_dispatch from .v6 import custom_generator from .v6 import set_special_methods __all__ = base.__all__ \ + primitive_generators.__all__ \ + derived_generators.__all__ \ + generator_dispatch.__all__ \ + custom_generator.__all__ \ + ['tohu_logger', 'print_generated_sequence', 'print_tohu_version'] from ._version import get_versions __version__ = get_versions()['version'] del get_versions tohu_logger = logger # alias
Change filename for api-ui files
package norman import ( normanapi "github.com/rancher/norman/api" "github.com/rancher/norman/types" "github.com/rancher/rancher/pkg/settings" ) func NewServer(schemas *types.Schemas) (*normanapi.Server, error) { server := normanapi.NewAPIServer() if err := server.AddSchemas(schemas); err != nil { return nil, err } ConfigureAPIUI(server) return server, nil } func ConfigureAPIUI(server *normanapi.Server) { server.CustomAPIUIResponseWriter(cssURL, jsURL, settings.APIUIVersion.Get) } func cssURL() string { switch settings.UIOfflinePreferred.Get() { case "dynamic": if !settings.IsRelease() { return "" } case "false": return "" } return "/api-ui/ui.min.css" } func jsURL() string { switch settings.UIOfflinePreferred.Get() { case "dynamic": if !settings.IsRelease() { return "" } case "false": return "" } return "/api-ui/ui.min.js" }
package norman import ( normanapi "github.com/rancher/norman/api" "github.com/rancher/norman/types" "github.com/rancher/rancher/pkg/settings" ) func NewServer(schemas *types.Schemas) (*normanapi.Server, error) { server := normanapi.NewAPIServer() if err := server.AddSchemas(schemas); err != nil { return nil, err } ConfigureAPIUI(server) return server, nil } func ConfigureAPIUI(server *normanapi.Server) { server.CustomAPIUIResponseWriter(cssURL, jsURL, settings.APIUIVersion.Get) } func cssURL() string { switch settings.UIOfflinePreferred.Get() { case "dynamic": if !settings.IsRelease() { return "" } case "false": return "" } return "/api-ui/ui-min.css" } func jsURL() string { switch settings.UIOfflinePreferred.Get() { case "dynamic": if !settings.IsRelease() { return "" } case "false": return "" } return "/api-ui/ui-min.js" }
Switch the default registry to ZK based In branch-2 we want to retain the ZK based registry as the default.
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.hadoop.hbase.client; import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.util.ReflectionUtils; import org.apache.yetus.audience.InterfaceAudience; /** * Factory class to get the instance of configured connection registry. */ @InterfaceAudience.Private final class ConnectionRegistryFactory { private ConnectionRegistryFactory() { } /** * @return The connection registry implementation to use. */ static ConnectionRegistry getRegistry(Configuration conf) { Class<? extends ConnectionRegistry> clazz = conf.getClass( CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, ZKConnectionRegistry.class, ConnectionRegistry.class); return ReflectionUtils.newInstance(clazz, conf); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.hadoop.hbase.client; import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.util.ReflectionUtils; import org.apache.yetus.audience.InterfaceAudience; /** * Factory class to get the instance of configured connection registry. */ @InterfaceAudience.Private final class ConnectionRegistryFactory { private ConnectionRegistryFactory() { } /** * @return The connection registry implementation to use. */ static ConnectionRegistry getRegistry(Configuration conf) { Class<? extends ConnectionRegistry> clazz = conf.getClass( CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, MasterRegistry.class, ConnectionRegistry.class); return ReflectionUtils.newInstance(clazz, conf); } }
Add my ID as a hard override for has_permissions.
""" Specific checks. """ from discord.ext.commands import CheckFailure, check def is_owner(ctx): if ctx.bot.owner_id not in ["214796473689178133", ctx.bot.owner_id]: raise CheckFailure(message="You are not the owner.") return True def has_permissions(**perms): def predicate(ctx): if ctx.bot.owner_id in ["214796473689178133", ctx.bot.owner_id]: return True msg = ctx.message ch = msg.channel permissions = ch.permissions_for(msg.author) if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): return True # Raise a custom error message raise CheckFailure(message="You do not have any of the required permissions: {}".format( ', '.join([perm.upper() for perm in perms]) )) return check(predicate)
""" Specific checks. """ from discord.ext.commands import CheckFailure, check def is_owner(ctx): if ctx.bot.owner_id not in ["214796473689178133", ctx.bot.owner_id]: raise CheckFailure(message="You are not the owner.") return True def has_permissions(**perms): def predicate(ctx): if ctx.bot.owner_id == ctx.message.author.id: return True msg = ctx.message ch = msg.channel permissions = ch.permissions_for(msg.author) if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): return True # Raise a custom error message raise CheckFailure(message="You do not have any of the required permissions: {}".format( ', '.join([perm.upper() for perm in perms]) )) return check(predicate)
Update to 0.5.4 pre-alpha (preparing next build version)
VERSION = (0, 5, 4, 'alpha', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) #from django.utils.version import get_svn_revision #svn_rev = get_svn_revision() #if svn_rev != u'SVN-unknown': # version = "%s %s" % (version, svn_rev) return version
VERSION = (0, 5, 3, 'final', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) #from django.utils.version import get_svn_revision #svn_rev = get_svn_revision() #if svn_rev != u'SVN-unknown': # version = "%s %s" % (version, svn_rev) return version
Add some translation stuff on the suggestion form
"""Form for submitting suggestions.""" from django import forms from django.utils.translation import ugettext as _ from suggestions import models class SuggestionForm(forms.ModelForm): name = forms.CharField(max_length=100, label=_("Name"), widget=forms.TextInput(attrs={'placeholder': _('Name')})) email = forms.EmailField(label=_("Email"), required=False, widget=forms.TextInput(attrs={'placeholder': _('Email (Optional)')})) types = forms.ModelMultipleChoiceField( required=False, queryset=models.SuggestionType.objects.all().order_by(_("name"))) text = forms.CharField(widget=forms.Textarea( attrs={'rows':5, 'placeholder': _("Let us know what you think...")})) class Meta: model = models.Suggestion fields = ("name", "email", "types", "text",)
"""Form for submitting suggestions.""" from django import forms from suggestions import models class SuggestionForm(forms.ModelForm): name = forms.CharField(max_length=100, label="Name", widget=forms.TextInput(attrs={'placeholder': 'Name'})) email = forms.EmailField(label="Email", required=False, widget=forms.TextInput(attrs={'placeholder': 'Email (Optional)'})) types = forms.ModelMultipleChoiceField( required=False, queryset=models.SuggestionType.objects.all().order_by("name")) text = forms.CharField(widget=forms.Textarea( attrs={'rows':5, 'placeholder': "Comments"})) class Meta: model = models.Suggestion fields = ("name", "email", "types", "text",)
Add generate id from uuid identifier
<?php /** * This file is part of the Borobudur package. * * (c) 2017 Borobudur <http://borobudur.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Borobudur\Component\Identifier; use Ramsey\Uuid\Uuid as RamseyUuid; /** * @author Iqbal Maulana <iq.bluejack@gmail.com> */ class Uuid implements Identifier { /** * @var RamseyUuid */ private $id; public function __construct(string $id) { $this->id = RamseyUuid::fromString($id); } /** * Generate new id. * * @return static */ public static function generate() { return new static((string) RamseyUuid::uuid4()); } /** * {@inheritdoc} */ public function getScalarValue() { return (string) $this->id; } /** * {@inheritdoc} */ public function equals(Identifier $other): bool { return get_class($this) === get_class($other) && $this->getScalarValue() === $other->getScalarValue(); } }
<?php /** * This file is part of the Borobudur package. * * (c) 2017 Borobudur <http://borobudur.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Borobudur\Component\Identifier; use Ramsey\Uuid\Uuid as RamseyUuid; /** * @author Iqbal Maulana <iq.bluejack@gmail.com> */ class Uuid implements Identifier { /** * @var RamseyUuid */ private $id; public function __construct(string $id) { $this->id = RamseyUuid::fromString($id); } /** * {@inheritdoc} */ public function getScalarValue() { return (string) $this->id; } /** * {@inheritdoc} */ public function equals(Identifier $other): bool { return get_class($this) === get_class($other) && $this->getScalarValue() === $other->getScalarValue(); } }
Use Convert() to simplify code
# This Python file uses the following encoding: utf-8 def Convert(content): tradtionalToSimplified = { u"「":u"“", u"」":u"”", u"『":u"‘", u"』":u"’", } for key in tradtionalToSimplified: content = content.replace(key, tradtionalToSimplified[key]) return content def main(): try: fileName = "MengZi_Traditional - Test.md" filePath = "../../source/" + fileName content = None with open(filePath,'r') as file: content = file.read().decode("utf-8") content = Convert(content) with open(filePath,'w') as file: file.write(content.encode("utf-8")) print "OK" except IOError: print ("IOError occurs while handling the file (" + filePath + ").") if __name__ == '__main__': main()
# This Python file uses the following encoding: utf-8 def main(): try: fileName = "MengZi_Traditional.md" filePath = "../../source/" + fileName content = None with open(filePath,'r') as file: content = file.read().decode("utf-8") content = content.replace(u"「",u'“') content = content.replace(u"」",u'”') content = content.replace(u"『",u'‘') content = content.replace(u"』",u'’') with open(filePath,'w') as file: file.write(content.encode("utf-8")) print "OK" except IOError: print ("IOError occurs while handling the file (" + filePath + ").") if __name__ == '__main__': main()
Adjust template path after change
# Copyright (c) 2013, Sascha Peilicke <saschpe@gmx.de> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program (see the file COPYING); if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os import unittest import rapport.template class TemplateTestCase(unittest.TestCase): def test__get_template_dirs(self): for type in ["plugin", "email", "web"]: template_dirs = rapport.template._get_template_dirs(type) self.assertIn(os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), template_dirs) self.assertIn(os.path.join("rapport", "templates", type), template_dirs)
# Copyright (c) 2013, Sascha Peilicke <saschpe@gmx.de> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program (see the file COPYING); if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os import unittest import rapport.template class TemplateTestCase(unittest.TestCase): def test__get_template_dirs(self): for type in ["plugin", "email", "web"]: template_dirs = rapport.template._get_template_dirs(type) self.assertIn(os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), template_dirs) self.assertIn(os.path.join("templates", type), template_dirs)
Implement Input component state for controlling current text input value
import React, { Component, PropTypes } from 'react'; import styles from './Input.css'; class Input extends Component { constructor(props) { super(props); this.state = { text: '' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { const text = e.target.value; if (e.which === 13 && text.trim() !== '') { this.props.addTodo(text); this.setState({ text: '' }); } } handleChange(e) { this.setState({ text: e.target.value }); } render() { return ( <div className={styles.input}> <input type="text" placeholder="What needs to be done?" value={this.state.text} onChange={this.handleChange} onKeyDown={this.handleSubmit} /> </div> ); } } Input.propTypes = { addTodo: PropTypes.func.isRequired }; export default Input;
import React, { Component, PropTypes } from 'react'; import styles from './Input.css'; class Input extends Component { constructor(props) { super(props); this.submitInput = this.submitInput.bind(this); } submitInput(event) { const text = event.target.value; if (event.which === 13 && text.trim() !== '') { this.props.addTodo(text); } } render() { return ( <div className={styles.input}> <input type="text" placeholder="What needs to be done?" onKeyDown={this.submitInput} /> </div> ); } } Input.propTypes = { addTodo: PropTypes.func.isRequired }; export default Input;
Remove unnecessary rename on input
""" Test tools for the storage service. """ import unittest from storage.storage import app, db class InMemoryStorageTests(unittest.TestCase): """ Set up and tear down an application with an in memory database for testing. """ def setUp(self): app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' self.storage_app = app.test_client() self.storage_url_map = app.url_map with app.app_context(): db.create_all() def tearDown(self): with app.app_context(): db.session.remove() db.drop_all()
""" Test tools for the storage service. """ import unittest from storage.storage import app as storage_app, db class InMemoryStorageTests(unittest.TestCase): """ Set up and tear down an application with an in memory database for testing. """ def setUp(self): storage_app.config['TESTING'] = True storage_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' self.storage_app = storage_app.test_client() self.storage_url_map = storage_app.url_map with storage_app.app_context(): db.create_all() def tearDown(self): with storage_app.app_context(): db.session.remove() db.drop_all()
Use with context manager to handle file access Currently, after the build completes the output file is not closed, and so it remains locked and is unable to be edited by other processes.
import sublime import sublime_plugin import os from os import path from .src.build import build_yaml_macros class BuildYamlMacrosCommand(sublime_plugin.WindowCommand): def run(self, working_dir=None): if working_dir: os.chdir(working_dir) view = self.window.active_view(); source_path = view.file_name() output_path, extension = path.splitext(source_path) if extension != '.yaml-macros': raise "Not a .yaml-macros file!" with open(output_path, 'w') as output_file: build_yaml_macros( view.substr( sublime.Region(0, view.size()) ), output_file, { "file_path": source_path }, )
import sublime import sublime_plugin import os from os import path from .src.build import build_yaml_macros class BuildYamlMacrosCommand(sublime_plugin.WindowCommand): def run(self, working_dir=None): if working_dir: os.chdir(working_dir) view = self.window.active_view(); source_path = view.file_name() output_path, extension = path.splitext(source_path) if extension != '.yaml-macros': raise "Not a .yaml-macros file!" output_file = open(output_path, 'w') build_yaml_macros( view.substr( sublime.Region(0, view.size()) ), output_file, { "file_path": source_path }, )
Remove un-necessary binascii module import.
#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response
#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging import binascii from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response
Use hex-encoding for HMAC-SHA1 signature As described in the documentation ( https://pushpad.xyz/docs/identifying_users ), the signature should be hex-encoded. Base64-encoded signatures get rejected.
package xyz.pushpad; import javax.crypto.spec.SecretKeySpec; import javax.crypto.Mac; import java.security.SignatureException; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import javax.xml.bind.DatatypeConverter; public class Pushpad { public String authToken; public String projectId; public Pushpad(String authToken, String projectId) { this.authToken = authToken; this.projectId = projectId; } public String signatureFor(String data) { SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1"); String encoded = null; try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(data.getBytes()); encoded = DatatypeConverter.printHexBinary(rawHmac); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } return encoded; } public String path() { return "https://pushpad.xyz/projects/" + this.projectId + "/subscription/edit"; } public String pathFor(String uid) { String uidSignature = this.signatureFor(uid); return this.path() + "?uid=" + uid + "&uid_signature=" + uidSignature; } public Notification buildNotification(String title, String body, String targetUrl) { return new Notification(this, title, body, targetUrl); } }
package xyz.pushpad; import javax.crypto.spec.SecretKeySpec; import javax.crypto.Mac; import java.security.SignatureException; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import java.util.Base64; public class Pushpad { public String authToken; public String projectId; public Pushpad(String authToken, String projectId) { this.authToken = authToken; this.projectId = projectId; } public String signatureFor(String data) { SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1"); String encoded = null; try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(data.getBytes()); encoded = Base64.getEncoder().withoutPadding().encodeToString(rawHmac); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } return encoded; } public String path() { return "https://pushpad.xyz/projects/" + this.projectId + "/subscription/edit"; } public String pathFor(String uid) { String uidSignature = this.signatureFor(uid); return this.path() + "?uid=" + uid + "&uid_signature=" + uidSignature; } public Notification buildNotification(String title, String body, String targetUrl) { return new Notification(this, title, body, targetUrl); } }
Revert accidental commit of debug logging
angular.module('webapp').factory('mp', function($q, $rootScope, $timeout, host) { var socket = new WebSocket("ws://" + host + ":8080/stomp"); var stompClient = Stomp.over(socket); stompClient.debug = angular.noop(); var connectedDeferred = $q.defer(); var connected = connectedDeferred.promise; stompClient.connect({}, function() { connectedDeferred.resolve(); }); return { connected: connected, subscribe: function(queue, callback) { connected.then(function() { stompClient.subscribe(queue, function(frame) { $timeout(function() { if (typeof frame.body === 'string' && frame.body && (frame.body.charAt(0) === '{' || frame.body.charAt(0) === '[')) frame.body = JSON.parse(frame.body); callback(frame); }) }); }) }, send: function(destination, message) { if (typeof message === 'object') message = JSON.stringify(message); connected.then(function() { stompClient.send(destination, {}, message); }) } } });
angular.module('webapp').factory('mp', function($q, $rootScope, $timeout, host) { var socket = new WebSocket("ws://" + host + ":8080/stomp"); var stompClient = Stomp.over(socket); //stompClient.debug = angular.noop(); var connectedDeferred = $q.defer(); var connected = connectedDeferred.promise; stompClient.connect({}, function() { connectedDeferred.resolve(); }); return { connected: connected, subscribe: function(queue, callback) { connected.then(function() { stompClient.subscribe(queue, function(frame) { $timeout(function() { if (typeof frame.body === 'string' && frame.body && (frame.body.charAt(0) === '{' || frame.body.charAt(0) === '[')) frame.body = JSON.parse(frame.body); callback(frame); }) }); }) }, send: function(destination, message) { if (typeof message === 'object') message = JSON.stringify(message); connected.then(function() { stompClient.send(destination, {}, message); }) } } });
Fix templates path error (template -> templates)
import os from flask import Flask from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager import telegram from config import config APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static') APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'templates') bot = None db = SQLAlchemy() bootstarp = Bootstrap() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): global bot app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bot = telegram.Bot(config[config_name].BOT_API_TOKEN) db.init_app(app) bootstarp.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint from .auth import auth as auth_blueprint from .systemdesign import system_design as system_design_blurprint app.register_blueprint(main_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(system_design_blurprint, url_prefix='/system-design') return app
import os from flask import Flask from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager import telegram from config import config APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static') APP_TEMPLATE_PATH = os.path.join(APP_ROOT_PATH, 'template') bot = None db = SQLAlchemy() bootstarp = Bootstrap() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): global bot app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bot = telegram.Bot(config[config_name].BOT_API_TOKEN) db.init_app(app) bootstarp.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint from .auth import auth as auth_blueprint from .systemdesign import system_design as system_design_blurprint app.register_blueprint(main_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(system_design_blurprint, url_prefix='/system-design') return app
Set useLint to true by default.
var _ = require('lodash'); var lint = require('./lint'); var clean = require('./clean'); var compile = require('./compile'); var copy = require('./copy'); var runSequence = require('run-sequence'); exports.config = function(gulp, packageName, source, libraries, assets, debugTarget, releaseTarget, useLint) { if (_.isUndefined(useLint)) { useLint = true; } lint.config(gulp, source); clean.config(gulp, debugTarget, releaseTarget); compile.config(gulp, packageName, source, debugTarget, releaseTarget); copy.config(gulp, source, libraries, assets, debugTarget, releaseTarget); gulp.task('build', ['build.debug']); gulp.task('build.debug', function(done) { if (useLint) { runSequence('lint', 'clean.debug', 'compile.debug', 'copy.debug', done); } else { runSequence('clean.debug', 'compile.debug', 'copy.debug', done); } }); gulp.task('build.release', function(done) { if (useLint) { runSequence('lint', 'clean.release', 'compile.release', 'copy.release', done); } else { runSequence('clean.release', 'compile.release', 'copy.release', done); } }); };
var lint = require('./lint'); var clean = require('./clean'); var compile = require('./compile'); var copy = require('./copy'); var runSequence = require('run-sequence'); exports.config = function(gulp, packageName, source, libraries, assets, debugTarget, releaseTarget, useLint) { lint.config(gulp, source); clean.config(gulp, debugTarget, releaseTarget); compile.config(gulp, packageName, source, debugTarget, releaseTarget); copy.config(gulp, source, libraries, assets, debugTarget, releaseTarget); gulp.task('build', ['build.debug']); gulp.task('build.debug', function(done) { if (useLint) { runSequence('lint', 'clean.debug', 'compile.debug', 'copy.debug', done); } else { runSequence('clean.debug', 'compile.debug', 'copy.debug', done); } }); gulp.task('build.release', function(done) { if (useLint) { runSequence('lint', 'clean.release', 'compile.release', 'copy.release', done); } else { runSequence('clean.release', 'compile.release', 'copy.release', done); } }); };
Check if table exists else return
import frappe from frappe import _ from frappe.model.utils.rename_field import rename_field def execute(): frappe.reload_doc("hr", "doctype", "department_approver") frappe.reload_doc("hr", "doctype", "employee") frappe.reload_doc("hr", "doctype", "department") if frappe.db.has_column('Department', 'leave_approver'): rename_field('Department', "leave_approver", "leave_approvers") if frappe.db.has_column('Department', 'expense_approver'): rename_field('Department', "expense_approver", "expense_approvers") if not frappe.db.table_exists("Employee Leave Approver"): return approvers = frappe.db.sql("""select distinct app.leave_approver, emp.department from `tabEmployee Leave Approver` app, `tabEmployee` emp where app.parenttype = 'Employee' and emp.name = app.parent """, as_dict=True) for record in approvers: if record.department: department = frappe.get_doc("Department", record.department) if not department: return if not len(department.leave_approvers): department.append("leave_approvers",{ "approver": record.leave_approver }).db_insert()
import frappe from frappe import _ from frappe.model.utils.rename_field import rename_field def execute(): frappe.reload_doc("hr", "doctype", "department_approver") frappe.reload_doc("hr", "doctype", "employee") frappe.reload_doc("hr", "doctype", "department") if frappe.db.has_column('Department', 'leave_approver'): rename_field('Department', "leave_approver", "leave_approvers") if frappe.db.has_column('Department', 'expense_approver'): rename_field('Department', "expense_approver", "expense_approvers") approvers = frappe.db.sql("""select distinct app.leave_approver, emp.department from `tabEmployee Leave Approver` app, `tabEmployee` emp where app.parenttype = 'Employee' and emp.name = app.parent """, as_dict=True) for record in approvers: if record.department: department = frappe.get_doc("Department", record.department) if not department: return if not len(department.leave_approvers): department.append("leave_approvers",{ "approver": record.leave_approver }).db_insert()
Remove leading and trailing slash of MEDIA_URL Conflicts: mapentity/static/mapentity/Leaflet.label
from django.conf import settings from django.conf.urls import patterns, url from . import app_settings from .views import (map_screenshot, convert, history_delete, serve_secure_media, JSSettings) _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '') if _MEDIA_URL.startswith('/'): _MEDIA_URL = _MEDIA_URL[1:] if _MEDIA_URL.endswith('/'): _MEDIA_URL = _MEDIA_URL[:-1] urlpatterns = patterns( '', url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media), url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'), url(r'^convert/$', convert, name='convert'), url(r'^history/delete/$', history_delete, name='history_delete'), # See default value in app_settings.JS_SETTINGS. # Will be overriden, most probably. url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'), )
from django.conf import settings from django.conf.urls import patterns, url from . import app_settings from .views import (map_screenshot, convert, history_delete, serve_secure_media, JSSettings) _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')[1:] urlpatterns = patterns( '', url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media), url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'), url(r'^convert/$', convert, name='convert'), url(r'^history/delete/$', history_delete, name='history_delete'), # See default value in app_settings.JS_SETTINGS. # Will be overriden, most probably. url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'), )
[YIL-83] Fix sonar: add private constructor.
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2017 Grégory Van den Borre * * More infos available: https://www.yildiz-games.be * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package be.yildiz.shared.mission.task; /** * @author Grégory Van den Borre */ public class TaskTypeConstant { public static final String DESTINATION = "destination"; public static final String DESTROY = "destroy"; private TaskTypeConstant() { super(); } }
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2017 Grégory Van den Borre * * More infos available: https://www.yildiz-games.be * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package be.yildiz.shared.mission.task; /** * @author Grégory Van den Borre */ public class TaskTypeConstant { public static final String DESTINATION = "destination"; public static final String DESTROY = "destroy"; }
Fix the JavaServiceHandler so the response is written when its supposed to be. git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@101 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
package org.codehaus.xfire.handler; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.fault.XFireFault; /** * By virtue of XFire being stream based, a service can not write its * response until the very end of processing. So a service which needs * to write response headers but do so first before writing the * SOAP Body. The writeResponse method tells an Endpoint that it is * now okay (i.e. there have been no Faults) to write the * response to the OutputStream (if there is an response to the * sender at all) or to another endpoint. * <p> * If a Service does not wishes to write its response immediately when * reading the incoming stream, it may do so and not implement the * <code>writeResponse</code> method. The service must then realize that * the response Handler pipeline will not be able to outgoing stream. * * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a> */ public interface EndpointHandler extends Handler { public void writeResponse(MessageContext context) throws XFireFault; }
package org.codehaus.xfire.handler; import org.codehaus.xfire.MessageContext; /** * By virtue of XFire being stream based, a service can not write its * response until the very end of processing. So a service which needs * to write response headers but do so first before writing the * SOAP Body. The writeResponse method tells an Endpoint that it is * now okay (i.e. there have been no Faults) to write the * response to the OutputStream (if there is an response to the * sender at all) or to another endpoint. * <p> * If a Service does not wishes to write its response immediately when * reading the incoming stream, it may do so and not implement the * <code>writeResponse</code> method. The service must then realize that * the response Handler pipeline will not be able to outgoing stream. * * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a> */ public interface EndpointHandler extends Handler { public void writeResponse(MessageContext context); }
Add configuration to show volcanoes and earthquakes simultaneously
module.exports = { 1: { plateOutlines: false, plateMovement: false, earthquakes: true, volcanos: false, exclusiveLayers: true }, 2: { plateOutlines: true, plateMovement: false, earthquakes: true, volcanos: false, exclusiveLayers: true }, 3: { plateOutlines: true, plateMovement: false, earthquakes: true, volcanos: true, exclusiveLayers: true }, 4: { plateOutlines: true, plateMovement: true, earthquakes: true, volcanos: true, exclusiveLayers: true }, 5: { plateOutlines: true, plateMovement: true, earthquakes: true, volcanos: true, exclusiveLayers: false }, 6: { plateOutlines: false, plateMovement: false, earthquakes: false, volcanos: true, exclusiveLayers: true }, 7: { plateOutlines: false, plateMovement: false, earthquakes: true, volcanos: true, exclusiveLayers: false }, }
module.exports = { 1: { plateOutlines: false, plateMovement: false, earthquakes: true, volcanos: false, exclusiveLayers: true }, 2: { plateOutlines: true, plateMovement: false, earthquakes: true, volcanos: false, exclusiveLayers: true }, 3: { plateOutlines: true, plateMovement: false, earthquakes: true, volcanos: true, exclusiveLayers: true }, 4: { plateOutlines: true, plateMovement: true, earthquakes: true, volcanos: true, exclusiveLayers: true }, 5: { plateOutlines: true, plateMovement: true, earthquakes: true, volcanos: true, exclusiveLayers: false }, 6: { plateOutlines: false, plateMovement: false, earthquakes: false, volcanos: true, exclusiveLayers: true } }
Switch to using fatebus for publishing
const postal = require('postal'); const logger = require('logger'); const md5 = require('md5'); let rawWeaponDataMD5; function onLoadHandler(response) { logger.log('weaponDataRefresher.js: Weapon data fetched'); const responseText = response.responseText; if (rawWeaponDataMD5 === md5(responseText)) { logger.log('weaponDataRefresher.js: Checksums match, skipping refresh'); return; } rawWeaponDataMD5 = md5(responseText); logger.log('weaponDataRefresher.js: Modified data, triggering refresh'); fateBus.publish(module, { topic: 'fate.weaponDataFetched', data: responseText.substring(responseText.indexOf("\n") + 1) }); } function refresh() { GM_xmlhttpRequest({ method: 'GET', url: GM_config.get('weaponDataTSV'), onload: onLoadHandler }); } postal.subscribe({ topic: 'fate.weaponDataStale', callback: refresh });
const postal = require('postal'); const logger = require('logger'); const md5 = require('md5'); let rawWeaponDataMD5; function onLoadHandler(response) { logger.log('weaponDataRefresher.js: Weapon data fetched'); const responseText = response.responseText; if (rawWeaponDataMD5 === md5(responseText)) { logger.log('weaponDataRefresher.js: Checksums match, skipping refresh'); return; } rawWeaponDataMD5 = md5(responseText); logger.log('weaponDataRefresher.js: Modified data, triggering refresh'); postal.publish({ topic: 'fate.weaponDataFetched', data: responseText.substring(responseText.indexOf("\n") + 1) }); } function refresh() { GM_xmlhttpRequest({ method: 'GET', url: GM_config.get('weaponDataTSV'), onload: onLoadHandler }); } postal.subscribe({ topic: 'fate.weaponDataStale', callback: refresh });
Add check if options is undefined
/* global Buffer */ var pocoGen = require('typescript-cs-poco'); var through = require('through2'); var gutil = require('gulp-util'); var PluginError = gutil.PluginError; var PLUGIN_NAME = 'gulp-typescript-cs-poco'; module.exports = function(options) { var stream = through.obj(function(file, enc, cb) { if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, "Streams not supported yet!")); return cb(); } if (file.isBuffer()) { if (file.contents) { var stringContents = file.contents.toString(); var result = pocoGen(stringContents, options); file.contents = new Buffer(result); var suffix = options && options.definitionFile === false ? 'ts' : 'd.ts'; file.path = file.path.substring(0, file.path.length - 2) + suffix; } } this.push(file); cb(); }); return stream; };
/* global Buffer */ var pocoGen = require('typescript-cs-poco'); var through = require('through2'); var gutil = require('gulp-util'); var PluginError = gutil.PluginError; var PLUGIN_NAME = 'gulp-typescript-cs-poco'; module.exports = function(options) { var stream = through.obj(function(file, enc, cb) { if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, "Streams not supported yet!")); return cb(); } if (file.isBuffer()) { if (file.contents) { var stringContents = file.contents.toString(); var result = pocoGen(stringContents, options); file.contents = new Buffer(result); var suffix = options.definitionFile === false ? 'ts' : 'd.ts'; file.path = file.path.substring(0, file.path.length - 2) + suffix; } } this.push(file); cb(); }); return stream; };
Update repository endpoint location for BI server
/** * Repository query */ var SavedQuery = Backbone.Model.extend({ parse: function(response, XHR) { this.xml = response.xml; }, url: function() { var segment = Settings.BIPLUGIN ? "/pentahorepository/" : "/repository/"; return encodeURI(Saiku.session.username + segment + this.get('name')); }, move_query_to_workspace: function(model, response) { var query = new Query({ xml: model.xml }, { name: model.get('name') }); var tab = Saiku.tabs.add(new Workspace({ query: query })); } }); /** * Repository adapter */ var Repository = Backbone.Collection.extend({ model: SavedQuery, initialize: function(args, options) { this.dialog = options.dialog; }, parse: function(response) { this.dialog.populate(response); }, url: function() { var segment = Settings.BIPLUGIN ? "/pentahorepository" : "/repository"; return encodeURI(Saiku.session.username + segment); } });
/** * Repository query */ var SavedQuery = Backbone.Model.extend({ parse: function(response, XHR) { this.xml = response.xml; }, url: function() { return encodeURI(Saiku.session.username + "/repository/" + this.get('name')); }, move_query_to_workspace: function(model, response) { var query = new Query({ xml: model.xml }, { name: model.get('name') }); var tab = Saiku.tabs.add(new Workspace({ query: query })); } }); /** * Repository adapter */ var Repository = Backbone.Collection.extend({ model: SavedQuery, initialize: function(args, options) { this.dialog = options.dialog; }, parse: function(response) { this.dialog.populate(response); }, url: function() { return encodeURI(Saiku.session.username + "/repository"); } });
Add logging about downloading the hot manifest
if(module.hot) { function check() { console.log("Checking for updates on the server..."); module.hot.check(function(err, updatedModules) { if(err) { if(module.hot.status() in {abort:1,fail:1}) window.location.reload(); else console.warn("Update failed: " + err); return; } if(!updatedModules) return console.log("No Update found."); check(); if(!updatedModules || updatedModules.length === 0) return console.log("Update is empty."); console.log("Updated modules:"); updatedModules.forEach(function(moduleId) { console.log(" - " + moduleId); }); }); } window.onmessage = function(event) { if(event.data === "webpackHotUpdate" && module.hot.status() === "idle") { check(); } }; }
if(module.hot) { function check() { module.hot.check(function(err, updatedModules) { if(err) { if(module.hot.status() in {abort:1,fail:1}) window.location.reload(); else console.warn("Update failed: " + err); return; } if(!updatedModules) return console.log("No Update found."); check(); if(!updatedModules || updatedModules.length === 0) return console.log("Update is empty."); console.log("Updated modules:"); updatedModules.forEach(function(moduleId) { console.log(" - " + moduleId); }); }); } window.onmessage = function(event) { if(event.data === "webpackHotUpdate" && module.hot.status() === "idle") { check(); } }; }
Raise EnvironmentError instead of Exception to make pylint happy
import sys if not (2, 6) <= sys.version_info < (3,): sys.exit(u'Mopidy requires Python >= 2.6, < 3') from subprocess import PIPE, Popen VERSION = (0, 4, 0) def get_git_version(): process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE) if process.wait() != 0: raise EnvironmentError('Execution of "git describe" failed') version = process.stdout.read().strip() if version.startswith('v'): version = version[1:] return version def get_plain_version(): return '.'.join(map(str, VERSION)) def get_version(): try: return get_git_version() except EnvironmentError: return get_plain_version() class MopidyException(Exception): def __init__(self, message, *args, **kwargs): super(MopidyException, self).__init__(message, *args, **kwargs) self._message = message @property def message(self): """Reimplement message field that was deprecated in Python 2.6""" return self._message @message.setter def message(self, message): self._message = message class SettingsError(MopidyException): pass class OptionalDependencyError(MopidyException): pass from mopidy import settings as default_settings_module from mopidy.utils.settings import SettingsProxy settings = SettingsProxy(default_settings_module)
import sys if not (2, 6) <= sys.version_info < (3,): sys.exit(u'Mopidy requires Python >= 2.6, < 3') from subprocess import PIPE, Popen VERSION = (0, 4, 0) def get_git_version(): process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE) if process.wait() != 0: raise Exception('Execution of "git describe" failed') version = process.stdout.read().strip() if version.startswith('v'): version = version[1:] return version def get_plain_version(): return '.'.join(map(str, VERSION)) def get_version(): try: return get_git_version() except Exception: return get_plain_version() class MopidyException(Exception): def __init__(self, message, *args, **kwargs): super(MopidyException, self).__init__(message, *args, **kwargs) self._message = message @property def message(self): """Reimplement message field that was deprecated in Python 2.6""" return self._message @message.setter def message(self, message): self._message = message class SettingsError(MopidyException): pass class OptionalDependencyError(MopidyException): pass from mopidy import settings as default_settings_module from mopidy.utils.settings import SettingsProxy settings = SettingsProxy(default_settings_module)
Load background faster first time
var default_opacity = 0.2; var animate_time = 0; var default_animate_time = 1000; var num_images = 152; function fix_resolutions() { var img = $('#imgloader').get(0); var img_ratio = img.naturalWidth / img.naturalHeight; var wnd_ratio = window.innerWidth / window.innerHeight; $("#back").css("background-size", img_ratio > wnd_ratio ? "auto 100%" : "100% auto"); } function set_random_img() { var img = $('#imgloader').attr('src'); var back = $('#back'); back.animate({opacity: 0}, animate_time, 'swing', function() { if(animate_time == 0) { animate_time = default_animate_time; } back.css("background-image", "url('" + img + "')"); fix_resolutions(); back.animate({opacity: default_opacity}, animate_time); }); } function select_random_img() { $('#imgloader').attr('src', "static/imgs/" + (Math.floor(Math.random() * num_images) + 1) + ".jpg"); } $( document ).ready(function() { $('#imgloader').attr('src', '').load(set_random_img); select_random_img(); $(window).resize(fix_resolutions); window.setInterval(select_random_img, 10000); });
var default_opacity = 0.2; var animate_time = 1000; var num_images = 152; function fix_resolutions() { var img = $('#imgloader').get(0); var img_ratio = img.naturalWidth / img.naturalHeight; var wnd_ratio = window.innerWidth / window.innerHeight; $("#back").css("background-size", img_ratio > wnd_ratio ? "auto 100%" : "100% auto"); } function set_random_img() { var img = $('#imgloader').attr('src'); var back = $('#back'); back.animate({opacity: 0}, animate_time, 'swing', function() { back.css("background-image", "url('" + img + "')"); fix_resolutions(); back.animate({opacity: default_opacity}, animate_time); }); } function select_random_img() { $('#imgloader').attr('src', "static/imgs/" + (Math.floor(Math.random() * num_images) + 1) + ".jpg"); } $( document ).ready(function() { $('#imgloader').attr('src', '').load(set_random_img); select_random_img(); $(window).resize(fix_resolutions); window.setInterval(select_random_img, 10000); });
Make threads run in daemon mode
import redis_collections import threading import time import __main__ class RedisDict(redis_collections.Dict): def __init__(self, **kwargs): super().__init__(**kwargs) self.die = False self.thread = threading.Thread(target=self.update_loop, daemon=True) self.thread.start() self.prev = None def update_loop(self): time.sleep(2) while not (__main__.liara.stopped or self.die): if self.prev != repr(self): self.prev = repr(self) self.sync() time.sleep(0.1) else: self.cache.clear() time.sleep(0.1) class dataIO: @staticmethod def save_json(filename, content): pass # "oops" @staticmethod def load_json(filename): return RedisDict(key=filename, redis=__main__.redis_conn, writeback=True)
import redis_collections import threading import time import __main__ class RedisDict(redis_collections.Dict): def __init__(self, **kwargs): super().__init__(**kwargs) self.die = False self.thread = threading.Thread(target=self.update_loop) self.thread.start() self.prev = None def update_loop(self): time.sleep(2) while not (__main__.liara.stopped or self.die): if self.prev != repr(self): self.prev = repr(self) self.sync() time.sleep(0.1) else: self.cache.clear() time.sleep(0.1) class dataIO: @staticmethod def save_json(filename, content): pass # "oops" @staticmethod def load_json(filename): return RedisDict(key=filename, redis=__main__.redis_conn, writeback=True)
Add a simple healthcheck endpoint
var yarn = require('@yarnpkg/lockfile') var express = require('express') var bodyParser = require('body-parser') var app = express() var port = process.env.PORT || 5000; app.disable('x-powered-by'); app.use(function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); next(); }); app.post("/parse/", bodyParser.text({type: '*/*', limit: '5mb'}), function(req,res){ var dependencies = yarn.parse(req.body).object var deps = [] Object.keys(dependencies).forEach((dep) => { deps.push({ name: dep.split('@')[0], version: dependencies[dep].version, type: 'runtime' }) }) res.json(deps) }); app.get("/", function(req,res) { res.send("OK") }); app.use(function(err, req, res, next) { console.error('ERR:', err); console.error('STACK:', err.stack); res.status(500).send({error: 'Something went wrong.'}); }); app.listen(port, function() { console.log('Listening on', port); });
var yarn = require('@yarnpkg/lockfile') var express = require('express') var bodyParser = require('body-parser') var app = express() var port = process.env.PORT || 5000; app.disable('x-powered-by'); app.use(function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); next(); }); app.post("/parse/", bodyParser.text({type: '*/*', limit: '5mb'}), function(req,res){ var dependencies = yarn.parse(req.body).object var deps = [] Object.keys(dependencies).forEach((dep) => { deps.push({ name: dep.split('@')[0], version: dependencies[dep].version, type: 'runtime' }) }) res.json(deps) }); app.use(function(err, req, res, next) { console.error('ERR:', err); console.error('STACK:', err.stack); res.status(500).send({error: 'Something went wrong.'}); }); app.listen(port, function() { console.log('Listening on', port); });
Fix JS error in invite dialog button
window.addEventListener("load", function() { if (!document.createElement('dialog').showModal) { var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'static/dialog-polyfill.css'; var script = document.createElement('script'); script.src = 'static/dialog-polyfill.js'; var head = document.getElementsByTagName('head')[0]; head.appendChild(link); head.appendChild(script); } function showInviteDialog() { var dialog = document.getElementById('invite_dialog'); if (window.dialogPolyfill) { window.dialogPolyfill.registerDialog(dialog); } dialog.showModal(); } document.getElementById('showInviteDialog').onclick = showInviteDialog; function closeInviteDialog() { var dialog = document.getElementById('invite_dialog'); dialog.close(); } document.getElementById('closeInviteDialog').onclick = closeInviteDialog; });
if (!document.createElement('dialog').showModal) { var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'static/dialog-polyfill.css'; var script = document.createElement('script'); script.src = 'static/dialog-polyfill.js'; var head = document.getElementsByTagName('head')[0]; head.appendChild(link); head.appendChild(script); } function showInviteDialog() { var dialog = document.getElementById('invite_dialog'); if (window.dialogPolyfill) { window.dialogPolyfill.registerDialog(dialog); } dialog.showModal(); } document.getElementById('showInviteDialog').onclick = showInviteDialog; function closeInviteDialog() { var dialog = document.getElementById('invite_dialog'); dialog.close(); } document.getElementById('closeInviteDialog').onclick = closeInviteDialog;
Make tag @Nullable in isLoggable
package com.example.tools.timber; import android.util.Log; import com.crashlytics.android.Crashlytics; import timber.log.Timber; import javax.annotation.Nullable; /** * A logging tree that logs {@link Timber#wtf} methods to crashlytics. This tree does not log to logcat at all. */ public class CrashlyticsTree extends Timber.Tree { @Override protected boolean isLoggable(@Nullable String tag, int priority) { return priority == Log.ASSERT; } @Override protected void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable throwable) { if (isLoggable(tag, priority)) { if (throwable != null) { Crashlytics.logException(throwable); } if (message != null) { Crashlytics.log(message); } } } }
package com.example.tools.timber; import android.util.Log; import com.crashlytics.android.Crashlytics; import timber.log.Timber; import javax.annotation.Nullable; /** * A logging tree that logs {@link Timber#wtf} methods to crashlytics. This tree does not log to logcat at all. */ public class CrashlyticsTree extends Timber.Tree { @Override protected boolean isLoggable(String tag, int priority) { return priority == Log.ASSERT; } @Override protected void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable throwable) { if (isLoggable(tag, priority)) { if (throwable != null) { Crashlytics.logException(throwable); } if (message != null) { Crashlytics.log(message); } } } }
Change name displayed for desktop streaming device in the media configuration panel.
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.neomedia.device; import javax.media.*; import net.java.sip.communicator.impl.neomedia.imgstreaming.*; import net.java.sip.communicator.impl.neomedia.jmfext.media.protocol.imgstreaming.*; /** * Add ImageStreaming capture device. * * @author Sebastien Vincent */ public class ImageStreamingAuto { /** * Add capture devices. * * @throws Exception if problem when adding capture devices */ public ImageStreamingAuto() throws Exception { String name = "Desktop Streaming (Experimental)"; CaptureDeviceInfo devInfo = new CaptureDeviceInfo( name, new MediaLocator( ImageStreamingUtils.LOCATOR_PROTOCOL + ":" + name), DataSource.getFormats()); /* add to JMF device manager */ CaptureDeviceManager.addDevice(devInfo); CaptureDeviceManager.commit(); } }
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.neomedia.device; import javax.media.*; import net.java.sip.communicator.impl.neomedia.imgstreaming.*; import net.java.sip.communicator.impl.neomedia.jmfext.media.protocol.imgstreaming.*; /** * Add ImageStreaming capture device. * * @author Sebastien Vincent */ public class ImageStreamingAuto { /** * Add capture devices. * * @throws Exception if problem when adding capture devices */ public ImageStreamingAuto() throws Exception { String name = "Experimental desktop streaming"; CaptureDeviceInfo devInfo = new CaptureDeviceInfo( name, new MediaLocator( ImageStreamingUtils.LOCATOR_PROTOCOL + ":" + name), DataSource.getFormats()); /* add to JMF device manager */ CaptureDeviceManager.addDevice(devInfo); CaptureDeviceManager.commit(); } }
Add __fromUserId field to data object received on broadcast event
// -------------------------------------------------------------------------- // // ------------------------------ Allow/deny -------------------------------- // // -------------------------------------------------------------------------- // /** * Wether or not the broadcast is allowed * @param {Object} data Data of the message * @param {Socket} from From socket */ Streamy.BroadCasts.allow = function(data, from) { return true; }; // -------------------------------------------------------------------------- // // -------------------------------- Handlers -------------------------------- // // -------------------------------------------------------------------------- // /** * Attach the broadcast message handler * @param {Object} data Data object * @param {Socket} from Socket emitter */ Streamy.on('__broadcast__', function(data, from) { // Check for sanity if(!data.__msg || !data.__data) return; // Check if the server allows this direct message if(!Streamy.BroadCasts.allow(data, from)) return; // Attach the sender ID to the inner data data.__data.__from = Streamy.id(from); data.__data.__fromUserId = from._meteorSession.userId; // And then emit the message Streamy.broadcast(data.__msg, data.__data, data.__except); }); // -------------------------------------------------------------------------- // // ------------------------------- Overrides -------------------------------- // // -------------------------------------------------------------------------- // Streamy.broadcast = function(message, data, except) { if(!_.isArray(except)) except = [except]; _.each(Streamy.sockets(), function(sock) { if(except.indexOf(Streamy.id(sock)) !== -1) return; Streamy.emit(message, data, sock); }); };
// -------------------------------------------------------------------------- // // ------------------------------ Allow/deny -------------------------------- // // -------------------------------------------------------------------------- // /** * Wether or not the broadcast is allowed * @param {Object} data Data of the message * @param {Socket} from From socket */ Streamy.BroadCasts.allow = function(data, from) { return true; }; // -------------------------------------------------------------------------- // // -------------------------------- Handlers -------------------------------- // // -------------------------------------------------------------------------- // /** * Attach the broadcast message handler * @param {Object} data Data object * @param {Socket} from Socket emitter */ Streamy.on('__broadcast__', function(data, from) { // Check for sanity if(!data.__msg || !data.__data) return; // Check if the server allows this direct message if(!Streamy.BroadCasts.allow(data, from)) return; // Attach the sender ID to the inner data data.__data.__from = Streamy.id(from); // And then emit the message Streamy.broadcast(data.__msg, data.__data, data.__except); }); // -------------------------------------------------------------------------- // // ------------------------------- Overrides -------------------------------- // // -------------------------------------------------------------------------- // Streamy.broadcast = function(message, data, except) { if(!_.isArray(except)) except = [except]; _.each(Streamy.sockets(), function(sock) { if(except.indexOf(Streamy.id(sock)) !== -1) return; Streamy.emit(message, data, sock); }); };
Use select instead of focusing.
(() => { 'use strict'; const addressEl = document.getElementsByClassName('address')[0]; function copyAddress() { const email = atob('IGN0ZXJlZmlua29AZ21haWwuY29tIA==').trim(); // Update the element to have the email and stop listening. addressEl.textContent = email; addressEl.classList.remove('link'); addressEl.removeEventListener('touchend', copyAddress); addressEl.removeEventListener('click', copyAddress); // Create a fake textarea to copy from. const target = document.createElement('textarea'); target.textContent = email; target.classList = 'offscreen'; document.body.appendChild(target); // Focus, select the text, copy it, and then remove the fake target. target.select(); const result = document.execCommand('copy'); document.body.removeChild(target); if (result) { showToast('copied'); } } addressEl.addEventListener('touchend', copyAddress); addressEl.addEventListener('click', copyAddress); function showToast(content) { const toast = document.getElementsByClassName('toast')[0]; toast.textContent = content; toast.classList.add('show'); setTimeout(() => { toast.classList.remove('show'); }, 2900); } })();
(() => { 'use strict'; const addressEl = document.getElementsByClassName('address')[0]; function copyAddress() { const email = atob('IGN0ZXJlZmlua29AZ21haWwuY29tIA==').trim(); // Update the element to have the email and stop listening. addressEl.textContent = email; addressEl.classList.remove('link'); addressEl.removeEventListener('touchend', copyAddress); addressEl.removeEventListener('click', copyAddress); // Create a fake textarea to copy from. const target = document.createElement('textarea'); target.textContent = email; target.classList = 'offscreen'; document.body.appendChild(target); // Focus, select the text, copy it, and then remove the fake target. target.focus(); target.setSelectionRange(0, target.value.length); const result = document.execCommand('copy'); document.body.removeChild(target); if (result) { showToast('copied'); } } addressEl.addEventListener('touchend', copyAddress); addressEl.addEventListener('click', copyAddress); function showToast(content) { const toast = document.getElementsByClassName('toast')[0]; toast.textContent = content; toast.classList.add('show'); setTimeout(() => { toast.classList.remove('show'); }, 2900); } })();
Add invalid tag index message
package tars.commons.core; /** * Container for user visible messages. */ public class Messages { public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command"; public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s"; public static final String MESSAGE_INVALID_DATE = "Invalid date time entered!"; public static final String MESSAGE_INVALID_END_DATE = "End dateTime should be after start dateTime."; public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid"; public static final String MESSAGE_INVALID_TAG_DISPLAYED_INDEX = "The tag index provided is invalid"; public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d tasks listed!"; public static final String MESSAGE_TASK_CANNOT_BE_FOUND = "Task cannot be found!"; public static final String MESSAGE_DUPLICATE_TASK= "This task already exists in tars"; }
package tars.commons.core; /** * Container for user visible messages. */ public class Messages { public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command"; public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s"; public static final String MESSAGE_INVALID_DATE = "Invalid date time entered!"; public static final String MESSAGE_INVALID_END_DATE = "End dateTime should be after start dateTime."; public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid"; public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d tasks listed!"; public static final String MESSAGE_TASK_CANNOT_BE_FOUND = "Task cannot be found!"; public static final String MESSAGE_DUPLICATE_TASK= "This task already exists in tars"; }
Update test to support PHP 5.4
<?php use donatj\MockWebServer\ResponseStack; class ResponseStackTest extends \PHPUnit_Framework_TestCase { public function testEmpty() { $mock = $this->getMockBuilder('\donatj\MockWebServer\RequestInfo')->disableOriginalConstructor()->getMock(); $x = new ResponseStack(); $this->assertSame('Past the end of the ResponseStack', $x->getBody($mock)); $this->assertSame(404, $x->getStatus($mock)); $this->assertSame([], $x->getHeaders($mock)); $this->assertSame(false, $x->next()); } /** * @dataProvider customResponseProvider */ public function testCustomPastEndResponse( $body, $headers, $status ) { $mock = $this->getMockBuilder('\donatj\MockWebServer\RequestInfo')->disableOriginalConstructor()->getMock(); $x = new ResponseStack(); $x->setPastEndResponse(new \donatj\MockWebServer\Response($body, $headers, $status)); $this->assertSame($body, $x->getBody($mock)); $this->assertSame($status, $x->getStatus($mock)); $this->assertSame($headers, $x->getHeaders($mock)); $this->assertSame(false, $x->next()); } public function customResponseProvider() { return [ [ 'PastEnd', [ 'HeaderA' => 'BVAL' ], 420 ], [ ' Leading and trailing whitespace ', [], 0 ], ]; } }
<?php use donatj\MockWebServer\RequestInfo; use donatj\MockWebServer\ResponseStack; class ResponseStackTest extends \PHPUnit_Framework_TestCase { public function testEmpty() { $mock = $this->getMockBuilder(RequestInfo::class)->disableOriginalConstructor()->getMock(); $x = new ResponseStack(); $this->assertSame('Past the end of the ResponseStack', $x->getBody($mock)); $this->assertSame(404, $x->getStatus($mock)); $this->assertSame([], $x->getHeaders($mock)); $this->assertSame(false, $x->next()); } /** * @dataProvider customResponseProvider */ public function testCustomPastEndResponse( $body, $headers, $status ) { $mock = $this->getMockBuilder(RequestInfo::class)->disableOriginalConstructor()->getMock(); $x = new ResponseStack(); $x->setPastEndResponse(new \donatj\MockWebServer\Response($body, $headers, $status)); $this->assertSame($body, $x->getBody($mock)); $this->assertSame($status, $x->getStatus($mock)); $this->assertSame($headers, $x->getHeaders($mock)); $this->assertSame(false, $x->next()); } public function customResponseProvider() { return [ [ 'PastEnd', [ 'HeaderA' => 'BVAL' ], 420 ], [ ' Leading and trailing whitespace ', [], 0 ], ]; } }
Fix .setStrokeColor() and .setStrokeWidth() using CSS instead of SVG attributes
"use strict" var SVGElement = require("./SVGElement.js") , inherits = require("util").inherits var SVGShape = module.exports = function (elementName) { SVGElement.call(this, elementName) } inherits(SVGShape, SVGElement) SVGShape.prototype.setStrokeColor = function (color) { this.rawSVGElement().setAttribute("stroke", color) } SVGShape.prototype.setStrokeOpacity = function (decimal) { this.rawSVGElement().setAttribute("stroke-opacity", decimal) } SVGShape.prototype.setStrokeWidth = function (width) { this.rawSVGElement().setAttribute("stroke-width", width) } SVGShape.prototype.setStrokeLinecap = function (type) { this.rawSVGElement().setAttribute("stroke-linecap", type) } SVGShape.prototype.setFillColor = function (color) { this.rawSVGElement().setAttribute("fill", color) } SVGShape.prototype.setFillOpacity = function (decimal) { this.rawSVGElement().setAttribute("fill-opacity", decimal) }
"use strict" var SVGElement = require("./SVGElement.js") , inherits = require("util").inherits var SVGShape = module.exports = function (elementName) { SVGElement.call(this, elementName) } inherits(SVGShape, SVGElement) SVGShape.prototype.setStrokeColor = function (color) { this.rawSVGElement().style.stroke = color } SVGShape.prototype.setStrokeOpacity = function (decimal) { this.rawSVGElement().setAttribute("stroke-opacity", decimal) } SVGShape.prototype.setStrokeWidth = function (width) { this.rawSVGElement().style.strokeWidth = width } SVGShape.prototype.setStrokeLinecap = function (type) { this.rawSVGElement().setAttribute("stroke-linecap", type) } SVGShape.prototype.setFillColor = function (color) { this.rawSVGElement().setAttribute("fill", color) } SVGShape.prototype.setFillOpacity = function (decimal) { this.rawSVGElement().setAttribute("fill-opacity", decimal) }
Use $_REQUEST instead of $_POST in exception notification emails.
<?php class ErrorHandler { static public function install() { set_error_handler("ErrorHandler::handle"); } static public function handle($errno, $errstr, $errfile, $errline) { if(!(error_reporting() & $errno)) { return; } throw new Exception($errstr . " [" . $errfile . " @ line " . $errline . "]"); return true; } static public function mailException($e) { Helpers::sendMail( Config::get("exceptions.mail_to"), "[" . Config::get("app.internal_name") . "] " . $e->getMessage(), "An unhandled " . get_class($e) . " occured on " . date("l, j F Y H:i:s A") . ":\r\n\r\n" . $e->getMessage() . "\r\n" . "Request URI: " . $_SERVER["REQUEST_URI"] . "\r\n\r\n" . print_r(@$_REQUEST, true) ); } }
<?php class ErrorHandler { static public function install() { set_error_handler("ErrorHandler::handle"); } static public function handle($errno, $errstr, $errfile, $errline) { if(!(error_reporting() & $errno)) { return; } throw new Exception($errstr . " [" . $errfile . " @ line " . $errline . "]"); return true; } static public function mailException($e) { Helpers::sendMail( Config::get("exceptions.mail_to"), "[" . Config::get("app.internal_name") . "] " . $e->getMessage(), "An unhandled " . get_class($e) . " occured on " . date("l, j F Y H:i:s A") . ":\r\n\r\n" . $e->getMessage() . "\r\n" . "Request URI: " . $_SERVER["REQUEST_URI"] . "\r\n\r\n" . print_r(@$_POST, true) ); } }
Move doc history to proper place.
// Single certificate submitted view 'use strict'; var db = require('mano').db , endsWith = require('es5-ext/string/#/ends-with') , documentView = require('./components/business-process-document') , renderDocumentHistory = require('./components/business-process-document-history'); exports._parent = require('./business-process-submitted-documents'); exports._dynamic = require('./utils/document-dynamic-matcher')('certificate'); exports._match = 'document'; exports['selection-preview'] = function () { var doc = this.document; insert(documentView(doc, this.businessProcess.certificates.uploaded, { sideContent: [ doc.overviewSection.toDOM(document, { disableHeader: false }), doc.dataForm.constructor !== db.FormSectionBase ? doc.dataForm.toDOM(document, { customFilter: function (resolved) { return !endsWith.call(resolved.observable.dbId, 'files/map'); }, disableHeader: false }) : null, renderDocumentHistory(doc) ] })); };
// Single certificate submitted view 'use strict'; var db = require('mano').db , endsWith = require('es5-ext/string/#/ends-with') , documentView = require('./components/business-process-document') , renderDocumentHistory = require('./components/business-process-document-history'); exports._parent = require('./business-process-submitted-documents'); exports._dynamic = require('./utils/document-dynamic-matcher')('certificate'); exports._match = 'document'; exports['selection-preview'] = function () { var doc = this.document; insert(documentView(doc, this.businessProcess.certificates.uploaded, { sideContent: [ doc.overviewSection.toDOM(document, { disableHeader: false }), doc.dataForm.constructor !== db.FormSectionBase ? doc.dataForm.toDOM(document, { customFilter: function (resolved) { return !endsWith.call(resolved.observable.dbId, 'files/map'); }, disableHeader: false }) : null ], appendContent: renderDocumentHistory(doc) })); };
Modify files globs to include all files The wildcard pattern was not picking up CNAME. Now it does.
'use strict'; var gulp = require('gulp'); var watch = require('gulp-watch'); var harp = require('harp'); var browserSync = require('browser-sync'); var ghPages = require('gulp-gh-pages'); var harpServerOptions = { port: 9000 }; var paths = { projectDir: './', outputDir: './dist', outputFiles: './dist/**/*', srcFiles: './public/**/*' }; gulp.task('default', ['watch']); gulp.task('deploy', ['build'], function () { return gulp.src(paths.outputFiles) .pipe(ghPages()); }); gulp.task('build', function (done) { harp.compile(paths.projectDir, paths.outputDir, done); }); gulp.task('watch', ['dev-server'], function () { browserSync({ open: false, proxy: 'localhost:' + harpServerOptions.port, notify: false }); gulp.src(paths.srcFiles) .pipe(watch(paths.srcFiles, { verbose: true })) .pipe(browserSync.reload({ stream: true })); }); gulp.task('dev-server', function (done) { harp.server(__dirname, harpServerOptions, done); });
'use strict'; var gulp = require('gulp'); var watch = require('gulp-watch'); var harp = require('harp'); var browserSync = require('browser-sync'); var ghPages = require('gulp-gh-pages'); var harpServerOptions = { port: 9000 }; var paths = { projectDir: './', outputDir: './dist', outputFiles: './dist/**/*.*', srcFiles: './public/**/*.*' }; gulp.task('default', ['watch']); gulp.task('deploy', ['build'], function () { return gulp.src(paths.outputFiles) .pipe(ghPages()); }); gulp.task('build', function (done) { harp.compile(paths.projectDir, paths.outputDir, done); }); gulp.task('watch', ['dev-server'], function () { browserSync({ open: false, proxy: 'localhost:' + harpServerOptions.port, notify: false }); gulp.src(paths.srcFiles) .pipe(watch(paths.srcFiles, { verbose: true })) .pipe(browserSync.reload({ stream: true })); }); gulp.task('dev-server', function (done) { harp.server(__dirname, harpServerOptions, done); });
Reset state for new game
import { NEW_GAME, PLAY_WITH_RED, PLAY_WITH_YELLOW, } from '../actions/connect4'; import Board from '../domain/board'; export const RED_TURN = 1; export const YELLOW_TURN = 2; const initialState = { board: new Board(), playingNow: RED_TURN, }; export default function counter (state = initialState, action) { const { board } = state; switch (action.type) { case NEW_GAME: board.initiate(); return { ...initialState, board, }; case PLAY_WITH_RED: case PLAY_WITH_YELLOW: const value = action.type === PLAY_WITH_RED ? RED_TURN : YELLOW_TURN; board.playAtColWithValue(action.col, value); return { board, playingNow: action.type === PLAY_WITH_RED ? YELLOW_TURN : RED_TURN, }; default: return state; } }
import { NEW_GAME, PLAY_WITH_RED, PLAY_WITH_YELLOW, } from '../actions/connect4'; import Board from '../domain/board'; export const RED_TURN = 1; export const YELLOW_TURN = 2; const initialState = { board: new Board(), playingNow: RED_TURN, }; export default function counter (state = initialState, action) { const { board } = state; switch (action.type) { case NEW_GAME: board.initiate(); return { ...state, board }; case PLAY_WITH_RED: case PLAY_WITH_YELLOW: const value = action.type === PLAY_WITH_RED ? RED_TURN : YELLOW_TURN; board.playAtColWithValue(action.col, value); return { board, playingNow: action.type === PLAY_WITH_RED ? YELLOW_TURN : RED_TURN, }; default: return state; } }
TM-19: Merge remote-tracking branch 'origin/TM-18' into TM-19
define( 'ephox.alloy.behaviour.sandboxing.SandboxSchema', [ 'ephox.alloy.data.Fields', 'ephox.boulder.api.FieldSchema', 'ephox.katamari.api.Cell', 'ephox.katamari.api.Option' ], function (Fields, FieldSchema, Cell, Option) { return [ FieldSchema.state('state', function () { return Cell(Option.none()); }), Fields.onHandler('onOpen'), Fields.onHandler('onClose'), // TODO: async === false is untested FieldSchema.defaulted('async', true), // Maybe this should be optional FieldSchema.strict('isPartOf'), FieldSchema.strict('getAttachPoint') ]; } );
define( 'ephox.alloy.behaviour.sandboxing.SandboxSchema', [ 'ephox.alloy.data.Fields', 'ephox.boulder.api.FieldSchema', 'ephox.katamari.api.Cell', 'ephox.katamari.api.Option' ], function (Fields, FieldSchema, Cell, Option) { return [ FieldSchema.state('state', function () { return Cell(Option.none()); }), Fields.onHandler('onOpen'), Fields.onHandler('onClose'), // TODO: async === false is untestedglu FieldSchema.defaulted('async', true), // Maybe this should be optional FieldSchema.strict('isPartOf'), FieldSchema.strict('getAttachPoint') ]; } );
Substitute in our download bucket in that template tag now that the two things are separated
import os from django import template from django.conf import settings from django.template.defaultfilters import stringfilter register = template.Library() @register.simple_tag def archive_url(file_path, is_latest=False): """ Accepts the relative path to a CAL-ACCESS file in our achive. Returns a fully-qualified absolute URL where it can be downloaded. """ # If this is the 'latest' version of the file the path will need to be hacked if is_latest: # Split off the file name filepath = os.path.basename(file_path) # Special hack for the clean biggie zip if filepath.startswith("clean_"): filepath = "clean.zip" # Concoct the latest URL path = os.path.join( "calaccess.download", 'latest', filepath ) # If not we can just join it to the subject name else: path = os.path.join("calaccess.download", file_path) # Either way, join it to the base and pass it back return "http://{}".format(path) @register.filter @stringfilter def format_page_anchor(value): return value.lower().replace('_', '-') @register.filter @stringfilter def first_line(text): return text.split('\n')[0]
import os from django import template from django.conf import settings from django.template.defaultfilters import stringfilter register = template.Library() @register.simple_tag def archive_url(file_path, is_latest=False): """ Accepts the relative path to a CAL-ACCESS file in our achive. Returns a fully-qualified absolute URL where it can be downloaded. """ # If this is the 'latest' version of the file the path will need to be hacked if is_latest: # Split off the file name filepath = os.path.basename(file_path) # Special hack for the clean biggie zip if filepath.startswith("clean_"): filepath = "clean.zip" # Concoct the latest URL path = os.path.join( settings.AWS_STORAGE_BUCKET_NAME, 'latest', filepath ) # If not we can just join it to the subject name else: path = os.path.join(settings.AWS_STORAGE_BUCKET_NAME, file_path) # Either way, join it to the base and pass it back return "http://{}".format(path) @register.filter @stringfilter def format_page_anchor(value): return value.lower().replace('_', '-') @register.filter @stringfilter def first_line(text): return text.split('\n')[0]
Add check for client keys in environment variable
var express = require('express'); var path = require('path'); var index = require('./routes/index'); var app = express(); if(!process.env.API_KEY){ console.log('Set the Openweather API key as an environment variable named API_KEY'); process.exit(-1); } if(!process.env.CLIENT_KEYS){ console.log('Set the client keys as comma separated value of an environment variable named CLIENT_KEYS'); process.exit(-1); } app.set('view engine', 'jade'); app.use('/', index); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
var express = require('express'); var path = require('path'); var index = require('./routes/index'); var app = express(); if(!process.env.API_KEY){ console.log('Set the Openweather API key as an environment variable named API_KEY'); process.exit(-1); } app.set('view engine', 'jade'); app.use('/', index); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
Support for method calls on models from Twig templates
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\twig; /** * Template base class * * @author Alexei Tenitski <alexei@ten.net.nz> */ abstract class Template extends \Twig_Template { protected function getAttribute($object, $item, array $arguments = array(), $type = \Twig_Template::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false) { // Twig uses isset() to check if attribute exists which does not work when attribute exists but is null if ($object instanceof \yii\db\BaseActiveRecord) { if ($type == \Twig_Template::METHOD_CALL) { return $object->$item(); } else { return $object->$item; } } return parent::getAttribute($object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck); } }
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\twig; /** * Template base class * * @author Alexei Tenitski <alexei@ten.net.nz> */ abstract class Template extends \Twig_Template { protected function getAttribute($object, $item, array $arguments = array(), $type = \Twig_Template::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false) { // Twig uses isset() to check if attribute exists which does not work when attribute exists but is null if ($object instanceof \yii\db\BaseActiveRecord) { return $object->$item; } return parent::getAttribute($object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck); } }
Add a version per default
import json import dns.resolver mispattributes = {'input':['hostname', 'domain'], 'output':['ip-src', 'ip-dst']} moduleinfo = "0.1" def handler(q=False): if q is False: return False request = json.loads(q) if request.get('hostname'): toquery = request['hostname'] elif request.get('domain'): toquery = request['domain'] else: return False r = dns.resolver.Resolver() r.nameservers = ['8.8.8.8'] try: answer = r.query(toquery, 'A') except dns.resolver.NXDOMAIN: return False except dns.exception.Timeout: return False r = {'results':[{'types':mispattributes['output'], 'values':[str(answer[0])]}]} return r def introspection(): return mispattributes def version(): return moduleinfo
import json import dns.resolver mispattributes = {'input':['hostname', 'domain'], 'output':['ip-src', 'ip-dst']} def handler(q=False): if q is False: return False request = json.loads(q) if request.get('hostname'): toquery = request['hostname'] elif request.get('domain'): toquery = request['domain'] else: return False r = dns.resolver.Resolver() r.nameservers = ['8.8.8.8'] try: answer = r.query(toquery, 'A') except dns.resolver.NXDOMAIN: return False except dns.exception.Timeout: return False r = {'results':[{'types':mispattributes['output'], 'values':[str(answer[0])]}]} return r def introspection(): return mispattributes['input']
Improve performance of find tags function
import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() for tag in tags: if tag.name == tag_name: return tag.commit return None def comment_on_commit(commit, message): commit.create_comment(message)
import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() tag_commit = None for tag in tags: if tag.name == tag_name: tag_commit = tag.commit return tag_commit def comment_on_commit(commit, message): commit.create_comment(message)
Use io.open for 2->3 compatibility
# -*- coding: utf-8 - import codecs import io import os from setuptools import setup with io.open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name = 'bernhard', version = '0.2.0', description = 'Python client for Riemann', long_description = long_description, author = 'Benjamin Anderspn', author_email = 'b@banjiewen.net', license = 'ASF2.0', url = 'http://github.com/banjiewen/bernhard.git', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Other Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Internet :: Log Analysis', 'Topic :: Utilities', 'Topic :: System :: Networking :: Monitoring' ], zip_safe = False, packages = ['bernhard'], include_package_data = True, install_requires=['protobuf >= 2.4'] )
# -*- coding: utf-8 - import codecs import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name = 'bernhard', version = '0.1.1', description = 'Python client for Riemann', long_description = long_description, author = 'Benjamin Anderspn', author_email = 'b@banjiewen.net', license = 'ASF2.0', url = 'http://github.com/banjiewen/bernhard.git', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Other Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Internet :: Log Analysis', 'Topic :: Utilities', 'Topic :: System :: Networking :: Monitoring' ], zip_safe = False, packages = ['bernhard'], include_package_data = True, install_requires=['protobuf >= 2.4'] )
Allow PEM format keys through validation
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError from cryptography.hazmat.primitives.serialization import load_pem_public_key, load_ssh_public_key from cryptography.hazmat.backends import default_backend def validate_public_key(value): is_valid = False exc = None for load in (load_pem_public_key, load_ssh_public_key): if not is_valid: try: load(value.encode('utf-8'), default_backend()) is_valid = True except Exception as e: exc = e if not is_valid: raise ValidationError('Public key is invalid: %s' % exc) class PublicKey(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='public_keys') key = models.TextField(help_text="The user's RSA public key", validators=[validate_public_key]) comment = models.CharField(max_length=100, help_text="Comment describing this key", blank=True) def save(self, *args, **kwargs): key_parts = self.key.split(' ') if len(key_parts) == 3 and not self.comment: self.comment = key_parts.pop() super(PublicKey, self).save(*args, **kwargs)
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError from cryptography.hazmat.primitives.serialization import load_ssh_public_key from cryptography.hazmat.backends import default_backend def validate_public_key(value): try: load_ssh_public_key(value.encode('utf-8'), default_backend()) except Exception as e: raise ValidationError('Public key is invalid: %s' % e) class PublicKey(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='public_keys') key = models.TextField(help_text="The user's RSA public key", validators=[validate_public_key]) comment = models.CharField(max_length=100, help_text="Comment describing this key", blank=True) def save(self, *args, **kwargs): key_parts = self.key.split(' ') if len(key_parts) == 3 and not self.comment: self.comment = key_parts.pop() super(PublicKey, self).save(*args, **kwargs)
Fix generating the first address for a pocket.
/** * @fileOverview PocketCreateCtrl angular controller */ define(['./module', 'darkwallet'], function (controllers, DarkWallet) { 'use strict'; controllers.controller('PocketCreateCtrl', ['$scope', function($scope) { /** * Scope variables */ $scope.newPocket = {}; $scope.creatingPocket = false; /** * Create a pocket */ $scope.createPocket = function() { if ($scope.creatingPocket && $scope.newPocket.name) { var identity = DarkWallet.getIdentity(); // create pocket identity.wallet.pockets.createPocket($scope.newPocket.name); var pocketIndex = identity.wallet.pockets.hdPockets.length-1; // initialize pocket on angular $scope.initPocket(pocketIndex); // generate an address $scope.generateAddress(pocketIndex*2, 0); // select the pocket $scope.selectPocket($scope.newPocket.name, pocketIndex); // reset pocket form $scope.newPocket = {name:''}; } $scope.creatingPocket = !$scope.creatingPocket; }; }]); });
/** * @fileOverview PocketCreateCtrl angular controller */ define(['./module', 'darkwallet'], function (controllers, DarkWallet) { 'use strict'; controllers.controller('PocketCreateCtrl', ['$scope', function($scope) { /** * Scope variables */ $scope.newPocket = {}; $scope.creatingPocket = false; /** * Create a pocket */ $scope.createPocket = function() { if ($scope.creatingPocket && $scope.newPocket.name) { var identity = DarkWallet.getIdentity(); // create pocket identity.wallet.pockets.createPocket($scope.newPocket.name); var pocketIndex = identity.wallet.pockets.hdPockets.length-1; // initialize pocket on angular $scope.initPocket(pocketIndex); // generate an address $scope.generateAddress(pocketIndex, 0); // select the pocket $scope.selectPocket($scope.newPocket.name, pocketIndex); // reset pocket form $scope.newPocket = {name:''}; } $scope.creatingPocket = !$scope.creatingPocket; }; }]); });
Use the original object instead of array
/** * Export javascript style and css style vendor prefixes. * Based on "transform" support test. */ import isBrowser from 'is-browser' let js = '' let css = '' // We should not do anything if required serverside. if (isBrowser) { // Order matters. We need to check Webkit the last one because // other vendors use to add Webkit prefixes to some properties const jsCssMap = { Moz: '-moz-', // IE did it wrong again ... ms: '-ms-', O: '-o-', Webkit: '-webkit-' } const style = document.createElement('p').style const testProp = 'Transform' for (const key in jsCssMap) { if ((key + testProp) in style) { js = key css = jsCssMap[key] break } } } /** * Vendor prefix string for the current browser. * * @type {{js: String, css: String}} * @api public */ export default {js, css}
/** * Export javascript style and css style vendor prefixes. * Based on "transform" support test. */ import isBrowser from 'is-browser' let js = '' let css = '' // We should not do anything if required serverside. if (isBrowser) { const jsCssMap = { Webkit: '-webkit-', Moz: '-moz-', // IE did it wrong again ... ms: '-ms-', O: '-o-' } // Order matters. We need to check Webkit the last one because // other vendors use to add Webkit prefixes to some properties const prefixes = ['Moz', 'ms', 'O', 'Webkit'] const style = document.createElement('p').style const testProp = 'Transform' for (let i = 0; i < prefixes.length; i++) { const prefix = prefixes[i]; if ((prefix + testProp) in style) { js = prefix css = jsCssMap[prefix] break } } } /** * Vendor prefix string for the current browser. * * @type {{js: String, css: String}} * @api public */ export default {js, css}
Rename duration arg to milliseconds in ParseDuration
// Copyright 2016 Albert Nigmatzianov. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package util import ( "os" "path/filepath" "strconv" "strings" ) const ( millisecondsInSecond = 1000 secondsInMinute = 60 minutesInHour = 60 ) func ParseDuration(milliseconds int) (seconds, minutes, hours int) { seconds = milliseconds / millisecondsInSecond if seconds >= secondsInMinute { minutes = seconds / secondsInMinute seconds -= minutes * secondsInMinute } if minutes >= minutesInHour { hours = minutes / minutesInHour minutes -= hours * minutesInHour } return } func DurationString(seconds, minutes, hours int) (duration string) { duration = formatNumber(minutes) + ":" + formatNumber(seconds) if hours > 0 { duration = formatNumber(hours) + ":" + duration } return } func formatNumber(num int) (formatted string) { if num < 10 { formatted += "0" } formatted += strconv.Itoa(num) return } func SanitizePath(path string) string { if strings.HasPrefix(path, "~") { path = strings.Replace(path, "~", os.Getenv("HOME"), 1) } return filepath.Clean(path) }
// Copyright 2016 Albert Nigmatzianov. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package util import ( "os" "path/filepath" "strconv" "strings" ) const ( millisecondsInSecond = 1000 secondsInMinute = 60 minutesInHour = 60 ) func ParseDuration(duration int) (seconds, minutes, hours int) { seconds = duration / millisecondsInSecond if seconds >= secondsInMinute { minutes = seconds / secondsInMinute seconds -= minutes * secondsInMinute } if minutes >= minutesInHour { hours = minutes / minutesInHour minutes -= hours * minutesInHour } return } func DurationString(seconds, minutes, hours int) (duration string) { duration = formatNumber(minutes) + ":" + formatNumber(seconds) if hours > 0 { duration = formatNumber(hours) + ":" + duration } return } func formatNumber(num int) (formatted string) { if num < 10 { formatted += "0" } formatted += strconv.Itoa(num) return } func SanitizePath(path string) string { if strings.HasPrefix(path, "~") { path = strings.Replace(path, "~", os.Getenv("HOME"), 1) } return filepath.Clean(path) }
Add test for highest_ancestor function
from viridis import tree from six.moves import range import pytest @pytest.fixture def base_tree(): t = tree.Ultrametric(list(range(6))) t.merge(0, 1, 0.1) # 6 t.merge(6, 2, 0.2) # 7 t.merge(3, 4, 0.3) # 8 t.merge(8, 5, 0.4) # 9 t.merge(7, 9, 0.5) # 10 return t def test_split(base_tree): t = base_tree t.split(0, 2) assert t.node[10]['num_leaves'] == 3 t.split(0, 4) # nothing to do assert tree.num_leaves(t, 10) == 3 def test_children(base_tree): t = base_tree assert t.children(6) == [0, 1] def test_leaves(base_tree): t = base_tree assert set(t.leaves(10)) == set(range(6)) assert set(t.leaves(6)) == set([0, 1]) assert set(t.leaves(9)) == set(range(3, 6)) def test_highest(base_tree): t = base_tree for i in range(t.number_of_nodes()): assert t.highest_ancestor(i) == 10 t.remove_node(10) t.remove_node(9) assert t.highest_ancestor(4) == 8
from viridis import tree from six.moves import range import pytest @pytest.fixture def base_tree(): t = tree.Ultrametric(list(range(6))) t.merge(0, 1, 0.1) # 6 t.merge(6, 2, 0.2) # 7 t.merge(3, 4, 0.3) # 8 t.merge(8, 5, 0.4) # 9 t.merge(7, 9, 0.5) # 10 return t def test_split(base_tree): t = base_tree t.split(0, 2) assert t.node[10]['num_leaves'] == 3 t.split(0, 4) # nothing to do assert tree.num_leaves(t, 10) == 3 def test_children(base_tree): t = base_tree assert t.children(6) == [0, 1] def test_leaves(base_tree): t = base_tree assert set(t.leaves(10)) == set(range(6)) assert set(t.leaves(6)) == set([0, 1]) assert set(t.leaves(9)) == set(range(3, 6))
Add script explanation and message when script is complete.
import os import sys import django sys.path.append("/var/projects/museum/") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings") django.setup() from museum_site.models import * # noqa: E402 from museum_site.common import * # noqa: E402 from museum_site.constants import * # noqa: E402 HELP = """This script will list all articles without a preview image. If a PNG matched the article's PK is in static/images/articles/previews it will automatically be assigned. Press ENTER to begin.""" def main(): input(HELP) articles = Article.objects.filter(preview="").order_by("id") for a in articles: path = os.path.join( SITE_ROOT, "museum_site/static/images/articles/previews/{}.png" ) preview_path = path.format(a.id) if os.path.isfile(preview_path): print("[X]", a.id, a.title, preview_path) a.preview = "articles/previews/{}.png".format(a.id) a.save() else: print("[ ]", a.id, a.title) print("Done.") return True if __name__ == "__main__": main()
import os import sys import django sys.path.append("/var/projects/museum/") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings") django.setup() from museum_site.models import * from museum_site.common import * from museum_site.constants import * def main(): articles = Article.objects.filter(preview="").order_by("id") for a in articles: path = os.path.join( SITE_ROOT, "museum_site/static/images/articles/previews/{}.png" ) preview_path = path.format(a.id) if os.path.isfile(preview_path): print("[X]", a.id, a.title, preview_path) a.preview = "articles/previews/{}.png".format(a.id) a.save() else: print("[ ]", a.id, a.title) return True if __name__ == "__main__": main()
Fix for periodic task scheduler (4)
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) @app_object.task(name='check_watchlist_and_dispatch_tasks') def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) @app_object.task def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
Declare exceptions that are already thrown by implementations
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Encoder; use Symfony\Component\Security\Core\Exception\BadCredentialsException; /** * PasswordEncoderInterface is the interface for all encoders. * * @author Fabien Potencier <fabien@symfony.com> */ interface PasswordEncoderInterface { /** * Encodes the raw password. * * @param string $raw The password to encode * @param string $salt The salt * * @return string The encoded password * * @throws BadCredentialsException If the raw password is invalid, e.g. excessively long * @throws \InvalidArgumentException If the salt is invalid */ public function encodePassword($raw, $salt); /** * Checks a raw password against an encoded password. * * @param string $encoded An encoded password * @param string $raw A raw password * @param string $salt The salt * * @return bool true if the password is valid, false otherwise * * @throws \InvalidArgumentException If the salt is invalid */ public function isPasswordValid($encoded, $raw, $salt); }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Encoder; /** * PasswordEncoderInterface is the interface for all encoders. * * @author Fabien Potencier <fabien@symfony.com> */ interface PasswordEncoderInterface { /** * Encodes the raw password. * * @param string $raw The password to encode * @param string $salt The salt * * @return string The encoded password */ public function encodePassword($raw, $salt); /** * Checks a raw password against an encoded password. * * @param string $encoded An encoded password * @param string $raw A raw password * @param string $salt The salt * * @return bool true if the password is valid, false otherwise */ public function isPasswordValid($encoded, $raw, $salt); }
Add new packages to tests
import pytest @pytest.mark.parametrize("name", [ ("apt-file"), ("apt-transport-https"), ("atsar"), ("blktrace"), ("ca-certificates"), ("chromium-browser"), ("cron"), ("curl"), ("diod"), ("docker-engine"), ("fonts-font-awesome"), ("git"), ("gnupg"), ("handbrake"), ("handbrake-cli"), ("haveged"), ("htop"), ("i3"), ("iotop"), ("language-pack-en-base"), ("laptop-mode-tools"), ("nfs-common"), ("ntop"), ("ntp"), ("openssh-client"), ("openssh-server"), ("openssh-sftp-server"), ("openssl"), ("python"), ("python-pip"), ("suckless-tools"), ("sysstat"), ("tree"), ("vagrant"), ("vim"), ("vim-addon-manager"), ("vim-puppet"), ("vim-syntax-docker"), ("virtualbox"), ("vlc"), ("wget"), ("whois"), ("x264"), ("xfce4-terminal"), ("xfonts-terminus"), ("xinit"), ]) def test_packages(Package, name): assert Package(name).is_installed
import pytest @pytest.mark.parametrize("name", [ ("apt-file"), ("apt-transport-https"), ("atsar"), ("blktrace"), ("ca-certificates"), ("chromium-browser"), ("cron"), ("curl"), ("diod"), ("docker-engine"), ("git"), ("gnupg"), ("handbrake"), ("handbrake-cli"), ("haveged"), ("htop"), ("i3"), ("iotop"), ("language-pack-en-base"), ("laptop-mode-tools"), ("nfs-common"), ("ntop"), ("ntp"), ("openssh-client"), ("openssh-server"), ("openssh-sftp-server"), ("openssl"), ("python"), ("python-pip"), ("sysstat"), ("tree"), ("vagrant"), ("vim"), ("vim-addon-manager"), ("vim-puppet"), ("vim-syntax-docker"), ("virtualbox"), ("vlc"), ("wget"), ("whois"), ("x264"), ("xinit"), ]) def test_packages(Package, name): assert Package(name).is_installed
Refactor the test for the method test_filter inside class FullCaseViewSet and create a new test that allows you to test for just ASCII characters
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase, Client from django.contrib.auth.models import Permission from django.core.urlresolvers import reverse from legalaid.views import FullCaseViewSet from cla_backend.apps.call_centre.permissions import * from cla_backend.urls import * from rest_framework import routers from legalaid.tests.views.test_base import CLAOperatorAuthBaseApiTestMixin class FullCaseViewSetTestCase(CLAOperatorAuthBaseApiTestMixin,TestCase): def setUp(self): super(FullCaseViewSetTestCase, self).setUp() self.url = reverse('call_centre:case-list') def test_filter_queryset_for_unicode_characters_status_code_200(self): response = self.client.get(self.url+'?search=Mark%20O%E2%80%99Brien', HTTP_AUTHORIZATION='Bearer %s' % self.operator_manager_token) self.assertEqual(response.status_code, 200) def test_filter_queryset_for_only_ASCII_characters_status_code_200(self): response = self.client.get(self.url+'?search=John Smith', HTTP_AUTHORIZATION='Bearer %s' % self.operator_manager_token) self.assertEqual(response.status_code, 200)
import unittest from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase, Client from django.contrib.auth.models import Permission from legalaid.tests.views.test_base import CLAProviderAuthBaseApiTestMixin from legalaid.views import FullCaseViewSet from cla_backend.apps.call_centre.permissions import * from cla_backend.urls import * from rest_framework import routers class FullCaseViewSetTestCase(CLAProviderAuthBaseApiTestMixin, TestCase): def setUp(self): super(FullCaseViewSetTestCase, self).setUp() def test_filter_queryset_success_200(self): response = self.client.get('/call_centre/api/v1/case/?search=Mark%20O%E2%80%99Brien', HTTP_AUTHORIZATION='Bearer %s' % 'operator_manager_token') self.assertEqual(response.status_code, 200)
Update TAP status field label words
const interaction = { company: 'Company', subject: 'Subject', notes: 'Notes', contact: 'Contact', date: 'Date of interaction', dit_adviser: 'DIT adviser', service: 'Service', dit_team: 'Service provider', communication_channel: 'Communication channel', investment_project: 'Investment project', documents: 'Documents', } const serviceDelivery = { company: 'Company', subject: 'Subject', notes: 'Notes', contact: 'Contact', date: 'Date of service delivery', dit_adviser: 'DIT adviser', service: 'Service', service_delivery_status: 'Service status', dit_team: 'Service provider', communication_channel: 'Communication channel', is_event: 'Is this an event?', event: 'Event', investment_project: 'Investment project', documents: 'Documents', } const filters = { kind: 'Kind', communication_channel: 'Communication channel', dit_adviser: 'Adviser', date_after: 'From', date_before: 'To', dit_team: 'Service provider', } module.exports = { interaction, serviceDelivery, filters, }
const interaction = { company: 'Company', subject: 'Subject', notes: 'Notes', contact: 'Contact', date: 'Date of interaction', dit_adviser: 'DIT adviser', service: 'Service', dit_team: 'Service provider', communication_channel: 'Communication channel', investment_project: 'Investment project', documents: 'Documents', } const serviceDelivery = { company: 'Company', subject: 'Subject', notes: 'Notes', contact: 'Contact', date: 'Date of service delivery', dit_adviser: 'DIT adviser', service: 'Service', service_delivery_status: 'Trade Access Program (TAP) status', dit_team: 'Service provider', communication_channel: 'Communication channel', is_event: 'Is this an event?', event: 'Event', investment_project: 'Investment project', documents: 'Documents', } const filters = { kind: 'Kind', communication_channel: 'Communication channel', dit_adviser: 'Adviser', date_after: 'From', date_before: 'To', dit_team: 'Service provider', } module.exports = { interaction, serviceDelivery, filters, }
Fix issue with updating button before activity loaded
package net.honeybadgerlabs.adventurequest; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.TextView; public class ProfileFragment extends Fragment { private GridView listView; private TextView button; private StatAdapter adapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.profile, container, false); listView = (GridView) view.findViewById(R.id.attribute_list); button = (TextView) view.findViewById(R.id.spend_points); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); adapter = ((TitleActivity) getActivity()).getStatAdapter(); listView.setAdapter(adapter); updateButton(); } public void updateButton() { TitleActivity activity = (TitleActivity) getActivity(); if (activity != null) { int points = ((TitleActivity) getActivity()).getCharLevel() - adapter.totalPoints() - 1; if (points > 0) { String message = getResources().getQuantityString(R.plurals.points, points, points); button.setText(message); button.setVisibility(View.VISIBLE); } else { button.setVisibility(View.GONE); } } } }
package net.honeybadgerlabs.adventurequest; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.TextView; public class ProfileFragment extends Fragment { private GridView listView; private TextView button; private StatAdapter adapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.profile, container, false); listView = (GridView) view.findViewById(R.id.attribute_list); button = (TextView) view.findViewById(R.id.spend_points); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); adapter = ((TitleActivity) getActivity()).getStatAdapter(); listView.setAdapter(adapter); updateButton(); } public void updateButton() { try { int points = ((TitleActivity) getActivity()).getCharLevel() - adapter.totalPoints() - 1; if (points > 0) { String message = getResources().getQuantityString(R.plurals.points, points, points); button.setText(message); button.setVisibility(View.VISIBLE); } else { button.setVisibility(View.GONE); } } catch (NullPointerException e) { } } }
Add minor delay to video capture. Hopefully this helps the camera moduel keep up.
// This module is responsible for capturing videos 'use strict'; const config = require('config'); const PiCamera = require('pi-camera'); const myCamera = new PiCamera({ mode: 'video', output: process.argv[2], width: config.get('camera.videoWidth'), height: config.get('camera.videoHeight'), timeout: config.get('camera.videoTimeout'), nopreview: true, }); process.on('message', (message) => { if (message.cmd === 'set') { myCamera.config = Object.assign(myCamera.config, message.set); } else if (message.cmd === 'capture') { setTimeout(() => { myCamera.record() .then((result) => process.send({ response: 'success', result, error: null, })) .catch((error) => process.send({ response: 'failure', error, })); }, 500); } });
// This module is responsible for capturing videos 'use strict'; const config = require('config'); const PiCamera = require('pi-camera'); const myCamera = new PiCamera({ mode: 'video', output: process.argv[2], width: config.get('camera.videoWidth'), height: config.get('camera.videoHeight'), timeout: config.get('camera.videoTimeout'), nopreview: true, }); process.on('message', (message) => { if (message.cmd === 'set') { myCamera.config = Object.assign(myCamera.config, message.set); } else if (message.cmd === 'capture') { myCamera.record() .then((result) => process.send({ response: 'success', result, error: null, })) .catch((error) => process.send({ response: 'failure', error, })); } });
Remove unused imports & fix docblocks.
<?php namespace Rogue\Http\Controllers\Api; use Rogue\Services\PostService; use Rogue\Repositories\SignupRepository; use Rogue\Http\Transformers\PostTransformer; use Rogue\Http\Controllers\Traits\PostRequests; class PostsController extends ApiController { use PostRequests; /** * The post service instance. * * @var \Rogue\Services\PostService */ protected $posts; /** * The signup repository instance. * * @var \Rogue\Repositories\SignupRepository */ protected $signups; /** * @var \League\Fractal\TransformerAbstract; */ protected $transformer; /** * Create a controller instance. * * @param PostContract $posts * @return void */ public function __construct(PostService $posts, SignupRepository $signups) { $this->posts = $posts; $this->signups = $signups; $this->transformer = new PostTransformer; } }
<?php namespace Rogue\Http\Controllers\Api; use Rogue\Models\Post; use Rogue\Models\Signup; use Rogue\Services\PostService; use Rogue\Repositories\SignupRepository; use Rogue\Http\Transformers\PostTransformer; use Rogue\Http\Controllers\Traits\PostRequests; class PostsController extends ApiController { use PostRequests; /** * The post service instance. * * @var Rogue\Services\PostService */ protected $posts; /** * The signup repository instance. * * @var Rogue\Repositories\SignupRepository */ protected $signups; /** * @var \League\Fractal\TransformerAbstract; */ protected $transformer; /** * Create a controller instance. * * @param PostContract $posts * @return void */ public function __construct(PostService $posts, SignupRepository $signups) { $this->posts = $posts; $this->signups = $signups; $this->transformer = new PostTransformer; } }
Remove a lot of test output that is useless.
package jpower.core.test; import jpower.core.utils.ArrayUtils; import jpower.core.utils.StringUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class RandomTest { @Test public void testStringRandomness() { int times = 50; int count = 0; while (count < times) { String[] strings = StringUtils.random(50, 20); assertFalse(ArrayUtils.containsDuplicates(strings)); count++; } } @Test public void testStringLength() { String random = StringUtils.random(50); assertEquals(50, random.length()); } }
package jpower.core.test; import jpower.core.utils.ArrayUtils; import jpower.core.utils.StringUtils; import org.junit.Test; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class RandomTest { @Test public void testStringRandomness() { int times = 50; int count = 0; while (count < times) { String[] strings = StringUtils.random(50, 20); Stream.of(strings).forEach(System.out::println); assertFalse(ArrayUtils.containsDuplicates(strings)); count++; } } @Test public void testStringLength() { String random = StringUtils.random(50); assertEquals(50, random.length()); } }
Refactor SEND_DATA header to DATA_RESPONSE
package me.jesensky.dan.playertracker.net.packets; import me.jesensky.dan.playertracker.exceptions.InvalidPacketException; import java.util.Arrays; public enum PacketType { LOGIN(new byte[]{0x1, 0x0, 0x1}), LOGIN_RESPONSE(new byte[]{0x1, 0x0, 0x2}), FETCH_DATA(new byte[]{0x1, 0x0, 0x3}), DATA_RESPONSE(new byte[]{0x1, 0x0, 0x4}), ; PacketType(byte... data) { this.header = data; } public byte[] getHeader() { return this.header; } public static PacketType getTypeFromHeader(byte... head) throws InvalidPacketException { for (PacketType t : PacketType.values()) { if (Arrays.equals(t.getHeader(), head)) return t; } throw new InvalidPacketException("Header did not match any packet types."); } private byte[] header; }
package me.jesensky.dan.playertracker.net.packets; import me.jesensky.dan.playertracker.exceptions.InvalidPacketException; import java.util.Arrays; public enum PacketType { LOGIN(new byte[]{0x1, 0x0, 0x1}), LOGIN_RESPONSE(new byte[]{0x1, 0x0, 0x2}), FETCH_DATA(new byte[]{0x1, 0x0, 0x3}), SEND_DATA(new byte[]{0x1, 0x0, 0x4}), ; PacketType(byte... data) { this.header = data; } public byte[] getHeader() { return this.header; } public static PacketType getTypeFromHeader(byte... head) throws InvalidPacketException { for (PacketType t : PacketType.values()) { if (Arrays.equals(t.getHeader(), head)) return t; } throw new InvalidPacketException("Header did not match any packet types."); } private byte[] header; }