text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add a boolean field to Store model (store.has_coffee)
# coding: utf-8 from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField('self', blank=True) def __unicode__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=255) num_awards = models.IntegerField() def __unicode__(self): return self.name class Book(models.Model): isbn = models.CharField(max_length=9) name = models.CharField(max_length=255) pages = models.IntegerField() rating = models.FloatField() price = models.DecimalField(decimal_places=2, max_digits=6) authors = models.ManyToManyField(Author) contact = models.ForeignKey(Author, related_name='book_contact_set') publisher = models.ForeignKey(Publisher) pubdate = models.DateField() def __unicode__(self): return self.name class Store(models.Model): name = models.CharField(max_length=255) books = models.ManyToManyField(Book) original_opening = models.DateTimeField() friday_night_closing = models.TimeField() has_coffee = models.BooleanField() def __unicode__(self): return self.name
# coding: utf-8 from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField('self', blank=True) def __unicode__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=255) num_awards = models.IntegerField() def __unicode__(self): return self.name class Book(models.Model): isbn = models.CharField(max_length=9) name = models.CharField(max_length=255) pages = models.IntegerField() rating = models.FloatField() price = models.DecimalField(decimal_places=2, max_digits=6) authors = models.ManyToManyField(Author) contact = models.ForeignKey(Author, related_name='book_contact_set') publisher = models.ForeignKey(Publisher) pubdate = models.DateField() def __unicode__(self): return self.name class Store(models.Model): name = models.CharField(max_length=255) books = models.ManyToManyField(Book) original_opening = models.DateTimeField() friday_night_closing = models.TimeField() def __unicode__(self): return self.name
Add paranthesis to function call
var GameController = require("./GameController"); exports.fire = function (req, res) { var player = req.body.username; var x = req.body.x; var y = req.body.y; GameController.findGame(player).then(function(game) { if (game != null) { // If game is over, the other player won. // The game's finished field is then set to true, so that findGame will not return it anymore.. if (game.gameOver()) { res.json({'message': "You lost"}); game.finished = true; game.save(); return; } // Fire at the enemy board. If game over after hit, you won. var shipWasHit = game.fire(player, x, y); var msg = game.gameOver ? "You won" : "Ongoing game"; res.json({'message': msg, 'shipWasHit': shipWasHit}); } else { res.json({'message': 'No game was found'}); } }); };
var GameController = require("./GameController"); exports.fire = function (req, res) { var player = req.body.username; var x = req.body.x; var y = req.body.y; GameController.findGame(player).then(function(game) { if (game != null) { // If game is over, the other player won. // The game's finished field is then set to true, so that findGame will not return it anymore.. if (game.gameOver) { res.json({'message': "You lost"}); game.finished = true; game.save(); return; } // Fire at the enemy board. If game over after hit, you won. var shipWasHit = game.fire(player, x, y); var msg = game.gameOver ? "You won" : "Ongoing game"; res.json({'message': msg, 'shipWasHit': shipWasHit}); } else { res.json({'message': 'No game was found'}); } }); };
Move fully qualified class name to a use statement
<?php namespace Joindin\Model\Db; use \Joindin\Service\Db as DbService; class User { protected $keyName = 'users'; protected $db; public function __construct() { $this->db = new DbService(); } public function getUriFor($username) { $data = $this->db->getOneByKey($this->keyName, 'username', $username); return $data['uri']; } public function load($uri) { $data = $this->db->getOneByKey($this->keyName, 'uri', $uri); return $data; } public function saveSlugToDatabase($user) { $data = array( 'uri' => $user->getUri(), 'username' => $user->getUsername(), 'slug' => $user->getUsername(), 'verbose_uri' => $user->getVerboseUri() ); $mongoUser = $this->load($user->getUri()); if ($mongoUser) { // user is already known - update this record $data = array_merge($mongoUser, $data); } return $this->db->save($this->keyName, $data); } }
<?php namespace Joindin\Model\Db; class User { protected $keyName = 'users'; protected $db; public function __construct() { $this->db = new \Joindin\Service\Db; } public function getUriFor($username) { $data = $this->db->getOneByKey($this->keyName, 'username', $username); return $data['uri']; } public function load($uri) { $data = $this->db->getOneByKey($this->keyName, 'uri', $uri); return $data; } public function saveSlugToDatabase($user) { $data = array( 'uri' => $user->getUri(), 'username' => $user->getUsername(), 'slug' => $user->getUsername(), 'verbose_uri' => $user->getVerboseUri() ); $mongoUser = $this->load($user->getUri()); if ($mongoUser) { // user is already known - update this record $data = array_merge($mongoUser, $data); } return $this->db->save($this->keyName, $data); } }
Include attempts when printing answer
// Package pu makes solving projecteuler problems easier and reduces boilerplate. package pu import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // Problem is a Project Euler (.net) problem type Problem struct { // ID is the id of the problem on projecteuler.net ID int // Solver is the function which solves the problem. Solver func() string // CorrectAnswer is the answer to the problem (used for testing purposes) CorrectAnswer string // Attempts is the count of submissions to projecteuler.net it took to submit the correct answer. Attempts int } // Bench benchmarks the problem. Great for testing for improvements. func (p Problem) Bench(b *testing.B) { for i := 0; i < b.N; i++ { p.Solver() } } // Answer prints out the answer for viewing. func (p Problem) Answer() { if p.CorrectAnswer == "NA" { fmt.Println("Problem", p.ID, "has not been solved yet.") } else { fmt.Println("Answer to problem", p.ID, "is", p.Solver(), "(took", p.Attempts, "attempts)") } } // Test ensures the answer is correct. Will fail until problem is solved. func (p Problem) Test(t *testing.T) { assert.Equal(t, p.CorrectAnswer, p.Solver(), "These should be equal. Either it hasn't been solved or something broke.") }
// Package pu makes solving projecteuler problems easier and reduces boilerplate. package pu import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // Problem is a Project Euler (.net) problem type Problem struct { // ID is the id of the problem on projecteuler.net ID int // Solver is the function which solves the problem. Solver func() string // CorrectAnswer is the answer to the problem (used for testing purposes) CorrectAnswer string // Attempts is the count of submissions to projecteuler.net it took to submit the correct answer. Attempts int } // Bench benchmarks the problem. Great for testing for improvements. func (p Problem) Bench(b *testing.B) { for i := 0; i < b.N; i++ { p.Solver() } } // Answer prints out the answer for viewing. func (p Problem) Answer() { if p.CorrectAnswer == "NA" { fmt.Println("Problem", p.ID, "has not been solved yet.") } else { fmt.Println("Answer to problem", p.ID, "is", p.Solver()) } } // Test ensures the answer is correct. Will fail until problem is solved. func (p Problem) Test(t *testing.T) { assert.Equal(t, p.CorrectAnswer, p.Solver(), "These should be equal. Either it hasn't been solved or something broke.") }
Use new menu contsants in home menu item Summary: Ref T11957, just lays in some minor bug fixes. Sets correct menu, removes sidebar on edit. Test Plan: Test /menu/ on home with Admin and Normal accounts. Reviewers: epriestley Reviewed By: epriestley Subscribers: Korvin Maniphest Tasks: T11957 Differential Revision: https://secure.phabricator.com/D17247
<?php final class PhabricatorHomeMenuItemController extends PhabricatorHomeController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $type = $request->getURIData('type'); $custom_phid = null; $menu = PhabricatorProfileMenuEngine::MENU_GLOBAL; if ($type == 'personal') { $custom_phid = $viewer->getPHID(); $menu = PhabricatorProfileMenuEngine::MENU_PERSONAL; } $application = 'PhabricatorHomeApplication'; $home_app = id(new PhabricatorApplicationQuery()) ->setViewer($viewer) ->withClasses(array($application)) ->withInstalled(true) ->executeOne(); $engine = id(new PhabricatorHomeProfileMenuEngine()) ->setProfileObject($home_app) ->setCustomPHID($custom_phid) ->setMenuType($menu) ->setController($this) ->setShowNavigation(false); return $engine->buildResponse(); } }
<?php final class PhabricatorHomeMenuItemController extends PhabricatorHomeController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $type = $request->getURIData('type'); $custom_phid = null; if ($type == 'personal') { $custom_phid = $viewer->getPHID(); } $application = 'PhabricatorHomeApplication'; $home_app = id(new PhabricatorApplicationQuery()) ->setViewer($viewer) ->withClasses(array($application)) ->withInstalled(true) ->executeOne(); $engine = id(new PhabricatorHomeProfileMenuEngine()) ->setProfileObject($home_app) ->setCustomPHID($custom_phid) ->setController($this); return $engine->buildResponse(); } }
Fix ReadAll to run on Windows. filepath.Clean converts filenames to filenames with native path separators. Use ToSlash to normalize. Signed-off-by: Anusha Ragunathan <11258be80bf4b196e47582a3113274a53ec55793@docker.com>
package dockerignore import ( "bufio" "fmt" "io" "path/filepath" "strings" ) // ReadAll reads a .dockerignore file and returns the list of file patterns // to ignore. Note this will trim whitespace from each line as well // as use GO's "clean" func to get the shortest/cleanest path for each. func ReadAll(reader io.ReadCloser) ([]string, error) { if reader == nil { return nil, nil } defer reader.Close() scanner := bufio.NewScanner(reader) var excludes []string for scanner.Scan() { pattern := strings.TrimSpace(scanner.Text()) if pattern == "" { continue } pattern = filepath.Clean(pattern) pattern = filepath.ToSlash(pattern) excludes = append(excludes, pattern) } if err := scanner.Err(); err != nil { return nil, fmt.Errorf("Error reading .dockerignore: %v", err) } return excludes, nil }
package dockerignore import ( "bufio" "fmt" "io" "path/filepath" "strings" ) // ReadAll reads a .dockerignore file and returns the list of file patterns // to ignore. Note this will trim whitespace from each line as well // as use GO's "clean" func to get the shortest/cleanest path for each. func ReadAll(reader io.ReadCloser) ([]string, error) { if reader == nil { return nil, nil } defer reader.Close() scanner := bufio.NewScanner(reader) var excludes []string for scanner.Scan() { pattern := strings.TrimSpace(scanner.Text()) if pattern == "" { continue } pattern = filepath.Clean(pattern) excludes = append(excludes, pattern) } if err := scanner.Err(); err != nil { return nil, fmt.Errorf("Error reading .dockerignore: %v", err) } return excludes, nil }
Add getter/setter so we can actually use this...
/* * Copyright (C) 2016 Prowave Consulting, LLC * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.prowave.chargify.webhook.bean; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class SubscriptionProductChange extends Payload { @JsonProperty("previous_product") private Product previousProduct; public Product getPreviousProduct() { return previousProduct; } public void setPreviousProduct(Product previousProduct) { this.previousProduct = previousProduct; } }
/* * Copyright (C) 2016 Prowave Consulting, LLC * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.prowave.chargify.webhook.bean; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class SubscriptionProductChange extends Payload { @JsonProperty("previous_product") private Product previousProduct; }
Update warnings to return on null or undefined.
/** * Internal dependencies */ import Data from 'googlesitekit-data'; import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants'; import classnames from 'classnames'; import ErrorIcon from '../../../svg/error.svg'; const { useSelect } = Data; /* * A single module. Keeps track of its own active state and settings. */ export default function ModuleSettingsWarning( { slug, // context, } ) { // @TODO: Resolver only runs once per set of args, so we are working around // this to rerun after modules are loaded. // Once #1769 is resolved, we can remove the call to getModules, // and remove the !! modules cache busting param. const modules = useSelect( ( select ) => select( CORE_MODULES )?.getModules() ); const requirementsStatus = useSelect( ( select ) => select( CORE_MODULES )?.getCheckRequirementsStatus( slug, !! modules ) ); if ( [ null, undefined ].includes( requirementsStatus ) ) { return null; } return ( <div className={ classnames( 'googlesitekit-settings-module-warning', 'googlesitekit-settings-module-warning--modules-list' ) } > <ErrorIcon height="20" width="23" /> { requirementsStatus } </div> ); }
/** * Internal dependencies */ import Data from 'googlesitekit-data'; import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants'; import classnames from 'classnames'; import ErrorIcon from '../../../svg/error.svg'; const { useSelect } = Data; /* * A single module. Keeps track of its own active state and settings. */ export default function ModuleSettingsWarning( { slug, // context, } ) { // @TODO: Resolver only runs once per set of args, so we are working around // this to rerun after modules are loaded. // Once #1769 is resolved, we can remove the call to getModules, // and remove the !! modules cache busting param. const modules = useSelect( ( select ) => select( CORE_MODULES )?.getModules() ); const requirementsStatus = useSelect( ( select ) => select( CORE_MODULES )?.getCheckRequirementsStatus( slug, !! modules ) ); if ( requirementsStatus === null ) { return null; } return ( <div className={ classnames( 'googlesitekit-settings-module-warning', 'googlesitekit-settings-module-warning--modules-list' ) } > <ErrorIcon height="20" width="23" /> { requirementsStatus } </div> ); }
Adjust maximum block size for lzo
import sys import os p1, p2 = sys.version_info[:2] curpath = os.path.abspath( sys.argv[0] ) if os.path.islink(curpath): curpath = os.readlink(curpath) currentdir = os.path.dirname( curpath ) build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lzo", "build") ) if not os.path.isdir(build_dir): build_dir = os.path.abspath( os.path.join(currentdir, "..", "lib-dynload", "lzo", "build") ) if not os.path.isdir(build_dir): build_dir = os.path.abspath( os.path.join(currentdir, "..", "..", "lib-dynload", "lzo", "build") ) dirs = os.listdir(build_dir) for d in dirs: if d.find("-%s.%s" % (p1, p2)) != -1 and d.find("lib.") != -1: sys.path.insert(0, os.path.join(build_dir, d) ) import importlib module = importlib.import_module("_lzo") module.set_block_size(16*1024*1024) compress = module.compress decompress = module.decompress sys.path.pop(0) break
import sys import os p1, p2 = sys.version_info[:2] curpath = os.path.abspath( sys.argv[0] ) if os.path.islink(curpath): curpath = os.readlink(curpath) currentdir = os.path.dirname( curpath ) build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lzo", "build") ) if not os.path.isdir(build_dir): build_dir = os.path.abspath( os.path.join(currentdir, "..", "lib-dynload", "lzo", "build") ) if not os.path.isdir(build_dir): build_dir = os.path.abspath( os.path.join(currentdir, "..", "..", "lib-dynload", "lzo", "build") ) dirs = os.listdir(build_dir) for d in dirs: if d.find("-%s.%s" % (p1, p2)) != -1 and d.find("lib.") != -1: sys.path.insert(0, os.path.join(build_dir, d) ) import importlib module = importlib.import_module("_lzo") compress = module.compress decompress = module.decompress sys.path.pop(0) break
Fix typo win -> won
const h = require('virtual-dom/h'); module.exports = function (data) { const {gameID, game} = data; return h('div', {className: 'room'}, [ game.playing ? null : h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'), game.playing ? null : h('form', {id: 'setup', method: 'post', action: `/${gameID}`}, [ h('input', {type: 'number', name: 'max-score', min: '1', value: game.maxScore}), h('button', {type: 'submit'}, 'Start') ]), h('div', {id: 'players'}, [ h('ul', Object.keys(game.players).map(playerID => { const player = game.players[playerID]; return h('li', { style: { backgroundColor: `rgb(${player.color[1]}, ${player.color[0]}, ${player.color[2]})` }, className: game.ended ? game.winner === playerID ? 'won' : 'lost' : '' }, [ h('h3', player.name), h('img', {src: player.type === 'nodemcu' ? '/nodemcu.png' : '/phone.png'}), h('span', String(player.score)) ]) })) ]) ]); };
const h = require('virtual-dom/h'); module.exports = function (data) { const {gameID, game} = data; return h('div', {className: 'room'}, [ game.playing ? null : h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'), game.playing ? null : h('form', {id: 'setup', method: 'post', action: `/${gameID}`}, [ h('input', {type: 'number', name: 'max-score', min: '1', value: game.maxScore}), h('button', {type: 'submit'}, 'Start') ]), h('div', {id: 'players'}, [ h('ul', Object.keys(game.players).map(playerID => { const player = game.players[playerID]; return h('li', { style: { backgroundColor: `rgb(${player.color[1]}, ${player.color[0]}, ${player.color[2]})` }, className: game.ended ? game.winner === playerID ? 'win' : 'lost' : '' }, [ h('h3', player.name), h('img', {src: player.type === 'nodemcu' ? '/nodemcu.png' : '/phone.png'}), h('span', String(player.score)) ]) })) ]) ]); };
fix: Fix syntax errors made in previous commit
import classNames from 'classnames'; import React, { PropTypes } from 'react'; const HeaderView = ({ items, githubLink, onLabelClick }) => (<div className="github-embed-nav"> {items.map(({ shown, label }, index) => <a className={classNames({ 'github-embed-nav-link': true, 'github-embed-nav-link-shown': shown })} key={index} onClick={() => onLabelClick(index)} > {label} </a> )} <a className="github-embed-nav-on-github" target="_blank" rel="noopener noreferrer" href={githubLink} > On Github </a> </div>); HeaderView.propTypes = { items: PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.string.isRequired, shown: PropTypes.bool.isRequired })), onLabelClick: PropTypes.func.isRequired, githubLink: PropTypes.string.isRequired }; export default HeaderView;
import classNames from 'classnames'; import React, { PropTypes } from 'react'; const HeaderView = ({ items, githubLink, onLabelClick }) => (<div className="github-embed-nav"> {items.map(({ shown, label }, index) => <a className={classNames({ 'github-embed-nav-link': true, 'github-embed-nav-link-shown': shown })} key={index} onClick={() => onLabelClick(index)} > {label} </a> )} <a className="github-embed-nav-on-github" target="_blank" rel="noopener noreferrer" href={githubLink} > On Github </div> </nav>); HeaderView.propTypes = { items: PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.string.isRequired, shown: PropTypes.bool.isRequired })), onLabelClick: PropTypes.func.isRequired, githubLink: PropTypes.string.isRequired }; export default HeaderView;
Add check if updates to not exist for a certain trigger
'use strict' const getNode = require('./getNode') const err = require('./err') require('setimmediate') module.exports = (db, path) => { let fns = db.updates.fns[path] if (!fns) { return } let len = fns.length for (let i = 0; i < len; i += 1) { setImmediate(() => { let val = getNode(db, path) let cacheTest = JSON.stringify(val) if (db.updates.cache[path][i] !== cacheTest) { db.updates.cache[path][i] = cacheTest ;(function () { try { fns[i].call(null, JSON.parse(cacheTest)) } catch (e) { err(db, '/err/types/on/2', { path: path, error: e }) } }()) } }) } }
'use strict' const getNode = require('./getNode') const err = require('./err') require('setimmediate') module.exports = (db, path) => { let fns = db.updates.fns[path] let len = fns.length for (let i = 0; i < len; i += 1) { setImmediate(() => { let val = getNode(db, path) let cacheTest = JSON.stringify(val) if (db.updates.cache[path][i] !== cacheTest) { db.updates.cache[path][i] = cacheTest ;(function () { try { fns[i].call(null, JSON.parse(cacheTest)) } catch (e) { err(db, '/err/types/on/2', { path: path, error: e }) } }()) } }) } }
Hide Nunjucks warnings from the dev console
'use strict'; const path = require('path'); const fractal = module.exports = require('@frctl/fractal').create(); const pkg = require(path.join(__dirname, 'package.json')); fractal.set('project.title', 'Kanbasu'); fractal.set('project.version', pkg.version); fractal.components.set('path', path.join(__dirname, 'components')); fractal.components.set('ext', '.html'); fractal.components.set('label', 'Patterns'); fractal.docs.set('path', path.join(__dirname, 'docs')); fractal.web.set('static.path', path.join(__dirname, 'public')); fractal.web.set('server.sync', true); fractal.web.set('builder.dest', path.join(__dirname, 'dist')); fractal.components.set('statuses', { prototype: { label: "Prototype", description: "Do not implement.", color: "#F67280" }, wip: { label: "WIP", description: "Work in progress. Implement with caution.", color: "#FFB270" }, ready: { label: "Ready", description: "Ready to implement.", color: "#2AAF74" } }) const kanbasuTheme = require('mandelbrot-kanbasu'); fractal.web.theme(kanbasuTheme); /** * Prevent Bluebird warnings like "a promise was created in a handler but was not returned from it" * caused by Nunjucks from polluting the console */ const bluebird = require('bluebird'); bluebird.config({ warnings: false });
'use strict'; const path = require('path'); const fractal = module.exports = require('@frctl/fractal').create(); const pkg = require(path.join(__dirname, 'package.json')); fractal.set('project.title', 'Kanbasu'); fractal.set('project.version', pkg.version); fractal.components.set('path', path.join(__dirname, 'components')); fractal.components.set('ext', '.html'); fractal.components.set('label', 'Patterns'); fractal.docs.set('path', path.join(__dirname, 'docs')); fractal.web.set('static.path', path.join(__dirname, 'public')); fractal.web.set('server.sync', true); fractal.web.set('builder.dest', path.join(__dirname, 'dist')); fractal.components.set('statuses', { prototype: { label: "Prototype", description: "Do not implement.", color: "#F67280" }, wip: { label: "WIP", description: "Work in progress. Implement with caution.", color: "#FFB270" }, ready: { label: "Ready", description: "Ready to implement.", color: "#2AAF74" } }) const kanbasuTheme = require('mandelbrot-kanbasu'); fractal.web.theme(kanbasuTheme);
SyntaxError: Use of const in strict mode.
/* jshint node: true */ 'use strict'; var BasePlugin = require('ember-cli-deploy-plugin'); module.exports = { name: 'ember-cli-deploy-firebase', createDeployPlugin: function(options) { var DeployPlugin = BasePlugin.extend({ name: options.name, upload: function(context) { let outer = this; let options = { firebase: context.config.fireBaseAppName, public: context.config.build.outputPath, }; if(context.revisionData){ options.message = context.revisionData.revisionKey; } return require('firebase-tools').deploy.hosting(options).then(function() { outer.log('it worked yay'); }).catch(function(err) { // handle error outer.log('something bad happened oh no', { color: 'red' }); outer.log(err, { color: 'red' }); }); }, }); return new DeployPlugin(); } };
/* jshint node: true */ 'use strict'; var BasePlugin = require('ember-cli-deploy-plugin'); module.exports = { name: 'ember-cli-deploy-firebase', createDeployPlugin: function(options) { var DeployPlugin = BasePlugin.extend({ name: options.name, upload: function(context) { const outer = this; const options = { firebase: context.config.fireBaseAppName, public: context.config.build.outputPath, }; if(context.revisionData){ options.message = context.revisionData.revisionKey; } return require('firebase-tools').deploy.hosting(options).then(function() { outer.log('it worked yay'); }).catch(function(err) { // handle error outer.log('something bad happened oh no', { color: 'red' }); outer.log(err, { color: 'red' }); }); }, }); return new DeployPlugin(); } };
Add iter task to Grunt
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ sass: { dist: { files: { 'css/main.css': 'sass/main.sass' } } }, cssmin: { target: { files: [{ expand: true, src: ['css/*.css'], dest: 'dist', }] } }, uglify: { build: { src: ['js/*.js'], dest: 'dist/js/main.js' } }, watch: { sass: { files: ['sass/**/*.sass', 'sass/**/*.scss'], tasks: ['sass'] } } }); grunt.registerTask('build', ['sass']); grunt.registerTask('iter', ['sass', 'watch']); grunt.registerTask('default', ['sass', 'cssmin', 'uglify', 'watch']); };
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ sass: { dist: { files: { 'css/main.css': 'sass/main.sass' } } }, cssmin: { target: { files: [{ expand: true, src: ['css/*.css'], dest: 'dist', }] } }, uglify: { build: { src: ['js/*.js'], dest: 'dist/js/main.js' } }, watch: { sass: { files: ['sass/**/*.sass', 'sass/**/*.scss'], tasks: ['sass'] } } }); grunt.registerTask('build', ['sass']); grunt.registerTask('default', ['sass', 'cssmin', 'uglify', 'watch']); };
Switch the CloudI Job API to use the binary output misultin job, instead of the list output one... both work.
# -*- coding: utf-8; Mode: python; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # ex: set softtabstop=4 tabstop=4 shiftwidth=4 expandtab fileencoding=utf-8: import sys, os sys.path.append( os.path.sep.join( os.path.dirname(os.path.abspath(__file__)) .split(os.path.sep) + ['jsonrpclib'] ) ) import jsonrpclib class CloudI(object): # initialize with configuration file defaults def __init__(self, host = 'localhost', port = 6464): address = 'http://%s:%d/cloudi/api/json_rpc/' % (host, port) self.__server = jsonrpclib.Server(address) def __getattr__(self, name): if name == 'jobs': return self.__jobs return self.__server.__getattr__(name) def __jobs(self): raw = self.__server.jobs() def split_tuple(s): entry = s.split('>>,\n ') return ('<<' + entry[0] + '>>', entry[1]) return map(split_tuple, raw[1:-1].split(',\n {<<'))
# -*- coding: utf-8; Mode: python; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # ex: set softtabstop=4 tabstop=4 shiftwidth=4 expandtab fileencoding=utf-8: import sys, os sys.path.append( os.path.sep.join( os.path.dirname(os.path.abspath(__file__)) .split(os.path.sep) + ['jsonrpclib'] ) ) import jsonrpclib class CloudI(object): # initialize with configuration file defaults def __init__(self, host = 'localhost', port = 6465): address = 'http://%s:%d/cloudi/api/json_rpc/' % (host, port) self.__server = jsonrpclib.Server(address) def __getattr__(self, name): if name == 'jobs': return self.__jobs return self.__server.__getattr__(name) def __jobs(self): raw = self.__server.jobs() def split_tuple(s): entry = s.split('>>,\n ') return ('<<' + entry[0] + '>>', entry[1]) return map(split_tuple, raw[1:-1].split(',\n {<<'))
Add test data and Fix assertion
package container import ( "fmt" "github.com/stretchr/testify/assert" "os" "reflect" "testing" ) type testtype struct { Foo string Bar string } type testdata struct { emp interface{} val interface{} } var testdataSet = []testdata{ {new(string), "value"}, {new(int), 1234}, {new(float64), 12.34}, {new(testtype), testtype{"hoge", "fuga"}}, {new(testtype), &testtype{"hoge", "fuga"}}, } func TestMain(m *testing.M) { for _, testdata := range testdataSet { Set(testdata.val) } os.Exit(m.Run()) } func TestContainer(t *testing.T) { type hoge string testdataSet = append(testdataSet, testdata{new(hoge), nil}) for _, testdata := range testdataSet { t.Run(fmt.Sprintf("type=%s", reflect.TypeOf(testdata.emp).Name()), func(t *testing.T) { a := testdata.emp Get(a) if testdata.val != nil { actual := reflect.Indirect(reflect.ValueOf(a)).Interface() expect := reflect.Indirect(reflect.ValueOf(testdata.val)).Interface() assert.EqualValues(t, expect, actual) } else { assert.EqualValues(t, testdata.emp, a) } }) } }
package container import ( "fmt" "github.com/stretchr/testify/assert" "os" "reflect" "testing" ) type testtype struct { Foo string Bar string } type testdata struct { emp interface{} val interface{} } var testdataSet = []testdata{ {new(string), "value"}, {new(int), 1234}, {new(float64), 12.34}, {new(testtype), testtype{"hoge", "fuga"}}, } func TestMain(m *testing.M) { for _, testdata := range testdataSet { Set(testdata.val) } os.Exit(m.Run()) } func TestContainer(t *testing.T) { for _, testdata := range testdataSet { t.Run(fmt.Sprintf("type=%s", reflect.TypeOf(testdata.emp).Name()), func(t *testing.T) { a := testdata.emp Get(a) actual := reflect.Indirect(reflect.ValueOf(a)).Interface() expect := reflect.Indirect(reflect.ValueOf(testdata.val)).Interface() assert.EqualValues(t, expect, actual) }) } }
Refactor to use export * from ...
import uuid from 'uuid' export * from './picture.js' export const reset = () => ({ type: 'RESET' }) export const addColour = (colour) => ({ type: 'ADD_COLOUR', id: uuid.v1(), colour, }) export const setPreviewColour = (colour) => ({ type: 'SET_PREVIEW_COLOUR', colour, }) export const setHexColour = (hex) => ({ type: 'SET_HEX_COLOUR', hex, }) export const setRgbColour = (rgb) => ({ type: 'SET_RGB_COLOUR', rgb, }) export const setHslColour = (hsl) => ({ type: 'SET_HSL_COLOUR', hsl, }) export const movePicture = (position) => ({ type: 'MOVE_PICTURE', position, }) export const showDropzoneOverlay = () => ({ type: 'SHOW_DROPZONE_OVERLAY', }) export const hideDropzoneOverlay = () => ({ type: 'HIDE_DROPZONE_OVERLAY', })
import uuid from 'uuid' import { loadPictureRequest, loadPictureSuccess, fetchPictureFromPath, fetchPictureFromUrl, fetchPictureIfNeeded } from './pictures.js' export { loadPictureRequest, loadPictureSuccess, fetchPictureFromPath, fetchPictureFromUrl, fetchPictureIfNeeded } export const reset = () => ({ type: 'RESET' }) export const addColour = (colour) => ({ type: 'ADD_COLOUR', id: uuid.v1(), colour, }) export const setPreviewColour = (colour) => ({ type: 'SET_PREVIEW_COLOUR', colour, }) export const setHexColour = (hex) => ({ type: 'SET_HEX_COLOUR', hex, }) export const setRgbColour = (rgb) => ({ type: 'SET_RGB_COLOUR', rgb, }) export const setHslColour = (hsl) => ({ type: 'SET_HSL_COLOUR', hsl, }) export const movePicture = (position) => ({ type: 'MOVE_PICTURE', position, }) export const showDropzoneOverlay = () => ({ type: 'SHOW_DROPZONE_OVERLAY', }) export const hideDropzoneOverlay = () => ({ type: 'HIDE_DROPZONE_OVERLAY', })
Test - fix output dir name
# Copyright 2015 0xc0170 # # 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 os from unittest import TestCase from project_generator.workspace import Workspace class TestWorkspace(TestCase): """test things related to the Workspace class""" def setUp(self): self.workspace = Workspace('test_projects/test_workspace/projects.yaml') def test_settings(self): # only check things which are affected by projects.yaml assert self.workspace.settings.paths['definitions'] == '~/.notpg' assert self.workspace.settings.generated_projects_dir == 'not_generated_projects' # def test_load_definitions(self): # self.workspace.load_definitions() # assert os.path.exists(os.path.expanduser(self.workspace.settings.paths['definitions'])) def test_list_projects(self): assert self.workspace.list_projects('raw') == set()
# Copyright 2015 0xc0170 # # 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 os from unittest import TestCase from project_generator.workspace import Workspace class TestWorkspace(TestCase): """test things related to the Workspace class""" def setUp(self): self.workspace = Workspace('test_projects/test_workspace/projects.yaml') def test_settings(self): # only check things which are affected by projects.yaml assert self.workspace.settings.paths['definitions'] == '~/.notpg' assert self.workspace.settings.generated_projects_folder == 'not_generated_projects' # def test_load_definitions(self): # self.workspace.load_definitions() # assert os.path.exists(os.path.expanduser(self.workspace.settings.paths['definitions'])) def test_list_projects(self): assert self.workspace.list_projects('raw') == set()
Use content or README.md as long_description
#!/usr/bin/env python from setuptools import setup # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='screenplain', version='0.9.0', description='Convert text file to viewable screenplay.', long_description=long_description, long_description_content_type='text/markdown', author='Martin Vilcans', author_email='screenplain@librador.com', url='http://www.screenplain.com/', project_urls={ 'Web Page': 'http://www.screenplain.com/', 'Source': 'https://github.com/vilcans/screenplain', }, license='MIT', install_requires=[ ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], )
#!/usr/bin/env python from setuptools import setup setup( name='screenplain', version='0.9.0', description='Convert text file to viewable screenplay.', author='Martin Vilcans', author_email='screenplain@librador.com', url='http://www.screenplain.com/', project_urls={ 'Web Page': 'http://www.screenplain.com/', 'Source': 'https://github.com/vilcans/screenplain', }, license='MIT', install_requires=[ ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], )
Remove configurable Base Path for js callout proxy
/** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const apickli = require("apickli"); const { Before: before } = require("cucumber"); before(function () { this.apickli = new apickli.Apickli( "https", process.env.APIGEE_ORG + "-" + process.env.APIGEE_ENV + ".apigee.net/js-callout/v1" ); this.apickli.addRequestHeader("Cache-Control", "no-cache"); });
/** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const apickli = require("apickli"); const { Before: before } = require("cucumber"); before(function () { this.apickli = new apickli.Apickli( "https", process.env.APIGEE_ORG + "-" + process.env.APIGEE_ENV + ".apigee.net" + process.env.PROXY_BASE_PATH || '/js-callout/v1' ); this.apickli.addRequestHeader("Cache-Control", "no-cache"); });
Fix all items needs key
import React, { PropTypes, Component } from 'react'; import { Link } from 'react-router'; import shouldPureComponentUpdate from '../../../../node_modules/react-pure-render/function'; export default class ToolBar extends Component { static propTypes = { links : PropTypes.array.isRequired, activeLinkIndex: PropTypes.number.isRequired }; shouldComponentUpdate = shouldPureComponentUpdate; render() { let activeLinkIndex = this.props.activeLinkIndex; return ( <div className="toolbar"> <div className="toolbar-inner"> {this.props.links.map((link, index) => { return <Link key={index} to={link.url}>{activeLinkIndex === index ? <strong>{link.text}</strong> : link.text}</Link> })} </div> </div> ); } }
import React, { PropTypes, Component } from 'react'; import { Link } from 'react-router'; import shouldPureComponentUpdate from '../../../../node_modules/react-pure-render/function'; export default class ToolBar extends Component { static propTypes = { links: PropTypes.array.isRequired, activeLinkIndex: PropTypes.number.isRequired }; shouldComponentUpdate = shouldPureComponentUpdate; render() { let activeLinkIndex = this.props.activeLinkIndex; return ( <div className="toolbar"> <div className="toolbar-inner"> {this.props.links.map((link, index) => { return <Link to={link.url}>{activeLinkIndex === index ? <strong>{link.text}</strong> : link.text}</Link> })} </div> </div> ); } }
Exclude Enhance-o Mechano from its own buff targets
from ..utils import * ## # Minions # Hobgoblin class GVG_104: events = [ OWN_MINION_PLAY.on( lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or [] ) ] # Piloted Sky Golem class GVG_105: def deathrattle(self): return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION, cost=4))] # Junkbot class GVG_106: events = [ Death(FRIENDLY + MECH).on(Buff(SELF, "GVG_106e")) ] # Enhance-o Mechano class GVG_107: def action(self): for target in self.controller.field.exclude(self): tag = random.choice((GameTag.WINDFURY, GameTag.TAUNT, GameTag.DIVINE_SHIELD)) yield SetTag(target, {tag: True}) # Recombobulator class GVG_108: def action(self, target): choice = randomCollectible(type=CardType.MINION, cost=target.cost) return [Morph(TARGET, choice)] # Clockwork Giant class GVG_121: def cost(self, value): return value - len(self.controller.opponent.hand)
from ..utils import * ## # Minions # Hobgoblin class GVG_104: events = [ OWN_MINION_PLAY.on( lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or [] ) ] # Piloted Sky Golem class GVG_105: def deathrattle(self): return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION, cost=4))] # Junkbot class GVG_106: events = [ Death(FRIENDLY + MECH).on(Buff(SELF, "GVG_106e")) ] # Enhance-o Mechano class GVG_107: def action(self): for target in self.controller.field: tag = random.choice((GameTag.WINDFURY, GameTag.TAUNT, GameTag.DIVINE_SHIELD)) yield SetTag(target, {tag: True}) # Recombobulator class GVG_108: def action(self, target): choice = randomCollectible(type=CardType.MINION, cost=target.cost) return [Morph(TARGET, choice)] # Clockwork Giant class GVG_121: def cost(self, value): return value - len(self.controller.opponent.hand)
Introduce integration tests using DropWizards ResourceTest. Include ability to return an Invalid Request message when the DLN or EnquiryId are missing.
package uk.gov.dvla.services.enquiry; import uk.gov.dvla.domain.Driver; import uk.gov.dvla.domain.Person; import uk.gov.dvla.services.ManagedService; public interface DriverEnquiry extends ManagedService { public static final String EXTERNAL_DRIVER_URI = "/external/driver/"; public static final String DRIVER_URI = "/driver/"; public static final String CUSTOMER_PORTAL = "customer.portal"; public static final String MIB = "mib"; public static final String DLN_PARAM = "dln"; public static final String ENQUIRY_ID_PARAM = "id"; public static final String FORENAME_PARAM = "fn"; public static final String SURNAME_PARAM = "sn"; public static final String DOB_PARAM = "d"; public static final String GENDER_PARAM = "g"; public static final String POSTCODE_PARAM = "p"; public Driver get(String dln); public Driver get(Person person); public Driver get(String forename, String surname, String dob, String gender, String postCode); }
package uk.gov.dvla.services.enquiry; import uk.gov.dvla.domain.Driver; import uk.gov.dvla.domain.Person; import uk.gov.dvla.services.ManagedService; public interface DriverEnquiry extends ManagedService { public static final String DRIVER_URI = "/driver/"; public static final String CUSTOMER_PORTAL = "customer.portal"; public static final String MIB = "mib"; public static final String DLN_PARAM = "dln"; public static final String ENQUIRY_ID_PARAM = "id"; public static final String FORENAME_PARAM = "fn"; public static final String SURNAME_PARAM = "sn"; public static final String DOB_PARAM = "d"; public static final String GENDER_PARAM = "g"; public static final String POSTCODE_PARAM = "p"; public Driver get(String dln); public Driver get(Person person); public Driver get(String forename, String surname, String dob, String gender, String postCode); }
Fix reviewer suggestions when suggestFrom > 0 RemoteSuggestOracle runs exactly one call to the SuggestAfterTypingNCharsOracle then waits until that completes. If SuggestAfterTypingNCharsOracle doesn't want to send this query, it must finish with no results to allow RemoteSuggestOracle to unblock and consider the next query. Change-Id: I2eb5dfe7a1aaa5c1f65002f918d4a115ab886224
// Copyright (C) 2012 The Android Open Source Project // // 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.google.gerrit.client.ui; import com.google.gerrit.client.Gerrit; import com.google.gwtexpui.safehtml.client.HighlightSuggestOracle; import java.util.Collections; import java.util.List; /** * Suggest oracle that only provides suggestions if the user has typed at least * as many characters as configured by 'suggest.from'. If 'suggest.from' is set * to 0, suggestions will always be provided. */ public abstract class SuggestAfterTypingNCharsOracle extends HighlightSuggestOracle { @Override protected void onRequestSuggestions(Request req, Callback cb) { if (req.getQuery().length() >= Gerrit.getConfig().getSuggestFrom()) { _onRequestSuggestions(req, cb); } else { List<Suggestion> none = Collections.emptyList(); cb.onSuggestionsReady(req, new Response(none)); } } protected abstract void _onRequestSuggestions(Request request, Callback done); }
// Copyright (C) 2012 The Android Open Source Project // // 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.google.gerrit.client.ui; import com.google.gerrit.client.Gerrit; import com.google.gwtexpui.safehtml.client.HighlightSuggestOracle; /** * Suggest oracle that only provides suggestions if the user has typed at least * as many characters as configured by 'suggest.from'. If 'suggest.from' is set * to 0, suggestions will always be provided. */ public abstract class SuggestAfterTypingNCharsOracle extends HighlightSuggestOracle { @Override protected void onRequestSuggestions(final Request request, final Callback done) { final int suggestFrom = Gerrit.getConfig().getSuggestFrom(); if (suggestFrom == 0 || request.getQuery().length() >= suggestFrom) { _onRequestSuggestions(request, done); } } protected abstract void _onRequestSuggestions(Request request, Callback done); }
Use `delete_all` instead of running cypher query
#!/usr/bin/env python # -*- coding: utf-8 -*- """Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Need NEO4J_URI environment variable set') graphdb = gryaml.connect(uri=os.environ['NEO4J_URI']) graphdb.delete_all() return graphdb @pytest.yield_fixture def graphdb_offline(): """Ensure the database is not connected.""" if py2neo_ver < 2: pytest.skip('Offline not supported in py2neo < 2') neo4j_uri_env = os.environ.get('NEO4J_URI', None) if neo4j_uri_env: del os.environ['NEO4J_URI'] old_graphdb = gryaml._py2neo.graphdb gryaml._py2neo.graphdb = None yield gryaml._py2neo.graphdb = old_graphdb if neo4j_uri_env: os.environ['NEO4J_URI'] = neo4j_uri_env
#!/usr/bin/env python # -*- coding: utf-8 -*- """Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Need NEO4J_URI environment variable set') graphdb = gryaml.connect(uri=os.environ['NEO4J_URI']) graphdb.cypher.execute('MATCH (n) DETACH DELETE n') return graphdb @pytest.yield_fixture def graphdb_offline(): """Ensure the database is not connected.""" if py2neo_ver < 2: pytest.skip('Offline not supported in py2neo < 2') neo4j_uri_env = os.environ.get('NEO4J_URI', None) if neo4j_uri_env: del os.environ['NEO4J_URI'] old_graphdb = gryaml._py2neo.graphdb gryaml._py2neo.graphdb = None yield gryaml._py2neo.graphdb = old_graphdb if neo4j_uri_env: os.environ['NEO4J_URI'] = neo4j_uri_env
Handle \ on Windows, normalize to /
var es = require('event-stream'); var path = require('path'); var gutil = require('gulp-util'); var concat = require('gulp-concat'); var header = require('gulp-header'); var footer = require('gulp-footer'); var PluginError = gutil.PluginError; var htmlJsStr = require('js-string-escape'); function templateCache(root) { return es.map(function(file, cb) { var template = '$templateCache.put("<%= url %>","<%= contents %>");'; var url = path.join(root, file.path.replace(file.base, '')); if (process.platform === 'win32') { url = url.replace(/\\/g, '/'); } file.contents = new Buffer(gutil.template(template, { url: url, contents: htmlJsStr(file.contents), file: file })); cb(null, file); }); } module.exports = function(filename, options) { if (!filename) { throw new PluginError('gulp-angular-templatecache', 'Missing filename option for gulp-angular-templatecache'); } options = options || {}; var templateHeader = 'angular.module("<%= module %>", []).run(["$templateCache", function($templateCache) {'; var templateFooter = '}]);' return es.pipeline( templateCache(options.root || ''), concat(filename), header(templateHeader, { module: options.module || 'templates' }), footer(templateFooter) ) };
var es = require('event-stream'); var path = require('path'); var gutil = require('gulp-util'); var concat = require('gulp-concat'); var header = require('gulp-header'); var footer = require('gulp-footer'); var PluginError = gutil.PluginError; var htmlJsStr = require('js-string-escape'); function templateCache(root) { return es.map(function(file, cb) { var template = '$templateCache.put("<%= url %>","<%= contents %>");'; file.contents = new Buffer(gutil.template(template, { url: path.join(root, file.path.replace(file.base, '')), contents: htmlJsStr(file.contents), file: file })); cb(null, file); }); } module.exports = function(filename, options) { if (!filename) { throw new PluginError('gulp-angular-templatecache', 'Missing filename option for gulp-angular-templatecache'); } options = options || {}; var templateHeader = 'angular.module("<%= module %>", []).run(["$templateCache", function($templateCache) {'; var templateFooter = '}]);' return es.pipeline( templateCache(options.root || ''), concat(filename), header(templateHeader, { module: options.module || 'templates' }), footer(templateFooter) ) };
Change import statement for external library yaml
import pathlib import socket import pyflare from yaml import load s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 53)) myip = s.getsockname()[0] s.close() with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r: update_list = load(r) for account in update_list: records = {} p = pyflare.PyflareClient(account['email'], account['token']) for target in account['targets']: if target['subdomain'].count('.') < 2: zone = target['subdomain'] else: zone = target['subdomain'][target['subdomain'].rfind('.', 0, target['subdomain'].rfind('.'))+1:] if zone not in records: records[zone] = list(p.rec_load_all(zone)) for record in records[zone]: if record['rec_id'] == target['id']: target_record = record break p.rec_edit(zone, 'A', target['id'], target_record['name'], myip, 1, 0) print('Successfully updated {} to {}'.format(target['subdomain'], myip))
import pathlib import socket import pyflare import yaml s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 53)) myip = s.getsockname()[0] s.close() with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r: update_list = yaml.load(r) for account in update_list: records = {} p = pyflare.PyflareClient(account['email'], account['token']) for target in account['targets']: if target['subdomain'].count('.') < 2: zone = target['subdomain'] else: zone = target['subdomain'][target['subdomain'].rfind('.', 0, target['subdomain'].rfind('.'))+1:] if zone not in records: records[zone] = list(p.rec_load_all(zone)) for record in records[zone]: if record['rec_id'] == target['id']: target_record = record break p.rec_edit(zone, 'A', target['id'], target_record['name'], myip, 1, 0) print('Successfully updated {} to {}'.format(target['subdomain'], myip))
Fix factory with proper variable name
<?php namespace Affinity { use Dotink\Flourish; /** * */ class Config implements ConfigInterface { /** * */ static public function create($types, $data = NULL) { if (func_num_args() == 1) { $types = []; $data = func_get_arg(0); } return new static($types, $data); } /** * */ public function __construct(Array $types, Array $data) { $this->types = array_unique($types); $this->data = $data; } /** * */ public function extend(ConfigInterface $config) { $this->types = array_unique(array_merge( $this->getTypes(), $config->getTypes() )); $this->data = array_replace_recursive( $this->getData(), $config->getData() ); } /** * */ public function getData() { return $this->data; } /** * */ public function getTypes() { return $this->types; } } }
<?php namespace Affinity { use Dotink\Flourish; /** * */ class Config implements ConfigInterface { /** * */ static public function create($types, $data = NULL) { if (func_num_args() == 1) { $types = []; $resource = func_get_arg(0); } return new static($types, $data); } /** * */ public function __construct(Array $types, Array $data) { $this->types = array_unique($types); $this->data = $data; } /** * */ public function extend(ConfigInterface $config) { $this->types = array_unique(array_merge( $this->getTypes(), $config->getTypes() )); $this->data = array_replace_recursive( $this->getData(), $config->getData() ); } /** * */ public function getData() { return $this->data; } /** * */ public function getTypes() { return $this->types; } } }
Add connection source function for using this for other purposes
package edu.umass.cs.ciir.waltz.dbindex; import com.j256.ormlite.jdbc.JdbcConnectionSource; import com.j256.ormlite.support.ConnectionSource; import java.io.File; import java.sql.SQLException; /** * @author jfoley */ public class DBConfig { private final String jdbcURL; private final String password; private final String user; public DBConfig(String jdbcURL, String user, String pass) { this.jdbcURL = jdbcURL; this.user = user; this.password = pass; } public DBConfig(String jdbcURL) { this(jdbcURL, "user", ""); } public String getJDBCURL() { return jdbcURL; } public String getUser() { return user; } public String getPassword() { return password; } public static DBConfig h2File(File file) { assert(!file.getName().endsWith(".mv.db")); return new DBConfig("jdbc:h2:file:"+file.getAbsolutePath()+";DB_CLOSE_DELAY=-1"); } public ConnectionSource getConnectionSource() throws SQLException { return new JdbcConnectionSource(getJDBCURL(), getUser(), getPassword()); } }
package edu.umass.cs.ciir.waltz.dbindex; import java.io.File; /** * @author jfoley */ public class DBConfig { private final String jdbcURL; private final String password; private final String user; public DBConfig(String jdbcURL, String user, String pass) { this.jdbcURL = jdbcURL; this.user = user; this.password = pass; } public DBConfig(String jdbcURL) { this(jdbcURL, "user", ""); } public String getJDBCURL() { return jdbcURL; } public String getUser() { return user; } public String getPassword() { return password; } public static DBConfig h2File(File file) { assert(!file.getName().endsWith(".mv.db")); return new DBConfig("jdbc:h2:file:"+file.getAbsolutePath()+";DB_CLOSE_DELAY=-1"); } }
Enable video content for cms pages [#110289088]
from django.db import models # Create your models here. from django.utils.translation import ugettext_lazy as _ from feincms.module.page.models import Page from feincms.content.richtext.models import RichTextContent from feincms.content.medialibrary.models import MediaFileContent from feincms.content.video.models import VideoContent # Page.register_extensions('datepublisher', 'translations') # Example set of extensions # Page.register_extensions('changedate') # in docs but not available Page.register_templates({ 'title': _('Standard template'), 'path': 'pages/base.html', 'regions': ( ('main', _('Main content area')), # ('sidebar', _('Sidebar'), 'inherited'), ), }) Page.create_content_type(RichTextContent) Page.create_content_type(MediaFileContent, TYPE_CHOICES=( ('default', _('default')), ('lightbox', _('lightbox')), )) Page.create_content_type(VideoContent)
from django.db import models # Create your models here. from django.utils.translation import ugettext_lazy as _ from feincms.module.page.models import Page from feincms.content.richtext.models import RichTextContent from feincms.content.medialibrary.models import MediaFileContent # Page.register_extensions('datepublisher', 'translations') # Example set of extensions # Page.register_extensions('changedate') # in docs but not available Page.register_templates({ 'title': _('Standard template'), 'path': 'pages/base.html', 'regions': ( ('main', _('Main content area')), # ('sidebar', _('Sidebar'), 'inherited'), ), }) Page.create_content_type(RichTextContent) Page.create_content_type(MediaFileContent, TYPE_CHOICES=( ('default', _('default')), ('lightbox', _('lightbox')), ))
Add auth header to the fixture loader It seems to work fine with the unauthenticated es instance
""" Commands for interacting with Elastic Search """ # pylint: disable=broad-except from os.path import join import requests from lib.tools import TEST_FOLDER def es_is_available(): """ Test if Elastic Search is running """ try: return ( requests.get("http://localhost:9200", auth=("elastic", "changeme")).json()[ "tagline" ] == "You Know, for Search" ) except Exception: return False def load_json_file(filename): """ Load JSON file into Elastic Search """ url = "http://localhost:9200/_bulk" path = join(TEST_FOLDER, "data", filename) headers = {"Content-Type": "application/x-ndjson"} with open(path, "r") as handle: body = handle.read().encode(encoding="utf-8") return requests.post( url, headers=headers, data=body, auth=("elastic", "changeme") )
""" Commands for interacting with Elastic Search """ # pylint: disable=broad-except from os.path import join import requests from lib.tools import TEST_FOLDER def es_is_available(): """ Test if Elastic Search is running """ try: return ( requests.get("http://localhost:9200").json()["tagline"] == "You Know, for Search" ) except Exception: return False def load_json_file(filename): """ Load JSON file into Elastic Search """ url = "http://localhost:9200/_bulk" path = join(TEST_FOLDER, "data", filename) headers = {"Content-Type": "application/x-ndjson"} with open(path, "r") as handle: body = handle.read().encode(encoding="utf-8") return requests.post(url, headers=headers, data=body)
Add compile_to_json invocation in Myrial test fixture
import collections import math import unittest import raco.fakedb import raco.myrial.interpreter as interpreter import raco.myrial.parser as parser from raco.myrialang import compile_to_json class MyrialTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() self.parser = parser.Parser() self.processor = interpreter.StatementProcessor(self.db) def execute_query(self, query, test_logical=False): '''Run a test query against the fake database''' statements = self.parser.parse(query) self.processor.evaluate(statements) if test_logical: plan = self.processor.get_logical_plan() else: plan = self.processor.get_physical_plan() json = compile_to_json(query, '', [('A', plan)]) self.db.evaluate(plan) return self.db.get_temp_table('__OUTPUT0__') def run_test(self, query, expected, test_logical=False): '''Execute a test query with an expected output''' actual = self.execute_query(query, test_logical) self.assertEquals(actual, expected)
import collections import math import unittest import raco.fakedb import raco.myrial.interpreter as interpreter import raco.myrial.parser as parser class MyrialTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() self.parser = parser.Parser() self.processor = interpreter.StatementProcessor(self.db) def execute_query(self, query, test_logical=False): '''Run a test query against the fake database''' statements = self.parser.parse(query) self.processor.evaluate(statements) if test_logical: plan = self.processor.get_logical_plan() else: plan = self.processor.get_physical_plan() self.db.evaluate(plan) return self.db.get_temp_table('__OUTPUT0__') def run_test(self, query, expected, test_logical=False): '''Execute a test query with an expected output''' actual = self.execute_query(query, test_logical) self.assertEquals(actual, expected)
Add another test for CallExplorer.history_glob
# Copyright (c) 2013 The SAYCBridge Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest2 from core.callexplorer import * class CallExplorerTest(unittest2.TestCase): def _assert_histories(self, glob_string, histories): explorer = CallExplorer() self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories)) def test_history_glob(self): self._assert_histories("", []) self._assert_histories(" ", []) self._assert_histories("P", ["P"]) self._assert_histories(" P ", ["P"]) self._assert_histories("P 1C", ["P 1C"]) self._assert_histories("* 1C", ["P 1C"]) self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"]) self._assert_histories("* 1C * 1D", ["P 1C X 1D", "P 1C P 1D"]) if __name__ == '__main__': unittest2.main()
# Copyright (c) 2013 The SAYCBridge Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest2 from core.callexplorer import * class CallExplorerTest(unittest2.TestCase): def _assert_histories(self, glob_string, histories): explorer = CallExplorer() self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories)) def test_history_glob(self): self._assert_histories("", []) self._assert_histories(" ", []) self._assert_histories("P", ["P"]) self._assert_histories(" P ", ["P"]) self._assert_histories("P 1C", ["P 1C"]) self._assert_histories("* 1C", ["P 1C"]) self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"]) if __name__ == '__main__': unittest2.main()
Make user loggin as the homepage
"""service_control URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from rest_framework.authtoken import views from rest_framework.urlpatterns import format_suffix_patterns from pages.views import profile_login urlpatterns = [ url(r'^$', profile_login, name='home_page'), url(r'^admin/', admin.site.urls), url(r'^api-token-auth/', views.obtain_auth_token), url(r'core/', include('core.urls')), url(r'profiles/', include('pages.urls.profile_urls')), ] urlpatterns = format_suffix_patterns(urlpatterns)
"""service_control URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from rest_framework.authtoken import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api-token-auth/', views.obtain_auth_token), url(r'core/', include('core.urls')), url(r'profiles/', include('pages.urls.profile_urls')), ] urlpatterns = format_suffix_patterns(urlpatterns)
Use more readable version for checking the final modifier is present. git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@374 c7a0535c-eda6-11de-83d8-6d5adf01d787
/* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.checkers; import static org.mutabilitydetector.checkers.AccessModifierQuery.type; import org.mutabilitydetector.MutabilityReason; public class FinalClassChecker extends AbstractMutabilityChecker { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if(type(access).isNotFinal()) { addResult("Is not declared final, and thus may be mutable.", null, MutabilityReason.NOT_DECLARED_FINAL); } } }
/* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.checkers; import org.mutabilitydetector.MutabilityReason; import org.objectweb.asm.Opcodes; public class FinalClassChecker extends AbstractMutabilityChecker { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if((access & Opcodes.ACC_FINAL) == 0) { addResult("Is not declared final, and thus may be mutable.", null, MutabilityReason.NOT_DECLARED_FINAL); } } }
Change create so it uses bulk edit, insteadt of just setAttributes
"use strict"; var domElementFactory = require( "./lib/domElementFactory" ), domElementListFactory = require( "./lib/domElementListFactory" ); function create( tagName, args ) { var $element = domElementFactory( document.createElement( tagName ) ); $element.bulkEdit( args ); return $element; } function createFromElement( element ) { return domElementFactory( element ); } function createFromElementList( elementList ) { return domElementListFactory( elementList ); } function getElementById( id ) { return domElementFactory( document.getElementById( id ) ); } function getElementByClassName( className ) { return domElementFactory( document.getElementsByClassName( className )[ 0 ] ); } function getElementByTagName( tagName ) { return domElementFactory( document.getElementsByTagName( tagName )[ 0 ] ); } function getElementsByClassName( className ) { return domElementListFactory( document.getElementsByClassName( className ) ); } function getElementsByTagName( tagName ) { return domElementListFactory( document.getElementsByTagName( tagName ) ); } module.exports = { create: create, createFromElement: createFromElement, createFromElementList: createFromElementList, getElementById: getElementById, getElementByClassName: getElementByClassName, getElementByTagName: getElementByTagName, getElementsByClassName: getElementsByClassName, getElementsByTagName: getElementsByTagName };
"use strict"; var domElementFactory = require( "./lib/domElementFactory" ), domElementListFactory = require( "./lib/domElementListFactory" ); function create( tagName, args ) { var $element = domElementFactory( document.createElement( tagName ) ); $element.setAttributes( args ); return $element; } function createFromElement( element ) { return domElementFactory( element ); } function createFromElementList( elementList ) { return domElementListFactory( elementList ); } function getElementById( id ) { return domElementFactory( document.getElementById( id ) ); } function getElementByClassName( className ) { return domElementFactory( document.getElementsByClassName( className )[ 0 ] ); } function getElementByTagName( tagName ) { return domElementFactory( document.getElementsByTagName( tagName )[ 0 ] ); } function getElementsByClassName( className ) { return domElementListFactory( document.getElementsByClassName( className ) ); } function getElementsByTagName( tagName ) { return domElementListFactory( document.getElementsByTagName( tagName ) ); } module.exports = { create: create, createFromElement: createFromElement, createFromElementList: createFromElementList, getElementById: getElementById, getElementByClassName: getElementByClassName, getElementByTagName: getElementByTagName, getElementsByClassName: getElementsByClassName, getElementsByTagName: getElementsByTagName };
Use the correct since value
/* * The MIT License (MIT) * * Copyright (c) 2014-2016 Ioannis Moutsatsos, Bruno P. Kinoshita * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Tests for global node properties issue. See JENKINS-34818. * @since 1.5.x */ package org.biouno.unochoice.issue34818;
/* * The MIT License (MIT) * * Copyright (c) 2014-2016 Ioannis Moutsatsos, Bruno P. Kinoshita * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Tests for global node properties issue. See JENKINS-34818. * @since 1.6 */ package org.biouno.unochoice.issue34818;
Hide notification bars after a few seconds.
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require_tree . //= require bootstrap // Replace link targets with JavaScript handlers to prevent iOS fullscreen web // app from opening links in extra browser app if (navigator.userAgent.match(/(ipod|iphone|ipad)/i)) { $(function() { $('body a[href]').click(function(e) { e.preventDefault(); top.location.href = this; }); }); } //hide notification bars after a few seconds $('.alert').delay(10000).fadeOut('slow');
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require_tree . //= require bootstrap // Replace link targets with JavaScript handlers to prevent iOS fullscreen web // app from opening links in extra browser app if (navigator.userAgent.match(/(ipod|iphone|ipad)/i)) { $(function() { $('body a[href]').click(function(e) { e.preventDefault(); top.location.href = this; }); }); }
Fix the extraction of the HttpServletRequest
package net.kencochrane.raven.servlet; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpServletRequest; @WebListener public class RavenServletRequestListener implements ServletRequestListener { private static final ThreadLocal<HttpServletRequest> THREAD_REQUEST = new ThreadLocal<HttpServletRequest>(); public static HttpServletRequest getServletRequest() { return THREAD_REQUEST.get(); } @Override public void requestDestroyed(ServletRequestEvent servletRequestEvent) { THREAD_REQUEST.remove(); } @Override public void requestInitialized(ServletRequestEvent servletRequestEvent) { ServletRequest servletRequest = servletRequestEvent.getServletRequest(); if (servletRequest instanceof HttpServletRequest) THREAD_REQUEST.set((HttpServletRequest) servletRequest); } }
package net.kencochrane.raven.servlet; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpServletRequest; @WebListener public class RavenServletRequestListener implements ServletRequestListener { private static final ThreadLocal<HttpServletRequest> THREAD_REQUEST = new ThreadLocal<HttpServletRequest>(); public static HttpServletRequest getServletRequest() { return THREAD_REQUEST.get(); } @Override public void requestDestroyed(ServletRequestEvent servletRequestEvent) { THREAD_REQUEST.remove(); } @Override public void requestInitialized(ServletRequestEvent servletRequestEvent) { if (servletRequestEvent instanceof HttpServletRequest) THREAD_REQUEST.set((HttpServletRequest) servletRequestEvent.getServletRequest()); } }
Revert "Use importlib instead of __import__" This reverts commit 1c40e03b487ae3dcef9a683de960f9895936d370.
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import haas import logging import sys LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ __import__(name) return sys.modules[name]
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import importlib import logging import haas LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ return importlib.import_module(name)
Change app name to Ninhursag.
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Flask application default config: # http://flask.pocoo.org/docs/config/#configuring-from-files # https://github.com/mbr/flask-appconfig project_name = u'Ninhursag' class Default(object): APP_NAME = project_name DEBUG = False TESTING = False JS_LOG_LEVEL = 3 # log (1) < debug (2) < info (3) < warn (4) < error (5) DUST_LOG_LEVEL = 'INFO' # Servers and URLs SERVER_NAME = 'localhost:5000' # Authentication etc SECRET_KEY = 'some-secret-key' CSRF_ENABLED = True # API API_SERVER = 'localhost:5000' API_TOKEN = 'some-api-token' class Dev(Default): APP_NAME = project_name + ' dev' DEBUG = True JS_LOG_LEVEL = 1 DUST_LOG_LEVEL = 'DEBUG' class Testing(Default): TESTING = True CSRF_ENABLED = False class Production(Default): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Flask application default config: # http://flask.pocoo.org/docs/config/#configuring-from-files # https://github.com/mbr/flask-appconfig project_name = u'Skeleton' class Default(object): APP_NAME = project_name DEBUG = False TESTING = False JS_LOG_LEVEL = 3 # log (1) < debug (2) < info (3) < warn (4) < error (5) DUST_LOG_LEVEL = 'INFO' # Servers and URLs SERVER_NAME = 'localhost:5000' # Authentication etc SECRET_KEY = 'some-secret-key' CSRF_ENABLED = True # API API_SERVER = 'localhost:5000' API_TOKEN = 'some-api-token' class Dev(Default): APP_NAME = project_name + ' dev' DEBUG = True JS_LOG_LEVEL = 1 DUST_LOG_LEVEL = 'DEBUG' class Testing(Default): TESTING = True CSRF_ENABLED = False class Production(Default): pass
Terminate app if handler throws exception.
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest', kill_on_exception=True) @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run()
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest') @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run()
Use .reduce to filter out null flags and account for new individuals for audit via Graphiql
// @flow import { manager } from '../../../../core/service-providers/manager' import { Auditor } from '../../../../core/auditor' import { individualStore } from '../../../../core/data/individual-store' import { groupStore } from '../../../../core/data/group-store' import type { FlaggedInfo } from '../../../../core/types' export function listAccounts (args: { serviceId: string }) { return manager.download(args.serviceId || 'all') } export async function performAudit () { const accounts = await manager.download('all') const auditor = new Auditor(individualStore, groupStore) return accounts.reduce((result, account) => { const flag = auditor.auditAccount(account) if (flag) { const individual = flag.individual ? mapIndividualInFlag(flag) : null result.push({ individual: individual, serviceId: flag.serviceId, userIdentity: flag.userIdentity, assets: flag.assets }) } return result }, []) } function mapIndividualInFlag(flag: FlaggedInfo) { let individual: any = flag.individual const serviceUserIdentities = individual.serviceUserIdentities individual.serviceUserIdentities = Object.keys(serviceUserIdentities).map((serviceId) => { return { serviceId: serviceId, userIdentity: serviceUserIdentities[serviceId] } }) individual.accessRules = Object.keys(individual.accessRules).map((serviceId) => { return { service: manager.getServiceInfo(serviceId), accessRules: individual.accessRules[serviceId] } }) return individual }
// @flow import { manager } from '../../../../core/service-providers/manager' import { Auditor } from '../../../../core/auditor' import { individualStore } from '../../../../core/data/individual-store' import { groupStore } from '../../../../core/data/group-store' import type { FlaggedInfo } from '../../../../core/types' export function listAccounts (args: { serviceId: string }) { return manager.download(args.serviceId || 'all') } export async function performAudit () { const accounts = await manager.download('all') const auditor = new Auditor(individualStore, groupStore) const flags = accounts.map((account) => { const flag = auditor.auditAccount(account) if (flag && flag.individual) { const individual = mapIndividualInFlag(flag) return { individual: individual, serviceId: flag.serviceId, userIdentity: flag.userIdentity, assets: flag.assets } } }) return flags } function mapIndividualInFlag(flag: FlaggedInfo) { let individual: any = flag.individual const serviceUserIdentities = individual.serviceUserIdentities individual.serviceUserIdentities = Object.keys(serviceUserIdentities).map((serviceId) => { return { serviceId: serviceId, userIdentity: serviceUserIdentities[serviceId] } }) individual.accessRules = Object.keys(individual.accessRules).map((serviceId) => { return { service: manager.getServiceInfo(serviceId), accessRules: individual.accessRules[serviceId] } }) return individual }
Add exp14.GoPackageList interface for exp14.GoPackages.
package exp14 import ( . "github.com/shurcooL/go/gists/gist7480523" . "github.com/shurcooL/go/gists/gist7802150" "github.com/shurcooL/go/gists/gist8018045" ) type GoPackageList interface { List() []*GoPackage DepNode2I } type GoPackages struct { SkipGoroot bool // Currently, works on initial run only; changing its value afterwards has no effect. Entries []*GoPackage DepNode2 } func (this *GoPackages) Update() { // TODO: Have a source? // TODO: Make it load in background, without blocking, etc. { goPackages := make(chan *GoPackage, 64) if this.SkipGoroot { go gist8018045.GetGopathGoPackages(goPackages) } else { go gist8018045.GetGoPackages(goPackages) } this.Entries = nil for { if goPackage, ok := <-goPackages; ok { this.Entries = append(this.Entries, goPackage) } else { break } } } } func (this *GoPackages) List() []*GoPackage { return this.Entries }
package exp14 import ( . "github.com/shurcooL/go/gists/gist7480523" . "github.com/shurcooL/go/gists/gist7802150" "github.com/shurcooL/go/gists/gist8018045" ) type GoPackages struct { SkipGoroot bool // Currently, works on initial run only; changing its value afterwards has no effect. Entries []*GoPackage DepNode2 } func (this *GoPackages) Update() { // TODO: Have a source? // TODO: Make it load in background, without blocking, etc. { goPackages := make(chan *GoPackage, 64) if this.SkipGoroot { go gist8018045.GetGopathGoPackages(goPackages) } else { go gist8018045.GetGoPackages(goPackages) } this.Entries = nil for { if goPackage, ok := <-goPackages; ok { this.Entries = append(this.Entries, goPackage) } else { break } } } }
Make verify function false by default
<?php class SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread extends XFCP_SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread { protected function _getFields() { $fields = parent::_getFields(); $fields['xf_thread']['word_count'] = array( 'type' => self::TYPE_UNKNOWN, 'verification' => array('$this', '_verifyWordCount') ); return $fields; } public function rebuildDiscussionCounters($replyCount = false, $firstPostId = false, $lastPostId = false) { parent::rebuildDiscussionCounters($replyCount, $firstPostId, $lastPostId); $wordCount = $this->_getThreadModel()->countThreadmarkWordsInThread($this->get('thread_id')); $this->set('word_count', $wordCount); } protected function _verifyWordCount($wordCount) { if (is_int($wordCount) || is_null($wordCount)) { return true; } return false; } }
<?php class SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread extends XFCP_SV_WordCountSearch_XenForo_DataWriter_Discussion_Thread { protected function _getFields() { $fields = parent::_getFields(); $fields['xf_thread']['word_count'] = array( 'type' => self::TYPE_UNKNOWN, 'verification' => array('$this', '_verifyWordCount') ); return $fields; } public function rebuildDiscussionCounters($replyCount = false, $firstPostId = false, $lastPostId = false) { parent::rebuildDiscussionCounters($replyCount, $firstPostId, $lastPostId); $wordCount = $this->_getThreadModel()->countThreadmarkWordsInThread($this->get('thread_id')); $this->set('word_count', $wordCount); } protected function _verifyWordCount($wordCount) { if (!is_int($wordCount) && !is_null($wordCount)) { return false; } return true; } }
Improve http logger output filenames
'use strict'; var fs = require( 'fs' ); var path = require( 'path' ); var fileStreamRotator = require( 'file-stream-rotator' ); // Use Morgan logger for HTTP access logging var morgan = require( 'morgan' ); var logDirPath = path.join( process.cwd(), 'logs' ); module.exports = { /** * Return a configured Morgan instance * * @param {String} mode 'dev' or 'combined', depending on environment * @param {Boolean} logToFile Whether to log to files or just to stdout * @return A Morgan logger middleware instance */ mode: function( mode, logToFile ) { var loggerOptions = {}; // Log to rotating file if in prod mode if ( logToFile ) { // ensure log directory exists fs.existsSync( logDirPath ) || fs.mkdirSync( logDirPath ); // create a file-rotating write stream loggerOptions.stream = fileStreamRotator.getStream({ filename: logDirPath + '/access-%DATE%.log', date_format: "YYYY-MM-DD", frequency: 'daily', verbose: false }); } // Return a configured morgan middleware instance return morgan( mode, loggerOptions ); } };
'use strict'; var fs = require( 'fs' ); var path = require( 'path' ); var fileStreamRotator = require( 'file-stream-rotator' ); // Use Morgan logger for HTTP access logging var morgan = require( 'morgan' ); var logDirPath = path.join( process.cwd(), 'logs' ); module.exports = { /** * Return a configured Morgan instance * * @param {String} mode 'dev' or 'combined', depending on environment * @param {Boolean} logToFile Whether to log to files or just to stdout * @return A Morgan logger middleware instance */ mode: function( mode, logToFile ) { var loggerOptions = {}; // Log to rotating file if in prod mode if ( logToFile ) { // ensure log directory exists fs.existsSync( logDirPath ) || fs.mkdirSync( logDirPath ); // create a file-rotating write stream loggerOptions.stream = fileStreamRotator.getStream({ filename: logDirPath + '/access-%DATE%.log', frequency: 'daily', verbose: false }); } // Return a configured morgan middleware instance return morgan( mode, loggerOptions ); } };
Fix double extension bug for nested files with non-pretty-URL
<?php namespace TightenCo\Jigsaw; class BasicOutputPathResolver { public function link($path, $name, $type, $page = 1) { $extension = $type ? '.' . $type : ''; $name = basename($name, $extension); return $page > 1 ? $this->clean('/' . $path . '/' . $page . '/' . $name . $extension) : $this->clean('/' . $path . '/' . $name . $extension); } public function path($path, $name, $type, $page = 1) { return $this->link($path, $name, $type, $page); } public function directory($path, $name, $type, $page = 1) { return $page > 1 ? $this->clean($path . '/' . $page) : $this->clean($path); } private function clean($path) { return str_replace('//', '/', $path); } }
<?php namespace TightenCo\Jigsaw; class BasicOutputPathResolver { public function link($path, $name, $type, $page = 1) { if ($page > 1) { return $this->clean('/' . $path . '/' . $page . '/' . $name . '.' . $type); } return $this->clean('/' . $path . '/' . $name . '.' . $type); } public function path($path, $name, $type, $page = 1) { return $this->link($path, $name, $type, $page); } public function directory($path, $name, $type, $page = 1) { if ($page > 1) { return $this->clean($path . '/' . $page); } return $this->clean($path); } private function clean($path) { return str_replace('//', '/', $path); } }
Update to the export file.
import EO from 'ember-orbit/main'; import Store from 'ember-orbit/store'; import Model from 'ember-orbit/model'; import RecordArrayManager from 'ember-orbit/record-array-manager'; import Schema from 'ember-orbit/schema'; import Source from 'ember-orbit/source'; import HasManyArray from 'ember-orbit/links/has-many-array'; import HasOneObject from 'ember-orbit/links/has-one-object'; import LinkProxyMixin from 'ember-orbit/links/link-proxy-mixin'; import FilteredRecordArray from 'ember-orbit/record-arrays/filtered-record-array'; import RecordArray from 'ember-orbit/record-arrays/record-array'; import key from 'ember-orbit/fields/key'; import attr from 'ember-orbit/fields/attr'; import hasMany from 'ember-orbit/fields/has-many'; import hasOne from 'ember-orbit/fields/has-one'; EO.Store = Store; EO.Model = Model; EO.RecordArrayManager = RecordArrayManager; EO.Schema = Schema; EO.Source = Source; EO.key = key; EO.attr = attr; EO.HasManyArray = HasManyArray; EO.HasOneObject = HasOneObject; EO.LinkProxyMixin = LinkProxyMixin; EO.FilteredRecordArray = FilteredRecordArray; EO.RecordArray = RecordArray; EO.hasOne = hasOne; EO.hasMany = hasMany; export default EO;
import EO from 'ember-orbit/main'; import Store from 'ember-orbit/store'; import Model from 'ember-orbit/model'; import RecordArrayManager from 'ember-orbit/record-array-manager'; import Schema from 'ember-orbit/schema'; import Source from 'ember-orbit/source'; import attr from 'ember-orbit/fields/attr'; import hasMany from 'ember-orbit/fields/has-many'; import hasOne from 'ember-orbit/fields/has-one'; import HasManyArray from 'ember-orbit/links/has-many-array'; import HasOneObject from 'ember-orbit/links/has-one-object'; import LinkProxyMixin from 'ember-orbit/links/link-proxy-mixin'; import FilteredRecordArray from 'ember-orbit/record-arrays/filtered-record-array'; import RecordArray from 'ember-orbit/record-arrays/record-array'; EO.Store = Store; EO.Model = Model; EO.RecordArrayManager = RecordArrayManager; EO.Schema = Schema; EO.Source = Source; EO.attr = attr; EO.hasOne = hasOne; EO.hasMany = hasMany; EO.HasManyArray = HasManyArray; EO.HasOneObject = HasOneObject; EO.LinkProxyMixin = LinkProxyMixin; EO.FilteredRecordArray = FilteredRecordArray; EO.RecordArray = RecordArray; export default EO;
Set csrf header in AngularJS’ $http requests CakePHP provides the csrf token in a cookie already. These two lines instruct AngularJS to read the token from that cookie and to send it as a header in all the requests emitted by the $http service.
(function() { 'use strict'; angular .module('app', ['ngMaterial', 'ngMessages']) .config(['$mdThemingProvider', '$mdIconProvider', '$httpProvider', function($mdThemingProvider, $mdIconProvider, $httpProvider) { $mdThemingProvider.theme('default') .primaryPalette('green') .accentPalette('grey') .warnPalette('red', {'default': '700'}); $httpProvider.defaults.transformRequest = function(data) { if (data === undefined) { return data; } return $.param(data); }; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token'; $httpProvider.defaults.xsrfCookieName = 'csrfToken'; }]); })();
(function() { 'use strict'; angular .module('app', ['ngMaterial', 'ngMessages']) .config(['$mdThemingProvider', '$mdIconProvider', '$httpProvider', function($mdThemingProvider, $mdIconProvider, $httpProvider) { $mdThemingProvider.theme('default') .primaryPalette('green') .accentPalette('grey') .warnPalette('red', {'default': '700'}); $httpProvider.defaults.transformRequest = function(data) { if (data === undefined) { return data; } return $.param(data); }; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; }]); })();
Use the string module instead of string methods; this should still work with Python 1.5.2 for now.
"""Core XML support for Python. This package contains three sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. """ __all__ = ["dom", "parsers", "sax"] import string __version__ = string.split("$Revision$")[1] del string _MINIMUM_XMLPLUS_VERSION = (0, 6, 1) try: import _xmlplus except ImportError: pass else: try: v = _xmlplus.version_info except AttributeError: # _xmlplue is too old; ignore it pass else: if v >= _MINIMUM_XMLPLUS_VERSION: import sys sys.modules[__name__] = _xmlplus else: del v
"""Core XML support for Python. This package contains three sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. """ __all__ = ["dom", "parsers", "sax"] __version__ = "$Revision$"[1:-1].split()[1] _MINIMUM_XMLPLUS_VERSION = (0, 6, 1) try: import _xmlplus except ImportError: pass else: try: v = _xmlplus.version_info except AttributeError: # _xmlplue is too old; ignore it pass else: if v >= _MINIMUM_XMLPLUS_VERSION: import sys sys.modules[__name__] = _xmlplus else: del v
Create line break for icons div.
import React from 'react'; import icons from '../weather_icons/WeatherIcons'; const TenDay = ({ tenDayForecast }) => { if (!tenDayForecast) { return null; } const forecastArray = tenDayForecast.simpleforecast.forecastday; const tenDayDataLoop = forecastArray.map((day, i) => { return ( <div className='ten-day-data' key={i}> <h4 className='ten-day-day ten-day' tabIndex="0">{day.date.weekday_short}</h4> <div className={`ten-day-icon ${icons[day.icon]}`} tabIndex="0" alt="daily weather icon" aria-label="daily weather icon"></div> <h4 className='ten-day-lo ten-day' tabIndex="0">{day.low.fahrenheit}°</h4> <h4 className='ten-day-hi ten-day' tabIndex="0">{day.high.fahrenheit}°</h4> </div> ); }); return ( <section className='ten-day-container'> {tenDayDataLoop} </section> ); }; export default TenDay;
import React from 'react'; import icons from '../weather_icons/WeatherIcons'; const TenDay = ({ tenDayForecast }) => { if (!tenDayForecast) { return null; } const forecastArray = tenDayForecast.simpleforecast.forecastday; const tenDayDataLoop = forecastArray.map((day, i) => { return ( <div className='ten-day-data' key={i}> <h4 className='ten-day-day ten-day' tabIndex="0">{day.date.weekday_short}</h4> <div className={`ten-day-icon ${icons[day.icon]}`} tabIndex="0" alt="daily weather icon" aria-label="daily weather icon"></div> <h4 className='ten-day-lo ten-day' tabIndex="0">{day.low.fahrenheit}°</h4> <h4 className='ten-day-hi ten-day' tabIndex="0">{day.high.fahrenheit}°</h4> </div> ); }); return ( <section className='ten-day-container'> {tenDayDataLoop} </section> ); }; export default TenDay;
Add NFD_NFC to unicode normalization comparison.
# -*- coding: utf-8 -*- import unicodedata def shortest_normalization_form(): """ Find unicode normalization that generates shortest utf8 encoded text. Result NFKC """ s = 'Iñtërnâtiônàlizætiøn☃ and string escaping are ticky &#160; things' nfc = unicodedata.normalize('NFC', s) nfd = unicodedata.normalize('NFD', s) nfkc = unicodedata.normalize('NFKC', s) nfkd = unicodedata.normalize('NFKD', s) nfd_nfkc = unicodedata.normalize('NFKC', nfd) nfd_nfc = unicodedata.normalize('NFC', nfd) print('UTF-8 length of normalized strings:\n') print(f'NFC: {len(nfc.encode("utf8"))}') print(f'NFD: {len(nfd.encode("utf8"))}') print(f'NFKC: {len(nfkc.encode("utf8"))}') print(f'NFKD: {len(nfkd.encode("utf8"))}') print(f'NFD_NFKC: {len(nfd_nfkc.encode("utf8"))}') print(f'NFD_NFC: {len(nfd_nfc.encode("utf8"))}') if __name__ == '__main__': shortest_normalization_form()
# -*- coding: utf-8 -*- import unicodedata def shortest_normalization_form(): """ Find unicode normalization that generates shortest utf8 encoded text. Result NFKC """ s = 'Iñtërnâtiônàlizætiøn☃ and string escaping are ticky &#160; things' nfc = unicodedata.normalize('NFC', s) nfd = unicodedata.normalize('NFD', s) nfkc = unicodedata.normalize('NFKC', s) nfkd = unicodedata.normalize('NFKD', s) nfd_nfkc = unicodedata.normalize('NFKC', nfd) print('UTF-8 length of normalized strings:\n') print(f'NFC: {len(nfc.encode("utf8"))}') print(f'NFD: {len(nfd.encode("utf8"))}') print(f'NFKC: {len(nfkc.encode("utf8"))}') print(f'NFKD: {len(nfkd.encode("utf8"))}') print(f'NFD_NFKC: {len(nfd_nfkc.encode("utf8"))}') if __name__ == '__main__': shortest_normalization_form()
Add backend to register form.
package controllers import ( "github.com/astaxie/beego" "ustackweb/models" ) type Registration struct { Username string Password string } type RegistrationsController struct { BaseController } func (this *RegistrationsController) Prepare() { this.PrepareXsrf() this.PrepareLayout() this.Layout = "layouts/default.html.tpl" } func (this *RegistrationsController) New() { this.TplNames = "registrations/new.html.tpl" } func (this *RegistrationsController) Create() { registration := Registration{} err := this.ParseForm(&registration) if err == nil { models.Users().Create(registration.Username, registration.Password) this.Redirect(beego.UrlFor("SessionsController.New"), 302) } else { this.Redirect(beego.UrlFor("RegistrationsController.New"), 302) } }
package controllers import ( "github.com/astaxie/beego" ) type Registration struct { Username string Password string } type RegistrationsController struct { BaseController } func (this *RegistrationsController) Prepare() { this.PrepareXsrf() this.PrepareLayout() this.Layout = "layouts/default.html.tpl" } func (this *RegistrationsController) New() { this.TplNames = "registrations/new.html.tpl" } func (this *RegistrationsController) Create() { registration := Registration{} err := this.ParseForm(&registration) if err == nil && registration.Username != "foo" && registration.Username != "admin" { this.SetSession("username", registration.Username) this.RequireAuth() this.Redirect(beego.UrlFor("HomeController.Get"), 302) } else { this.Redirect(beego.UrlFor("RegistrationsController.New"), 302) } }
Add support for thumbs down in radio mode on Yandex.Music
controller = new BasicController({ supports: { playpause: true, next: true, previous: true, favorite: true, thumbsDown: false // Changes dynamically }, playPauseSelector: '.player-controls__btn_play', previousSelector: '.player-controls__btn_prev', nextSelector: '.player-controls__btn_next', titleSelector: '.player-controls .track__title', artistSelector: '.player-controls .track__artists', playStateSelector: '.player-controls__btn_play', playStateClass: 'player-controls__btn_pause', artworkImageSelector: '.player-controls .album-cover', favoriteSelector: '.player-controls .like', isFavoriteSelector: '.player-controls .like_on', thumbsDownSelector: '.player-controls__btn_dislike' }); controller.override('getAlbumArt', function() { var img = document.querySelector(this.artworkImageSelector); if (img) { return img.src.replace('40x40', '150x150'); } return undefined }); controller.override('isPlaying', function(_super) { this.supports.thumbsDown = window.getComputedStyle(document.querySelector(this.thumbsDownSelector)).display != 'none' return _super() });
controller = new BasicController({ supports: { playpause: true, next: true, previous: true, favorite: true }, playPauseSelector: '.player-controls__btn_play', previousSelector: '.player-controls__btn_prev', nextSelector: '.player-controls__btn_next', titleSelector: '.player-controls .track__title', artistSelector: '.player-controls .track__artists', playStateSelector: '.player-controls__btn_play', playStateClass: 'player-controls__btn_pause', artworkImageSelector: '.player-controls .album-cover', favoriteSelector: '.player-controls .like', isFavoriteSelector: '.player-controls .like_on' }); controller.override('getAlbumArt', function() { var img = document.querySelector(this.artworkImageSelector); if (img) { return img.src.replace('40x40', '150x150'); } return undefined });
Handle case of no identifiers at all in meta data
#!/usr/bin/env python import sys import os import yaml import isbnlib metafile = sys.argv[1] metadata = open(metafile, 'r').read() yamldata = yaml.load(metadata) identifier = {} if "identifier" in yamldata: for id in yamldata["identifier"]: if "key" in id: isbnlike = isbnlib.get_isbnlike(id["text"])[0] if isbnlib.is_isbn13(isbnlike): identifier[id["key"]] = isbnlib.EAN13(isbnlike) isbn = identifier[sys.argv[2]] if sys.argv[2] in identifier else "9786056644504" if len(sys.argv) >= 4 and sys.argv[3] == "mask": print(isbnlib.mask(isbn)) else: print(isbn)
#!/usr/bin/env python import sys import os import yaml import isbnlib metafile = sys.argv[1] metadata = open(metafile, 'r').read() yamldata = yaml.load(metadata) identifier = {} for id in yamldata["identifier"]: if "key" in id: isbnlike = isbnlib.get_isbnlike(id["text"])[0] if isbnlib.is_isbn13(isbnlike): identifier[id["key"]] = isbnlib.EAN13(isbnlike) isbn = identifier[sys.argv[2]] if sys.argv[2] in identifier else "9786056644504" if len(sys.argv) >= 4 and sys.argv[3] == "mask": print(isbnlib.mask(isbn)) else: print(isbn)
Fix hover depth for connections
/** * * Copyright 2016 Netflix, 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. * */ const DEPTH = { normalNode: -5000, // Moves more negative normalConnection: -9999, // Stays static dimmedNode: -15000, // Moves more negative dimmedConnection: -19999, // Stays static }; export default { DEPTH: DEPTH };
/** * * Copyright 2016 Netflix, 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. * */ const DEPTH = { normalNode: -5000, // Moves more negative normalConnection: -9999, // Stays static dimmedNode: -10000, // Moves more negative dimmedConnection: -14999, // Stays static }; export default { DEPTH: DEPTH };
Change router action so it occurs on all pages rather than 404s
<?php namespace FrontRouterPlugin; call_user_func(function() { // thisfile $thisfile = basename(__FILE__, '.php'); // language i18n_merge($thisfile) || i18n_merge($thisfile, 'en_US'); // requires require_once(GSPLUGINPATH . $thisfile . '/php/functions.php'); require_once(GSPLUGINPATH . $thisfile . '/php/constants.php'); require_once(GSPLUGINPATH . $thisfile . '/php/router.class.php'); require_once(GSPLUGINPATH . $thisfile . '/php/api.php'); // register plugin call_user_func_array('register_plugin', array( 'id' => ID, 'name' => i18n_r('PLUGIN_NAME'), 'version' => '0.1', 'author' => 'Lawrence Okoth-Odida', 'url' => 'https://github.com/lokothodida', 'desc' => i18n_r('PLUGIN_DESC'), 'tab' => 'plugins', 'admin' => function() { admin(); } )); // activate actions/filters // front-end add_action('index-post-dataindex', function() { executeRoutes(); }); // back-end add_action('plugins-sidebar', 'createSideMenu' , array(ID, i18n_r('PLUGIN_SIDEBAR'))); // sidebar link });
<?php namespace FrontRouterPlugin; call_user_func(function() { // thisfile $thisfile = basename(__FILE__, '.php'); // language i18n_merge($thisfile) || i18n_merge($thisfile, 'en_US'); // requires require_once(GSPLUGINPATH . $thisfile . '/php/functions.php'); require_once(GSPLUGINPATH . $thisfile . '/php/constants.php'); require_once(GSPLUGINPATH . $thisfile . '/php/router.class.php'); require_once(GSPLUGINPATH . $thisfile . '/php/api.php'); // register plugin call_user_func_array('register_plugin', array( 'id' => ID, 'name' => i18n_r('PLUGIN_NAME'), 'version' => '0.1', 'author' => 'Lawrence Okoth-Odida', 'url' => 'https://github.com/lokothodida', 'desc' => i18n_r('PLUGIN_DESC'), 'tab' => 'plugins', 'admin' => function() { admin(); } )); // activate actions/filters // front-end add_action('error-404', function() { executeRoutes(); }); // back-end add_action('plugins-sidebar', 'createSideMenu' , array(ID, i18n_r('PLUGIN_SIDEBAR'))); // sidebar link });
[FEATURE] Change withdrawal status from pending to notified.
var gateway = require(__dirname+'/../'); var request = require('request'); function getQueuedWithdrawal(fn){ gateway.api.listWithdrawals(function(err, withdrawals){ if (err){ fn(err, null); } else { if (withdrawals && withdrawals[0]){ fn(null, withdrawals[0]); } else { fn(null,null); } } }); } function loop() { getQueuedWithdrawal(function(err, withdrawal){ if (err || !withdrawal) { setTimeout(loop, 500); return; } var url = gateway.config.get('WITHDRAWALS_CALLBACK_URL'); postWithdrawalCallback(withdrawal, url, function(err, resp){ if (err) { setTimeout(loop, 500); } else { withdrawal.status = 'notified'; withdrawal.save().complete(function(){ setTimeout(loop, 500); }); } }); }); } function postWithdrawalCallback(withdrawal, url, fn) { body = withdrawal.toJSON(); console.log('about to post withdrawal', body); console.log('WITHDRAWAL', body); request({ method: 'POST', uri: url, form: body }, function(err, resp, body){ console.log('CODE', resp.statusCode); console.log('ERROR', err); console.log('BODY', body); fn(err, body); }); } loop();
var gateway = require(__dirname+'/../'); var request = require('request'); function getQueuedWithdrawal(fn){ gateway.api.listWithdrawals(function(err, withdrawals){ if (err){ fn(err, null); } else { if (withdrawals && withdrawals[0]){ fn(null, withdrawals[0]); } else { fn(null,null); } } }); } function loop() { getQueuedWithdrawal(function(err, withdrawal){ if (err || !withdrawal) { setTimeout(loop, 500); return; } var url = gateway.config.get('WITHDRAWALS_CALLBACK_URL'); postWithdrawalCallback(withdrawal, url, function(err, resp){ if (err) { setTimeout(loop, 500); } else { withdrawal.status = 'pending'; withdrawal.save().complete(function(){ setTimeout(loop, 500); }); } }); }); } function postWithdrawalCallback(withdrawal, url, fn) { body = withdrawal.toJSON(); console.log('about to post withdrawal', body); console.log('WITHDRAWAL', body); request({ method: 'POST', uri: url, form: body }, function(err, resp, body){ console.log('CODE', resp.statusCode); console.log('ERROR', err); console.log('BODY', body); fn(err, body); }); } loop();
Change Test to not mock a non existing method
<?php declare(strict_types = 1); namespace Templado\Engine; use DOMDocument; use PHPUnit\Framework\TestCase; class StripRDFaAttributesTransformationTest extends TestCase { public function testTransformationRemovedExpectedAttributes(): void { $transformation = new StripRDFaAttributesTransformation(); $selector = $transformation->getSelector(); $dom = new DOMDocument(); $dom->loadXML('<?xml version="1.0" ?><root property="p" resource="r" prefix="p" typeof="t" />'); $selection = $selector->select($dom->documentElement); $transformation->apply($selection->getIterator()->item(0)); $this->assertEqualXMLStructure($dom->createElement('root'), $dom->documentElement, true); } public function testApplyingOnNoneElementDoesNothing(): void { $transformation = new StripRDFaAttributesTransformation(); $node = new class extends \DOMText { public function removeAttribute(): void { throw new \RuntimeException('removeAttribute should not have been called'); } }; $transformation->apply($node); $this->assertTrue(true); } }
<?php declare(strict_types = 1); namespace Templado\Engine; use DOMDocument; use PHPUnit\Framework\TestCase; class StripRDFaAttributesTransformationTest extends TestCase { public function testTransformationRemovedExpectedAttributes(): void { $transformation = new StripRDFaAttributesTransformation(); $selector = $transformation->getSelector(); $dom = new DOMDocument(); $dom->loadXML('<?xml version="1.0" ?><root property="p" resource="r" prefix="p" typeof="t" />'); $selection = $selector->select($dom->documentElement); $transformation->apply($selection->getIterator()->item(0)); $this->assertEqualXMLStructure($dom->createElement('root'), $dom->documentElement, true); } public function testApplyingOnNoneElementDoesNothing(): void { $transformation = new StripRDFaAttributesTransformation(); $node = $this->createPartialMock('DOMText', ['removeAttribute']); $node->expects($this->never())->method('removeAttribute'); $transformation->apply($node); } }
FIX Assert not empty on something that actually is in every composer.json
<?php namespace BringYourOwnIdeas\Maintenance\Tests\Util; use BringYourOwnIdeas\Maintenance\Util\ComposerLoader; use PHPUnit_Framework_TestCase; use SapphireTest; /** * @mixin PHPUnit_Framework_TestCase */ class ComposerLoaderTest extends SapphireTest { public function testGetJson() { $loader = new ComposerLoader(); $this->assertNotEmpty( $loader->getJson()->name, 'JSON file is loaded and parsed' ); } public function testGetLock() { $loader = new ComposerLoader(); $this->assertNotEmpty( $loader->getLock()->packages, 'Lock file is loaded and parsed' ); } }
<?php namespace BringYourOwnIdeas\Maintenance\Tests\Util; use BringYourOwnIdeas\Maintenance\Util\ComposerLoader; use PHPUnit_Framework_TestCase; use SapphireTest; /** * @mixin PHPUnit_Framework_TestCase */ class ComposerLoaderTest extends SapphireTest { public function testGetJson() { $loader = new ComposerLoader(); $this->assertNotEmpty( $loader->getJson()->require->{'silverstripe/framework'}, 'JSON file is loaded and parsed' ); } public function testGetLock() { $loader = new ComposerLoader(); $this->assertNotEmpty( $loader->getLock()->packages, 'Lock file is loaded and parsed' ); } }
Use a bigger buffer size for the ``lots of sets'' test.
package net.spy.memcached; import java.util.Arrays; import java.util.concurrent.TimeUnit; /** * Small test program that does a bunch of sets in a tight loop. */ public class DoLotsOfSets { public static void main(String[] args) throws Exception { // Create a client with a queue big enough to hold the 300,000 items // we're going to add. MemcachedClient client=new MemcachedClient( new DefaultConnectionFactory(350000, 32768), AddrUtil.getAddresses("localhost:11211")); long start=System.currentTimeMillis(); byte[] toStore=new byte[26]; Arrays.fill(toStore, (byte)'a'); for(int i=0; i<300000; i++) { client.set("k" + i, 300, toStore); } long added=System.currentTimeMillis(); System.err.printf("Finished queuing in %sms\n", added-start); client.waitForQueues(Long.MAX_VALUE, TimeUnit.MILLISECONDS); long end=System.currentTimeMillis(); System.err.printf("Completed everything in %sms (%sms to flush)\n", end-start, end-added); client.shutdown(); } }
package net.spy.memcached; import java.util.Arrays; import java.util.concurrent.TimeUnit; /** * Small test program that does a bunch of sets in a tight loop. */ public class DoLotsOfSets { public static void main(String[] args) throws Exception { // Create a client with a queue big enough to hold the 300,000 items // we're going to add. MemcachedClient client=new MemcachedClient( new DefaultConnectionFactory(350000, 8192), AddrUtil.getAddresses("localhost:11211")); long start=System.currentTimeMillis(); byte[] toStore=new byte[26]; Arrays.fill(toStore, (byte)'a'); for(int i=0; i<300000; i++) { client.set("k" + i, 300, toStore); } long added=System.currentTimeMillis(); System.err.printf("Finished queuing in %sms\n", added-start); client.waitForQueues(Long.MAX_VALUE, TimeUnit.MILLISECONDS); long end=System.currentTimeMillis(); System.err.printf("Completed everything in %sms (%sms to flush)\n", end-start, end-added); client.shutdown(); } }
Fix problem with dropping Q on enc that only supports O (for example)
'use strict'; angular.module('vleApp') .directive('fieldDrop', function (Dataset) { return { templateUrl: 'templates/fielddrop.html', restrict: 'E', scope: { fieldDef: '=', types: '=' }, controller: function ($scope) { $scope.removeField = function() { $scope.fieldDef.name = null; $scope.fieldDef.type = null; }; $scope.fieldDropped = function() { var fieldType = Dataset.stats[$scope.fieldDef.name].type; if (_.contains($scope.types, fieldType)) { $scope.fieldDef.type = fieldType; } else if (!$scope.fieldDef.type) { $scope.fieldDef.type = $scope.types[0]; } } } }; });
'use strict'; angular.module('vleApp') .directive('fieldDrop', function (Dataset) { return { templateUrl: 'templates/fielddrop.html', restrict: 'E', scope: { fieldDef: '=', types: '=' }, controller: function ($scope) { $scope.removeField = function() { $scope.fieldDef.name = null; $scope.fieldDef.type = null; }; $scope.fieldDropped = function() { $scope.fieldDef.type = Dataset.stats[$scope.fieldDef.name].type; } } }; });
Revert " 版本信息及地址qobx.me --> qiniu.com" This reverts commit 118febda31caca805a1746d386cfc4f1568f5b08.
package com.qiniu.api.config; /** * The Config class is a global configuration file for the sdk, used for serve * side only. */ public class Config { public static final String CHARSET = "utf-8"; public static String USER_AGENT="qiniu java-sdk v6.0.0"; /** * You can get your accesskey from <a href="https://dev.qiniutek.com" * target="blank"> https://dev.qiniutek.com </a> */ public static String ACCESS_KEY = "<Please apply your access key>"; /** * You can get your accesskey from <a href="https://dev.qiniutek.com" * target="blank"> https://dev.qiniutek.com </a> */ public static String SECRET_KEY = "<Apply your secret key here, and keep it secret!>"; public static String RS_HOST = "http://rs.qbox.me"; public static String UP_HOST = "http://up.qbox.me"; public static String RSF_HOST = "http://rsf.qbox.me"; }
package com.qiniu.api.config; /** * The Config class is a global configuration file for the sdk, used for serve * side only. */ public class Config { public static final String CHARSET = "utf-8"; public static String USER_AGENT="qiniu java-sdk v6.1.2"; /** * You can get your accesskey from <a href="https://dev.qiniutek.com" * target="blank"> https://dev.qiniutek.com </a> */ public static String ACCESS_KEY = "<Please apply your access key>"; /** * You can get your accesskey from <a href="https://dev.qiniutek.com" * target="blank"> https://dev.qiniutek.com </a> */ public static String SECRET_KEY = "<Apply your secret key here, and keep it secret!>"; public static String RS_HOST = "http://rs.qiniu.com"; public static String UP_HOST = "http://up.qiniu.com"; public static String RSF_HOST = "http://rsf.qiniu.com"; }
Remove xfail from working test
# trivial_example.py # # Copyright 2014 BitVault. # # Reproduces the tests in trivial_example.rb from __future__ import print_function import pytest from random import randint from patchboard.tests.fixtures import (trivial_net_pb, trivial_net_resources, trivial_net_users) pytest.mark.usefixtures(trivial_net_pb, trivial_net_resources, trivial_net_users) def test_users_create(trivial_net_users): login = "foo-{0}".format(randint(1, 100000)) user = trivial_net_users.create({u'login': login})
# trivial_example.py # # Copyright 2014 BitVault. # # Reproduces the tests in trivial_example.rb from __future__ import print_function import pytest from random import randint from patchboard.tests.fixtures import (trivial_net_pb, trivial_net_resources, trivial_net_users) pytest.mark.usefixtures(trivial_net_pb, trivial_net_resources, trivial_net_users) @pytest.mark.xfail def test_users_create(trivial_net_users): login = "foo-{0}".format(randint(1, 100000)) user = trivial_net_users.create({u'login': login})
[Migrations] Add missing mysql check for migrations
<?php declare(strict_types=1); namespace Sylius\Bundle\CoreBundle\Migrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20220210135918 extends AbstractMigration { public function getDescription(): string { return 'Add by_guest field to mark orders made by guests'; } public function up(Schema $schema): void { $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_order ADD by_guest TINYINT(1) DEFAULT \'1\' NOT NULL'); $this->addSql('UPDATE sylius_order o SET o.by_guest = 0 WHERE o.customer_id IN (SELECT customer_id FROM sylius_shop_user)'); } public function down(Schema $schema): void { $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_order DROP by_guest'); } }
<?php declare(strict_types=1); namespace Sylius\Bundle\CoreBundle\Migrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20220210135918 extends AbstractMigration { public function getDescription(): string { return 'Add by_guest field to mark orders made by guests'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE sylius_order ADD by_guest TINYINT(1) DEFAULT \'1\' NOT NULL'); $this->addSql('UPDATE sylius_order o SET o.by_guest = 0 WHERE o.customer_id IN (SELECT customer_id FROM sylius_shop_user)'); } public function down(Schema $schema): void { $this->addSql('ALTER TABLE sylius_order DROP by_guest'); } }
Fix linting error (import extension missing)
import Map from '../../../src/ol/Map.js'; import View from '../../../src/ol/View.js'; import Static from '../../../src/ol/source/ImageStatic.js'; import { get as getProjection, transformExtent } from '../../../src/ol/proj.js'; import ImageLayer from '../../../src/ol/layer/Image.js'; const source = new Static({ url: '/data/tiles/osm/5/5/12.png', imageExtent: transformExtent([-123, 37, -122, 38], 'EPSG:4326', 'EPSG:3857'), projection: getProjection('EPSG:3857') }); new Map({ pixelRatio: 1, target: 'map', layers: [new ImageLayer({ source: source })], view: new View({ center: [-122.416667, 37.783333], zoom: 8, projection: 'EPSG:4326' }) }); render();
import Map from '../../../src/ol/Map.js'; import View from '../../../src/ol/View.js'; import Static from '../../../src/ol/source/ImageStatic.js'; import { get as getProjection, transformExtent } from '../../../src/ol/proj'; import ImageLayer from '../../../src/ol/layer/Image.js'; const source = new Static({ url: '/data/tiles/osm/5/5/12.png', imageExtent: transformExtent([-123, 37, -122, 38], 'EPSG:4326', 'EPSG:3857'), projection: getProjection('EPSG:3857') }); new Map({ pixelRatio: 1, target: 'map', layers: [new ImageLayer({ source: source })], view: new View({ center: [-122.416667, 37.783333], zoom: 8, projection: 'EPSG:4326' }) }); render();
Edit Swewify transition to only target transform property
//@flow import styled from "styled-components"; const random = (severity = 1): number => (Math.random() - 0.5) * severity; const randomTranslate = (n: number, s): number => random(s) * n; const randomRotate = (n: number, s): number => random(s) * n * 2; const randomScale = (n = 1, s): number => random(s) * n + 1; export const SkewSpan = styled.span.attrs({ style: ({ isActive, severity, theme }) => isActive ? { transformOrigin: "center center", transform: `scale(${randomScale( 0.25, severity )}) rotate(${randomRotate( 15, severity )}deg) translate(${randomTranslate( 0.125, severity )}em, ${randomTranslate(0.125, severity)}em)` } : { transform: "none" } })` ${({ isActive }: { isActive: boolean }) => ` display: inline-block; will-change: transform; transition: transform 0.2s; `} `;
//@flow import styled from "styled-components"; const random = (severity = 1): number => (Math.random() - 0.5) * severity; const randomTranslate = (n: number, s): number => random(s) * n; const randomRotate = (n: number, s): number => random(s) * n * 2; const randomScale = (n = 1, s): number => random(s) * n + 1; export const SkewSpan = styled.span.attrs({ style: ({ isActive, severity }) => isActive ? { transformOrigin: "center center", transform: `scale(${randomScale(0.25, severity)}) rotate(${randomRotate(15, severity)}deg) translate(${randomTranslate(0.125, severity)}em, ${randomTranslate(0.125, severity)}em)` } : { transform: "none" } })` ${({ isActive }: { isActive: boolean }) => ` display: inline-block; will-change: transform; transition: all 0.2s; `} `;
Use state.single to not upgrade npm
import pytest from salt.exceptions import CommandExecutionError @pytest.fixture(scope="module", autouse=True) def install_npm(sminion): try: sminion.functions.state.single("pkg.installed", name="npm") # Just name the thing we're looking for sminion.functions.npm # pylint: disable=pointless-statement except (CommandExecutionError, AttributeError) as e: pytest.skip("Unable to install npm - " + str(e)) @pytest.mark.slow_test @pytest.mark.destructive_test @pytest.mark.requires_network def test_removed_installed_cycle(sminion): project_version = "pm2@5.1.0" success = sminion.functions.npm.uninstall("pm2") assert success, "Unable to uninstall pm2 in prep for tests" ret = next( iter( sminion.functions.state.single( "npm.installed", name=project_version ).values() ) ) success = ret["result"] assert success, "Failed to states.npm.installed " + project_version + ret["comment"] ret = next( iter( sminion.functions.state.single("npm.removed", name=project_version).values() ) ) success = ret["result"] assert success, "Failed to states.npm.removed " + project_version
import pytest from salt.exceptions import CommandExecutionError @pytest.fixture(scope="module", autouse=True) def install_npm(sminion): try: sminion.functions.pkg.install("npm") # Just name the thing we're looking for sminion.functions.npm # pylint: disable=pointless-statement except (CommandExecutionError, AttributeError): pytest.skip("Unable to install npm") @pytest.mark.slow_test @pytest.mark.destructive_test @pytest.mark.requires_network def test_removed_installed_cycle(sminion): project_version = "pm2@5.1.0" success = sminion.functions.npm.uninstall("pm2") assert success, "Unable to uninstall pm2 in prep for tests" ret = next( iter( sminion.functions.state.single( "npm.installed", name=project_version ).values() ) ) success = ret["result"] assert success, "Failed to states.npm.installed " + project_version + ret["comment"] ret = next( iter( sminion.functions.state.single("npm.removed", name=project_version).values() ) ) success = ret["result"] assert success, "Failed to states.npm.removed " + project_version
Change README file format from .md to .rst
"""Setup script for pygoogling.""" from codecs import open as open_codec from os import path from setuptools import setup HERE = path.abspath(path.dirname(__file__)) with open_codec(path.join(HERE, 'README.rst'), encoding='utf-8') as f: LONG_DESCRIPTION = f.read() setup( name='pygoogling', version='0.0.2', description='Python library to do google search', long_description=LONG_DESCRIPTION, url='https://github.com/essanpupil/pygoogling', author='Ikhsan Noor Rosyidin', author_email='jakethitam1985@gmail.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], keywords='google search python module', py_modules=['pygoogling.googling'], install_requires=['bs4', 'requests', 'html5lib'], )
"""Setup script for pygoogling.""" from codecs import open as open_codec from os import path from setuptools import setup HERE = path.abspath(path.dirname(__file__)) with open_codec(path.join(HERE, 'README.md'), encoding='utf-8') as f: LONG_DESCRIPTION = f.read() setup( name='pygoogling', version='0.0.2', description='Python library to do google search', long_description=LONG_DESCRIPTION, url='https://github.com/essanpupil/pygoogling', author='Ikhsan Noor Rosyidin', author_email='jakethitam1985@gmail.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], keywords='google search python module', py_modules=['pygoogling.googling'], install_requires=['bs4', 'requests', 'html5lib'], )
Make the Bing images search pick a random top 20 image.
import random from aiohttp import BasicAuth from plumeria import config, scoped_config from plumeria.command import commands, CommandError from plumeria.config.common import nsfw from plumeria.message import Response from plumeria.util import http from plumeria.util.ratelimit import rate_limit SEARCH_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Image" api_key = config.create("bing", "key", fallback="unset", comment="An API key from Bing") @commands.register("image", "images", "i", category="Search") @rate_limit() async def image(message): """ Search Bing for an image and returns a URL to that image. Example:: /image socially awkward penguin """ q = message.content.strip() if not q: raise CommandError("Search term required!") r = await http.get(SEARCH_URL, params=[ ('$format', 'json'), ('$top', '20'), ('Adult', "'Off'" if scoped_config.get(nsfw, message.channel) else "'Strict'"), ('Query', "'{}'".format(q)), ], auth=BasicAuth("", password=api_key())) data = r.json()['d'] if len(data['results']): return Response(random.choice(data['results'])['MediaUrl']) else: raise CommandError("no results found")
from aiohttp import BasicAuth from plumeria import config, scoped_config from plumeria.command import commands, CommandError from plumeria.config.common import nsfw from plumeria.message import Response from plumeria.util import http from plumeria.util.ratelimit import rate_limit SEARCH_URL = "https://api.datamarket.azure.com/Bing/Search/v1/Image" api_key = config.create("bing", "key", fallback="unset", comment="An API key from Bing") @commands.register("image", "images", "i", category="Search") @rate_limit() async def image(message): """ Search Bing for an image and returns a URL to that image. Example:: /image socially awkward penguin """ q = message.content.strip() if not q: raise CommandError("Search term required!") r = await http.get(SEARCH_URL, params=[ ('$format', 'json'), ('$top', '10'), ('Adult', "'Off'" if scoped_config.get(nsfw, message.channel) else "'Strict'"), ('Query', "'{}'".format(q)), ], auth=BasicAuth("", password=api_key())) data = r.json()['d'] if len(data['results']): return Response(data['results'][0]['MediaUrl']) else: raise CommandError("no results found")
Synchronize access to static instance in clear()
package org.apache.lucene.spatial.base.context; import org.apache.lucene.spatial.base.context.simple.SimpleSpatialContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO -- i think there is a more standard way to approach this problem */ public class SpatialContextProvider { static final Logger log = LoggerFactory.getLogger(SpatialContextProvider.class); private static SpatialContext instance = null; private SpatialContextProvider() { } @SuppressWarnings("unchecked") public static synchronized SpatialContext getContext() { if (instance != null) { return instance; } String cname = System.getProperty("SpatialContextProvider"); if (cname != null) { try { Class<? extends SpatialContext> clazz = (Class<? extends SpatialContext>) Class.forName(cname); instance = clazz.newInstance(); return instance; } catch (Exception e) { //don't log full stack trace log.warn("Using default SpatialContext because: " + e.toString()); } } instance = new SimpleSpatialContext(); return instance; } static synchronized void clear() { instance = null; } }
package org.apache.lucene.spatial.base.context; import org.apache.lucene.spatial.base.context.simple.SimpleSpatialContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO -- i think there is a more standard way to approach this problem */ public class SpatialContextProvider { static final Logger log = LoggerFactory.getLogger(SpatialContextProvider.class); private static SpatialContext instance = null; private SpatialContextProvider() { } @SuppressWarnings("unchecked") public static synchronized SpatialContext getContext() { if (instance != null) { return instance; } String cname = System.getProperty("SpatialContextProvider"); if (cname != null) { try { Class<? extends SpatialContext> clazz = (Class<? extends SpatialContext>) Class.forName(cname); instance = clazz.newInstance(); return instance; } catch (Exception e) { //don't log full stack trace log.warn("Using default SpatialContext because: " + e.toString()); } } instance = new SimpleSpatialContext(); return instance; } static void clear() { instance = null; } }
Revert "Simplify the use of `phutil_get_library_root`" Summary: This reverts commit 67a17d0efb025665237d0d174d55d1887f9a6064. This doesn't actually work because the call to `phutil_get_current_library_name()` always occurs within `libphutil`. Test Plan: N/A Reviewers: epriestley, #blessed_reviewers Reviewed By: epriestley, #blessed_reviewers Subscribers: Korvin, epriestley Differential Revision: https://secure.phabricator.com/D13187
<?php function phutil_get_library_root($library) { $bootloader = PhutilBootloader::getInstance(); return $bootloader->getLibraryRoot($library); } function phutil_get_library_root_for_path($path) { foreach (Filesystem::walkToRoot($path) as $dir) { if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) { return $dir; } } return null; } function phutil_get_library_name_for_root($path) { $path = rtrim(Filesystem::resolvePath($path), '/'); $bootloader = PhutilBootloader::getInstance(); $libraries = $bootloader->getAllLibraries(); foreach ($libraries as $library) { $root = $bootloader->getLibraryRoot($library); if (rtrim(Filesystem::resolvePath($root), '/') == $path) { return $library; } } return null; } function phutil_get_current_library_name() { $caller = head(debug_backtrace(false)); $root = phutil_get_library_root_for_path($caller['file']); return phutil_get_library_name_for_root($root); } /** * Warns about use of deprecated behavior. */ function phutil_deprecated($what, $why) { PhutilErrorHandler::dispatchErrorMessage( PhutilErrorHandler::DEPRECATED, $what, array( 'why' => $why, )); }
<?php function phutil_get_library_root($library = null) { if (!$library) { $library = phutil_get_current_library_name(); } $bootloader = PhutilBootloader::getInstance(); return $bootloader->getLibraryRoot($library); } function phutil_get_library_root_for_path($path) { foreach (Filesystem::walkToRoot($path) as $dir) { if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) { return $dir; } } return null; } function phutil_get_library_name_for_root($path) { $path = rtrim(Filesystem::resolvePath($path), '/'); $bootloader = PhutilBootloader::getInstance(); $libraries = $bootloader->getAllLibraries(); foreach ($libraries as $library) { $root = $bootloader->getLibraryRoot($library); if (rtrim(Filesystem::resolvePath($root), '/') == $path) { return $library; } } return null; } function phutil_get_current_library_name() { $caller = head(debug_backtrace(false)); $root = phutil_get_library_root_for_path($caller['file']); return phutil_get_library_name_for_root($root); } /** * Warns about use of deprecated behavior. */ function phutil_deprecated($what, $why) { PhutilErrorHandler::dispatchErrorMessage( PhutilErrorHandler::DEPRECATED, $what, array( 'why' => $why, )); }
client: Add server link to thumbnails.
import React from 'react'; import { Card, CardHeader, CardMedia, CardTitle } from 'material-ui/Card'; const ServerThumbnail = ({ server, media }) => ( <Card className="thumb"> <a href={server.url}> <CardHeader title={server.name} subtitle={server.description} /> {media && ( <CardMedia overlay={( <CardTitle title={media.title} subtitle={media.artist} /> )} > <img src={media.media.thumbnail} /> </CardMedia> )} </a> <style jsx>{` .thumb { width: 360px; } `}</style> </Card> ); export default ServerThumbnail;
import React from 'react'; import { Card, CardHeader, CardTitle, CardMedia } from 'material-ui/Card'; const ServerThumbnail = ({ server, media }) => ( <Card className="thumb"> <CardHeader title={server.name} /> {media && ( <CardMedia overlay={( <CardTitle title={media.title} subtitle={media.artist} /> )} > <img src={media.media.thumbnail} /> </CardMedia> )} <style jsx>{` .thumb { width: 360px; } `}</style> </Card> ); export default ServerThumbnail;
Add more markdown syntax detection's Detect 'markdown gfm', 'multimarkdown' and 'markdown extended'. Closes #2
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2017 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended') cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 1.0' regex = (r'.+?:\s' r'(?P<line>\d+):\s' r'(?P<error>MD\d+)\s' r'(?P<message>.+)') multiline = False line_col_base = (1, 1) tempfile_suffix = 'md' error_stream = util.STREAM_STDERR selectors = {} word_re = None defaults = {} inline_settings = None inline_overrides = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2017 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = 'markdown' cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 1.0' regex = (r'.+?:\s' r'(?P<line>\d+):\s' r'(?P<error>MD\d+)\s' r'(?P<message>.+)') multiline = False line_col_base = (1, 1) tempfile_suffix = 'md' error_stream = util.STREAM_STDERR selectors = {} word_re = None defaults = {} inline_settings = None inline_overrides = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
Add method to encrypt files
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os GPG = 'gpg2' SERVER_KEY = '' # replace with gpg key ID of server key class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def encrypt_file(self, input_file, output_file, recipient): args = [GPG, '--output', output_file, '--recipient', recipient, '-sea', input_file] subprocess.call(args) def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
Use unresolved-incidents when page-status is empty
import requests from bs4 import BeautifulSoup from isserviceup.services.models.service import Service, Status class StatusPagePlugin(Service): def get_status(self): r = requests.get(self.status_url) if r.status_code != 200: return Status.unavailable b = BeautifulSoup(r.content, 'html.parser') page_status = b.find(class_='page-status') if page_status is None: if b.find(class_='unresolved-incidents'): return Status.major status = next(x for x in page_status.attrs['class'] if x.startswith('status-')) if status == 'status-none': return Status.ok elif status == 'status-critical': return Status.critical elif status == 'status-major': return Status.major elif status == 'status-minor': return Status.minor elif status == 'status-maintenance': return Status.maintenance else: raise Exception('unexpected status')
import requests from bs4 import BeautifulSoup from isserviceup.services.models.service import Service, Status class StatusPagePlugin(Service): def get_status(self): r = requests.get(self.status_url) if r.status_code != 200: return Status.unavailable b = BeautifulSoup(r.content, 'html.parser') status = next(x for x in b.find(class_='page-status').attrs['class'] if x.startswith('status-')) if status == 'status-none': return Status.ok elif status == 'status-critical': return Status.critical elif status == 'status-major': return Status.major elif status == 'status-minor': return Status.minor elif status == 'status-maintenance': return Status.maintenance else: raise Exception('unexpected status')
Fix type casts and incorrect numbers Replaced int casts to float casts to eliminate need for recasting to float. Was resetting dayHours to 0 when it should have been 0.0 and if hourIn was bigger than hourOut it was adding 24 when it should have been adding 12.
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = float(inSplit[0]) minuteIn = float(inSplit[1]) hourOut = float(outSplit[0]) minuteOut = float(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 12) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += newHour + (newMinutes / 60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0.0 print '\nTotal hours for the week: ' + str(weekHours)
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = int(inSplit[0]) minuteIn = int(inSplit[1]) hourOut = int(outSplit[0]) minuteOut = int(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 24) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += float(newHour) + (float(newMinutes)/60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0 print '\nTotal hours for the week: ' + str(weekHours)
Add __all__ in package init for the test runner
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Photutils is an Astropy affiliated package to provide tools for detecting and performing photometry of astronomical sources. It also has tools for background estimation, ePSF building, PSF matching, centroiding, and morphological measurements. """ import os # Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- if not _ASTROPY_SETUP_: # noqa from .aperture import * # noqa from .background import * # noqa from .centroids import * # noqa from .detection import * # noqa from .morphology import * # noqa from .psf import * # noqa from .segmentation import * # noqa __all__ = ['test'] # the test runner is defined in _astropy_init # Set the bibtex entry to the article referenced in CITATION. def _get_bibtex(): citation_file = os.path.join(os.path.dirname(__file__), 'CITATION') with open(citation_file, 'r') as citation: refs = citation.read().split('@misc')[1:] if len(refs) == 0: return '' bibtexreference = "@misc{0}".format(refs[0]) return bibtexreference __citation__ = __bibtex__ = _get_bibtex()
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Photutils is an Astropy affiliated package to provide tools for detecting and performing photometry of astronomical sources. It also has tools for background estimation, ePSF building, PSF matching, centroiding, and morphological measurements. """ import os # Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- if not _ASTROPY_SETUP_: # noqa from .aperture import * # noqa from .background import * # noqa from .centroids import * # noqa from .detection import * # noqa from .morphology import * # noqa from .psf import * # noqa from .segmentation import * # noqa # Set the bibtex entry to the article referenced in CITATION. def _get_bibtex(): citation_file = os.path.join(os.path.dirname(__file__), 'CITATION') with open(citation_file, 'r') as citation: refs = citation.read().split('@misc')[1:] if len(refs) == 0: return '' bibtexreference = "@misc{0}".format(refs[0]) return bibtexreference __citation__ = __bibtex__ = _get_bibtex()
Use Ember.get in Object Proxy This allows the use of POJOs
import Ember from 'ember'; import RecordKeeperMixin from 'ember-time-machine/mixins/time-machine'; import Record from 'ember-time-machine/-private/Record'; import { wrapValue, unwrapValue } from 'ember-time-machine/utils/value'; import { pathInGlobs } from 'ember-time-machine/utils/utils'; const { get } = Ember; export default Ember.ObjectProxy.extend(RecordKeeperMixin, { unknownProperty(key) { return wrapValue(this, key, this._super(...arguments)); }, setUnknownProperty(key, value) { let content = get(this, 'content'); let state = get(this, '_rootMachineState'); let path = get(this, '_path'); if (state && !pathInGlobs(path.concat(key).join('.'), get(state, 'frozenProperties'))) { this._addRecord(new Record({ target: content, path, key, before: get(content, key), after: value })); return this._super(key, unwrapValue(value)); } this.notifyPropertyChange(key); return; } });
import Ember from 'ember'; import RecordKeeperMixin from 'ember-time-machine/mixins/time-machine'; import Record from 'ember-time-machine/-private/Record'; import { wrapValue, unwrapValue } from 'ember-time-machine/utils/value'; import { pathInGlobs } from 'ember-time-machine/utils/utils'; export default Ember.ObjectProxy.extend(RecordKeeperMixin, { unknownProperty(key) { return wrapValue(this, key, this._super(...arguments)); }, setUnknownProperty(key, value) { let content = this.get('content'); let state = this.get('_rootMachineState'); let path = this.get('_path'); if (state && !pathInGlobs(path.concat(key).join('.'), state.get('frozenProperties'))) { this._addRecord(new Record({ target: content, path, key, before: content.get(key), after: value })); return this._super(key, unwrapValue(value)); } this.notifyPropertyChange(key); return; } });
Fix issue with "password" grant type, fix map order
package lv.ctco.cukes.oauth; import lv.ctco.cukes.core.internal.context.GlobalWorldFacade; import java.util.HashMap; import java.util.Map; public enum GrantType { client_credentials, password(OAuthCukesConstants.USER_NAME, OAuthCukesConstants.PASSWORD); private static final Map<String, String> attributeNameMapping = new HashMap<>(); static { attributeNameMapping.put(OAuthCukesConstants.USER_NAME, "username"); attributeNameMapping.put(OAuthCukesConstants.PASSWORD, "password"); } private String[] requiredAttributes; GrantType(String... requiredAttributes) { this.requiredAttributes = requiredAttributes; } public Map<String, String> getParameters(GlobalWorldFacade world) { Map<String, String> parameters = new HashMap<>(); parameters.put("grant_type", name()); for (String attribute : requiredAttributes) { parameters.put(attributeNameMapping.get(attribute), world.getOrThrow(attribute)); } return parameters; } }
package lv.ctco.cukes.oauth; import lv.ctco.cukes.core.internal.context.GlobalWorldFacade; import java.util.HashMap; import java.util.Map; public enum GrantType { client_credentials, password(OAuthCukesConstants.USER_NAME, OAuthCukesConstants.PASSWORD); private static final Map<String, String> attributeNameMapping = new HashMap<>(); static { attributeNameMapping.put("username", OAuthCukesConstants.USER_NAME); attributeNameMapping.put("password", OAuthCukesConstants.PASSWORD); } private String[] requiredAttributes; GrantType(String... requiredAttributes) { this.requiredAttributes = requiredAttributes; } public Map<String, String> getParameters(GlobalWorldFacade world) { Map<String, String> parameters = new HashMap<>(); parameters.put("grant_type", name()); for (String attribute : requiredAttributes) { parameters.put(attributeNameMapping.get(attribute), world.getOrThrow(attribute)); } return parameters; } }
Print everything on individual lines
#! /usr/bin/python from __future__ import print_function import db, os, sys, re import argparse import json from collections import namedtuple tf2_key = namedtuple('tf2_key', "server_account server_token steam_account host") # Initial setup of DB # We keep the connection & cursor seperate so we can do commits when we want dbPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tf2_keys.db") if not os.path.isfile(dbPath): db.createDB(dbPath) dbconn = db.startDB(dbPath) dbcursor = dbconn.cursor() # End initial setup parser = argparse.ArgumentParser(description='Manage TF2 keys') parser.add_argument('-a', '--add', nargs=3, help="Add key, format: <server_account> <server_token> <steam_account>" ) parser.add_argument('host', nargs='?', help="Host to retrieve keys for") args = parser.parse_args() if args.add: key = tf2_key(int(args.add[0]), args.add[1], args.add[2], args.host) db.addKey(dbcursor, key) elif args.host: key = db.getKey(dbcursor, args.host) for entry in key: print(entry) else: sys.exit(1) # Close the cursor & commit the DB one last time just for good measure dbcursor.close() dbconn.commit()
#! /usr/bin/python from __future__ import print_function import db, os, sys, re import argparse import json from collections import namedtuple tf2_key = namedtuple('tf2_key', "server_account server_token steam_account host") # Initial setup of DB # We keep the connection & cursor seperate so we can do commits when we want dbPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tf2_keys.db") if not os.path.isfile(dbPath): db.createDB(dbPath) dbconn = db.startDB(dbPath) dbcursor = dbconn.cursor() # End initial setup parser = argparse.ArgumentParser(description='Manage TF2 keys') parser.add_argument('-a', '--add', nargs=3, help="Add key, format: <server_account> <server_token> <steam_account>" ) parser.add_argument('host', nargs='?', help="Host to retrieve keys for") args = parser.parse_args() if args.add: key = tf2_key(int(args.add[0]), args.add[1], args.add[2], args.host) db.addKey(dbcursor, key) elif args.host: print(json.dumps(tf2_key(*key))) key = db.getKey(dbcursor, args.host) else: sys.exit(1) # Close the cursor & commit the DB one last time just for good measure dbcursor.close() dbconn.commit()
Document project is stable and ready for use in production
#!/usr/bin/env python from setuptools import setup #from distutils.core import setup setup(name='imagesize', version='0.7.1', description='Getting image size from png/jpeg/jpeg2000/gif file', long_description=''' It parses image files' header and return image size. * PNG * JPEG * JPEG2000 * GIF This is a pure Python library. ''', author='Yoshiki Shibukawa', author_email='yoshiki at shibu.jp', url='https://github.com/shibukawa/imagesize_py', license="MIT", py_modules=['imagesize'], test_suite='test', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Operating System :: OS Independent', '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', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Multimedia :: Graphics' ] )
#!/usr/bin/env python from setuptools import setup #from distutils.core import setup setup(name='imagesize', version='0.7.1', description='Getting image size from png/jpeg/jpeg2000/gif file', long_description=''' It parses image files' header and return image size. * PNG * JPEG * JPEG2000 * GIF This is a pure Python library. ''', author='Yoshiki Shibukawa', author_email='yoshiki at shibu.jp', url='https://github.com/shibukawa/imagesize_py', license="MIT", py_modules=['imagesize'], test_suite='test', classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Operating System :: OS Independent', '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', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Multimedia :: Graphics' ] )
Change copyright in Apache 2 license to 2013
/** * Copyright © 2011-2013 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.phenotype.dao; /** * * Ontology DB data access manager interface. * * @author Gautier Koscielny (EMBL-EBI) <koscieln@ebi.ac.uk> * @since February 2012 */ import java.util.List; public interface OntodbDAO { /** * Get all cell terms * @return all cell terms */ public List<String> getAllCellTerms(); }
/** * Copyright © 2011-2012 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.phenotype.dao; /** * * Ontology DB data access manager interface. * * @author Gautier Koscielny (EMBL-EBI) <koscieln@ebi.ac.uk> * @since February 2012 */ import java.util.List; public interface OntodbDAO { /** * Get all cell terms * @return all cell terms */ public List<String> getAllCellTerms(); }
Update the package for godns
package main import ( "net" "dns" ) func main() { // A simple example. Publish an A record for my router at 192.168.1.254. mdns.PublishA("router.local.", 3600, net.IPv4(192, 168, 1, 254)) // A more compilcated example. Publish a SVR record for ssh running on port // 22 for my home NAS. // Publish an A record as before mdns.PublishA("stora.local.", 3600, net.IPv4(192, 168, 1, 200)) // Publish a PTR record for the _ssh._tcp DNS-SD type mdns.PublishPTR("_ssh._tcp.local.", 3600, "stora._ssh._tcp.local.") // Publish a SRV record typing the _ssh._tcp record to an A record and a port. mdns.PublishSRV("stora._ssh._tcp.local.", 3600, "stora.local.", 22) // Most mDNS browsing tools expect a TXT record for the service even if there // are not records defined by RFC 2782. mdns.PublishTXT("stora._ssh._tcp.local.", 3600, "") select {} }
package main import ( "net" "github.com/davecheney/mdns" ) func main() { // A simple example. Publish an A record for my router at 192.168.1.254. mdns.PublishA("router.local.", 3600, net.IPv4(192, 168, 1, 254)) // A more compilcated example. Publish a SVR record for ssh running on port // 22 for my home NAS. // Publish an A record as before mdns.PublishA("stora.local.", 3600, net.IPv4(192, 168, 1, 200)) // Publish a PTR record for the _ssh._tcp DNS-SD type mdns.PublishPTR("_ssh._tcp.local.", 3600, "stora._ssh._tcp.local.") // Publish a SRV record typing the _ssh._tcp record to an A record and a port. mdns.PublishSRV("stora._ssh._tcp.local.", 3600, "stora.local.", 22) // Most mDNS browsing tools expect a TXT record for the service even if there // are not records defined by RFC 2782. mdns.PublishTXT("stora._ssh._tcp.local.", 3600, "") select {} }
Remove the (dodgy) function to convert from an image to data.
""" The FVCOM Python toolbox (PyFvcom) """ __version__ = '1.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import numpy so we have it across the board. import numpy as np # Import everything! from PyFVCOM import buoy_tools from PyFVCOM import cst_tools from PyFVCOM import ctd_tools from PyFVCOM import grid_tools from PyFVCOM import ll2utm from PyFVCOM import ocean_tools from PyFVCOM import stats_tools from PyFVCOM import tide_tools from PyFVCOM import tidal_ellipse from PyFVCOM import process_results from PyFVCOM import read_results # External TAPPY now instead of my bundled version. Requires my forked version # of TAPPY from https://github.com/pwcazenave/tappy or # http://gitlab.em.pml.ac.uk/pica/tappy. from tappy import tappy # For backwards-compatibility. process_FVCOM_results = process_results read_FVCOM_results = read_results
""" The FVCOM Python toolbox (PyFvcom) """ __version__ = '1.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import numpy so we have it across the board. import numpy as np # Import everything! from PyFVCOM import buoy_tools from PyFVCOM import cst_tools from PyFVCOM import ctd_tools from PyFVCOM import grid_tools from PyFVCOM import img2xyz from PyFVCOM import ll2utm from PyFVCOM import ocean_tools from PyFVCOM import stats_tools from PyFVCOM import tide_tools from PyFVCOM import tidal_ellipse from PyFVCOM import process_results from PyFVCOM import read_results # External TAPPY now instead of my bundled version. Requires my forked version # of TAPPY from https://github.com/pwcazenave/tappy or # http://gitlab.em.pml.ac.uk/pica/tappy. from tappy import tappy # For backwards-compatibility. process_FVCOM_results = process_results read_FVCOM_results = read_results
Document prerequisites for the algorithm
package algorithms.trees; public class TreeHeightCalculator { private final int parents[]; /** * @param parents * defines index of parent for each node. Value -1 determines a root node */ public TreeHeightCalculator(int parents[]) { this.parents = parents; } /** * assumptions: there is exactly one root and the input represents a tree */ public int computeHeight() { TreeNode root = createTree(); return recursiveHeightCalculation(root); } private TreeNode createTree() { TreeNode[] nodes = new TreeNode[parents.length]; for (int i = 0; i < parents.length; i++) { nodes[i] = new TreeNode(); } TreeNode root = null; for (int i = 0; i < parents.length; i++) { int parentId = parents[i]; if (parentId >= 0) { nodes[i].setParent(nodes[parentId]); nodes[parentId].getChildren().add(nodes[i]); } else { root = nodes[i]; } } return root; } private int recursiveHeightCalculation(TreeNode treeNode) { int max = 0; for (TreeNode child : treeNode.getChildren()) { int newMax = recursiveHeightCalculation(child); if (newMax > max) { max = newMax; } } return ++max; } }
package algorithms.trees; public class TreeHeightCalculator { private final int parents[]; /** * @param parents * defines index of parent for each node. Value -1 determines a root node */ public TreeHeightCalculator(int parents[]) { this.parents = parents; } public int computeHeight() { TreeNode root = createTree(); return recursiveHeightCalculation(root); } private TreeNode createTree() { TreeNode[] nodes = new TreeNode[parents.length]; for (int i = 0; i < parents.length; i++) { nodes[i] = new TreeNode(); } TreeNode root = null; for (int i = 0; i < parents.length; i++) { int parentId = parents[i]; if (parentId >= 0) { nodes[i].setParent(nodes[parentId]); nodes[parentId].getChildren().add(nodes[i]); } else { root = nodes[i]; } } return root; } private int recursiveHeightCalculation(TreeNode treeNode) { int max = 0; for (TreeNode child : treeNode.getChildren()) { int newMax = recursiveHeightCalculation(child); if (newMax > max) { max = newMax; } } return ++max; } }
Add another check for missing workflow
import { expeditions } from 'constants/expeditions'; const RECENT_EXPEDITIONS_LENGTH = 4; export function findExpedition(key) { return expeditions[key] ? expeditions[key] : expeditions.DEFAULT; } export const expeditionsInGroup = (group, allWorkflows) => allWorkflows.filter(e => e.display_name.startsWith(group)); export function recentExpeditions(allWorkflows, classifications) { const recent = classifications.map(c => c.links.workflow) .filter((v, i, self) => self.indexOf(v) === i) .map(id => { const workflow = allWorkflows.find(w => w.id === id); if (workflow) { const expedition = findExpedition(workflow.display_name); expedition.id = workflow.id; expedition.active = workflow.active; return expedition; } }); if (recent.length > RECENT_EXPEDITIONS_LENGTH) { recent.length = RECENT_EXPEDITIONS_LENGTH; } return recent; }
import { expeditions } from 'constants/expeditions'; const RECENT_EXPEDITIONS_LENGTH = 4; export function findExpedition(key) { return expeditions[key] ? expeditions[key] : expeditions.DEFAULT; } export const expeditionsInGroup = (group, allWorkflows) => allWorkflows.filter(e => e.display_name.startsWith(group)); export function recentExpeditions(allWorkflows, classifications) { const recent = classifications.map(c => c.links.workflow) .filter((v, i, self) => self.indexOf(v) === i) .map(id => { const workflow = allWorkflows.find(w => w.id === id); const expedition = findExpedition(workflow.display_name); expedition.id = workflow.id; expedition.active = workflow.active; return expedition; }); if (recent.length > RECENT_EXPEDITIONS_LENGTH) { recent.length = RECENT_EXPEDITIONS_LENGTH; } return recent; }
Add length to Buffer.concat invoke Add length to Buffer.concat invoke. That should increase performance according to the node documenation. If totalLength is not provided, it is calculated from the Buffer instances in list. This however causes an additional loop to be executed in order to calculate the totalLength, so it is faster to provide the length explicitly if it is already known.
const crypto = require('crypto'); const {debugLog} = require('./utilities'); /** * memHandler - In memory upload handler * @param {Object} options * @param {String} fieldname * @param {String} filename * @returns {Object} */ module.exports = (options, fieldname, filename) => { let buffers = []; let fileSize = 0; // eslint-disable-line let hash = crypto.createHash('md5'); const getBuffer = () => Buffer.concat(buffers, fileSize); const emptyFunc = () => ''; return { dataHandler: (data) => { buffers.push(data); hash.update(data); fileSize += data.length; debugLog(options, `Uploading ${fieldname} -> ${filename}, bytes: ${fileSize}`); }, getBuffer: getBuffer, getFilePath: emptyFunc, getFileSize: () => fileSize, getHash: () => hash.digest('hex'), complete: getBuffer, cleanup: emptyFunc }; };
const crypto = require('crypto'); const {debugLog} = require('./utilities'); /** * memHandler - In memory upload handler * @param {Object} options * @param {String} fieldname * @param {String} filename * @returns {Object} */ module.exports = (options, fieldname, filename) => { let buffers = []; let fileSize = 0; // eslint-disable-line let hash = crypto.createHash('md5'); const getBuffer = () => Buffer.concat(buffers); const emptyFunc = () => ''; return { dataHandler: (data) => { buffers.push(data); hash.update(data); fileSize += data.length; debugLog(options, `Uploading ${fieldname} -> ${filename}, bytes: ${fileSize}`); }, getBuffer: getBuffer, getFilePath: emptyFunc, getFileSize: () => fileSize, getHash: () => hash.digest('hex'), complete: getBuffer, cleanup: emptyFunc }; };
Fix overshadowed tests by giving test functions unique names
""" :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import PaymentState from testfixtures.shop_order import create_order from testfixtures.user import create_user def test_is_open(): payment_state = PaymentState.open order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == True assert order.is_canceled == False assert order.is_paid == False def test_is_canceled(): payment_state = PaymentState.canceled order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == False assert order.is_canceled == True assert order.is_paid == False def test_is_paid(): payment_state = PaymentState.paid order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == False assert order.is_canceled == False assert order.is_paid == True # helpers def create_order_with_payment_state(payment_state): user = create_user(42) party_id = 'acme-party-2016' placed_by = user order = create_order(party_id, placed_by) order.payment_state = payment_state return order
""" :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import PaymentState from testfixtures.shop_order import create_order from testfixtures.user import create_user def test_is_open(): payment_state = PaymentState.open order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == True assert order.is_canceled == False assert order.is_paid == False def test_is_open(): payment_state = PaymentState.canceled order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == False assert order.is_canceled == True assert order.is_paid == False def test_is_open(): payment_state = PaymentState.paid order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == False assert order.is_canceled == False assert order.is_paid == True # helpers def create_order_with_payment_state(payment_state): user = create_user(42) party_id = 'acme-party-2016' placed_by = user order = create_order(party_id, placed_by) order.payment_state = payment_state return order
Rename settings' `extensions.values` to `sandbox.selectionListFetchers`.
// Register 'usergroups' special setting values fetcher. // Allows to use `values: usergroups` in setting definitions. 'use strict'; var _ = require('lodash'); module.exports = function (N) { function usergroups(env, callback) { N.models.users.UserGroup .find() .select('_id short_name') .sort('_id') .setOptions({ lean: true }) .exec(function (err, groups) { callback(err, _.map(groups, function (group) { var translation = 'admin.users.usergroup_names.' + group.short_name; return { name: group.short_name , value: group._id , title: env && env.helpers.t.exists(translation) ? env.helpers.t(translation) : group.short_name }; })); }); } N.wire.before('init:settings', function (sandbox) { sandbox.selectionListFetchers['usergroups'] = usergroups; }); };
// Register 'usergroups' special setting values fetcher. // Allows to use `values: usergroups` in setting definitions. 'use strict'; var _ = require('lodash'); module.exports = function (N) { function usergroups(env, callback) { N.models.users.UserGroup .find() .select('_id short_name') .sort('_id') .setOptions({ lean: true }) .exec(function (err, groups) { callback(err, _.map(groups, function (group) { var translation = 'admin.users.usergroup_names.' + group.short_name; return { name: group.short_name , value: group._id , title: env && env.helpers.t.exists(translation) ? env.helpers.t(translation) : group.short_name }; })); }); } N.wire.before('init:settings', function (extensions) { extensions.values['usergroups'] = usergroups; }); };
Add hooks to the right place
module.exports = { parser: "@typescript-eslint/parser", plugins: ["react-hooks"], extends: [ "plugin:react/recommended", "plugin:@typescript-eslint/recommended", "prettier/@typescript-eslint", // Disables rules from @typescript-eslint that would conflict with Prettier "plugin:prettier/recommended" // Make sure this always the last config to be loaded. ], parserOptions: { ecmaVersion: 2018, sourceType: "module", ecmaFeatures: { jsx: true } }, rules: { camelcase: "off", "@typescript-eslint/camelcase": "off", "@typescript-eslint/no-inferrable-types": "off", "@typescript-eslint/no-explicit-any": "off", "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn" }, settings: { react: { version: "detect" } } };
module.exports = { parser: "@typescript-eslint/parser", extends: [ "plugin:react/recommended", "plugin:react-hooks", "plugin:@typescript-eslint/recommended", "prettier/@typescript-eslint", // Disables rules from @typescript-eslint that would conflict with Prettier "plugin:prettier/recommended" // Make sure this always the last config to be loaded. ], parserOptions: { ecmaVersion: 2018, sourceType: "module", ecmaFeatures: { jsx: true } }, rules: { camelcase: "off", "@typescript-eslint/camelcase": "off", "@typescript-eslint/no-inferrable-types": "off", "@typescript-eslint/no-explicit-any": "off", "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn" }, settings: { react: { version: "detect" } } };
DROP DATABASE IF EXISTS in tests.
import sys import os import argparse def write_csv(filename, nb_users): with open(filename, "w") as csv_file: csv_file.write("SEQUENTIAL\n") for x in xrange(nb_users): line = "{uname};localhost;[authentication username={uname} password={uname}];\n".format(uname=str(1000+x)) csv_file.write(line) def write_sql(filename, nb_users): with open(filename, "w") as sql_file: header = """DROP DATABASE IF EXISTS tests; CREATE DATABASE tests; USE tests; CREATE TABLE accounts (user VARCHAR(20),password VARCHAR(20));""" sql_file.write(header) for x in xrange(nb_users): line = """INSERT into accounts (user, password) VALUES ("{uname}", "{uname}");\n""".format(uname=str(1000+x)) sql_file.write(line) def main(argv=None): if argv == None: argv = sys.argv argparser = argparse.ArgumentParser(description="Prepare load tests for Flexisip.") argparser.add_argument('-N', '--users', help="How many different users should be registering to flexisip", dest="users", default=5000) args, additional_args = argparser.parse_known_args() write_csv("users.csv", args.users) write_sql("users.sql", args.users) if __name__ == '__main__': main()
import sys import os import argparse def write_csv(filename, nb_users): with open(filename, "w") as csv_file: csv_file.write("SEQUENTIAL\n") for x in xrange(nb_users): line = "{uname};localhost;[authentication username={uname} password={uname}];\n".format(uname=str(1000+x)) csv_file.write(line) def write_sql(filename, nb_users): with open(filename, "w") as sql_file: header = """DROP DATABASE tests; CREATE DATABASE tests; USE tests; CREATE TABLE accounts (user VARCHAR(20),password VARCHAR(20));""" sql_file.write(header) for x in xrange(nb_users): line = """INSERT into accounts (user, password) VALUES ("{uname}", "{uname}");\n""".format(uname=str(1000+x)) sql_file.write(line) def main(argv=None): if argv == None: argv = sys.argv argparser = argparse.ArgumentParser(description="Prepare load tests for Flexisip.") argparser.add_argument('-N', '--users', help="How many different users should be registering to flexisip", dest="users", default=5000) args, additional_args = argparser.parse_known_args() write_csv("users.csv", args.users) write_sql("users.sql", args.users) if __name__ == '__main__': main()
Fix Nest Leafs on Energy page Remove GROUP BY date(date) ORDER BY date ASC Old sql included a group by date that resulted in there always being one leaf per day (if any)
<?php $ini = parse_ini_file("params.ini", true); date_default_timezone_set($ini['common']['timezone']); $date = date('Y-m-d H:i:s', time()); $connection = mysqli_connect($ini['mysql']['mysql_hostname'],$ini['mysql']['mysql_username'],$ini['mysql']['mysql_password'],$ini['mysql']['mysql_database']) or die("Connection Error " . mysqli_error($connection)); $sql = "SELECT SUM(nest_heat_state) AS IS_HEATING, SUM(if(auto_away = '1', 1, 0)) AS AT_HOME, SUM(if(auto_away = '0', 1, 0)) AS AUTO_AWAY, (SELECT COUNT(*) AS leaf FROM (SELECT leaf FROM status WHERE leaf = 1 AND (DATE(date) BETWEEN (date('".$_GET['start']."')) AND (date('".$_GET['end']."'))) ) status) AS LEAF FROM status WHERE (DATE(date) BETWEEN (date('".$_GET['start']."')) AND (date('".$_GET['end']."')));"; $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection)); $rows = array(); while($r = mysqli_fetch_assoc($result)) { $rows[] = $r; } mysqli_close($connection); echo json_encode($rows); ?>
<?php $ini = parse_ini_file("params.ini", true); date_default_timezone_set($ini['common']['timezone']); $date = date('Y-m-d H:i:s', time()); $connection = mysqli_connect($ini['mysql']['mysql_hostname'],$ini['mysql']['mysql_username'],$ini['mysql']['mysql_password'],$ini['mysql']['mysql_database']) or die("Connection Error " . mysqli_error($connection)); $sql = "SELECT SUM(nest_heat_state) AS IS_HEATING, SUM(if(auto_away = '1', 1, 0)) AS AT_HOME, SUM(if(auto_away = '0', 1, 0)) AS AUTO_AWAY, (SELECT COUNT(*) AS leaf FROM (SELECT leaf FROM status WHERE leaf = 1 AND (DATE(date) BETWEEN (date('".$_GET['start']."')) AND (date('".$_GET['end']."'))) GROUP BY date(date) ORDER BY date ASC) status) AS LEAF FROM status WHERE (DATE(date) BETWEEN (date('".$_GET['start']."')) AND (date('".$_GET['end']."')));"; $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection)); $rows = array(); while($r = mysqli_fetch_assoc($result)) { $rows[] = $r; } mysqli_close($connection); echo json_encode($rows); ?>
Fix incorrect column in IndexFile model * Change `reference` to `index`. * Removed unused import of `enum`
from sqlalchemy import Column, Enum, Integer, String from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String, nullable=False) index = Column(String, nullable=False) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \ f"size={self.size}"
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String, nullable=False) index = Column(String, nullable=False) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, reference={self.reference}, type={self.type}, " \ f"size={self.size}"
Fix for webpack output location on CI server (part deux)
const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); module.exports = { // webpack folder's entry js - excluded from jekll's build process. entry: './webpack/entry.js', output: { // we're going to put the generated file in the assets folder so jekyll will grab it. path: path.resolve(__dirname, '../assets/js/'), filename: 'bundle.js', }, stats: { assets: true, children: false, chunks: false, errors: true, errorDetails: true, modules: false, timings: true, colors: true, }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { js: 'babel?presets[]=es2015', }, }, }, { test: /\.js?$/, exclude: /(node_modules)/, loader: 'babel-loader', }, ], }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js', }, extensions: ['*', '.js', '.vue', '.json'], }, plugins: [ new VueLoaderPlugin(), ], };
const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); module.exports = { // webpack folder's entry js - excluded from jekll's build process. entry: './webpack/entry.js', output: { // we're going to put the generated file in the assets folder so jekyll will grab it. path: path.resolve(__dirname, './assets/js/'), filename: 'bundle.js', }, stats: { assets: true, children: false, chunks: false, errors: true, errorDetails: true, modules: false, timings: true, colors: true, }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { js: 'babel?presets[]=es2015', }, }, }, { test: /\.js?$/, exclude: /(node_modules)/, loader: 'babel-loader', }, ], }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js', }, extensions: ['*', '.js', '.vue', '.json'], }, plugins: [ new VueLoaderPlugin(), ], };
Clear payment type form data after succesfully saving a modified payment type
import { takeLatest, call, put } from 'redux-saga/effects'; import axios from 'axios'; import { MODIFY_PAYMENTTYPE_REQUEST, MODIFY_PAYMENTTYPE_RECEIVE, MODIFY_PAYMENTTYPE_FAILURE, CLEAR_PAYMENT_TYPE_FORM, } from '../actiontypes'; function doModifyPaymenttype(paymenttype) { return axios.post('/ukelonn/api/admin/paymenttype/modify', paymenttype); } function* requestReceiveModifyPaymenttypeSaga(action) { try { const response = yield call(doModifyPaymenttype, action.payload); const paymenttypes = (response.headers['content-type'] == 'application/json') ? response.data : []; yield put(MODIFY_PAYMENTTYPE_RECEIVE(paymenttypes)); } catch (error) { yield put(MODIFY_PAYMENTTYPE_FAILURE(error)); } } function* clearPaymenttypeForm() { yield put(CLEAR_PAYMENT_TYPE_FORM()); } export default function* modifyPaymenttypeSaga() { yield takeLatest(MODIFY_PAYMENTTYPE_REQUEST, requestReceiveModifyPaymenttypeSaga); yield takeLatest(MODIFY_PAYMENTTYPE_RECEIVE, clearPaymenttypeForm); }
import { takeLatest, call, put } from 'redux-saga/effects'; import axios from 'axios'; import { MODIFY_PAYMENTTYPE_REQUEST, MODIFY_PAYMENTTYPE_RECEIVE, MODIFY_PAYMENTTYPE_FAILURE, } from '../actiontypes'; function doModifyPaymenttype(paymenttype) { return axios.post('/ukelonn/api/admin/paymenttype/modify', paymenttype); } function* requestReceiveModifyPaymenttypeSaga(action) { try { const response = yield call(doModifyPaymenttype, action.payload); const paymenttypes = (response.headers['content-type'] == 'application/json') ? response.data : []; yield put(MODIFY_PAYMENTTYPE_RECEIVE(paymenttypes)); } catch (error) { yield put(MODIFY_PAYMENTTYPE_FAILURE(error)); } } export default function* modifyPaymenttypeSaga() { yield takeLatest(MODIFY_PAYMENTTYPE_REQUEST, requestReceiveModifyPaymenttypeSaga); }
Create tables on application start
import logging import sys from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine import virtool.models logger = logging.getLogger(__name__) async def connect(postgres_connection_string: str) -> AsyncConnection: """ Create a connection of Postgres. :param postgres_connection_string: the postgres connection string :return: an AsyncConnection object """ if not postgres_connection_string.startswith("postgresql+asyncpg://"): logger.fatal("Invalid PostgreSQL connection string") sys.exit(1) try: postgres = create_async_engine(postgres_connection_string) await virtool.models.create_tables(postgres) async with postgres.connect() as connection: await check_version(connection) return connection except ConnectionRefusedError: logger.fatal("Could not connect to PostgreSQL: Connection refused") sys.exit(1) async def check_version(connection: AsyncConnection): """ Check and log the Postgres sever version. :param connection:an AsyncConnection object """ info = await connection.execute(text('SHOW server_version')) version = info.first()[0].split()[0] logger.info(f"Found PostgreSQL {version}")
import logging import sys from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine logger = logging.getLogger(__name__) async def connect(postgres_connection_string: str) -> AsyncConnection: """ Create a connection of Postgres. :param postgres_connection_string: the postgres connection string :return: an AsyncConnection object """ if not postgres_connection_string.startswith("postgresql+asyncpg://"): logger.fatal("Invalid PostgreSQL connection string") sys.exit(1) try: postgres = create_async_engine(postgres_connection_string) async with postgres.connect() as connection: await check_version(connection) return connection except ConnectionRefusedError: logger.fatal("Could not connect to PostgreSQL: Connection refused") sys.exit(1) async def check_version(connection: AsyncConnection): """ Check and log the Postgres sever version. :param connection:an AsyncConnection object """ info = await connection.execute(text('SHOW server_version')) version = info.first()[0].split()[0] logger.info(f"Found PostgreSQL {version}")
Allow for setting path as part of options object as well as as a function parameter
var path = require('path'), static = require('serve-static'); module.exports = { setup: function (app, assetpath, options) { if (arguments.length === 2 && typeof assetpath === 'object') { options = assetpath; assetpath = ''; } options = options || {}; assetpath = assetpath || options.path || '/govuk-assets'; app.use(assetpath, static(path.join(__dirname, './node_modules/govuk_template_mustache/assets'), options)); app.use(function (req, res, next) { res.locals.govukAssetPath = assetpath + '/'; res.locals.partials = res.locals.partials || {}; res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template'); next(); }); } };
var path = require('path'), static = require('serve-static'); module.exports = { setup: function (app, assetpath, options) { if (arguments.length === 2 && typeof assetpath === 'object') { options = assetpath; assetpath = ''; } assetpath = assetpath || '/govuk-assets'; options = options || {}; app.use(assetpath, static(path.join(__dirname, './node_modules/govuk_template_mustache/assets'), options)); app.use(function (req, res, next) { res.locals.govukAssetPath = assetpath + '/'; res.locals.partials = res.locals.partials || {}; res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template'); next(); }); } };
Remove cards == [] from Deck()
var Deck = function() { this.cards = []; }; Deck.prototype.addCard = function(card) { this.cards.push(card); }; Deck.prototype.nextCard = function(card) { return this.cards.pop(); }; Deck.prototype.fetchCards = function() { var request = $.ajax({ method: 'POST', url: '/decks/new', data: $("input").serialize() }) .done(function(resp) { deckCallBack(resp); }) }; Deck.prototype.updateHistory = function(card, state) { // Send back the result of the card json_card = { card_id: card["id"], card_name: card["name"], card_state: state } $.ajax({ method: 'PUT', url: '/decks/' + card["id"] + '/update', data: json_card }) };
var Deck = function(cards = []) { this.cards = cards; }; Deck.prototype.addCard = function(card) { this.cards.push(card); }; Deck.prototype.nextCard = function(card) { return this.cards.pop(); }; Deck.prototype.fetchCards = function() { var request = $.ajax({ method: 'POST', url: '/decks/new', data: $("input").serialize() }) .done(function(resp) { deckCallBack(resp); }) }; Deck.prototype.updateHistory = function(card, state) { // Send back the result of the card json_card = { card_id: card["id"], card_name: card["name"], card_state: state } $.ajax({ method: 'PUT', url: '/decks/' + card["id"] + '/update', data: json_card }) };