text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
BB-2229: Implement template based loop - fixed typo
<?php namespace Oro\Bundle\LayoutBundle\Twig; use Symfony\Bridge\Twig\Form\TwigRendererEngineInterface; use Symfony\Bridge\Twig\Form\TwigRendererInterface; use Oro\Component\Layout\Renderer; /** * Heavily inspired by TwigRenderer class * * @see \Symfony\Bridge\Twig\Form\TwigRenderer */ class TwigRenderer extends Renderer implements TwigRendererInterface { /** * @var TwigRendererEngineInterface */ protected $engine; /** * @param TwigRendererEngineInterface $engine */ public function __construct(TwigRendererEngineInterface $engine) { parent::__construct($engine); } /** * {@inheritdoc} */ public function setEnvironment(\Twig_Environment $environment) { $this->engine->setEnvironment($environment); } }
<?php namespace Oro\Bundle\LayoutBundle\Twig; use Symfony\Bridge\Twig\Form\TwigRendererEngineInterface; use Symfony\Bridge\Twig\Form\TwigRendererInterface; use Oro\Component\Layout\Renderer; /** * Heavily inspired by FormRenderer class * * @see \Symfony\Bridge\Twig\Form\TwigRenderer */ class TwigRenderer extends Renderer implements TwigRendererInterface { /** * @var TwigRendererEngineInterface */ protected $engine; /** * @param TwigRendererEngineInterface $engine */ public function __construct(TwigRendererEngineInterface $engine) { parent::__construct($engine); } /** * {@inheritdoc} */ public function setEnvironment(\Twig_Environment $environment) { $this->engine->setEnvironment($environment); } }
Skynet: Fix in collectd event notifier script. This patch adds a fix to collectd event notifier script, by providing a value the "severity" field in the event that it sends to salt-master event bus. with out that event listener in the skyring server will fail to process it. Change-Id: I20b738468c8022a25024e4327434ae6dab43a123 Signed-off-by: nnDarshan <d2c6d450ab98b078f2f1942c995e6d92dd504bc8@gmail.com>
#!/usr/bin/python import sys import os import salt.client def getNotification(): notification_dict = {} isEndOfDictionary = False for line in sys.stdin: if not line.strip(): isEndOfDictionary = True continue if isEndOfDictionary: break key, value = line.split(':') notification_dict[key] = value.lstrip()[:-1] return notification_dict, line def postTheNotificationToSaltMaster(): salt_payload = {} threshold_dict = {} caller = salt.client.Caller() threshold_dict['tags'], threshold_dict['message'] = getNotification() threshold_dict['severity'] = threshold_dict['tags']["Severity"] tag = "skyring/collectd/node/{0}/threshold/{1}/{2}".format( threshold_dict['tags']["Host"], threshold_dict['tags']["Plugin"], threshold_dict['tags']["Severity"]) caller.sminion.functions['event.send'](tag, threshold_dict) if __name__ == '__main__': postTheNotificationToSaltMaster()
#!/usr/bin/python import sys import os import salt.client def getNotification(): notification_dict = {} isEndOfDictionary = False for line in sys.stdin: if not line.strip(): isEndOfDictionary = True continue if isEndOfDictionary: break key, value = line.split(':') notification_dict[key] = value.lstrip()[:-1] return notification_dict, line def postTheNotificationToSaltMaster(): salt_payload = {} threshold_dict = {} caller = salt.client.Caller() threshold_dict['tags'], threshold_dict['message'] = getNotification() tag = "skyring/collectd/node/{0}/threshold/{1}/{2}".format( threshold_dict['tags']["Host"], threshold_dict['tags']["Plugin"], threshold_dict['tags']["Severity"]) caller.sminion.functions['event.send'](tag, threshold_dict) if __name__ == '__main__': postTheNotificationToSaltMaster()
Make it easy to do a full deploy with fab
from fabric.api import * env.runtime = 'production' env.hosts = ['chimera.ericholscher.com'] env.user = 'docs' env.code_dir = '/home/docs/sites/readthedocs.org/checkouts/readthedocs.org' env.virtualenv = '/home/docs/sites/readthedocs.org' env.rundir = '/home/docs/sites/readthedocs.org/run' def push(): "Push new code, but don't restart/reload." local('git push origin master') with cd(env.code_dir): run('git pull origin master') def update_requirements(): "Update requirements in the virtualenv." run("%s/bin/pip install -r %s/deploy_requirements.txt" % (env.virtualenv, env.code_dir)) def migrate(project=None): if project: run('django-admin.py migrate %s' % project) else: run('django-admin.py migrate') def restart(): "Restart (or just start) the server" env.user = "root" run("restart readthedocs-gunicorn") def celery(): "Restart (or just start) the server" env.user = "root" run("restart readthedocs-celery") def pull(): "Pull new code" with cd(env.code_dir): run('git pull origin master') def full_deploy(): push() update_requirements() migrate() restart() celery()
from fabric.api import * env.runtime = 'production' env.hosts = ['chimera.ericholscher.com'] env.user = 'docs' env.code_dir = '/home/docs/sites/readthedocs.org/checkouts/readthedocs.org' env.virtualenv = '/home/docs/sites/readthedocs.org' env.rundir = '/home/docs/sites/readthedocs.org/run' def update_requirements(): "Update requirements in the virtualenv." run("%s/bin/pip install -r %s/deploy_requirements.txt" % (env.virtualenv, env.code_dir)) def push(): "Push new code, but don't restart/reload." local('git push origin master') with cd(env.code_dir): run('git pull origin master') def pull(): "Pull new code" with cd(env.code_dir): run('git pull origin master') def restart(): "Restart (or just start) the server" env.user = "root" run("restart readthedocs-gunicorn") def celery(): "Restart (or just start) the server" env.user = "root" run("restart readthedocs-celery") def migrate(project=None): if project: run('django-admin.py migrate %s' % project) else: run('django-admin.py migrate')
Make venue coordinates non required in form
<?php class Admin_FormAction_Venue_Add extends CM_FormAction_Abstract { public function __construct() { parent::__construct('add'); } public function setup(CM_Form_Abstract $form) { $this->required_fields = array('name'); parent::setup($form); } protected function _process(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) { $name = $params->getString('name'); $url = $params->has('url') ? $params->getString('url') : null; $address = $params->has('address') ? $params->getString('address') : null; $coordinates = $params->has('coordinates') ? $params->getGeoPoint('coordinates') : null; $venue = Denkmal_Model_Venue::create(array( 'name' => $name, 'url' => $url, 'address' => $address, 'coordinates' => $coordinates, 'queued' => false, 'enabled' => true, )); $response->redirect('Admin_Page_Venue', array('venue' => $venue->getId())); } }
<?php class Admin_FormAction_Venue_Add extends CM_FormAction_Abstract { public function __construct() { parent::__construct('add'); } public function setup(CM_Form_Abstract $form) { $this->required_fields = array('name', 'coordinates'); parent::setup($form); } protected function _process(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) { $name = $params->getString('name'); $url = $params->has('url') ? $params->getString('url') : null; $address = $params->has('address') ? $params->getString('address') : null; $coordinates = $params->has('coordinates') ? $params->getGeoPoint('coordinates') : null; $venue = Denkmal_Model_Venue::create(array( 'name' => $name, 'url' => $url, 'address' => $address, 'coordinates' => $coordinates, 'queued' => false, 'enabled' => true, )); $response->redirect('Admin_Page_Venue', array('venue' => $venue->getId())); } }
Remove return type of transformable method
<?php namespace Flugg\Responder\Contracts; /** * A contract you can apply to your models to map a specific transformer to a model. * * @package Laravel Responder * @author Alexander Tømmerås <flugged@gmail.com> * @license The MIT License */ interface Transformable { /** * The path to the transformer class. * * @return string */ public static function transformer(); /** * Get the table associated with the model. * * @return string */ public function getTable(); /** * Get the table associated with the model. * * @return string */ public function getRelations(); /** * Determine if the given relation is loaded. * * @param string $key * @return bool */ public function relationLoaded( $key ); }
<?php namespace Flugg\Responder\Contracts; /** * A contract you can apply to your models to map a specific transformer to a model. * * @package Laravel Responder * @author Alexander Tømmerås <flugged@gmail.com> * @license The MIT License */ interface Transformable { /** * The path to the transformer class. * * @return string */ public static function transformer():string; /** * Get the table associated with the model. * * @return string */ public function getTable(); /** * Get the table associated with the model. * * @return string */ public function getRelations(); /** * Determine if the given relation is loaded. * * @param string $key * @return bool */ public function relationLoaded( $key ); }
Tweak test code for config base
seajs.config({ base: './base/' }) define(function(require) { var test = require('../../../test') var a = require('a') test.assert(a.name === 'a', a.name) // relative seajs.config({ base: '.' }) var base = seajs.data.base test.assert(/tests\/specs\/config\/$/.test(base), base) // root seajs.config({ base: '/root-path/' }) function expectedPath(str) { if (typeof process !== 'undefined') { return '/root-path/' + str + '.js' } return location.protocol + '//' + location.host + '/root-path/' + str + '.js' } test.assert(require.resolve('z') === expectedPath('z'), 'actual = ' + require.resolve('z') + ' expected = ' + expectedPath('z')) test.next() })
seajs.config({ base: './base/' }) define(function(require) { var test = require('../../../test') var a = require('a') test.assert(a.name === 'a', a.name) // relative seajs.config({ base: './' }) var base = seajs.data.base test.assert(/tests\/specs\/config\/$/.test(base), base) // root seajs.config({ base: '/root-path/' }) function expectedPath(str) { if (typeof process !== 'undefined') { return '/root-path/' + str + '.js' } return location.protocol + '//' + location.host + '/root-path/' + str + '.js' } test.assert(require.resolve('z') === expectedPath('z'), 'actual = ' + require.resolve('z') + ' expected = ' + expectedPath('z')) test.next() })
Use prerender and postrender events on Vector Clipping Layer example for better readability
import GeoJSON from '../src/ol/format/GeoJSON.js'; import Map from '../src/ol/Map.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; import View from '../src/ol/View.js'; import {Fill, Style} from '../src/ol/style.js'; import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import {fromLonLat} from '../src/ol/proj.js'; import {getVectorContext} from '../src/ol/render.js'; const base = new TileLayer({ source: new OSM(), }); const clipLayer = new VectorLayer({ style: new Style({ fill: new Fill({ color: 'black', }), }), source: new VectorSource({ url: './data/geojson/switzerland.geojson', format: new GeoJSON(), }), }); clipLayer.on('prerender', function (e) { e.context.globalCompositeOperation = 'destination-in'; }); clipLayer.on('postrender', function (e) { e.context.globalCompositeOperation = 'source-over'; }); const map = new Map({ layers: [base, clipLayer], target: 'map', view: new View({ center: fromLonLat([8.23, 46.86]), zoom: 7, }), });
import GeoJSON from '../src/ol/format/GeoJSON.js'; import Map from '../src/ol/Map.js'; import OSM from '../src/ol/source/OSM.js'; import VectorSource from '../src/ol/source/Vector.js'; import View from '../src/ol/View.js'; import {Fill, Style} from '../src/ol/style.js'; import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js'; import {fromLonLat} from '../src/ol/proj.js'; import {getVectorContext} from '../src/ol/render.js'; const base = new TileLayer({ source: new OSM(), }); const clipLayer = new VectorLayer({ style: null, source: new VectorSource({ url: './data/geojson/switzerland.geojson', format: new GeoJSON(), }), }); const style = new Style({ fill: new Fill({ color: 'black', }), }); base.on('postrender', function (e) { e.context.globalCompositeOperation = 'destination-in'; const vectorContext = getVectorContext(e); clipLayer.getSource().forEachFeature(function (feature) { vectorContext.drawFeature(feature, style); }); e.context.globalCompositeOperation = 'source-over'; }); const map = new Map({ layers: [base, clipLayer], target: 'map', view: new View({ center: fromLonLat([8.23, 46.86]), zoom: 7, }), });
Move GET to a different route
'use strict'; const Firebase = require('firebase'); const express = require('express'); const router = express.Router(); const FBURI = process.env.FBURI; const ref = new Firebase(FBURI); router.route('/') .head(function(req, res) { res.send({ message: 'Hello world!' }); }) .post(function(req, res) { const mandrillEvent = JSON.parse(req.body.mandrill_events); mandrillEvent.map(function(event) { ref.child('inbound').push(event, function(error) { if (error) { return res .status(501) .send({ sync: 'failed', error: error }); } res.send({ sync: 'successfull' }); }); }); }); router.get('/about', function(req, res) { res.send({ message: 'Hi, I\'m webhook!', status: 'OK' }); }); module.exports = router;
'use strict'; const Firebase = require('firebase'); const express = require('express'); const router = express.Router(); const FBURI = process.env.FBURI; const ref = new Firebase(FBURI); router.route('/') .head(function(req, res) { res.send({ message: 'Hi, I\'m webhook!' }); }) .get(function(req, res) { res.send({ status: 'OK' }); }) .post(function(req, res) { const mandrillEvent = JSON.parse(req.body.mandrill_events); mandrillEvent.map(function(event) { ref.child('inbound').push(event, function(error) { if (error) { return res .status(501) .send({ sync: 'failed', error: error }); } res.send({ sync: 'successfull' }); }); }); }); module.exports = router;
Add url for searching user by name
from django.conf.urls import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin from members import views admin.autodiscover() urlpatterns = patterns('', url(r'^$', views.homepage, name='homepage'), # Examples: # url(r'^$', 'hackfmi.views.home', name='home'), # url(r'^hackfmi/', include('hackfmi.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^search/(?P<name>\w+)/$', 'members.views.search', name='search'), url(r'^protocols/add/$', 'protocols.views.add', name='add-protocol'), url(r'^projects/add/$', 'projects.views.add_project', name='add-project'), url(r'^reports/add/$', 'reports.views.add_report', name='add-report'), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT,}),)
from django.conf.urls import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin from members import views admin.autodiscover() urlpatterns = patterns('', url(r'^$', views.homepage, name='homepage'), # Examples: # url(r'^$', 'hackfmi.views.home', name='home'), # url(r'^hackfmi/', include('hackfmi.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^protocols/add/$', 'protocols.views.add', name='add-protocol'), url(r'^projects/add/$', 'projects.views.add_project', name='add-project'), url(r'^reports/add/$', 'reports.views.add_report', name='add-report'), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT,}),)
Convert AppComponent constructor to oninit
import m from 'mithril'; import GameComponent from './game.js'; import UpdateNotificationComponent from './update-notification.js'; import SWUpdateManager from 'sw-update-manager'; class AppComponent { oninit() { if (navigator.serviceWorker && !window.__karma__ && window.location.port !== '8080') { let serviceWorker = navigator.serviceWorker.register('service-worker.js'); this.updateManager = new SWUpdateManager(serviceWorker); this.updateManager.on('updateAvailable', () => m.redraw()); this.updateManager.checkForUpdates(); } } view() { return m('div#app', [ this.updateManager ? m(UpdateNotificationComponent, { updateManager: this.updateManager }) : null, m(GameComponent) ]); } } export default AppComponent;
import m from 'mithril'; import GameComponent from './game.js'; import UpdateNotificationComponent from './update-notification.js'; import SWUpdateManager from 'sw-update-manager'; class AppComponent { constructor() { if (navigator.serviceWorker && !window.__karma__ && window.location.port !== '8080') { let serviceWorker = navigator.serviceWorker.register('service-worker.js'); this.updateManager = new SWUpdateManager(serviceWorker); this.updateManager.on('updateAvailable', () => m.redraw()); this.updateManager.checkForUpdates(); } } view() { return m('div#app', [ this.updateManager ? m(UpdateNotificationComponent, { updateManager: this.updateManager }) : null, m(GameComponent) ]); } } export default AppComponent;
Fix defect for root route
const express = require('express'); const app = express(); const portNumber = process.env.PORT || 3000; const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser') if (process.env.NODE_ENV !== 'production') { require('dotenv').config(); } const path = require('path'); const users = require('./routes/users'); const token = require('./routes/token'); const resorts = require('./routes/resorts'); const trails = require('./routes/trails'); const ratings = require('./routes/ratings'); const favorites = require('./routes/favorites'); app.use(bodyParser.json()); app.use(cookieParser()); app.use('/apidoc', express.static(path.join(__dirname, 'apidoc'))); app.get('/', (req, res) => { res.status(200).send('Welcome to skiski.'); }); app.use(users); app.use(token); app.use(resorts); app.use(trails); app.use(ratings); app.use(favorites); app.use((req, res) => { res.sendStatus(404); }); app.listen(portNumber, () => { console.log(`Listening on port ${portNumber}`); }); module.exports = app;
const express = require('express'); const app = express(); const portNumber = process.env.PORT || 3000; const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser') if (process.env.NODE_ENV !== 'production') { require('dotenv').config(); } const path = require('path'); const users = require('./routes/users'); const token = require('./routes/token'); const resorts = require('./routes/resorts'); const trails = require('./routes/trails'); const ratings = require('./routes/ratings'); const favorites = require('./routes/favorites'); app.use(bodyParser.json()); app.use(cookieParser()); app.use('/apidoc', express.static(path.join(__dirname, 'apidoc'))); app.get('/', (req, res) => { res.status(200).send('Welcome to skiski.'); }; app.use(users); app.use(token); app.use(resorts); app.use(trails); app.use(ratings); app.use(favorites); app.use((req, res) => { res.sendStatus(404); }); app.listen(portNumber, () => { console.log(`Listening on port ${portNumber}`); }); module.exports = app;
Test on winning point for Nadal
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(MockitoJUnitRunner.class) public class TennisGameTest { @InjectMocks private TennisGame tennisGame; @Mock private TennisGameScore tennisGameScore; @Before public void setUp() { initTennisGameScore(); } @Test public void should_federer_wins_point_when_it_has_an_even_number() { assertThat(tennisGame.isFedererWinPoint(2)).isTrue(); } @Test public void should_nadal_wins_point_when_it_has_an_odd_number() { assertThat(tennisGame.isFedererWinPoint(1)).isFalse(); } private void initTennisGameScore() { tennisGameScore.init(); tennisGameScore.addPoint(0, 1, "Nadal"); tennisGameScore.addPoint(0, 2, "Nadal"); tennisGameScore.addPoint(0, 3, "Nadal"); tennisGameScore.addPoint(0, 4, "Nadal"); } }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(MockitoJUnitRunner.class) public class TennisGameTest { @InjectMocks private TennisGame tennisGame; @Mock private TennisGameScore tennisGameScore; @Before public void setUp() { initTennisGameScore(); } @Test public void should_federer_wins_point_when_it_has_an_even_number() { assertThat(tennisGame.isFedererWinPoint(2)).isTrue(); } private void initTennisGameScore() { tennisGameScore.init(); tennisGameScore.addPoint(0, 1, "Nadal"); tennisGameScore.addPoint(0, 2, "Nadal"); tennisGameScore.addPoint(0, 3, "Nadal"); tennisGameScore.addPoint(0, 4, "Nadal"); } }
Fix non existent env var and simplify string operations 1. `DRSS_BOT_CONTROLLER` is missing in `app.json` manifest, maybe meant `DRSS_BOT_CONTROLLER_IDS` ? 2. `.replace(' ', '')` doesn't make sense because it replaces only the first occurrence 3. Simple array creation without internal spaces 4. Heroku config vars parser should trim leading and trailing spaces by itself, if not, then in this case it is necessary to trim all vars
const config = require('./config.json') // Environment variable in Docker container and Heroku if available config.bot.token = !process.env.DRSS_BOT_TOKEN || process.env.DRSS_BOT_TOKEN === 'drss_docker_token' ? (config.bot.token || 's') : process.env.DRSS_BOT_TOKEN // process.env.MONGODB_URI is intended for use by Heroku config.database.uri = process.env.DRSS_DATABASE_URI || process.env.MONGODB_URI || config.database.uri // Heroku deployment configuration config.bot.prefix = process.env.DRSS_BOT_PREFIX || config.bot.prefix config.bot.controllerIds = process.env.DRSS_BOT_CONTROLLER_IDS ? process.env.DRSS_BOT_CONTROLLER_IDS.split(/\s*,\s*/) : config.bot.controllerIds config.feeds.refreshTimeMinutes = Number(process.env.DRSS_FEEDS_REFRESH_TIME_MINUTES) || config.feeds.refreshTimeMinutes config.feeds.defaultMessage = process.env.DRSS_FEEDS_DEFAULT_MESSAGE || config.feeds.defaultMessage module.exports = config
const config = require('./config.json') // Environment variable in Docker container and Heroku if available config.bot.token = !process.env.DRSS_BOT_TOKEN || process.env.DRSS_BOT_TOKEN === 'drss_docker_token' ? (config.bot.token || 's') : process.env.DRSS_BOT_TOKEN // process.env.MONGODB_URI is intended for use by Heroku config.database.uri = process.env.DRSS_DATABASE_URI || process.env.MONGODB_URI || config.database.uri // Heroku deployment configuration config.bot.prefix = process.env.DRSS_BOT_PREFIX || config.bot.prefix config.bot.controllerIds = process.env.DRSS_BOT_CONTROLLER ? process.env.DRSS_BOT_CONTROLLER_IDS.replace(' ', '').split(',').map(id => id.trim()) : config.bot.controllerIds config.feeds.refreshTimeMinutes = Number(process.env.DRSS_FEEDS_REFRESH_TIME_MINUTES) || config.feeds.refreshTimeMinutes config.feeds.defaultMessage = process.env.DRSS_FEEDS_DEFAULT_MESSAGE || config.feeds.defaultMessage module.exports = config
Make redirection in language switcher
<?php use yii\helpers\Url; ?> <div class="layout-header_languages"> <?php $page = Yii::$app->request->getPage(); $section = Yii::$app->request->getSection(); $lang = Yii::$app->request->getLang(); ?> <div class="layout-header_languages-item"><a href="http://new.he-he.org/ru/">Ru</a></div> <div class="layout-header_languages-item"><a href="https://he-he.org/en/">En</a></div> <div class="layout-header_languages-item"><a href="https://he-he.org/es/">Es</a></div> <?php /* <?php foreach($items as $item) { ?> <?php $href = Url::toRoute([$page, 'section' => $section, 'lang' => $item['lang']]); $classes = 'layout-header_languages-item'; $classes .= ($lang === $item['lang']) ? ' layout-header_languages-item--active' : ''; ?> <div class="<?= $classes ?>"> <a href="<?= $href ?>"> <?= $item['title'] ?> </a> </div> <?php } ?> */?> </div>
<?php use yii\helpers\Url; ?> <div class="layout-header_languages"> <?php $page = Yii::$app->request->getPage(); $section = Yii::$app->request->getSection(); $lang = Yii::$app->request->getLang(); ?> <?php foreach($items as $item) { ?> <?php $href = Url::toRoute([$page, 'section' => $section, 'lang' => $item['lang']]); $classes = 'layout-header_languages-item'; $classes .= ($lang === $item['lang']) ? ' layout-header_languages-item--active' : ''; ?> <div class="<?= $classes ?>"> <a href="<?= $href ?>"> <?= $item['title'] ?> </a> </div> <?php } ?> </div>
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-background-size/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-background-size/tachyons-background-size.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_background-size.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/background-size/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/themes/background-size/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-background-size/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-background-size/tachyons-background-size.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_background-size.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/background-size/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/themes/background-size/index.html', html)
Fix error when favorite list is empty
/* This file is part of Indico. * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN). * * Indico is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. */ import * as actions from '../actions'; const initialState = {}; export default function reducer(state = initialState, action) { switch (action.type) { case actions.SET_FAVORITE_ROOMS: return {...state, favoriteRooms: Object.assign({}, ...action.rooms.map((id) => ({[id]: true})))}; case actions.ADD_FAVORITE_ROOM: return {...state, favoriteRooms: {...state.favoriteRooms, [action.id]: true}}; case actions.DEL_FAVORITE_ROOM: return {...state, favoriteRooms: {...state.favoriteRooms, [action.id]: false}}; default: return state; } }
/* This file is part of Indico. * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN). * * Indico is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. */ import * as actions from '../actions'; const initialState = {}; export default function reducer(state = initialState, action) { switch (action.type) { case actions.SET_FAVORITE_ROOMS: return {...state, favoriteRooms: Object.assign(...action.rooms.map((id) => ({[id]: true})))}; case actions.ADD_FAVORITE_ROOM: return {...state, favoriteRooms: {...state.favoriteRooms, [action.id]: true}}; case actions.DEL_FAVORITE_ROOM: return {...state, favoriteRooms: {...state.favoriteRooms, [action.id]: false}}; default: return state; } }
Add wiring constant for kicker power
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.templates.Wiring; /** * * @author TJ2 */ public class KickerAuto extends CommandBase { double timeout; double power = Wiring.kickerPower; public KickerAuto(double time) { super("kicker auto"); requires(kicker); timeout = time; // Use requires() here to declare subsystem dependencies // eg. requires(chassis); } // Called just before this Command runs the first time protected void initialize() { setTimeout(timeout); } // Called repeatedly when this Command is scheduled to run protected void execute() { kicker.KickerOpenLoop(power); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return isTimedOut(); } // Called once after isFinished returns true protected void end() { kicker.KickerOpenLoop(0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands; /** * * @author TJ2 */ public class KickerAuto extends CommandBase { double timeout; double power = 1; public KickerAuto(double time) { super("kicker auto"); requires(kicker); timeout = time; // Use requires() here to declare subsystem dependencies // eg. requires(chassis); } // Called just before this Command runs the first time protected void initialize() { setTimeout(timeout); } // Called repeatedly when this Command is scheduled to run protected void execute() { kicker.KickerOpenLoop(power); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return isTimedOut(); } // Called once after isFinished returns true protected void end() { kicker.KickerOpenLoop(0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
Mark c.Redirect as todo item
package auth import ( "github.com/robfig/revel" //_ "github.com/pjvds/acvte/modules/auth/routes" ) type AuthenticatedResource struct { Resource interface{} Role string } func init() { revel.OnAppStart(func() { }) } var SessionAuthenticationFilter = func(c *revel.Controller, fc []revel.Filter) { // TODO: Fix redirect //c.Redirect() } func AclApply(m []AuthenticatedResource) { // revel.FilterController(controllers.Admin{}). // Add(AuthenticationFilter) for _, a := range m { var fc revel.FilterConfigurator if reflect.TypeOf(a.Resource).Kind() == reflect.Func { // revel action fc = revel.FilterAction(a.Resource) } else { // revel controller fc = revel.FilterController(a.Resource) } fc.Add(SessionAuthenticationFilter) } } // func GetRole(u *models.User) string { // return "user" // } // func GetUser() *models.User { // u := new(models.User) // return u // }
package auth import ( "github.com/robfig/revel" //_ "github.com/pjvds/acvte/modules/auth/routes" ) type AuthenticatedResource struct { Resource interface{} Role string } func init() { revel.OnAppStart(func() { }) } var SessionAuthenticationFilter = func(c *revel.Controller, fc []revel.Filter) { c.Redirect() } func AclApply(m []AuthenticatedResource) { // revel.FilterController(controllers.Admin{}). // Add(AuthenticationFilter) for _, a := range m { var fc revel.FilterConfigurator if reflect.TypeOf(a.Resource).Kind() == reflect.Func { // revel action fc = revel.FilterAction(a.Resource) } else { // revel controller fc = revel.FilterController(a.Resource) } fc.Add(SessionAuthenticationFilter) } } // func GetRole(u *models.User) string { // return "user" // } // func GetUser() *models.User { // u := new(models.User) // return u // }
Fix variable name in `TDecoratedCategoryMenuPageHandler`
<?php namespace wcf\system\page\handler; use wcf\data\category\AbstractDecoratedCategory; use wcf\data\IAccessibleObject; /** * Implementation of the `IMenuPageHandler::isVisible()` methods for decorated category-bound pages. * * @author Matthias Schmidt * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Page\Handler * @since 3.0 */ trait TDecoratedCategoryMenuPageHandler { /** * Returns the name of the decorated class name. * * @return string */ abstract protected function getDecoratedCategoryClass(); /** * @see IMenuPageHandler::isVisible() */ public function isVisible($objectID = null) { $className = $this->getDecoratedCategoryClass(); /** @var AbstractDecoratedCategory $category */ $category = $className::getCategory($objectID); // check if category exists if ($category === null) { return false; } // check if access to category is restricted if ($category instanceof IAccessibleObject && !$category->isAccessible()) { return false; } // fallback to default value of AbstractMenuPageHandler::isVisible() return true; } }
<?php namespace wcf\system\page\handler; use wcf\data\category\AbstractDecoratedCategory; use wcf\data\IAccessibleObject; /** * Implementation of the `IMenuPageHandler::isVisible()` methods for decorated category-bound pages. * * @author Matthias Schmidt * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Page\Handler * @since 3.0 */ trait TDecoratedCategoryMenuPageHandler { /** * Returns the name of the decorated class name. * * @return string */ abstract protected function getDecoratedCategoryClass(); /** * @see IMenuPageHandler::isVisible() */ public function isVisible($objectID = null) { $className = $this->getDecoratedCategoryClass(); /** @var AbstractDecoratedCategory $category */ $category = $className::getCategory($objectID); // check if category exists if ($category === null) { return false; } // check if access to category is restricted if ($category instanceof IAccessibleObject && !$className->isAccessible()) { return false; } // fallback to default value of AbstractMenuPageHandler::isVisible() return true; } }
Make Model.all work as expected.
var resourceful = require('resourceful'); var Riak = resourceful.engines.Riak = function(config) { if(config && config.bucket) { this.bucket = config.bucket; } else { throw new Error('bucket must be set in the config for each model.') } this.db = require('riak-js').getClient(config); this.cache = new resourceful.Cache(); } Riak.prototype.protocol = 'riak'; Riak.prototype.save = function (key, val, callback) { this.db.save(this.bucket, key, val, {}, callback); }; Riak.prototype.get = function (key, callback) { this.db.get(this.bucket, key, {}, function(e, value, meta) { value._id = meta.key; callback(e, value); }); } Riak.prototype.update = function(key, val, callback) { var that = this; that.get(key, function(err, old) { that.save(key, resourceful.mixin(old, val), callback); }); } Riak.prototype.all = function(callback) { this.db.getAll(this.bucket, function(e, all) { if(e) { callback(e); } else { var models = all.map(function(obj) { return obj.data; }); callback(null, models); } }); } Riak.prototype.destroy = function(key, callback) { this.db.remove(this.bucket, key, callback); }
var resourceful = require('resourceful'); var Riak = resourceful.engines.Riak = function(config) { if(config && config.bucket) { this.bucket = config.bucket; } else { throw new Error('bucket must be set in the config for each model.') } this.db = require('riak-js').getClient(config); this.cache = new resourceful.Cache(); } Riak.prototype.protocol = 'riak'; Riak.prototype.save = function (key, val, callback) { this.db.save(this.bucket, key, val, {}, callback); }; Riak.prototype.get = function (key, callback) { this.db.get(this.bucket, key, {}, function(e, value, meta) { value._id = meta.key; callback(e, value); }); } Riak.prototype.update = function(key, val, callback) { var that = this; that.get(key, function(err, old) { that.save(key, resourceful.mixin(old, val), callback); }); } Riak.prototype.all = function(callback) { this.db.getAll(this.bucket, callback); } Riak.prototype.destroy = function(key, callback) { this.db.remove(this.bucket, key, callback); }
Use scoped session for celery tasks
# -*- coding: utf-8 -*- import sys import yaml from celery.signals import worker_process_init from pyvac.helpers.sqla import create_engine from pyvac.helpers.ldap import LdapCache from pyvac.helpers.mail import SmtpCache try: from yaml import CSafeLoader as YAMLLoader except ImportError: from yaml import SafeLoader as YAMLLoader @worker_process_init.connect def configure_workers(sender=None, conf=None, **kwargs): # The Worker (child process of the celeryd) must have # it's own SQL Connection (A unix forking operation preserve fd) with open(sys.argv[1]) as fdesc: conf = yaml.load(fdesc, YAMLLoader) # XXX Register the database create_engine('pyvac', conf.get('databases').get('pyvac'), scoped=True) LdapCache.configure(conf.get('ldap').get('conf')) SmtpCache.configure(conf.get('smtp'))
# -*- coding: utf-8 -*- import sys import yaml from celery.signals import worker_process_init from pyvac.helpers.sqla import create_engine from pyvac.helpers.ldap import LdapCache from pyvac.helpers.mail import SmtpCache try: from yaml import CSafeLoader as YAMLLoader except ImportError: from yaml import SafeLoader as YAMLLoader @worker_process_init.connect def configure_workers(sender=None, conf=None, **kwargs): # The Worker (child process of the celeryd) must have # it's own SQL Connection (A unix forking operation preserve fd) with open(sys.argv[1]) as fdesc: conf = yaml.load(fdesc, YAMLLoader) # XXX Register the database create_engine('pyvac', conf.get('databases').get('pyvac'), scoped=False) LdapCache.configure(conf.get('ldap').get('conf')) SmtpCache.configure(conf.get('smtp'))
Simplify and update the repository interface
<?php /** * (c) Gordon Franke <info@nevalon.de> * (c) Thibault Duplessis <thibault.duplessis@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Bundle\DoctrineUserBundle\DAO; interface UserRepositoryInterface { /** * Find a user by its username * @param string $username * @return User or null if user does not exist */ public function findOneByUsername($username); /** * Find a user by its email * @param string $email * @return User or null if user does not exist */ public function findOneByEmail($email); /** * Find a user by its username or email * @param string $usernameOrEmail * @return User or null if user does not exist */ public function findOneByUsernameOrEmail($usernameOrEmail); /** * Get the Entity manager or the Document manager, depending on the db driver * * @return mixed **/ public function getObjectManager(); /** * Get the class of the User Entity or Document, depending on the db driver * * @return string a model fully qualified class name **/ public function getObjectClass(); }
<?php /** * (c) Gordon Franke <info@nevalon.de> * (c) Thibault Duplessis <thibault.duplessis@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Bundle\DoctrineUserBundle\DAO; interface UserRepositoryInterface { /** * Find a user by its id * @param mixed $id * @return User or null if user does not exist */ public function findOneById($id); /** * Find a user by its username * @param string $username * @return User or null if user does not exist */ public function findOneByUsername($username); /** * Find a user by its email * @param string $email * @return User or null if user does not exist */ public function findOneByEmail($email); /** * Find a user by its username or email * @param string $usernameOrEmail * @return User or null if user does not exist */ public function findOneByUsernameOrEmail($usernameOrEmail); }
Add a LogoutSuccessHandler to show usage of a RedirectStrategy that's not context-relative
package app.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { http.headers().defaultsDisabled().cacheControl(); http.logout() .logoutSuccessUrl("/") .invalidateHttpSession(true) .logoutSuccessHandler(logoutHandler()) .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); } private LogoutSuccessHandler logoutHandler() { final SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler(); final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); redirectStrategy.setContextRelative(false); logoutSuccessHandler.setRedirectStrategy(redirectStrategy); return logoutSuccessHandler; } }
package app.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { http.headers().defaultsDisabled().cacheControl(); http.logout() .logoutSuccessUrl("/") .invalidateHttpSession(true) .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); } }
Add example time zones to option definition
#!/usr/bin/env node const chalk = require('chalk'); const yargs = require('yargs'); // ./modules const rocketLaunch = require('./lib/modules/rocketLaunch'); var argv = yargs .usage('Usage: $0 <command> [options]') .demandCommand(1) .command('about', 'Info about the CLI', about) .command('next', 'Get next rocket launch', function (yargs) { return yargs.option('d', { alias: 'details', describe: 'Details about the next launch' }).option('tz', { alias: 'timezone', describe: 'Define time zone for time info e.g. America/New_York, Europe/Paris, Asia/Shanghai' }); }, rocketLaunch.nextLaunch ) .help('h') .alias('h', 'help') .argv; function about() { console.log(chalk.green('Welcome to Space CLI'), '- a CLI for space information' + '\n\n' + 'Credits:' + '\n' + 'https://launchlibrary.net/ - API documentation for upcoming launches'); }
#!/usr/bin/env node const chalk = require('chalk'); const yargs = require('yargs'); // ./modules const rocketLaunch = require('./lib/modules/rocketLaunch'); var argv = yargs .usage('Usage: $0 <command> [options]') .demandCommand(1) .command('about', 'Info about the CLI', about) .command('next', 'Get next rocket launch', function (yargs) { return yargs.option('d', { alias: 'details', describe: 'Details about the next launch' }).option('tz', { alias: 'timezone', describe: 'Define time zone for time info' }); }, rocketLaunch.nextLaunch ) .help('h') .alias('h', 'help') .argv; function about() { console.log(chalk.green('Welcome to Space CLI'), '- a CLI for space information' + '\n\n' + 'Credits:' + '\n' + 'https://launchlibrary.net/ - API documentation for upcoming launches'); }
Revert "Send error-type info to pillow error DD metrics"
from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from django.db.models import Count from corehq.util.datadog.gauges import datadog_gauge from pillow_retry.models import PillowError @periodic_task( run_every=crontab(minute="*/15"), queue=settings.CELERY_PERIODIC_QUEUE, ) def record_pillow_error_queue_size(): data = PillowError.objects.values('pillow').annotate(num_errors=Count('id')) for row in data: datadog_gauge('commcare.pillowtop.error_queue', row['num_errors'], tags=[ 'pillow_name:%s' % row['pillow'], 'host:celery', 'group:celery' ])
from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from django.db.models import Count from corehq.util.datadog.gauges import datadog_gauge from pillow_retry.models import PillowError @periodic_task( run_every=crontab(minute="*/15"), queue=settings.CELERY_PERIODIC_QUEUE, ) def record_pillow_error_queue_size(): data = PillowError.objects.values('pillow').annotate(num_errors=Count('id')) for row in data: datadog_gauge('commcare.pillowtop.error_queue', row['num_errors'], tags=[ 'pillow_name:%s' % row['pillow'], 'host:celery', 'group:celery', 'error_type:%s' % row['error_type'] ])
Fix compatibility with Phalcon 2 in Catalog module
<?php /** * @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me> */ namespace Catalog; use Phalcon\DiInterface; class Module implements \Phalcon\Mvc\ModuleDefinitionInterface { public function registerAutoloaders(DiInterface $dependencyInjector = null) { $loader = new \Phalcon\Loader(); $loader->registerNamespaces(array( 'Catalog\Controller' => APPLICATION_PATH . '/modules/catalog/controllers/', 'Catalog\Model' => APPLICATION_PATH . '/modules/catalog/models/', )); $loader->register(); } public function registerServices(DiInterface $dependencyInjector) { $dispatcher = $dependencyInjector->get('dispatcher'); $dispatcher->setDefaultNamespace('Catalog\Controller'); /** * @var $view \Phalcon\Mvc\View */ $view = $dependencyInjector->get('view'); $view->setLayout('index'); $view->setViewsDir(APPLICATION_PATH . '/modules/catalog/views/'); $view->setLayoutsDir('../../common/layouts/'); $view->setPartialsDir('../../common/partials/'); $dependencyInjector->set('view', $view); } }
<?php /** * @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me> */ namespace Catalog; class Module implements \Phalcon\Mvc\ModuleDefinitionInterface { public function registerAutoloaders() { $loader = new \Phalcon\Loader(); $loader->registerNamespaces(array( 'Catalog\Controller' => APPLICATION_PATH . '/modules/catalog/controllers/', 'Catalog\Model' => APPLICATION_PATH . '/modules/catalog/models/', )); $loader->register(); } public function registerServices($di) { $dispatcher = $di->get('dispatcher'); $dispatcher->setDefaultNamespace('Catalog\Controller'); /** * @var $view \Phalcon\Mvc\View */ $view = $di->get('view'); $view->setLayout('index'); $view->setViewsDir(APPLICATION_PATH . '/modules/catalog/views/'); $view->setLayoutsDir('../../common/layouts/'); $view->setPartialsDir('../../common/partials/'); $di->set('view', $view); } }
Change version number to '1.0.3' Signed-off-by: daniel <3d0f3b9ddcacec30c4008c5e030e6c13a478cb4f@yunify.com>
# coding:utf-8 from setuptools import setup, find_packages setup( name = 'qsctl', version = '1.0.3', description = 'Advanced command line tool for QingStor.', long_description = open('README.rst', 'rb').read().decode('utf-8'), keywords = 'qingcloud qingstor qsctl', author = 'Daniel Zheng', author_email = 'daniel@yunify.com', url = 'https://docs.qingcloud.com', scripts = ['bin/qsctl', 'bin/qsctl.cmd'], packages = find_packages('.'), package_dir = {'qsctl': 'qingstor',}, namespace_packages = ['qingstor',], include_package_data = True, install_requires = [ 'argparse >= 1.1', 'PyYAML >= 3.1', 'qingcloud-sdk >= 1.0.7', 'docutils >= 0.10', ] )
# coding:utf-8 from setuptools import setup, find_packages setup( name = 'qsctl', version = '1.0.2', description = 'Advanced command line tool for QingStor.', long_description = open('README.rst', 'rb').read().decode('utf-8'), keywords = 'qingcloud qingstor qsctl', author = 'Daniel Zheng', author_email = 'daniel@yunify.com', url = 'https://docs.qingcloud.com', scripts = ['bin/qsctl', 'bin/qsctl.cmd'], packages = find_packages('.'), package_dir = {'qsctl': 'qingstor',}, namespace_packages = ['qingstor',], include_package_data = True, install_requires = [ 'argparse >= 1.1', 'PyYAML >= 3.1', 'qingcloud-sdk >= 1.0.7', 'docutils >= 0.10', ] )
Fix encoding of characters like (
var crypto = require('crypto') , qs = require('querystring') ; function sha1 (key, body) { return crypto.createHmac('sha1', key).update(body).digest('base64') } function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret, body) { // adapted from https://dev.twitter.com/docs/auth/oauth var base = httpMethod + "&" + encodeURIComponent( base_uri ) + "&" + Object.keys(params).sort().map(function (i) { // big WTF here with the escape + encoding but it's what twitter wants return encodeURIComponent(escape(i)) + "%3D" + encodeURIComponent(escape(params[i])) }).join("%26") var key = consumer_secret + '&' if (token_secret) key += token_secret return sha1(key, base) } exports.hmacsign = hmacsign
var crypto = require('crypto') , qs = require('querystring') ; function sha1 (key, body) { return crypto.createHmac('sha1', key).update(body).digest('base64') } function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret, body) { // adapted from https://dev.twitter.com/docs/auth/oauth var base = httpMethod + "&" + encodeURIComponent( base_uri ) + "&" + Object.keys(params).sort().map(function (i) { // big WTF here with the escape + encoding but it's what twitter wants return encodeURIComponent(qs.escape(i)) + "%3D" + encodeURIComponent(qs.escape(params[i])) }).join("%26") var key = consumer_secret + '&' if (token_secret) key += token_secret return sha1(key, base) } exports.hmacsign = hmacsign
openvidu-ce: Check if mediaNode property is empty
package io.openvidu.server.utils; import io.openvidu.java.client.Recording.OutputMode; import io.openvidu.java.client.RecordingProperties; import io.openvidu.server.core.Session; public final class RecordingUtils { public final static boolean IS_COMPOSED(OutputMode outputMode) { return (OutputMode.COMPOSED.equals(outputMode) || OutputMode.COMPOSED_QUICK_START.equals(outputMode)); } public final static RecordingProperties RECORDING_PROPERTIES_WITH_MEDIA_NODE(Session session) { RecordingProperties recordingProperties = session.getSessionProperties().defaultRecordingProperties(); if (recordingProperties.mediaNode() == null || recordingProperties.mediaNode().isEmpty()) { recordingProperties = new RecordingProperties.Builder(recordingProperties) .mediaNode(session.getMediaNodeId()).build(); } return recordingProperties; } }
package io.openvidu.server.utils; import io.openvidu.java.client.Recording.OutputMode; import io.openvidu.java.client.RecordingProperties; import io.openvidu.server.core.Session; public final class RecordingUtils { public final static boolean IS_COMPOSED(OutputMode outputMode) { return (OutputMode.COMPOSED.equals(outputMode) || OutputMode.COMPOSED_QUICK_START.equals(outputMode)); } public final static RecordingProperties RECORDING_PROPERTIES_WITH_MEDIA_NODE(Session session) { RecordingProperties recordingProperties = session.getSessionProperties().defaultRecordingProperties(); if (recordingProperties.mediaNode() == null) { recordingProperties = new RecordingProperties.Builder(recordingProperties) .mediaNode(session.getMediaNodeId()).build(); } return recordingProperties; } }
Remove python 3.2 from trove classifiers
from setuptools import setup setup( name = 'sphinx-csharp', version = '0.1.0', author = 'djungelorm', author_email = 'djungelorm@users.noreply.github.com', packages = ['sphinx_csharp'], url = 'https://github.com/djungelorm/sphinx-csharp', license = 'MIT', description = 'C# domain for Sphinx', install_requires = ['Sphinx'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Operating System :: OS Independent', 'Topic :: Documentation :: Sphinx' ] )
from setuptools import setup setup( name = 'sphinx-csharp', version = '0.1.0', author = 'djungelorm', author_email = 'djungelorm@users.noreply.github.com', packages = ['sphinx_csharp'], url = 'https://github.com/djungelorm/sphinx-csharp', license = 'MIT', description = 'C# domain for Sphinx', install_requires = ['Sphinx'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Operating System :: OS Independent', 'Topic :: Documentation :: Sphinx' ] )
Change datetime property to date
# coding: utf-8 from __future__ import absolute_import from google.appengine.ext import ndb from api import fields import config import model import util class Pay(model.Base): name = ndb.StringProperty(default='') date_for = ndb.DateProperty(auto_now_add=True) date_paid = ndb.DateProperty(auto_now_add=True) code = ndb.StringProperty(default='') amount = ndb.FloatProperty(default=0.0) @ndb.ComputedProperty def amount_format(self): return u'%s %0.2f' % (config.CONFIG_DB.currency, self.amount) @ndb.ComputedProperty def is_positive(self): return self.amount >= 0 @classmethod def get_dbs(cls, is_positive=None, **kwargs): return super(Pay, cls).get_dbs( is_positive=is_positive or util.param('is_positive', bool), **kwargs ) PAY_FIELDS = { 'amount': fields.Float, 'amount_format': fields.String, 'code': fields.String, 'date_for': fields.DateTimeField, 'date_paid': fields.DateTimeField, 'is_positive': fields.Boolean, 'name': fields.String, } PAY_FIELDS.update(model.BASE_FIELDS)
# coding: utf-8 from __future__ import absolute_import from google.appengine.ext import ndb from api import fields import config import model import util class Pay(model.Base): name = ndb.StringProperty(default='') date_for = ndb.DateTimeProperty(auto_now_add=True) date_paid = ndb.DateTimeProperty(auto_now_add=True) code = ndb.StringProperty(default='') amount = ndb.FloatProperty(default=0.0) @ndb.ComputedProperty def amount_format(self): return u'%s %0.2f' % (config.CONFIG_DB.currency, self.amount) @ndb.ComputedProperty def is_positive(self): return self.amount >= 0 @classmethod def get_dbs(cls, is_positive=None, **kwargs): return super(Pay, cls).get_dbs( is_positive=is_positive or util.param('is_positive', bool), **kwargs ) PAY_FIELDS = { 'amount': fields.Float, 'amount_format': fields.String, 'code': fields.String, 'date_for': fields.DateTimeField, 'date_paid': fields.DateTimeField, 'is_positive': fields.Boolean, 'name': fields.String, } PAY_FIELDS.update(model.BASE_FIELDS)
Fix multivar for nodes with variable length stacks
from nodes import Node class MultiVar(Node): char = "'" args = 0 results = None contents = -1 def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle): self.node_1 = node_1 self.node_2 = node_2 def prepare(self, stack): self.node_1.prepare(stack) self.node_2.prepare(stack) self.args = max([self.node_1.args,self.node_2.args]) @Node.is_func def apply(self, *stack): rtn = self.node_2(stack[:self.node_2.args]) rtn.extend(self.node_1(stack[:self.node_1.args])) return rtn
from nodes import Node class MultiVar(Node): char = "'" args = 0 results = None contents = -1 def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle): self.node_1 = node_1 self.node_2 = node_2 self.args = max([node_1.args, node_2.args]) def prepare(self, stack): if len(stack) == 0: self.add_arg(stack) @Node.is_func def apply(self, *stack): self.node_2.prepare(stack) rtn = self.node_2(stack[:self.node_2.args]) self.node_1.prepare(stack) rtn.extend(self.node_1(stack[:self.node_1.args])) return rtn
Add some access function to inverted index
#!/usr/bin/env python3 # -*- coding: utf8 -*- # import class InvertedIndex: def __init__(self): self.index = dict() def add_mail(self, mail): for key in ["simple_terms_body", "complexe_terms_body"]: for terms in mail[key]: if terms in self.index.keys(): self.index[terms].append((mail["name"], mail[key][terms])) else: self.index[terms] = list() self.index[terms].append((mail["name"], mail[key][terms])) def terms(self): for terms in self.index.keys(): yield terms def get_terms(self): return self.index.keys() def file_counter(self, terms): for val in self.index[terms]: yield val def get_file_counter(self, terms): return self.index.values() def file(self, terms): for val in file_counter(terms): yield val[0] def counter(self, terms): for val in file_counter(terms): yield val[1]
#!/usr/bin/env python3 # -*- coding: utf8 -*- # import class InvertedIndex: def __init__(self): self.index = dict() def add_mail(self, mail): for key in ["simple_terms_body", "complexe_terms_body"]: for terms in mail[key]: if terms in self.index.keys(): self.index[terms].append((mail["name"], mail[key][terms])) else: self.index[terms] = list() self.index[terms].append((mail["name"], mail[key][terms]))
Initialize object under test in setup
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.service; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class UselessBeanTest { private UselessBean uselessBean; @Mock private ABeanIWantToMock aBeanIWantToMock; @Before public void setUp() { uselessBean = new UselessBean(aBeanIWantToMock); } @Test public void testMyMockReturnFalseInTest() { Mockito.when(aBeanIWantToMock.iAlwaysReturnFalse()).thenReturn(true); Assert.assertTrue(uselessBean.iWantToMockThisMethod()); } }
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate.service; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class UselessBeanTest { @InjectMocks private UselessBean uselessBean; @Mock private ABeanIWantToMock aBeanIWantToMock; @Test public void testMyMockReturnFalseInTest() { Mockito.when(aBeanIWantToMock.iAlwaysReturnFalse()).thenReturn(true); Assert.assertTrue(uselessBean.iWantToMockThisMethod()); } }
Update for latest Sendgrid webhook format
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for event in json.loads(data): events.append(Event.objects.create( kind=event["event"], email=event["email"], data=event )) batch_processed.send(sender=Event, events=events) return events
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for line in data.split("\r\n"): if line: d = json.loads(line.strip()) events.append(Event.objects.create( kind=d["event"], email=d["email"], data=d )) batch_processed.send(sender=Event, events=events) return events
Fix imports for Django 1.6 and above
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # 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 django.conf.urls import patterns, handler500, url # Fallback for Django versions < 1.4 except ImportError: from django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # 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 django.conf.urls.defaults import patterns, handler500, url urlpatterns = patterns( 'djangosaml2.views', url(r'^login/$', 'login', name='saml2_login'), url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'), url(r'^logout/$', 'logout', name='saml2_logout'), url(r'^ls/$', 'logout_service', name='saml2_ls'), url(r'^metadata/$', 'metadata', name='saml2_metadata'), ) handler500 = handler500
Update ingress to use new async render
import BaseWorker from '../base' import redis from 'redis' export class IngressWorker extends BaseWorker { constructor (rsmq) { super('ingress', rsmq) this.rsmq = rsmq this.redisClient = redis.createClient({ host: 'redis' }) } store (session, body) { return new Promise((resolve, reject) => { this.redisClient.set(`phonebox:ingress:${session}`, JSON.stringify(body), (err, reply) => { if (err) return reject(err) resolve(reply) }) }) } async process (message, next) { const { session, type, attempts, channel } = message.meta if (attempts >= 3) return next() message.meta.attempts = message.meta.attempts + 1 await this.store(session, message) const body = await this.render(`${__dirname}/${type}.ejs`, message) this.rsmq.sendMessage({ qname: channel, message: body, delay: attempts * 180 }, next) } } export default IngressWorker
import BaseWorker from '../base' import utils from 'async' import uuid from 'uuid' import redis from 'redis' export class IngressWorker extends BaseWorker { constructor (rsmq) { super('ingress', rsmq) this.rsmq = rsmq this.redisClient = redis.createClient({ host: 'redis' }) } store (session, body) { return new Promise((resolve, reject) => { this.redisClient.set(`phonebox:ingress:${session}`, body, (err, reply) => { if (err) return reject(err) resolve(reply) }) }) } async process (message, next) { const session = uuid.v1() const body = this.render(`${__dirname}/${message.type}.ejs`, Object.assign(message, { session })) await this.store(session, body) utils.each(this.channels, (channel, cb) => { this.rsmq.sendMessage({ qname: channel, message: body }, cb) }, err => { if (err) return next(err) next() }) } } export default IngressWorker
Add PATH env manipulation when platform is darwin
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. var process = require('process'); // avoid https://github.com/atom/electron/issues/550 if (process.platform == "darwin") { process.env['PATH'] = "/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" } // Report crashes to our server. require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function() { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform != 'darwin') { app.quit(); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function() { // Create the browser window. mainWindow = new BrowserWindow({width: 1024, height: 600}); // and load the index.html of the app. mainWindow.loadUrl('file://' + __dirname + '/build/index.html'); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); });
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. // Report crashes to our server. require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function() { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform != 'darwin') { app.quit(); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function() { // Create the browser window. mainWindow = new BrowserWindow({width: 1024, height: 600}); // and load the index.html of the app. mainWindow.loadUrl('file://' + __dirname + '/build/index.html'); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); });
Add a default URL value
<?php class FreshRSS_Share { static public function generateUrl($options, $selected, $link, $title) { if (!array_key_exists('url', $selected)) { $selected['url'] = ''; } $share = $options[$selected['type']]; $matches = array( '~URL~', '~TITLE~', '~LINK~', ); $replaces = array( $selected['url'], self::transformData($title, self::getTransform($share, 'title')), self::transformData($link, self::getTransform($share, 'link')), ); $url = str_replace($matches, $replaces, $share['url']); return $url; } static private function transformData($data, $transform) { if (!is_array($transform)) { return $data; } if (count($transform) === 0) { return $data; } foreach ($transform as $action) { $data = call_user_func($action, $data); } return $data; } static private function getTransform($options, $type) { $transform = $options['transform']; if (array_key_exists($type, $transform)) { return $transform[$type]; } return $transform; } }
<?php class FreshRSS_Share { static public function generateUrl($options, $selected, $link, $title) { $share = $options[$selected['type']]; $matches = array( '~URL~', '~TITLE~', '~LINK~', ); $replaces = array( $selected['url'], self::transformData($title, self::getTransform($share, 'title')), self::transformData($link, self::getTransform($share, 'link')), ); $url = str_replace($matches, $replaces, $share['url']); return $url; } static private function transformData($data, $transform) { if (!is_array($transform)) { return $data; } if (count($transform) === 0) { return $data; } foreach ($transform as $action) { $data = call_user_func($action, $data); } return $data; } static private function getTransform($options, $type) { $transform = $options['transform']; if (array_key_exists($type, $transform)) { return $transform[$type]; } return $transform; } }
Make basic example more a11y
import React from 'react'; import ReactDOM from 'react-dom'; import { Formik, Field, Form } from 'formik'; const Basic = () => ( <div> <h1>Sign Up</h1> <Formik initialValues={{ firstName: '', lastName: '', email: '', }} onSubmit={async values => { await new Promise(r => setTimeout(r, 500)); alert(JSON.stringify(values, null, 2)); }} > <Form> <label htmlFor="firstName">First Name</label> <Field id="firstName" name="firstName" placeholder="Jane" /> <label htmlFor="lastName">Last Name</label> <Field id="lastName" name="lastName" placeholder="Doe" /> <label htmlFor="email">Email</label> <Field id="email" name="email" placeholder="jane@acme.com" type="email" /> <button type="submit">Submit</button> </Form> </Formik> </div> ); ReactDOM.render(<Basic />, document.getElementById('root'));
import React from "react"; import ReactDOM from "react-dom"; import { Formik, Field, Form } from "formik"; const sleep = ms => new Promise(r => setTimeout(r, ms)); const Basic = () => ( <div> <h1>Sign Up</h1> <Formik initialValues={{ firstName: "", lastName: "", email: "" }} onSubmit={async values => { await sleep(500); alert(JSON.stringify(values, null, 2)); }} > <Form> <label htmlFor="firstName">First Name</label> <Field name="firstName" placeholder="Jane" /> <label htmlFor="lastName">Last Name</label> <Field name="lastName" placeholder="Doe" /> <label htmlFor="email">Email</label> <Field name="email" placeholder="jane@acme.com" type="email" /> <button type="submit">Submit</button> </Form> </Formik> </div> ); ReactDOM.render(<Basic />, document.getElementById("root"));
Set cookie expiration to 365 days (was session)
(function($) { var notificationBar = { open: function(barId, barCloseId, cookie) { $('#' + barId).slideDown(); $('#' + barCloseId).on('click', function() { notificationBar.close(barId, cookie); }); }, close: function(barId, cookie) { $('#' + barId).slideUp(); $.cookie(cookie, true, { path: '/', expires: 365 }); }, reset: function(cookie) { $.removeCookie(cookie, { path: '/' }); }, setup: function(barId, barCloseId, cookie, func) { if (func()) this.open(barId, barCloseId, cookie); } }; $('#reset-cookiebar').click(function() { notificationBar.reset('seen-cookie-notice'); }); notificationBar.setup('cookie', 'cookie-hide', 'seen-cookie-notice', function() { return !$.cookie('seen-cookie-notice'); }); notificationBar.setup('incompability', 'incompability-hide', 'seen-incompability-notice', function() { return $('html').is('.lt-ie8'); }); })(jQuery);
(function($) { var notificationBar = { open: function(barId, barCloseId, cookie) { $('#' + barId).slideDown(); $('#' + barCloseId).on('click', function() { notificationBar.close(barId, cookie); }); }, close: function(barId, cookie) { $('#' + barId).slideUp(); $.cookie(cookie, true, { path: '/' }); }, reset: function(cookie) { $.removeCookie(cookie, { path: '/' }); }, setup: function(barId, barCloseId, cookie, func) { if (func()) this.open(barId, barCloseId, cookie); } }; $('#reset-cookiebar').click(function() { notificationBar.reset('seen-cookie-notice'); }); notificationBar.setup('cookie', 'cookie-hide', 'seen-cookie-notice', function() { return !$.cookie('seen-cookie-notice'); }); notificationBar.setup('incompability', 'incompability-hide', 'seen-incompability-notice', function() { return $('html').is('.lt-ie8'); }); })(jQuery);
Add availability2 comand, this command uses curl to do the availability check.
package executors; /** * Transform user commands in Nmap commands */ public class CommandCreator { public String createCommand(String userCommand) { String[] tokens = userCommand.split("\\s+"); switch(tokens[0]) { case "security": switch (tokens[1]) { case "tls": return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2]; case "ecrypt2lvl": return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2]; case "open_ports": return "nmap " + tokens[2]; default : return null; } case "availability2": return "curl +X GET " + tokens[1]; default : return null; } } }
package executors; /** * Transform user commands in Nmap commands */ public class CommandCreator { public String createCommand(String userCommand) { String[] tokens = userCommand.split("\\s+"); switch(tokens[0]) { case "security": switch (tokens[1]) { case "tls": return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2]; case "ecrypt2lvl": return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2]; case "open_ports": return "nmap " + tokens[2]; default : return null; } default : return null; } } }
Fix issues with importing the Login form The Login form lives in openstack_auth.forms and should be directly imported from that file. Change-Id: I42808530024bebb01604adbf4828769812856bf3 Closes-Bug: #1332149
# Copyright 2012 Nebula, 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. from django import shortcuts from django.views.decorators import vary import horizon from horizon import base from openstack_auth import forms def get_user_home(user): dashboard = None if user.is_superuser: try: dashboard = horizon.get_dashboard('admin') except base.NotRegistered: pass if dashboard is None: dashboard = horizon.get_default_dashboard() return dashboard.get_absolute_url() @vary.vary_on_cookie def splash(request): if request.user.is_authenticated(): return shortcuts.redirect(horizon.get_user_home(request.user)) form = forms.Login(request) request.session.clear() request.session.set_test_cookie() return shortcuts.render(request, 'splash.html', {'form': form})
# Copyright 2012 Nebula, 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. from django import shortcuts from django.views.decorators import vary import horizon from horizon import base from openstack_auth import views def get_user_home(user): dashboard = None if user.is_superuser: try: dashboard = horizon.get_dashboard('admin') except base.NotRegistered: pass if dashboard is None: dashboard = horizon.get_default_dashboard() return dashboard.get_absolute_url() @vary.vary_on_cookie def splash(request): if request.user.is_authenticated(): return shortcuts.redirect(horizon.get_user_home(request.user)) form = views.Login(request) request.session.clear() request.session.set_test_cookie() return shortcuts.render(request, 'splash.html', {'form': form})
Add logout feature for acceptance testing
<?php /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * * @SuppressWarnings(PHPMD) */ class AcceptanceTester extends \Codeception\Actor { use _generated\AcceptanceTesterActions; /** * Define custom actions here */ /** * @param string $username * @param string $password */ public function login($username, $password) { $I = $this; // Log In $I->seeElement('#loginform'); $I->fillField('#user_name', $username); $I->fillField('#user_password', $password); $I->click('Log In'); $I->dontSeeElement('#loginform'); } /** * Clicks the logout link in the users menu */ public function logout() { $tabletNavigationBar = new NavigationBar($this); $tabletNavigationBar->clickUserMenuItem('#logout_link'); } }
<?php /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * * @SuppressWarnings(PHPMD) */ class AcceptanceTester extends \Codeception\Actor { use _generated\AcceptanceTesterActions; /** * Define custom actions here */ /** * @param string $username * @param string $password */ public function login($username, $password) { $I = $this; // if snapshot exists - skipping login if ($I->loadSessionSnapshot('login')) { return; } // Loggin In $I->seeElement('#loginform'); $I->fillField('#user_name', $username); $I->fillField('#user_password', $password); $I->click('Log In'); $I->dontSeeElement('#loginform'); // Saving snapshot $I->saveSessionSnapshot('login'); } }
Add PHP_EOL to the marker shape helper
<?php namespace Ivory\GoogleMapBundle\Templating\Helper; use Ivory\GoogleMapBundle\Model\MarkerShape; /** * Marker shape helper allows easy rendering * * @author GeLo <geloen.eric@gmail.com> */ class MarkerShapeHelper { /** * Renders the marker shape * * @param Ivory\GoogleMapBundle\Model\MarkerShape $markerShape * @return string HTML output */ public function render(MarkerShape $markerShape) { return sprintf('var %s = %s;'.PHP_EOL, $markerShape->getJavascriptVariable(), json_encode(array( 'type' => $markerShape->getType(), 'coords' => $markerShape->getCoordinates() )) ); } }
<?php namespace Ivory\GoogleMapBundle\Templating\Helper; use Ivory\GoogleMapBundle\Model\MarkerShape; /** * Marker shape helper allows easy rendering * * @author GeLo <geloen.eric@gmail.com> */ class MarkerShapeHelper { /** * Renders the marker shape * * @param Ivory\GoogleMapBundle\Model\MarkerShape $markerShape * @return string HTML output */ public function render(MarkerShape $markerShape) { return sprintf('var %s = %s;', $markerShape->getJavascriptVariable(), json_encode(array( 'type' => $markerShape->getType(), 'coords' => $markerShape->getCoordinates() )) ); } }
Use PDO driver for unit tests so everything works on PHP 5.5
<?php spl_autoload_register(function($class) { $file = __DIR__.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.str_replace('_', '/', $class).'.php'; if (is_file($file)) { require_once $file; } }); require_once __DIR__.'/../vendor/autoload.php'; Kohana::modules(array( 'database' => MODPATH.'database', 'jam' => __DIR__.'/../modules/jam', 'jam-freezable' => __DIR__.'/..', )); Kohana::$config ->load('database') ->set('default', array( 'type' => 'PDO', 'connection' => array( 'dsn' => 'mysql:dbname=test-jam-freezable;host=127.0.0.1', 'username' => 'root', 'password' => '', 'persistent' => TRUE, ), 'table_prefix' => '', 'charset' => 'utf8', 'caching' => FALSE, )); Kohana::$environment = Kohana::TESTING;
<?php spl_autoload_register(function($class) { $file = __DIR__.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.str_replace('_', '/', $class).'.php'; if (is_file($file)) { require_once $file; } }); require_once __DIR__.'/../vendor/autoload.php'; Kohana::modules(array( 'database' => MODPATH.'database', 'jam' => __DIR__.'/../modules/jam', 'jam-freezable' => __DIR__.'/..', )); Kohana::$config ->load('database') ->set('default', array( 'type' => 'MySQL', 'connection' => array( 'hostname' => 'localhost', 'database' => 'test-jam-freezable', 'username' => 'root', 'password' => '', 'persistent' => TRUE, ), 'table_prefix' => '', 'charset' => 'utf8', 'caching' => FALSE, )); Kohana::$environment = Kohana::TESTING;
Update SUPPORTS_TRANSACTIONS attribute to what is expected by Django 1.2. Patch contributed by Felix Leong. Thanks. Fixes Issue #162.
#!/usr/bin/python2.4 # # Copyright 2008 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. import logging from django.conf import settings from django.db.backends.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): def create_test_db(self, *args, **kw): """Destroys the test datastore. A new store will be recreated on demand""" # Only needed for Django 1.1, deprecated @ 1.2. settings.DATABASE_SUPPORTS_TRANSACTIONS = False self.connection.settings_dict['SUPPORTS_TRANSACTIONS'] = False self.destroy_test_db() self.connection.use_test_datastore = True self.connection.flush() def destroy_test_db(self, *args, **kw): """Destroys the test datastore files.""" from appengine_django.db.base import destroy_datastore from appengine_django.db.base import get_test_datastore_paths destroy_datastore(*get_test_datastore_paths()) logging.debug("Destroyed test datastore")
#!/usr/bin/python2.4 # # Copyright 2008 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. import logging from django.conf import settings from django.db.backends.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): def create_test_db(self, *args, **kw): """Destroys the test datastore. A new store will be recreated on demand""" settings.DATABASE_SUPPORTS_TRANSACTIONS = False self.destroy_test_db() self.connection.use_test_datastore = True self.connection.flush() def destroy_test_db(self, *args, **kw): """Destroys the test datastore files.""" from appengine_django.db.base import destroy_datastore from appengine_django.db.base import get_test_datastore_paths destroy_datastore(*get_test_datastore_paths()) logging.debug("Destroyed test datastore")
Use KSC auth's register_conf_options instead of oslo.cfg import A newer keystoneclient is not happy with simply using oslo_config to import the config group. Instead, use register_conf_options() from keystoneclient.auth. Change-Id: I798dad7ad5bd90362e1fa10c2eecb3e1d5bade71
# Copyright (c) 2015 Akanda, Inc. 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 keystoneclient import auth as ksauth from keystoneclient import session as kssession from oslo_config import cfg CONF = cfg.CONF class KeystoneSession(object): def __init__(self): self._session = None self.region_name = CONF.auth_region ksauth.register_conf_options(CONF, 'keystone_authtoken') @property def session(self): if not self._session: # Construct a Keystone session for configured auth_plugin # and credentials auth_plugin = ksauth.load_from_conf_options( cfg.CONF, 'keystone_authtoken') self._session = kssession.Session(auth=auth_plugin) return self._session
# Copyright (c) 2015 Akanda, Inc. 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 keystoneclient import auth as ksauth from keystoneclient import session as kssession from oslo_config import cfg CONF = cfg.CONF CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_token') class KeystoneSession(object): def __init__(self): self._session = None self.region_name = CONF.auth_region @property def session(self): if not self._session: # Construct a Keystone session for configured auth_plugin # and credentials auth_plugin = ksauth.load_from_conf_options( cfg.CONF, 'keystone_authtoken') self._session = kssession.Session(auth=auth_plugin) return self._session
Add test support for Windows
var readFile = require('fs').readFile; var assert = require('assert'); var exec = require('child_process').exec; var join = require('path').join; var platform = require('os').platform; // Test the expected output. exec('node .', function(err, stdout, stderr) { if (err) { throw err; } readFile(join(__dirname, 'expected.txt'), 'UTF-8', function(err, exp) { if (err) { throw err; } var expected = platform() == 'win32' ? exp.split('\r\n') : exp.split('\n'); var actual = stdout.split('\n'); for (var i = 0, mx = expected.length; i < mx; i++) { assert.equal(actual[i], expected[i], "Expected '" + actual[i] + "' to be '" + expected[i] + "' on line " + (i + 1) + "."); } console.log('All tests pass!'); }); });
var readFile = require('fs').readFile; var assert = require('assert'); var exec = require('child_process').exec; var join = require('path').join; // Test the expected output. exec('node .', function(err, stdout, stderr) { if (err) { throw err; } readFile(join(__dirname, 'expected.txt'), 'UTF-8', function(err, exp) { if (err) { throw err; } var expected = exp.split('\r\n'); var actual = stdout.split('\n'); for (var i = 0, mx = expected.length; i < mx; i++) { assert.equal(actual[i], expected[i], "Expected '" + actual[i] + "' to be '" + expected[i] + "' on line " + (i + 1) + "."); } console.log('All tests pass!'); }); });
Fix For Loop to Iterate Every Link in Primary Nav
var fs = require('fs'); var links; function getLinks() { var links = document.querySelectorAll('.nav-link.t-nav-link'); return Array.prototype.map.call(links, function (e) { return e.getAttribute('href') }); } casper.start('http://192.168.13.37/index.php', function() { fs.write('tests/validation/html_output/homepage.html', this.getPageContent(), 'w'); }); casper.then(function () { var links = this.evaluate(getLinks); var current = 1; var end = links.length; for (;current < end;) { //console.log(current,' Outer:', current); (function(cntr) { casper.thenOpen(links[cntr], function() { console.log(cntr, ' Inner:', links[cntr]); fs.write('tests/validation/html_output/_' + cntr + '.html', this.getPageContent(), 'w'); }); })(current); current++; } }); casper.run(function() { this.exit(); })
var fs = require('fs'); var links; function getLinks() { // Scrape the links from primary nav of the website var links = document.querySelectorAll('.nav-link.t-nav-link'); return Array.prototype.map.call(links, function (e) { return e.getAttribute('href') }); } casper.start('http://192.168.13.37/index.php', function() { fs.write('tests/validation/html_output/index.html', this.getPageContent(), 'w'); }); casper.then(function () { links = this.evaluate(getLinks); for(var i in links) { console.log(i,' Outer:', links[i]); casper.start(links[i], function() { console.log(i, ' Inner:', links[i]); fs.write('tests/validation/html_output/page-' + i + '.html', this.getPageContent(), 'w'); }); } }); casper.run(function() { this.exit(); })
Add APIError flask error handler This is modelled after the similar change in the supplier frontend https://github.com/alphagov/digitalmarketplace-supplier-frontend/commit/233f8840d55cadb9fb7fe60ff12c53b0f59f23a5
from flask import render_template from app.main import main from dmutils.apiclient import APIError @main.app_errorhandler(APIError) def api_error(e): return _render_error_template(e.status_code) @main.app_errorhandler(400) def bad_request(e): return _render_error_template(400) @main.app_errorhandler(404) def page_not_found(e): return _render_error_template(404) @main.app_errorhandler(500) def exception(e): return _render_error_template(500) @main.app_errorhandler(503) def service_unavailable(e): return _render_error_template(503) def _render_error_template(status_code): return render_template( _get_template(status_code), **main.config['BASE_TEMPLATE_DATA'] ), status_code def _get_template(status_code): if status_code == 404: return "errors/404.html" else: return "errors/500.html"
from flask import render_template from app.main import main @main.app_errorhandler(400) def bad_request(e): return render_template("errors/500.html", **main.config['BASE_TEMPLATE_DATA']), 400 @main.app_errorhandler(404) def page_not_found(e): return render_template("errors/404.html", **main.config['BASE_TEMPLATE_DATA']), 404 @main.app_errorhandler(500) def exception(e): return render_template("errors/500.html", **main.config['BASE_TEMPLATE_DATA']), 500 @main.app_errorhandler(503) def service_unavailable(e): return render_template("errors/500.html", **main.config['BASE_TEMPLATE_DATA']), 503
Bots: Adjust Incrementor bot to use StateHandler
# See readme.md for instructions on running this code. class IncrementorHandler(object): def usage(self): return ''' This is a boilerplate bot that makes use of the update_message function. For the first @-mention, it initially replies with one message containing a `1`. Every time the bot is @-mentioned, this number will be incremented in the same message. ''' def handle_message(self, message, bot_handler, state_handler): state = state_handler.get_state() or {'number': 0, 'message_id': None} state['number'] += 1 state_handler.set_state(state) if state['message_id'] is None: result = bot_handler.send_reply(message, str(state['number'])) state['message_id'] = result['id'] state_handler.set_state(state) else: bot_handler.update_message(dict( message_id = state['message_id'], content = str(state['number']) )) handler_class = IncrementorHandler
# See readme.md for instructions on running this code. class IncrementorHandler(object): def __init__(self): self.number = 0 self.message_id = None def usage(self): return ''' This is a boilerplate bot that makes use of the update_message function. For the first @-mention, it initially replies with one message containing a `1`. Every time the bot is @-mentioned, this number will be incremented in the same message. ''' def handle_message(self, message, bot_handler, state_handler): self.number += 1 if self.message_id is None: result = bot_handler.send_reply(message, str(self.number)) self.message_id = result['id'] else: bot_handler.update_message(dict( message_id=self.message_id, content=str(self.number), )) handler_class = IncrementorHandler
:art: Use `@clear` instead of clearing manually
'use strict' let Message = require('./message') class BottomPanel extends HTMLElement{ prepare(){ this.panel = atom.workspace.addBottomPanel({item: this, visible: true}) return this } destroy(){ this.panel.destroy() } set panelVisibility(value){ if(value) this.panel.show() else this.panel.hide() } set visibility(value){ if(value){ this.removeAttribute('hidden') } else { this.setAttribute('hidden', true) } } updateMessages(messages, isProject){ this.clear() if(!messages.length){ return this.visibility = false } this.visibility = true messages.forEach(function(message){ this.appendChild(Message.fromMessage(message, {addPath: isProject, cloneNode: true})) }.bind(this)) } clear(){ while(this.firstChild){ this.removeChild(this.firstChild) } } } module.exports = document.registerElement('linter-panel', {prototype: BottomPanel.prototype})
'use strict' let Message = require('./message') class BottomPanel extends HTMLElement{ prepare(){ this.panel = atom.workspace.addBottomPanel({item: this, visible: true}) return this } destroy(){ this.panel.destroy() } set panelVisibility(value){ if(value) this.panel.show() else this.panel.hide() } set visibility(value){ if(value){ this.removeAttribute('hidden') } else { this.setAttribute('hidden', true) } } updateMessages(messages, isProject){ while(this.firstChild){ this.removeChild(this.firstChild) } if(!messages.length){ return this.visibility = false } this.visibility = true messages.forEach(function(message){ this.appendChild(Message.fromMessage(message, {addPath: isProject, cloneNode: true})) }.bind(this)) } clear(){ while(this.firstChild){ this.removeChild(this.firstChild) } } } module.exports = document.registerElement('linter-panel', {prototype: BottomPanel.prototype})
Check that kaffe doesn't allow invocation of a null pointer.
/* * test that caught null pointers exceptions in finalizers work correctly * and that local variables are accessible in null pointer exception handlers. */ import java.io.*; public class NullPointerTest { static String s; public static void main(String[] args) { System.out.println(tryfinally() + s); try { // Note: String.concat("") will not dereference 'this' ((String)null).concat(""); System.out.println("FAILED!"); } catch (NullPointerException e) { System.out.println("This is good too"); } } public static String tryfinally() { String yuck = null; String local_s = null; try { return "This is "; } finally { try { local_s = "Perfect"; /* trigger null pointer exception */ String x = yuck.toLowerCase(); } catch (Exception _) { /* * when the null pointer exception is caught, we must still * be able to access local_s. * Our return address for the finally clause must also still * be intact. */ s = local_s; } } } } /* Expected Output: This is Perfect This is good too */
/* * test that caught null pointers exceptions in finalizers work correctly * and that local variables are accessible in null pointer exception handlers. */ import java.io.*; public class NullPointerTest { static String s; public static void main(String[] args) { System.out.println(tryfinally() + s); } public static String tryfinally() { String yuck = null; String local_s = null; try { return "This is "; } finally { try { local_s = "Perfect"; /* trigger null pointer exception */ String x = yuck.toLowerCase(); } catch (Exception _) { /* * when the null pointer exception is caught, we must still * be able to access local_s. * Our return address for the finally clause must also still * be intact. */ s = local_s; } } } } /* Expected Output: This is Perfect */
Make an exception for debian in tests.test_correct_os_version This is because of a known issue where downburst gives us 7.1 when we ask for 7.0. We're ok with this behavior for now. See: issue #10878 Signed-off-by: Andrew Schoen <1bb641dc23c3a93cce4eee683bcf4b2bea7903a3@redhat.com>
import pytest class TestLocking(object): def test_correct_os_type(self, ctx, config): os_type = ctx.config.get("os_type") if os_type is None: pytest.skip('os_type was not defined') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.name == os_type def test_correct_os_version(self, ctx, config): os_version = ctx.config.get("os_version") if os_version is None: pytest.skip('os_version was not defined') if ctx.config.get("os_type") == "debian": pytest.skip('known issue with debian versions; see: issue #10878') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.version == os_version def test_correct_machine_type(self, ctx, config): machine_type = ctx.machine_type for remote in ctx.cluster.remotes.iterkeys(): assert remote.machine_type in machine_type
import pytest class TestLocking(object): def test_correct_os_type(self, ctx, config): os_type = ctx.config.get("os_type") if os_type is None: pytest.skip('os_type was not defined') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.name == os_type def test_correct_os_version(self, ctx, config): os_version = ctx.config.get("os_version") if os_version is None: pytest.skip('os_version was not defined') for remote in ctx.cluster.remotes.iterkeys(): assert remote.os.version == os_version def test_correct_machine_type(self, ctx, config): machine_type = ctx.machine_type for remote in ctx.cluster.remotes.iterkeys(): assert remote.machine_type in machine_type
Use correct named view for organization detail view
from django.contrib.auth.models import User from django.db import models from uuidfield.fields import UUIDField from storybase.fields import ShortTextField class Organization(models.Model): """ An organization or a community group that users and stories can be associated with. """ organization_id = UUIDField(auto=True) name = ShortTextField() slug = models.SlugField() website_url = models.URLField(blank=True) members = models.ManyToManyField(User, related_name='organizations', blank=True) def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): return ('organization_detail', [self.organization_id]) class Project(models.Model): """ A project that collects related stories. Users can also be related to projects. """ project_id = UUIDField(auto=True) name = models.CharField(max_length=200) slug = models.SlugField() members = models.ManyToManyField(User, related_name='projects', blank=True) def __unicode__(self): return self.name
from django.contrib.auth.models import User from django.db import models from uuidfield.fields import UUIDField from storybase.fields import ShortTextField class Organization(models.Model): """ An organization or a community group that users and stories can be associated with. """ organization_id = UUIDField(auto=True) name = ShortTextField() slug = models.SlugField() website_url = models.URLField(blank=True) members = models.ManyToManyField(User, related_name='organizations', blank=True) def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): # TODO: Implement this view and URL pattern return ('organization_bootstrap', [self.organization_id]) class Project(models.Model): """ A project that collects related stories. Users can also be related to projects. """ project_id = UUIDField(auto=True) name = models.CharField(max_length=200) slug = models.SlugField() members = models.ManyToManyField(User, related_name='projects', blank=True) def __unicode__(self): return self.name
Add jobs to second test queen, add assertions
import threading import time import sys from busybees import worker from busybees import hive import pash class ErrWorker(worker.Worker): def work(self, command): proc = pash.ShellProc() proc.run(command) return "Exit code: %s" % proc.get_val('exit_code') def test_hive(): apiary = hive.Hive() apiary.create_queen('A1') apiary.create_queen('A2') apiary.start_queen('A1') apiary.start_queen('A2') job1 = ["iscsiadm -m discovery -t st -p 192.168.88.110", "iscsiadm -m discovery -t st -p 192.168.90.110", "iscsiadm -m discovery -t st -p 192.168.88.110"] apiary.instruct_queen('A1', job1, ErrWorker) job2 = ["ls -l ~", "date", "cal"] apiary.instruct_queen('A2', job2) apiary.kill_queen('A1') time.sleep(3) this = apiary.die() for key in this.keys(): for i in this[key]: assert i != '' and i != None
import threading import time import sys from busybees import worker from busybees import hive import pash class ErrWorker(worker.Worker): def work(self, command): proc = pash.ShellProc() proc.run(command) return "Exit code: %s" % proc.get_val('exit_code') def test_hive(): apiary = hive.Hive() apiary.create_queen('A1') apiary.create_queen('A2') apiary.start_queen('A1') apiary.start_queen('A2') jobs = ["iscsiadm -m discovery -t st -p 192.168.88.110", "iscsiadm -m discovery -t st -p 192.168.90.110", "iscsiadm -m discovery -t st -p 192.168.88.110"] apiary.instruct_queen('A1', jobs, ErrWorker) apiary.kill_queen('A1') time.sleep(3) this = apiary.die() for key in this.keys(): for i in this[key]: assert i == "Exit code: 6" print i sys.exit(0)
Test that asJson returns minimum viable json for slack
<?php namespace FullyBaked\Pslackr\Messages; use PHPUnit_Framework_TestCase; use Exception; class CustomMessageTest extends PHPUnit_Framework_TestCase { public function testConstructorSetsTextProperty() { $text = 'This is a test message'; $relection = new \ReflectionClass('FullyBaked\Pslackr\Messages\CustomMessage'); $property = $relection->getProperty('text'); $property->setAccessible(true); $message = $this->getMockBuilder('FullyBaked\Pslackr\Messages\CustomMessage') ->setConstructorArgs([$text]) ->getMock(); $this->assertEquals($text, $property->getValue($message)); } public function testAsJsonReturnsMinimumJsonRequired() { $text = 'This is a test message'; $message = new CustomMessage($text); $expected = '{"text":"This is a test message"}'; $result = $message->asJson(); $this->assertEquals($result, $expected); } }
<?php namespace FullyBaked\Pslackr\Messages; use PHPUnit_Framework_TestCase; use Exception; class CustomMessageTest extends PHPUnit_Framework_TestCase { public function testConstructorSetsTextProperty() { $text = 'This is a test message'; $relection = new \ReflectionClass('FullyBaked\Pslackr\Messages\CustomMessage'); $property = $relection->getProperty('text'); $property->setAccessible(true); $message = $this->getMockBuilder('FullyBaked\Pslackr\Messages\CustomMessage') ->setConstructorArgs([$text]) ->getMock(); $this->assertEquals($text, $property->getValue($message)); } }
Remove browser history for now ...since it was playing up on github pages
/* @flow */ import React from 'react'; import ReactDOM from 'react-dom'; import makeRoutes from './routes'; import Root from './containers/Root'; import configureStore from './redux/configureStore'; // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the key "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState, null); // Now that we have the Redux store, we can create our routes. We provide // the store to the route definitions so that routes have access to it for // hooks such as `onEnter`. const routes = makeRoutes(store); // Now that redux and react-router have been configured, we can render the // React application to the DOM! ReactDOM.render( <Root history={null} routes={routes} store={store} />, document.getElementById('root') );
/* @flow */ import React from 'react'; import ReactDOM from 'react-dom'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import { useRouterHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import makeRoutes from './routes'; import Root from './containers/Root'; import configureStore from './redux/configureStore'; // Configure history for react-router const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }); // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the key "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState, browserHistory); const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: (state) => state.router }); // Now that we have the Redux store, we can create our routes. We provide // the store to the route definitions so that routes have access to it for // hooks such as `onEnter`. const routes = makeRoutes(store); // Now that redux and react-router have been configured, we can render the // React application to the DOM! ReactDOM.render( <Root history={history} routes={routes} store={store} />, document.getElementById('root') );
Fix date bug in moment.js
import moment from 'moment'; import { maxPages } from '../../data/config'; // Prevent webpack window problem const isBrowser = () => typeof window !== 'undefined'; const isPage = () => (isBrowser() ? window.location.pathname.indexOf('page') === -1 : false); const getCurrentPage = () => { if (isBrowser() === true) { const str = window.location.pathname; if (str.indexOf('page') !== -1) { // Return the last pathname in number return +window.location.pathname.match(/page[/](\d)/)[1]; } } return 0; }; const getPath = () => (isBrowser() ? window.location.href : ''); const getMaxPages = () => maxPages; const overflow = () => getCurrentPage() === getMaxPages(); const parseDate = date => moment(date).locale('zh-hk').format('YYYY/MM/DD'); const parseChineseDate = date => moment(date).locale('zh-hk').format('DD/MM/YYYY'); const isFirstPage = () => (isBrowser() ? isPage() : false); const isLastPage = () => (isBrowser() ? overflow() : false); export { isBrowser, isPage, getCurrentPage, getMaxPages, overflow, parseDate, isFirstPage, isLastPage, parseChineseDate, getPath, };
import moment from 'moment'; import { maxPages } from '../../data/config'; // Prevent webpack window problem const isBrowser = () => typeof window !== 'undefined'; const isPage = () => (isBrowser() ? window.location.pathname.indexOf('page') === -1 : false); const getCurrentPage = () => { if (isBrowser() === true) { const str = window.location.pathname; if (str.indexOf('page') !== -1) { // Return the last pathname in number return +window.location.pathname.match(/page[/](\d)/)[1]; } } return 0; }; const getPath = () => (isBrowser() ? window.location.href : ''); const getMaxPages = () => maxPages; const overflow = () => getCurrentPage() === getMaxPages(); const parseDate = date => moment(date).locale('zh-hk').format('YYYY/MM/DD'); const parseChineseDate = date => moment(date).locale('zh-hk').format('L'); const isFirstPage = () => (isBrowser() ? isPage() : false); const isLastPage = () => (isBrowser() ? overflow() : false); export { isBrowser, isPage, getCurrentPage, getMaxPages, overflow, parseDate, isFirstPage, isLastPage, parseChineseDate, getPath, };
Handle SAML 1 in addition to SAML 2.
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: for value in attribute[attribute_value_key]: roles.append(value['#text']) return roles
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: for value in attribute['saml2:AttributeValue']: roles.append(value['#text']) return roles
Mark wiki edits as bot edit
import ConfigParser import datetime from wikitools import wiki from wikitools import category from plugin import Plugin class MediaWiki(Plugin): def __init__(self, config=None): if config: try: self.site = wiki.Wiki(config.get('MediaWiki', 'wikiapiurl')) self.site.login(config.get('MediaWiki', 'user'), config.get('MediaWiki', 'password')) except ConfigParser.NoSectionError: print "MediaWiki Error: Please configure the [MediaWiki] section in your config.ini" except ConfigParser.NoOptionError: print "MediaWiki Error: Mediawiki Url or login credentials are not configured in your config.ini" super(MediaWiki, self).__init__() def wikiupdate(self, title, url): now = datetime.datetime.now() date = now.strftime("%Y-%m-%d %H:%M") cat = category.Category(self.site, "Linklist") for article in cat.getAllMembersGen(namespaces=[0]): print article.edit(appendtext="\n* {title} - {url} ({date}) \n".format(title=title, url=url, date=date), bot=True)
import ConfigParser import datetime from wikitools import wiki from wikitools import category from plugin import Plugin class MediaWiki(Plugin): def __init__(self, config=None): if config: try: self.site = wiki.Wiki(config.get('MediaWiki', 'wikiapiurl')) self.site.login(config.get('MediaWiki', 'user'), config.get('MediaWiki', 'password')) except ConfigParser.NoSectionError: print "MediaWiki Error: Please configure the [MediaWiki] section in your config.ini" except ConfigParser.NoOptionError: print "MediaWiki Error: Mediawiki Url or login credentials are not configured in your config.ini" super(MediaWiki, self).__init__() def wikiupdate(self, title, url): now = datetime.datetime.now() date = now.strftime("%Y-%m-%d %H:%M") cat = category.Category(self.site, "Linklist") for article in cat.getAllMembersGen(namespaces=[0]): print article.edit(appendtext="\n* {title} - {url} ({date}) \n".format(title=title, url=url, date=date))
Add corrected destructure of a transactions other party
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { createRecord } from '../../../database/utilities'; import { UIDatabase } from '../../../database'; /** * Utility to refund a collection of TransactionBatch records. Creates a * single CustomerCredit and for each TransactionBatch that should be * refunded, a RefundLine record, which enters the batch back into stock * and adds credit for the patient. * * * @param {User} currentUser The currently logged in user. * @param {Name} patient The patient to refund to * @param {TransactionBatch[]} batches Array of batches to be refund */ export const refund = (currentUser, patient, batches) => { const forSamePatient = batches.every(({ transaction }) => { const { otherParty } = transaction; return patient.id === otherParty?.id; }); if (!batches.length) throw new Error('Trying to refund void'); if (!forSamePatient) throw new Error('Batches for different patients!'); const sumOfCredit = batches.reduce((acc, { total }) => acc + total, 0); const customerCredit = createRecord( UIDatabase, 'CustomerCredit', currentUser, patient, sumOfCredit ); const addedBatches = batches.map(batch => createRecord(UIDatabase, 'RefundLine', customerCredit, batch) ); return [customerCredit, addedBatches]; };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { createRecord } from '../../../database/utilities'; import { UIDatabase } from '../../../database'; /** * Utility to refund a collection of TransactionBatch records. Creates a * single CustomerCredit and for each TransactionBatch that should be * refunded, a RefundLine record, which enters the batch back into stock * and adds credit for the patient. * * * @param {User} currentUser The currently logged in user. * @param {Name} patient The patient to refund to * @param {TransactionBatch[]} batches Array of batches to be refund */ export const refund = (currentUser, patient, batches) => { const forSamePatient = batches.every(({ transaction }) => { const { otherPartyName } = transaction; return patient.id === otherPartyName.id; }); if (!batches.length) throw new Error('Trying to refund void'); if (!forSamePatient) throw new Error('Batches for different patients!'); const sumOfCredit = batches.reduce((acc, { total }) => acc + total, 0); const customerCredit = createRecord( UIDatabase, 'CustomerCredit', currentUser, patient, sumOfCredit ); const addedBatches = batches.map(batch => createRecord(UIDatabase, 'RefundLine', customerCredit, batch) ); return [customerCredit, addedBatches]; };
Fix add to collections bug
package com.vimeo.networking.utils; import com.vimeo.networking.Vimeo; import com.vimeo.networking.model.Privacy; import java.util.HashMap; import java.util.Map; /** * Builder for setting privacy params for a video. * * Created by Mohit Sarveiya on 3/20/18. */ public final class PrivacySettingsParams { private final Map<String, Object> params = new HashMap<>(); public PrivacySettingsParams comments(final Privacy.PrivacyCommentValue privacyCommentValue) { params.put(Vimeo.PARAMETER_VIDEO_COMMENTS, privacyCommentValue); return this; } public PrivacySettingsParams download(final boolean download) { params.put(Vimeo.PARAMETER_VIDEO_DOWNLOAD, download); return this; } public PrivacySettingsParams addToCollections(final boolean add) { params.put(Vimeo.PARAMETER_VIDEO_ADD, add); return this; } public PrivacySettingsParams embed(final Privacy.PrivacyEmbedValue privacyEmbedType) { params.put(Vimeo.PARAMETER_VIDEO_EMBED, privacyEmbedType); return this; } public PrivacySettingsParams view(final Privacy.PrivacyViewValue privacyViewType) { params.put(Vimeo.PARAMETER_VIDEO_VIEW, privacyViewType); return this; } public Map<String, Object> getParams() { return params; } }
package com.vimeo.networking.utils; import com.vimeo.networking.Vimeo; import com.vimeo.networking.model.Privacy; import java.util.HashMap; import java.util.Map; /** * Builder for setting privacy params for a video. * * Created by Mohit Sarveiya on 3/20/18. */ public final class PrivacySettingsParams { private final Map<String, Object> params = new HashMap<>(); public PrivacySettingsParams comments(final Privacy.PrivacyCommentValue privacyCommentValue) { params.put(Vimeo.PARAMETER_VIDEO_COMMENTS, privacyCommentValue); return this; } public PrivacySettingsParams download(final boolean download) { params.put(Vimeo.PARAMETER_VIDEO_DOWNLOAD, download); return this; } public PrivacySettingsParams addToCollections(final boolean add) { params.put(Vimeo.PARAMETER_VIDEO_DOWNLOAD, add); return this; } public PrivacySettingsParams embed(final Privacy.PrivacyEmbedValue privacyEmbedType) { params.put(Vimeo.PARAMETER_VIDEO_EMBED, privacyEmbedType); return this; } public PrivacySettingsParams view(final Privacy.PrivacyViewValue privacyViewType) { params.put(Vimeo.PARAMETER_VIDEO_VIEW, privacyViewType); return this; } public Map<String, Object> getParams() { return params; } }
Add logbook 0.6.0 as a dependency
#!/usr/bin/env python2 import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() os.environ['PYTHONDONTWRITEBYTECODE'] = '1' packages = [ 'connman_dispatcher' ] requires = [ 'pyee >= 0.0.9', 'Logbook == 0.6.0' ] setup( name='connman-dispatcher', version='0.0.6', description='Call scripts on network changes', long_description=open('README.md').read(), author='Alexandr Skurikhin', author_email='a.skurikhin@gmail.com', url='http://github.com/a-sk/connman-dispatcher', scripts=['bin/connman-dispatcher'], packages=packages, package_data={'': ['LICENSE']}, install_requires=requires, license=open('LICENSE').read(), ) del os.environ['PYTHONDONTWRITEBYTECODE']
#!/usr/bin/env python2 import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() os.environ['PYTHONDONTWRITEBYTECODE'] = '1' packages = [ 'connman_dispatcher' ] requires = [ 'pyee >= 0.0.9' ] setup( name='connman-dispatcher', version='0.0.6', description='Call scripts on network changes', long_description=open('README.md').read(), author='Alexandr Skurikhin', author_email='a.skurikhin@gmail.com', url='http://github.com/a-sk/connman-dispatcher', scripts=['bin/connman-dispatcher'], packages=packages, package_data={'': ['LICENSE']}, install_requires=requires, license=open('LICENSE').read(), ) del os.environ['PYTHONDONTWRITEBYTECODE']
Change package_data to have LICENSE in a list This is required by setuptools and as of a recent version fails if the value(s) are not provided as a list or tuple of strings. See: https://github.com/pypa/setuptools/commit/8f848bd777278fc8dcb42dc45751cd8b95ec2a02
from setuptools import setup setup( \ name='blendplot', version='0.1.0', description='A program for plotting 3D scatter plots for use in Blender', long_description=open('README.md').read(), url='https://github.com/ExcaliburZero/blender-astro-visualization', author='Christopher Wells', author_email='cwellsny@nycap.rr.com', license='MIT', packages=['blendplot'], install_requires=[ 'pyCLI', 'sklearn', 'scipy', 'pandas' ], include_package_data=True, package_data={ '': ['LICENSE'] }, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Operating System :: OS Independent', 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License' ], entry_points = { 'console_scripts': [ 'blendplot = blendplot.__main__:run', ], }, )
from setuptools import setup setup( \ name='blendplot', version='0.1.0', description='A program for plotting 3D scatter plots for use in Blender', long_description=open('README.md').read(), url='https://github.com/ExcaliburZero/blender-astro-visualization', author='Christopher Wells', author_email='cwellsny@nycap.rr.com', license='MIT', packages=['blendplot'], install_requires=[ 'pyCLI', 'sklearn', 'scipy', 'pandas' ], include_package_data=True, package_data={ '': 'LICENSE' }, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Operating System :: OS Independent', 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License' ], entry_points = { 'console_scripts': [ 'blendplot = blendplot.__main__:run', ], }, )
Fix a broken constant name, should be CLOUDFILES_UK. git-svn-id: 353d90d4d8d13dcb4e0402680a9155a727f61a5a@1101075 13f79535-47bb-0310-9956-ffa450edef68
# 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. from pprint import pprint from libcloud.storage.types import Provider from libcloud.storage.providers import get_driver CloudFiles = get_driver(Provider.CLOUDFILES_UK) driver = CloudFiles('access key id', 'secret key') containers = driver.list_containers() container_objects = driver.list_container_objects(containers[0]) pprint(containers) pprint(container_objects)
# 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. from pprint import pprint from libcloud.storage.types import Provider from libcloud.storage.providers import get_driver CloudFiles = get_driver(Provider.CLOUDFILES) driver = CloudFiles('access key id', 'secret key') containers = driver.list_containers() container_objects = driver.list_container_objects(containers[0]) pprint(containers) pprint(container_objects)
Fix checkstyle if-statements must use braces sal-common-util Change-Id: I518b9fa156af55c080d7e6a55067deab2c789a42 Signed-off-by: Thanh Ha <09ea4d3a79c8bee41a16519f6a431f6bc0fd8d6f@linuxfoundation.org>
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.common.util; public final class Arguments { private Arguments() { throw new UnsupportedOperationException("Utility class"); } /** * Checks if value is instance of provided class * * * @param value Value to check * @param type Type to check * @return Reference which was checked */ @SuppressWarnings("unchecked") public static <T> T checkInstanceOf(Object value, Class<T> type) { if(!type.isInstance(value)) { throw new IllegalArgumentException(String.format("Value %s is not of type %s", value, type)); } return (T) value; } }
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.common.util; public final class Arguments { private Arguments() { throw new UnsupportedOperationException("Utility class"); } /** * Checks if value is instance of provided class * * * @param value Value to check * @param type Type to check * @return Reference which was checked */ @SuppressWarnings("unchecked") public static <T> T checkInstanceOf(Object value, Class<T> type) { if(!type.isInstance(value)) throw new IllegalArgumentException(String.format("Value %s is not of type %s", value, type)); return (T) value; } }
Make yaml fields lowercase in serfnode section
import os import uuid from mischief.actors.pipe import get_local_ip import yaml def read_serfnode_yml(): with open('/serfnode.yml') as input: conf = yaml.load(input) or {} return conf.get('serfnode') or {} yml = read_serfnode_yml() role = os.environ.get('ROLE') or yml.get('role') or 'no_role' peer = os.environ.get('PEER') or yml.get('peer') ip = (os.environ.get('SERF_IP') or yml.get('serf_ip') or get_local_ip('8.8.8.8')) bind_port = os.environ.get('SERF_PORT') or yml.get('serf_port') or 7946 node = os.environ.get('NODE_NAME') or uuid.uuid4().hex rpc_port = os.environ.get('RPC_PORT') or 7373 service = os.environ.get('SERVICE_IP') or yml.get('service_ip') service_port = os.environ.get('SERVICE_PORT') or yml.get('service_port') or 0
import os import uuid from mischief.actors.pipe import get_local_ip import yaml def read_serfnode_yml(): with open('/serfnode.yml') as input: conf = yaml.load(input) or {} return conf.get('serfnode') or {} yml = read_serfnode_yml() role = os.environ.get('ROLE') or yml.get('ROLE') or 'no_role' peer = os.environ.get('PEER') or yml.get('PEER') ip = (os.environ.get('SERF_IP') or yml.get('SERF_IP') or get_local_ip('8.8.8.8')) bind_port = os.environ.get('SERF_PORT') or yml.get('SERF_PORT') or 7946 node = os.environ.get('NODE_NAME') or uuid.uuid4().hex rpc_port = os.environ.get('RPC_PORT') or 7373 service = os.environ.get('SERVICE_IP') or yml.get('SERVICE_IP') service_port = os.environ.get('SERVICE_PORT') or yml.get('SERVICE_PORT') or 0
Add repository user & broker vars
package com.emc.ecs.serviceBroker.config; import java.net.URL; import org.cloudfoundry.community.servicebroker.model.BrokerApiVersion; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.emc.ecs.managementClient.Connection; import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials; @Configuration @ComponentScan(basePackages = "com.emc.ecs.serviceBroker") public class BrokerConfig { @Value("${endpoint}") private String endpoint; @Value("${port}") private String port; @Value("${username}") private String username; @Value("${password}") private String password; @Value("${replicationGroup}") private String replicationGroup; @Value("${namespace}") private String namespace; @Value("${repositoryUser}") private String repositoryUser; @Value("${repositoryBucket}") private String repositoryBucket; @Bean public Connection ecsConnection() { URL certificate = getClass().getClassLoader().getResource("localhost.pem"); return new Connection("https://" + endpoint + ":" + port, username, password, certificate); } @Bean public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion("2.7"); } @Bean public EcsRepositoryCredentials getRepositoryCredentials() { return new EcsRepositoryCredentials(repositoryBucket, repositoryUser, namespace, replicationGroup); } }
package com.emc.ecs.serviceBroker.config; import java.net.URL; import org.cloudfoundry.community.servicebroker.model.BrokerApiVersion; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.emc.ecs.managementClient.Connection; import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials; @Configuration @ComponentScan(basePackages = "com.emc.ecs.serviceBroker") public class BrokerConfig { @Value("${endpoint}") private String endpoint; @Value("${port}") private String port; @Value("${username}") private String username; @Value("${password}") private String password; @Value("${replicationGroup}") private String replicationGroup; @Value("${namespace}") private String namespace; @Bean public Connection ecsConnection() { URL certificate = getClass().getClassLoader().getResource("localhost.pem"); return new Connection("https://" + endpoint + ":" + port, username, password, certificate); } @Bean public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion("2.7"); } @Bean public EcsRepositoryCredentials getRepositoryCredentials() { return new EcsRepositoryCredentials(null, null, namespace, replicationGroup); } }
Use specific skipped testSetMultipleWithIntegerArrayKey now it is merged
<?php declare(strict_types = 1); namespace RoaveTest\DoctrineSimpleCache; use Cache\IntegrationTests\SimpleCacheTest; use Doctrine\Common\Cache\ArrayCache; use Roave\DoctrineSimpleCache\SimpleCacheAdapter; /** * @coversNothing */ final class CacheIntegrationTest extends SimpleCacheTest { /** * @return \Psr\SimpleCache\CacheInterface that is used in the tests */ public function createSimpleCache() : \Psr\SimpleCache\CacheInterface { return new SimpleCacheAdapter(new ArrayCache()); } protected function setUp() : void { parent::setUp(); // @todo: Let's make these tests pass $this->skippedTests['testObjectDoesNotChangeInCache'] = true; // https://github.com/php-cache/integration-tests/pull/74/files $this->skippedTests['testSetMultipleWithIntegerArrayKey'] = true; } }
<?php declare(strict_types = 1); namespace RoaveTest\DoctrineSimpleCache; use Cache\IntegrationTests\SimpleCacheTest; use Doctrine\Common\Cache\ArrayCache; use Roave\DoctrineSimpleCache\SimpleCacheAdapter; /** * @coversNothing */ final class CacheIntegrationTest extends SimpleCacheTest { /** * @return \Psr\SimpleCache\CacheInterface that is used in the tests */ public function createSimpleCache() : \Psr\SimpleCache\CacheInterface { return new SimpleCacheAdapter(new ArrayCache()); } protected function setUp() : void { parent::setUp(); // @todo: Let's make these tests pass $this->skippedTests['testObjectDoesNotChangeInCache'] = true; // https://github.com/php-cache/integration-tests/pull/74/files $this->skippedTests['testSetMultiple'] = true; } }
Remove unnecessarily specific null check
(function($) { $(document).ready(function() { (function markEmailsAsReadOnOpen() { $(".panel-info").click(function() { var $el = $(this); if ($el.hasClass("panel-info")) { var email_id = $el.data("email_id"); if (email_id) { $.ajax({ url: "/email/read/" + email_id, success: function() { $el.removeClass("panel-info").addClass("panel-default"); } }); } } }); }()); (function printEmailOnPrintButtonClick() { $(".print-trigger").click(function() { var $printRoot = $(this).closest(".print-root"); $printRoot.printThis(); }); }()); }); })(window.jQuery);
(function($) { $(document).ready(function() { (function markEmailsAsReadOnOpen() { $(".panel-info").click(function() { var $el = $(this); if ($el.hasClass("panel-info")) { var email_id = $el.data("email_id"); if (email_id != null) { $.ajax({ url: "/email/read/" + email_id, success: function() { $el.removeClass("panel-info").addClass("panel-default"); } }); } } }); }()); (function printEmailOnPrintButtonClick() { $(".print-trigger").click(function() { var $printRoot = $(this).closest(".print-root"); $printRoot.printThis(); }); }()); }); })(window.jQuery);
Set window size to something a little bigger.
import os from urlparse import urljoin from django.conf import settings from splinter.browser import Browser from inthe_am.taskmanager import models TEST_COUNTERS = {} def before_all(context): context.browser = Browser('phantomjs') def after_all(context): context.browser.quit() context.browser = None def before_scenario(context, step): models.User.objects.filter( email=settings.TESTING_LOGIN_USER ).delete() context.browser.driver.set_window_size(1024, 768) def after_scenario(context, step): context.browser.visit(urljoin(context.config.server_url, '/logout/')) def after_step(context, step): global TEST_COUNTERS if context.failed: name = '-'.join([ context.scenario.name.replace(' ', '_'), ]) if name not in TEST_COUNTERS: TEST_COUNTERS[name] = 0 TEST_COUNTERS[name] += 1 name = name + '_%s_' % TEST_COUNTERS[name] context.browser.screenshot(name) with open(os.path.join('/tmp', name + '.html'), 'w') as out: out.write(context.browser.html)
import os from urlparse import urljoin from django.conf import settings from splinter.browser import Browser from inthe_am.taskmanager import models TEST_COUNTERS = {} def before_all(context): context.browser = Browser('phantomjs') def after_all(context): context.browser.quit() context.browser = None def before_scenario(context, step): models.User.objects.filter( email=settings.TESTING_LOGIN_USER ).delete() def after_scenario(context, step): context.browser.visit(urljoin(context.config.server_url, '/logout/')) def after_step(context, step): global TEST_COUNTERS if context.failed: name = '-'.join([ context.scenario.name.replace(' ', '_'), ]) if name not in TEST_COUNTERS: TEST_COUNTERS[name] = 0 TEST_COUNTERS[name] += 1 name = name + '_%s_' % TEST_COUNTERS[name] context.browser.screenshot(name) with open(os.path.join('/tmp', name + '.html'), 'w') as out: out.write(context.browser.html)
Fix for when category description has html. Could be better.
/** This view handles rendering of a combobox that can view a category @class ComboboxViewCategory @extends Discourse.ComboboxView @namespace Discourse @module Discourse **/ Discourse.ComboboxViewCategory = Discourse.ComboboxView.extend({ none: 'category.none', classNames: ['combobox category-combobox'], overrideWidths: true, dataAttributes: ['name', 'color', 'text_color', 'description'], valueBinding: Ember.Binding.oneWay('source'), template: function(text, templateData) { if (!templateData.color) return text; var result = "<span class='badge-category' style='background-color: #" + templateData.color + '; color: #' + templateData.text_color + ";'>" + templateData.name + "</span>"; if (templateData.description && templateData.description !== 'null') { result += '<div class="category-desc">' + Handlebars.Utils.escapeExpression(templateData.description) + '</div>'; } return result; } });
/** This view handles rendering of a combobox that can view a category @class ComboboxViewCategory @extends Discourse.ComboboxView @namespace Discourse @module Discourse **/ Discourse.ComboboxViewCategory = Discourse.ComboboxView.extend({ none: 'category.none', classNames: ['combobox category-combobox'], overrideWidths: true, dataAttributes: ['color', 'text_color', 'description'], valueBinding: Ember.Binding.oneWay('source'), template: function(text, templateData) { if (!templateData.color) return text; var result = "<span class='badge-category' style='background-color: #" + templateData.color + '; color: #' + templateData.text_color + ";' >" + text + "</span>"; if (templateData.description && templateData.description !== 'null') { result += '<div class="category-desc">' + templateData.description + '</div>'; } return result; } });
Add test for single addIvar call. For some reason this fixes the segfault from before... WTF...
var $ = require('../') , assert = require('assert') $.import('Foundation') $.NSAutoreleasePool('alloc')('init') // Subclass 'NSObject', creating a new class named 'NRTest' var NRTest = $.NSObject.extend('NRTest') , counter = 0 // Add a new method to the NRTest class responding to the "description" selector assert.ok(NRTest.addMethod('description', '@@:', function (self, _cmd) { counter++ console.log(_cmd) console.log(self.ivar('name')) return $.NSString('stringWithUTF8String', 'test') })) // Add an instance variable, an NSString* instance. assert.ok(NRTest.addIvar('name', '@')) // Finalize the class so the we can make instances of it NRTest.register() // Create an instance var instance = NRTest('alloc')('init') // call [instance description] in a variety of ways (via toString()) console.log(instance('description')+'') console.log(instance.toString()) instance.ivar('name', $._('NodObjC Rules!')) console.log(String(instance)) console.log(''+instance) console.log(instance+'') console.log(instance) assert.equal(counter, 6)
var $ = require('../') , assert = require('assert') $.import('Foundation') $.NSAutoreleasePool('alloc')('init') // Subclass 'NSObject', creating a new class named 'NRTest' var NRTest = $.NSObject.extend('NRTest') , counter = 0 // Add a new method to the NRTest class responding to the "description" selector NRTest.addMethod('description', '@@:', function (self, _cmd) { counter++ console.log(_cmd) return $.NSString('stringWithUTF8String', 'test') }) // Finalize the class so the we can make instances of it NRTest.register() // Create an instance var instance = NRTest('alloc')('init') // call [instance description] in a variety of ways (via toString()) console.log(instance('description')+'') console.log(instance.toString()) //console.log(String(instance)) // now this one segfaults? WTF!?!?! console.log(''+instance) console.log(instance+'') console.log(instance) assert.equal(counter, 5)
Disable keystone auto update feature to avoid the "missing updates folder" error when starting it.
var config = require('./config.json'); var keystone = require('keystone'); keystone.init({ 'name': 'anapi', 'brand': 'anapi', 'favicon': 'public/favicon.ico', 'view engine': 'jade', 'wysiwyg images': true, 'wysiwyg menubar': true, 'wysiwyg additional plugins': 'table', 'mongo' : config.mongo.uri, // 'auto update': true, 'session': true, 'auth': true, 'user model': 'User', 'cookie secret': '0T=?C|`ed@N&amp;,&lt;!)BQ&lt;Nh/7+e3TeO&#34;$^cl{7Z$7i@mfnybN1{*H.ETQ=(-&gt;75^MB' }); keystone.import('models'); keystone.set('locals', { // _: require('underscore'), env: keystone.get('env'), utils: keystone.utils, editable: keystone.content.editable }); keystone.set('routes', require('./routes')); keystone.set('nav', { // 'bills': 'bills' }); keystone.start();
var config = require('./config.json'); var keystone = require('keystone'); keystone.init({ 'name': 'anapi', 'brand': 'anapi', 'favicon': 'public/favicon.ico', 'view engine': 'jade', 'wysiwyg images': true, 'wysiwyg menubar': true, 'wysiwyg additional plugins': 'table', 'mongo' : config.mongo.uri, 'auto update': true, 'session': true, 'auth': true, 'user model': 'User', 'cookie secret': '0T=?C|`ed@N&amp;,&lt;!)BQ&lt;Nh/7+e3TeO&#34;$^cl{7Z$7i@mfnybN1{*H.ETQ=(-&gt;75^MB' }); keystone.import('models'); keystone.set('locals', { // _: require('underscore'), env: keystone.get('env'), utils: keystone.utils, editable: keystone.content.editable }); keystone.set('routes', require('./routes')); keystone.set('nav', { // 'bills': 'bills' }); keystone.start();
Add view for the events modules
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/' class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase): template_prefix = 'events/' def _getBody(self, params): return WPJinjaMixin._getPageContent(self, params) def getCSSFiles(self): return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from MaKaC.webinterface.pages.admins import WPAdminsBase from MaKaC.webinterface.pages.base import WPJinjaMixin class WPReferenceTypes(WPJinjaMixin, WPAdminsBase): template_prefix = 'events/'
Upgrade jsonschema to latest (v4.4.0)
#!/usr/bin/env python # coding=utf-8 from setuptools import setup # Get long description (used on PyPI project page) def get_long_description(): with open('README.md', 'r') as readme_file: return readme_file.read() setup( name='alfred-workflow-packager', version='1.2.1', description='A CLI utility for packaging and exporting Alfred workflows', long_description=get_long_description(), long_description_content_type='text/markdown', url='https://github.com/caleb531/alfred-workflow-packager', author='Caleb Evans', author_email='caleb@calebevans.me', license='MIT', keywords='alfred workflow package export', packages=['awp'], package_data={ 'awp': ['data/config-schema.json'] }, install_requires=[ 'jsonschema >= 4, < 5' ], entry_points={ 'console_scripts': [ 'awp=awp.main:main' ] } )
#!/usr/bin/env python # coding=utf-8 from setuptools import setup # Get long description (used on PyPI project page) def get_long_description(): with open('README.md', 'r') as readme_file: return readme_file.read() setup( name='alfred-workflow-packager', version='1.2.1', description='A CLI utility for packaging and exporting Alfred workflows', long_description=get_long_description(), long_description_content_type='text/markdown', url='https://github.com/caleb531/alfred-workflow-packager', author='Caleb Evans', author_email='caleb@calebevans.me', license='MIT', keywords='alfred workflow package export', packages=['awp'], package_data={ 'awp': ['data/config-schema.json'] }, install_requires=[ 'jsonschema >= 2, < 3' ], entry_points={ 'console_scripts': [ 'awp=awp.main:main' ] } )
Move network registry to common setup event. That is sufficient
package info.u_team.u_team_core.intern.init; import info.u_team.u_team_core.UCoreMod; import info.u_team.u_team_core.intern.network.*; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.network.NetworkRegistry; import net.minecraftforge.fml.network.simple.SimpleChannel; public class UCoreNetwork { public static final String PROTOCOL = "1.15.2-2"; public static final SimpleChannel NETWORK = NetworkRegistry.newSimpleChannel(new ResourceLocation(UCoreMod.MODID, "network"), () -> PROTOCOL, PROTOCOL::equals, PROTOCOL::equals); public static void setup(FMLCommonSetupEvent event) { NETWORK.registerMessage(0, BufferPropertyContainerMessage.class, BufferPropertyContainerMessage::encode, BufferPropertyContainerMessage::decode, BufferPropertyContainerMessage.Handler::handle); NETWORK.registerMessage(1, FluidSetAllContainerMessage.class, FluidSetAllContainerMessage::encode, FluidSetAllContainerMessage::decode, FluidSetAllContainerMessage.Handler::handle); NETWORK.registerMessage(2, FluidSetSlotContainerMessage.class, FluidSetSlotContainerMessage::encode, FluidSetSlotContainerMessage::decode, FluidSetSlotContainerMessage.Handler::handle); NETWORK.registerMessage(3, FluidClickContainerMessage.class, FluidClickContainerMessage::encode, FluidClickContainerMessage::decode, FluidClickContainerMessage.Handler::handle); } }
package info.u_team.u_team_core.intern.init; import info.u_team.u_team_core.UCoreMod; import info.u_team.u_team_core.intern.network.*; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.network.NetworkRegistry; import net.minecraftforge.fml.network.simple.SimpleChannel; public class UCoreNetwork { public static final String PROTOCOL = "1.15.2-2"; public static final SimpleChannel NETWORK = NetworkRegistry.newSimpleChannel(new ResourceLocation(UCoreMod.MODID, "network"), () -> PROTOCOL, PROTOCOL::equals, PROTOCOL::equals); public static void construct() { NETWORK.registerMessage(0, BufferPropertyContainerMessage.class, BufferPropertyContainerMessage::encode, BufferPropertyContainerMessage::decode, BufferPropertyContainerMessage.Handler::handle); NETWORK.registerMessage(1, FluidSetAllContainerMessage.class, FluidSetAllContainerMessage::encode, FluidSetAllContainerMessage::decode, FluidSetAllContainerMessage.Handler::handle); NETWORK.registerMessage(2, FluidSetSlotContainerMessage.class, FluidSetSlotContainerMessage::encode, FluidSetSlotContainerMessage::decode, FluidSetSlotContainerMessage.Handler::handle); NETWORK.registerMessage(3, FluidClickContainerMessage.class, FluidClickContainerMessage::encode, FluidClickContainerMessage::decode, FluidClickContainerMessage.Handler::handle); } }
Allow or deny access to graphql based on JWT
const jwt = require('jsonwebtoken'); const AuthPolicy = require('./policy').AuthPolicy; module.exports.authorize = (token, secret, authInfo, cb) => { const options = {}; return jwt.verify(token, secret, options, (err, identity) => { const username = identity ? identity.username : ''; console.log(`Building policy for ${username} with: `, authInfo); const policy = new AuthPolicy(username, authInfo.accountId, authInfo); if (err) { console.log('Error verifing jwt', err); policy.denyAllMethods(); } else { policy.allowMethod(AuthPolicy.HttpVerb.POST, '/graphql'); } const result = policy.build(); console.log('Returning auth result: ', result, result.policyDocument.Statement); return cb(null, result); }); };
const jwt = require('jsonwebtoken'); const AuthPolicy = require('./policy').AuthPolicy; module.exports.authorize = (token, secret, authInfo, cb) => { const options = {}; return jwt.verify(token, secret, options, (err, identity) => { if (err) return cb(err); console.log(`Building policy for ${identity.username} with: `, authInfo); const policy = new AuthPolicy(identity.username, authInfo.accountId, authInfo); policy.denyAllMethods(); // policy.allowAllMethods(); // Or define subset based on scop - verifiedJwt.body.scope // policy.allowMethod(AuthPolicy.HttpVerb.GET, "*"); // policy.allowMethod(AuthPolicy.HttpVerb.POST, "/users/" + verifiedJwt.body.sub); const result = policy.build(); console.log('Returning auth result: ', result, result.policyDocument.Statement); return cb(null, result); }); };
Update content in default blocker page.
<?php use yii\helpers\Url; use yii\helpers\Html; /* @var $this yii\web\View */ ?> <div class="ishtar-default-index"> <h1><?= $this->context->module->name ?> <?= $this->context->module->version ?></h1> <?php if ($this->context->module->isAlphaLogin):?> <p><?= Html::a('Sign out ', Url::toRoute(['/' . $this->context->module->id . '/gate/signout']))?></p> <?php endif;?> <p> <?= $this->context->module->name?> is an yii2.0 extension provides enhanced maintenance mode with restricted access for internal tests. </p> <p> You may customize this page by editing the following file:<br> <code><?= __FILE__ ?></code><br /> </p> <p> <strong>Custom message:</strong> <?= $this->context->module->customField; ?> </p> </div>
<?php use yii\helpers\Url; use yii\helpers\Html; /* @var $this yii\web\View */ ?> <div class="ishtar-default-index"> <h1><?= $this->context->action->uniqueId ?></h1> <?php if ($this->context->module->isAlphaLogin):?> <p><?= Html::a('Sign out', Url::toRoute(['/' . $this->context->module->id . '/gate/signout']))?></p> <?php endif;?> <p> This is the view content for action "<?= $this->context->action->id ?>". The action belongs to the controller "<?= get_class($this->context) ?>" in the "<?= $this->context->module->id ?>" module. </p> <p> You may customize this page by editing the following file:<br> <code><?= __FILE__ ?></code><br /> </p> <h3> <?= $this->context->module->customField; ?> </h3> </div>
Update test harness to use new REST API path for OpenShift.
from pytest import fixture, mark from ..openshift import OpenShiftOAuthenticator from .mocks import setup_oauth_mock def user_model(username): """Return a user model""" return { 'metadata': { 'name': username, } } @fixture def openshift_client(client): setup_oauth_mock(client, host=['localhost'], access_token_path='/oauth/token', user_path='/apis/user.openshift.io/v1/users/~', ) return client async def test_openshift(openshift_client): authenticator = OpenShiftOAuthenticator() handler = openshift_client.handler_for_user(user_model('wash')) user_info = await authenticator.authenticate(handler) assert sorted(user_info) == ['auth_state', 'name'] name = user_info['name'] assert name == 'wash' auth_state = user_info['auth_state'] assert 'access_token' in auth_state assert 'openshift_user' in auth_state
from pytest import fixture, mark from ..openshift import OpenShiftOAuthenticator from .mocks import setup_oauth_mock def user_model(username): """Return a user model""" return { 'metadata': { 'name': username, } } @fixture def openshift_client(client): setup_oauth_mock(client, host=['localhost'], access_token_path='/oauth/token', user_path='/oapi/v1/users/~', ) return client async def test_openshift(openshift_client): authenticator = OpenShiftOAuthenticator() handler = openshift_client.handler_for_user(user_model('wash')) user_info = await authenticator.authenticate(handler) assert sorted(user_info) == ['auth_state', 'name'] name = user_info['name'] assert name == 'wash' auth_state = user_info['auth_state'] assert 'access_token' in auth_state assert 'openshift_user' in auth_state
Remove spaces from version string.
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2012-2013 by its contributors. See AUTHORS for details. # # Distributed under the MIT/X11 software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. # VERSION = (0,0,1, '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 = '%spre-alpha' % version else: if VERSION[3] != 'final': version = "%s%s" % (version, VERSION[3]) if VERSION[4] != 0: version = '%s%s' % (version, VERSION[4]) return version # # End of File #
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2012-2013 by its contributors. See AUTHORS for details. # # Distributed under the MIT/X11 software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. # VERSION = (0,0,1, '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" % (version, VERSION[3]) if VERSION[4] != 0: version = '%s%s' % (version, VERSION[4]) return version # # End of File #
Fix a copy/paste error in a comment.
// Copyright (C) 2014 Tom <tw201207@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.gitblit.utils; import java.io.ByteArrayOutputStream; /** * A {@link ByteArrayOutputStream} that can be reset to a specified position. * * @author Tom <tw201207@gmail.com> */ public class ResettableByteArrayOutputStream extends ByteArrayOutputStream { /** * Reset the stream to the given position. If {@code mark} is <= 0, see {@link #reset()}. * A no-op if the stream contains less than {@code mark} bytes. Otherwise, resets the * current writing position to {@code mark}. Previously allocated buffer space will be * reused in subsequent writes. * * @param mark * to set the current writing position to. */ public synchronized void resetTo(int mark) { if (mark <= 0) { reset(); } else if (mark < count) { count = mark; } } }
// Copyright (C) 2014 Tom <tw201207@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.package com.gitblit.utils; package com.gitblit.utils; import java.io.ByteArrayOutputStream; /** * A {@link ByteArrayOutputStream} that can be reset to a specified position. * * @author Tom <tw201207@gmail.com> */ public class ResettableByteArrayOutputStream extends ByteArrayOutputStream { /** * Reset the stream to the given position. If {@code mark} is <= 0, see {@link #reset()}. * A no-op if the stream contains less than {@code mark} bytes. Otherwise, resets the * current writing position to {@code mark}. Previously allocated buffer space will be * reused in subsequent writes. * * @param mark * to set the current writing position to. */ public synchronized void resetTo(int mark) { if (mark <= 0) { reset(); } else if (mark < count) { count = mark; } } }
Remove useless return. warnings is always an array after a split.
module.exports = function parseWarningHeader (header) { if (!header || typeof header !== 'string') return var warnings = header.split(/([0-9]{3} [a-z0-9.@\-\/]*) /g) var previous function generateObject (all, w) { w = w.trim() var newError = w.match(/^([0-9]{3}) (.*)/) if (newError) previous = {code: newError[1], agent: newError[2]} else if (w) { var errorContent = w.split(/" "/) if (errorContent) { previous.message = strip(errorContent[0]) previous.date = strip(errorContent[1]) all.push(previous) } } return all } return warnings.reduce(generateObject, []) } function strip (s) { if (!s) return return s.replace(/(^"|[",]*$)/, '') }
module.exports = function parseWarningHeader (header) { if (!header || typeof header !== 'string') return var warnings = header.split(/([0-9]{3} [a-z0-9.@\-\/]*) /g) if (!warnings) return var previous function generateObject (all, w) { w = w.trim() var newError = w.match(/^([0-9]{3}) (.*)/) if (newError) previous = {code: newError[1], agent: newError[2]} else if (w) { var errorContent = w.split(/" "/) if (errorContent) { previous.message = strip(errorContent[0]) previous.date = strip(errorContent[1]) all.push(previous) } } return all } return warnings.reduce(generateObject, []) } function strip (s) { if (!s) return return s.replace(/(^"|[",]*$)/, '') }
Add css class to register form button
<div id="<?=$_id?>" class="well"> <h2>Register</h2> <form action="<?=$registerUrl?>" method="post"> <label>Email</label> <input name="email" type="text" value="<?=empty($email) ? '' : $email?>" placeholder="Email" /><br /> <label>Password</label> <input name="password" type="password" placeholder="Password" /><br /> <label>Confirm Password</label> <input name="password_confirm" type="password" placeholder="Confirm password" /><br /> <input type="hidden" name="register" value="1" /> <button class="btn">Register</button> <!-- add captcha --> <?=app()->createCaptcha()?> </form> <h2>PHP</h2> <h3>Create validator</h3> <pre> $validator = app()->createValidator(); </pre> <h3>Create rule to validate email address format</h3> <pre> $rule = $validator->createRule('email') ->setErrorMessage('Invalid email address') ->setAction('isEmail'); $validator->addRule($rule); </pre> <h3>Add more rules and finally get validation result</h3> <pre> $result = $validator->validate()->getResult(); </pre> </div>
<div id="<?=$_id?>" class="well"> <h2>Register</h2> <form action="<?=$registerUrl?>" method="post"> <label>Email</label> <input name="email" type="text" value="<?=empty($email) ? '' : $email?>" placeholder="Email" /><br /> <label>Password</label> <input name="password" type="password" placeholder="Password" /><br /> <label>Confirm Password</label> <input name="password_confirm" type="password" placeholder="Confirm password" /><br /> <input type="hidden" name="register" value="1" /> <button>Register</button> <!-- add captcha --> <?=app()->createCaptcha()?> </form> <h2>PHP</h2> <h3>Create validator</h3> <pre> $validator = app()->createValidator(); </pre> <h3>Create rule to validate email address format</h3> <pre> $rule = $validator->createRule('email') ->setErrorMessage('Invalid email address') ->setAction('isEmail'); $validator->addRule($rule); </pre> <h3>Add more rules and finally get validation result</h3> <pre> $result = $validator->validate()->getResult(); </pre> </div>
Print help info if no flag specified
// harbour project main.go package main import ( "fmt" "os" "os/exec" "github.com/huawei-openlab/harbour/mflag" "github.com/huawei-openlab/harbour/opts" "github.com/Sirupsen/logrus" ) func main() { mflag.Parse() if *flVersion { showVersion() return } if *flHelp { mflag.Usage() return } if *flDebug { logrus.SetLevel(logrus.DebugLevel) } if len(flHosts) == 0 { defaultHost := fmt.Sprintf("unix://%s", opts.DEFAULTUNIXSOCKET) flHosts = append(flHosts, defaultHost) } _, ok := exec.LookPath("docker") if ok != nil { logrus.Fatal("Can't find docker") } if *flDaemon { mainDaemon() return } if len(flHosts) > 1 { fmt.Fprintf(os.Stderr, "Please specify only one -H") os.Exit(0) } // If no flag specified, print help info. mflag.Usage() } func showVersion() { fmt.Printf("harbour version 0.0.1\n") }
// harbour project main.go package main import ( "fmt" "os" "os/exec" "github.com/huawei-openlab/harbour/mflag" "github.com/huawei-openlab/harbour/opts" "github.com/Sirupsen/logrus" ) func main() { mflag.Parse() if *flVersion { showVersion() return } if *flHelp { mflag.Usage() return } if *flDebug { logrus.SetLevel(logrus.DebugLevel) } if len(flHosts) == 0 { defaultHost := fmt.Sprintf("unix://%s", opts.DEFAULTUNIXSOCKET) flHosts = append(flHosts, defaultHost) } _, ok := exec.LookPath("docker") if ok != nil { logrus.Fatal("Can't find docker") } if *flDaemon { mainDaemon() return } if len(flHosts) > 1 { fmt.Fprintf(os.Stderr, "Please specify only one -H") os.Exit(0) } } func showVersion() { fmt.Printf("harbour version 0.0.1\n") }
Simplify checkbox to functional component and to use connect
import React from 'react'; import PropTypes from 'prop-types'; import {updateValue} from '../actions/controls'; import {connect} from '../store'; const Checkbox = ({id, name, className, style, value, updateValue}) => <input type="checkbox" className={className} style={style} id={id} name={name} checked={value || false} onChange={(e) => updateValue(name, e.target.checked)} />; Checkbox.propTypes = { className: PropTypes.string, id: PropTypes.string, name: PropTypes.string.isRequired, style: PropTypes.string, value: PropTypes.bool, }; const mapStateToProps = ({controls}, props) => ({ value: controls.get(props.name), }); const mapDispatchToProps = { updateValue, }; export default connect(mapStateToProps, mapDispatchToProps)(Checkbox);
import React from 'react'; import PropTypes from 'prop-types'; import Control from './Control'; class Checkbox extends Control { static propTypes = { className: PropTypes.string, id: PropTypes.string, name: PropTypes.string.isRequired, style: PropTypes.string, }; static defaultProps = { type: 'text', }; render() { const {id, name, className, style} = this.props; return ( <input type="checkbox" className={className} style={style} id={id} name={name} checked={this._getValue() || false} onChange={(e) => this._onChange(e.target.checked)} /> ); } } export default Checkbox;
Reformat code, remove auth hack
<?php defined('SYSPATH') or die('No direct script access.'); class Controller_Auth extends Controller_Template { public $template = 'templates/public'; public function action_index() { if ($this->request->post('username')) { $username = $this->request->post('username'); $password = $this->request->post('password'); $is_logged_in = Auth::instance()->login($username, $password); if ($is_logged_in) { Notify::success('Success!'); $this->redirect('welcome'); } else { Notify::error('Kasutajanimi või parool vale!'); } } } public function action_logout() { Auth::instance()->logout(); $this->redirect('auth'); } } // End Welcome
<?php defined('SYSPATH') or die('No direct script access.'); class Controller_Auth extends Controller_Template { public $template = 'templates/public'; public function action_index() { if( $this->request->post('username') ) { $username = $this->request->post('username'); $password = $this->request->post('password'); // Hack: repair later //todo Auth::instance()->force_login('demo'); $is_logged_in = Auth::instance()->logged_in(); if ($is_logged_in) { Notify::success('Success!'); $this->redirect('welcome'); } else { Notify::error('Kasutajanimi või parool vale!'); } } } public function action_logout() { Auth::instance()->logout(); $this->redirect('auth'); } } // End Welcome
Update to new e-mail adress.
# -*- coding: utf-8 -*- import os from setuptools import setup # type: ignore VERSION = '4.2.2' setup( name='conllu', packages=["conllu"], package_data={ "": ["py.typed"] }, version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="emil@emilstenstrom.se", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", ], )
# -*- coding: utf-8 -*- import os from setuptools import setup # type: ignore VERSION = '4.2.2' setup( name='conllu', packages=["conllu"], package_data={ "": ["py.typed"] }, version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", ], )
Test return in create() method
<?php namespace Uploadify; use Illuminate\Contracts\Filesystem\Factory as Storage; use Illuminate\Http\UploadedFile; use Intervention\Image\Image as InterventionImage; use Illuminate\Database\Eloquent\Model as Eloquent; class UploadifyManager { /** * The filesystem factory instance * * @var \Illuminate\Contracts\Filesystem\Factory */ protected $storage; /** * The list of settings * * @var array */ protected $settings = []; /** * Create new uploadify instance * * @param \Illuminate\Contracts\Filesystem\Factory $storage * @param array $settings * @return void */ public function __construct(Storage $storage, array $settings = []) { $this->storage = $storage; $this->settings = $settings; } /** * Create new uploadify instance * * @param \Illuminate\Http\UploadedFile $file * @param \Illuminate\Database\Eloquent\Model $model * @param \Uploadify\Uploadify $field * @return self */ public function create(UploadedFile $file, Eloquent $model, $field) { return; } }
<?php namespace Uploadify; use Illuminate\Contracts\Filesystem\Factory as Storage; use Illuminate\Http\UploadedFile; use Intervention\Image\Image as InterventionImage; use Illuminate\Database\Eloquent\Model as Eloquent; class UploadifyManager { /** * The filesystem factory instance * * @var \Illuminate\Contracts\Filesystem\Factory */ protected $storage; /** * The list of settings * * @var array */ protected $settings = []; /** * Create new uploadify instance * * @param \Illuminate\Contracts\Filesystem\Factory $storage * @param array $settings * @return void */ public function __construct(Storage $storage, array $settings = []) { $this->storage = $storage; $this->settings = $settings; } /** * Create new uploadify instance * * @param \Illuminate\Http\UploadedFile $file * @param \Illuminate\Database\Eloquent\Model $model * @param \Uploadify\Uploadify $field * @return self */ public function create(UploadedFile $file, Eloquent $model, $field) { } }
Replace constructors with static factory methods.
package uk.ac.ebi.quickgo.ontology.common.coterms; import java.io.IOException; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; /** * Configuration class related to loading and using co-occurring terms information. * @author Tony Wardell * Date: 29/09/2016 * Time: 11:50 * Created with IntelliJ IDEA. */ @Configuration public class CoTermRepoConfig { @Value("${coterm.source.manual}") private Resource manualResource; @Value("${coterm.source.all}") private Resource allResource; @Bean public CoTermRepository coTermRepository() { CoTermRepositorySimpleMap coTermRepository; try{ coTermRepository = CoTermRepositorySimpleMap.createCoTermRepositorySimpleMap(manualResource, allResource); } catch (IOException e) { throw new RuntimeException("Failed to load co-occurring terms from manual source " + (manualResource!=null?manualResource.getDescription():"unknown") + " or from all source " + (allResource!=null?allResource.getDescription():"unknown")); } return coTermRepository; } }
package uk.ac.ebi.quickgo.ontology.common.coterms; import java.io.IOException; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; /** * Configuration class related to loading and using co-occurring terms information. * @author Tony Wardell * Date: 29/09/2016 * Time: 11:50 * Created with IntelliJ IDEA. */ @Configuration public class CoTermRepoConfig { @Value("${coterm.source.manual}") private Resource manualResource; @Value("${coterm.source.all}") private Resource allResource; @Bean public CoTermRepository coTermRepository() { CoTermRepositorySimpleMap coTermRepository = new CoTermRepositorySimpleMap(); CoTermRepositorySimpleMap.CoTermLoader coTermLoader = coTermRepository.new CoTermLoader(manualResource, allResource); try { coTermLoader.load(); } catch (IOException e) { throw new RuntimeException("Failed to load co-occurring terms from manual source " + (manualResource!=null?manualResource.getDescription():"unknown") + " or from all source " + (allResource!=null?allResource.getDescription():"unknown")); } return coTermRepository; } }
Add global middleware to initialize shared namespace
/** * Entry point of hyperion server * @module server/server */ 'use strict'; var bodyParser = require('body-parser'); var express = require('express'); var mongoose = require('mongoose'); var log = require('logger')(__filename); var routes = require('routes/routes'); var sequences = require('models/sequences'); var app = express(); var exports = module.exports = app; exports._expressListenCallback = (port, err) => { if (err) { return log.error({ err: err }, '_expressListenCallback error'); } log.trace('_expressListenCallback success PORT: '+ port); }; /** * @param {String} connectionUrl */ exports._initializeMongoose = (connectionUrl) => { //new Promise() mongoose.connect(connectionUrl); //TODO: Add logic to block until connection completes }; /** * */ exports._initializeMiddleware = (app) => { app.use(bodyParser.json()); app.use((req, res, next) => { // initialize middleware shared data namespace req.runnableData = {}; next(); }); }; /** * Initialize application. * - Initialize sequences * - Bind routes * - Start express server */ exports.start = (opts) => { //new Promise() sequences.initialize(opts.sequences); exports._initializeMongoose(); exports._initializeMiddleware(app); routes.initialize(app); exports.listen(opts.port, exports._expressListenCallback.bind(this, opts.port)); };
/** * Entry point of hyperion server * @module server/server */ 'use strict'; var bodyParser = require('body-parser'); var express = require('express'); var mongoose = require('mongoose'); var log = require('logger')(__filename); var routes = require('routes/routes'); var sequences = require('models/sequences'); var app = express(); var exports = module.exports = app; exports._expressListenCallback = (port, err) => { if (err) { return log.error({ err: err }, '_expressListenCallback error'); } log.trace('_expressListenCallback success PORT: '+ port); }; /** * @param {String} connectionUrl */ exports._initializeMongoose = (connectionUrl) => { //new Promise() mongoose.connect(connectionUrl); //TODO: Add logic to block until connection completes }; /** * */ exports._initializeMiddleware = (app) => { app.use(bodyParser.json()); }; /** * Initialize application. * - Initialize sequences * - Bind routes * - Start express server */ exports.start = (opts) => { //new Promise() sequences.initialize(opts.sequences); exports._initializeMongoose(); exports._initializeMiddleware(app); routes.initialize(app); exports.listen(opts.port, exports._expressListenCallback.bind(this, opts.port)); };
Add a description content type for PyPI A long_description_content_type is required since our README is in markdown instead of restructured text.
from distutils.core import setup from setuptools import find_packages with open('README.md') as fp: long_description = fp.read() setup( name='sendwithus', version='5.2.0', author='sendwithus', author_email='us@sendwithus.com', packages=find_packages(), scripts=[], url='https://github.com/sendwithus/sendwithus_python', license='LICENSE.txt', description='Python API client for sendwithus.com', long_description=long_description, long_description_content_type='text/markdown', test_suite="sendwithus.test", install_requires=[ "requests >= 2.0.0", "six >= 1.9.0" ], extras_require={ "test": [ "pytest >= 3.0.5", "pytest-xdist >= 1.15.0" ] }, classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "License :: OSI Approved :: Apache Software License", "Development Status :: 5 - Production/Stable", "Topic :: Communications :: Email" ] )
from distutils.core import setup from setuptools import find_packages with open('README.md') as fp: long_description = fp.read() setup( name='sendwithus', version='5.2.0', author='sendwithus', author_email='us@sendwithus.com', packages=find_packages(), scripts=[], url='https://github.com/sendwithus/sendwithus_python', license='LICENSE.txt', description='Python API client for sendwithus.com', long_description=long_description, test_suite="sendwithus.test", install_requires=[ "requests >= 2.0.0", "six >= 1.9.0" ], extras_require={ "test": [ "pytest >= 3.0.5", "pytest-xdist >= 1.15.0" ] }, classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "License :: OSI Approved :: Apache Software License", "Development Status :: 5 - Production/Stable", "Topic :: Communications :: Email" ] )
Add scalar typehints/return types on final/internal/private code
<?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\PropertyAccess; /** * Entry point of the PropertyAccess component. * * @author Bernhard Schussek <bschussek@gmail.com> */ final class PropertyAccess { /** * Creates a property accessor with the default configuration. * * @return PropertyAccessor */ public static function createPropertyAccessor(): PropertyAccessor { return self::createPropertyAccessorBuilder()->getPropertyAccessor(); } public static function createPropertyAccessorBuilder(): PropertyAccessorBuilder { return new PropertyAccessorBuilder(); } /** * This class cannot be instantiated. */ private function __construct() { } }
<?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\PropertyAccess; /** * Entry point of the PropertyAccess component. * * @author Bernhard Schussek <bschussek@gmail.com> */ final class PropertyAccess { /** * Creates a property accessor with the default configuration. * * @return PropertyAccessor */ public static function createPropertyAccessor() { return self::createPropertyAccessorBuilder()->getPropertyAccessor(); } /** * Creates a property accessor builder. * * @return PropertyAccessorBuilder */ public static function createPropertyAccessorBuilder() { return new PropertyAccessorBuilder(); } /** * This class cannot be instantiated. */ private function __construct() { } }
Add correct clases to factory
<?php abstract class Dao_Factory { abstract public function setConnection($conn); abstract public function getConnection(); abstract public function getSpotDao(); abstract public function getSpotSearchDao(); abstract public function getUserDao(); abstract public function getCacheDao(); abstract public function getAuditDao(); abstract public function getUserFilterDao(); abstract public function getSessionDao(); abstract public function getBlackWhiteListDao(); abstract public function getNotificationDao(); abstract public function getCommentDao(); abstract public function getSpotReportDao(); abstract public function getSettingDao(); /* * Factory class which instantiates the specified DAO factory object */ public static function getDAOFactory($which) { switch($which) { case 'postgresql' : return new Dao_Postgresql_Factory(); break; case 'mysql' : return new Dao_Mysql_Factory(); break; case 'sqlite' : return new Dao_Sqlite_actory(); break; default : throw new Exception("Unknown DAO factory specified"); } // switch } # getDayFactory() } // Dao_Factory
<?php abstract class Dao_Factory { abstract public function setConnection($conn); abstract public function getConnection(); abstract public function getSpotDao(); abstract public function getSpotSearchDao(); abstract public function getUserDao(); abstract public function getCacheDao(); abstract public function getAuditDao(); abstract public function getUserFilterDao(); abstract public function getSessionDao(); abstract public function getBlackWhiteListDao(); abstract public function getNotificationDao(); abstract public function getCommentDao(); abstract public function getSpotReportDao(); abstract public function getSettingDao(); /* * Factory class which instantiates the specified DAO factory object */ public static function getDAOFactory($which) { switch($which) { case 'postgresql' : return new PostgresqlDaoFactory(); break; case 'mysql' : return new MysqlDaoFactory(); break; case 'sqlite' : return new SqliteDaoFactory(); break; default : throw new Exception("Unknown DAO factory specified"); } // switch } # getDayFactory() } // Dao_Factory
Improve error catching logic for update
import os import subprocess import sys try: from flask import Flask import flask_login from flask_restless import APIManager from flask_sqlalchemy import SQLAlchemy import requests except ImportError: INTERP = "venv/bin/python" if os.path.relpath(sys.executable, os.getcwd()) != INTERP: try: os.execl(INTERP, INTERP, *sys.argv) except OSError: sys.exit("Could not find virtual environment. Run `:~$ ./setup.sh`") else: sys.exit("Could not find requirements. Are they all included in requirements.txt? Run `:~$ ./setup.sh`") application = Flask(__name__) @application.route("/") def index(): return "Hello, world!" @application.route("/update") def update(): subprocess.call(['git', 'fetch', 'origin']) subprocess.call(['git', 'pull']) try: subprocess.check_call(['mkdir', 'tmp']) except subprocess.CalledProcessError, e: pass subprocess.call(['touch', 'tmp/restart.txt']) return "Please restart." @application.route("/big_update") def bigUpdate(): subprocess.call(['./setup.sh']) if __name__ == "__main__": application.run()
import os import subprocess import sys try: from flask import Flask import flask_login from flask_restless import APIManager from flask_sqlalchemy import SQLAlchemy import requests except ImportError: INTERP = "venv/bin/python" if os.path.relpath(sys.executable, os.getcwd()) != INTERP: try: os.execl(INTERP, INTERP, *sys.argv) except OSError: sys.exit("Could not find virtual environment. Run `:~$ ./setup.sh`") else: sys.exit("Could not find requirements. Are they all included in requirements.txt? Run `:~$ ./setup.sh`") application = Flask(__name__) @application.route("/") def index(): return "Hello, world!" @application.route("/update") def update(): subprocess.call(['git', 'fetch', 'origin']) subprocess.call(['git', 'pull']) subprocess.call(['mkdir', 'tmp']) subprocess.call(['touch', 'tmp/restart.txt']) @application.route("/big_update") def bigUpdate(): subprocess.call(['./setup.sh']) if __name__ == "__main__": application.run()
Remove API since we aren't using it
/** * Angular.js application configuration * * @author eugene.trounev(a)gmail.com */ angular.module('app', [ 'ngRoute', 'com.likalo.ui' ]) .constant('APP_META', { title: 'pal-pal', description: 'A simple palette management tool.', icon: 'palette' }) .config([ '$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){ /* * Setting up router */ $routeProvider .when('/:sequence?', { templateUrl: 'templates/page.home.html', controller: 'HomeCtrl' }) .otherwise({ redirectTo: '/' }); /* * Disable HTML5 aws it conflicts with SVG specs */ $locationProvider .html5Mode(false); }]);
/** * Angular.js application configuration * * @author eugene.trounev(a)gmail.com */ angular.module('app', [ 'ngRoute', 'com.likalo.ui' ]) .constant('APP_META', { title: 'pal-pal', description: 'A simple palette management tool.', icon: 'palette' }) .constant('APP_API', { user: '/api/users' }) .config([ '$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){ /* * Setting up router */ $routeProvider .when('/:sequence?', { templateUrl: 'templates/page.home.html', controller: 'HomeCtrl' }) .otherwise({ redirectTo: '/' }); $locationProvider .html5Mode(false); }]);
Fix code comment on PhaseSecurity
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cloudup import "k8s.io/apimachinery/pkg/util/sets" // Phase is a portion of work that kops completes. type Phase string const ( // PhaseStageAssets uploads various assets such as containers in a private registry PhaseStageAssets Phase = "assets" // PhaseNetwork creates network infrastructure. PhaseNetwork Phase = "network" // PhaseSecurity creates IAM profiles and roles, security groups and firewalls PhaseSecurity Phase = "security" // PhaseCluster creates the servers, and load-alancers PhaseCluster Phase = "cluster" ) // Phases are used for validation and cli help. var Phases = sets.NewString( string(PhaseStageAssets), string(PhaseSecurity), string(PhaseNetwork), string(PhaseCluster), )
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cloudup import "k8s.io/apimachinery/pkg/util/sets" // Phase is a portion of work that kops completes. type Phase string const ( // PhaseStageAssets uploads various assets such as containers in a private registry PhaseStageAssets Phase = "assets" // PhaseNetwork creates network infrastructure. PhaseNetwork Phase = "network" // PhaseIAM creates IAM profiles and roles, security groups and firewalls PhaseSecurity Phase = "security" // PhaseCluster creates the servers, and load-alancers PhaseCluster Phase = "cluster" ) // Phases are used for validation and cli help. var Phases = sets.NewString( string(PhaseStageAssets), string(PhaseSecurity), string(PhaseNetwork), string(PhaseCluster), )
Allow admin preview in minutes as well
from django.forms import ModelForm, Textarea, ChoiceField from django.urls import reverse_lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input', 'data-endpoint': reverse_lazy('utilities:preview_safe') } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelForm): folder = ChoiceField(choices=sorted_folders) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Meeting fields = ['name', 'folder', 'title', 'body', 'date'] widgets = { 'body': Textarea(attrs=MD_INPUT), } def clean_folder(self): return Folder.objects.get(pk=self.cleaned_data['folder'])
from django.forms import ModelForm, Textarea, ChoiceField from django.utils.functional import lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input' } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelForm): folder = ChoiceField(choices=sorted_folders) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Meeting fields = ['name', 'folder', 'title', 'body', 'date'] widgets = { 'body': Textarea(attrs=MD_INPUT), } def clean_folder(self): return Folder.objects.get(pk=self.cleaned_data['folder'])