text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update tests so they pass
package main import ( "errors" "testing" . "github.com/franela/goblin" ) func Test(t *testing.T) { g := Goblin(t) g.Describe("Run", func() { g.Describe(".command_for_file", func() { g.Describe("when a filename is given with a known extension", func() { g.It("should be a valid command", func() { command, err := commandForFile("hello.rb") g.Assert(command).Equal("ruby hello.rb") g.Assert(err).Equal(nil) }) }) g.Describe("when a filename is given without a known extension", func() { g.It("should return an error", func() { _, err := commandForFile("hello.unknown") g.Assert(err).Equal(errors.New("run could not determine how to run this file because it does not have a known extension")) }) }) g.Describe("when a filename is given without any extension", func() { g.It("should return an error", func() { _, err := commandForFile("hello") g.Assert(err).Equal(errors.New("run could not determine how to run this file because it does not have a known extension")) }) }) }) }) }
package main import ( "testing" . "github.com/franela/goblin" ) func Test(t *testing.T) { g := Goblin(t) g.Describe("Run", func() { g.Describe(".command_for_file", func() { g.Describe("when a filename is given with a known extension", func() { g.It("should be a valid command", func() { g.Assert(Run.command_for_file("hello.rb")).Equal("ruby hello.rb") }) }) g.Describe("when a filename is given without a known extension", func() { g.It("should be nil", func() { g.Assert(Run.command_for_file("hello.unknown")).Equal(nil) }) }) g.Describe("when a filename is given without any extension", func() { g.It("should be nil", func() { g.Assert(Run.command_for_file("hello")).Equal(nil) }) }) }) }) }
Use the updated file names for image components in import statements
import ImgComponent from 'ember-cli-image/components/img-component'; import BackgroundImageComponent from 'ember-cli-image/components/background-image-component'; import LazyImageMixin from 'ember-cli-image-lazy/mixins/lazy-image-mixin'; export function initialize() { var hasDOM = typeof document !== 'undefined'; if (typeof ImgComponent.enableLazyLoading === 'undefined') { ImgComponent.reopenClass({ enableLazyLoading: hasDOM }); } if (typeof BackgroundImageComponent.enableLazyLoading === 'undefined') { BackgroundImageComponent.reopenClass({ enableLazyLoading: hasDOM }); } if (ImgComponent.enableLazyLoading) { ImgComponent.reopen( LazyImageMixin ); } if (BackgroundImageComponent.enableLazyLoading) { BackgroundImageComponent.reopen( LazyImageMixin ); } } export default { name: 'image-lazy', initialize: initialize };
import ImgComponent from 'ember-cli-image/components/x-img'; import BackgroundImageComponent from 'ember-cli-image/components/background-image'; import LazyImageMixin from 'ember-cli-image-lazy/mixins/lazy-image-mixin'; export function initialize() { var hasDOM = typeof document !== 'undefined'; if (typeof ImgComponent.enableLazyLoading === 'undefined') { ImgComponent.reopenClass({ enableLazyLoading: hasDOM }); } if (typeof BackgroundImageComponent.enableLazyLoading === 'undefined') { BackgroundImageComponent.reopenClass({ enableLazyLoading: hasDOM }); } if (ImgComponent.enableLazyLoading) { ImgComponent.reopen( LazyImageMixin ); } if (BackgroundImageComponent.enableLazyLoading) { BackgroundImageComponent.reopen( LazyImageMixin ); } } export default { name: 'image-lazy', initialize: initialize };
Use refs to access child components
import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { constructor(){ super(); this.state = { red: 0, green: 0, blue: 0 }; this.update = this.update.bind(this); } update(e){ this.setState({ red: ReactDOM.findDOMNode(this.refs.red.refs.input).value, green: ReactDOM.findDOMNode(this.refs.green.refs.input).value, blue: ReactDOM.findDOMNode(this.refs.blue.refs.input).value }); } render() { return( <div> <Slider ref="red" update={this.update} /> {this.state.red} <Slider ref="green" update={this.update} /> {this.state.green} <Slider ref="blue" update={this.update} /> {this.state.blue} </div> ) } } class Slider extends React.Component { render() { return ( <div> <input ref="input" type="range" min="0" max="255" onChange={this.props.update}/> </div> ); } }; export default App;
import React from 'react'; class App extends React.Component { constructor(){ super(); this.state = { txt: ''}; this.update = this.update.bind(this); } update(e){ this.setState({txt: e.target.value}); } render() { return( <div> <Widget txt={this.state.txt} update={this.update} /> <Widget txt={this.state.txt} update={this.update} /> <Widget txt={this.state.txt} update={this.update} /> <Widget txt={this.state.txt} update={this.update} /> <Widget txt={this.state.txt} update={this.update} /> </div> ) } } const Widget = (props) => { return ( <div> <input type="text" onChange={props.update}/> <h1>{props.txt}</h1> </div> ) }; export default App;
Fix bug in JWT error handling
import datetime from flask import current_app, request from passlib.hash import sha256_crypt from flask_jwt import JWT from tmaps.models import User jwt = JWT() # TODO: Use HTTPS for connections to /auth @jwt.authentication_handler def authenticate(username, password): """Check if there is a user with this username-pw-combo and return the user object if a matching user has been found.""" user = User.query.filter_by(name=username).first_or_404() if user and sha256_crypt.verify(password, user.password): return user else: return None @jwt.identity_handler def load_user(payload): """Lookup the user for a token payload.""" user = User.query.get(payload['uid']) return user @jwt.jwt_payload_handler def make_payload(user): """Create the token payload for some user""" iat = datetime.datetime.utcnow() exp = iat + current_app.config.get('JWT_EXPIRATION_DELTA') nbf = iat + current_app.config.get('JWT_NOT_BEFORE_DELTA') return { 'uid': user.id, 'uname': user.name, 'iat': iat, 'nbf': nbf, 'exp': exp } # @jwt.jwt_error_handler # def error_handler(e): # """This function is called whenever flask-jwt encounters an error.""" # return 'No valid access token in header', 401
import datetime from flask import current_app from passlib.hash import sha256_crypt from flask_jwt import JWT from tmaps.models import User jwt = JWT() # TODO: Use HTTPS for connections to /auth @jwt.authentication_handler def authenticate(username, password): """Check if there is a user with this username-pw-combo and return the user object if a matching user has been found.""" user = User.query.filter_by(name=username).first_or_404() if user and sha256_crypt.verify(password, user.password): return user else: return None @jwt.identity_handler def load_user(payload): """Lookup the user for a token payload.""" user = User.query.get(payload['uid']) return user @jwt.jwt_payload_handler def make_payload(user): """Create the token payload for some user""" iat = datetime.datetime.utcnow() exp = iat + current_app.config.get('JWT_EXPIRATION_DELTA') nbf = iat + current_app.config.get('JWT_NOT_BEFORE_DELTA') return { 'uid': user.id, 'uname': user.name, 'iat': iat, 'nbf': nbf, 'exp': exp } @jwt.jwt_error_handler def error_handler(e): """This function is called whenever flask-jwt encounters an error.""" return 'No valid access token in header', 401
Fix unicode handling in bugwarrior run log.
from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = u'\n'.join(lines) self.save() @property def error_message(self): if not self.stack_trace: return None lines = [line for line in self.stack_trace.split('\n') if line.strip()] return lines.pop() def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager'
from django.db import models from .bugwarriorconfig import BugwarriorConfig class BugwarriorConfigRunLog(models.Model): config = models.ForeignKey( BugwarriorConfig, related_name='run_logs', ) success = models.BooleanField(default=False) output = models.TextField() stack_trace = models.TextField() started = models.DateTimeField() finished = models.DateTimeField(null=True) def add_output(self, new): lines = [line for line in self.output.split('\n') if line] lines.append(new) self.output = '\n'.join(lines) self.save() @property def error_message(self): if not self.stack_trace: return None lines = [line for line in self.stack_trace.split('\n') if line.strip()] return lines.pop() def __unicode__(self): if self.success: category = 'Successful' else: category = 'Failed' return u"{category} bugwarrior-pull run of {config}".format( category=category, config=self.config ) class Meta: app_label = 'taskmanager'
Improve window sizing on Windows tested on Windows 7 and 10
var electron = require('electron'); // Module to control application life. var process = require('process'); require('electron-debug')({showDevTools: false}); const {app} = electron; const {BrowserWindow} = electron; let win; // Ensure that our win isn't garbage collected app.on('ready', function() { // Create the browser window. if (process.platform == 'win32') win = new BrowserWindow({width: 659, height: 510, frame: true, resizable: false}); else win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false}); // Load the main interface win.loadURL('file://' + __dirname + '/index.html'); //Disable the menubar for dev versions win.setMenu(null); win.on('closed', function() { // Dereference the window object so our app exits win = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function() { app.quit(); });
var electron = require('electron'); // Module to control application life. var process = require('process'); require('electron-debug')({showDevTools: false}); const {app} = electron; const {BrowserWindow} = electron; let win; // Ensure that our win isn't garbage collected app.on('ready', function() { // Create the browser window. if (process.platform == 'win32') win = new BrowserWindow({width: 670, height: 510, frame: true, resizable: false}); else win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false}); // Load the main interface win.loadURL('file://' + __dirname + '/index.html'); //Disable the menubar for dev versions win.setMenu(null); win.on('closed', function() { // Dereference the window object so our app exits win = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function() { app.quit(); });
Fix an API change (since 2.3) that crashed form submission
<?php namespace Djebbz\BlogBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Djebbz\BlogBundle\Entity\Enquiry; use Djebbz\BlogBundle\Form\EnquiryType; class PageController extends Controller { public function indexAction() { return $this->render('DjebbzBlogBundle:Page:index.html.twig'); } public function aboutAction() { return $this->render('DjebbzBlogBundle:Page:about.html.twig'); } public function contactAction() { $enquiry = new Enquiry(); $form = $this->createForm(new EnquiryType(), $enquiry); $request = $this->getRequest(); if ($request->getMethod() == 'POST') { $form->handleRequest($request); if ($form->isValid()) { return $this->redirect($this->generateUrl('DjebbzBlogBundle_contact')); } } return $this->render('DjebbzBlogBundle:Page:contact.html.twig', array( 'form' => $form->createView() )); } }
<?php namespace Djebbz\BlogBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Djebbz\BlogBundle\Entity\Enquiry; use Djebbz\BlogBundle\Form\EnquiryType; class PageController extends Controller { public function indexAction() { return $this->render('DjebbzBlogBundle:Page:index.html.twig'); } public function aboutAction() { return $this->render('DjebbzBlogBundle:Page:about.html.twig'); } public function contactAction() { $enquiry = new Enquiry(); $form = $this->createForm(new EnquiryType(), $enquiry); $request = $this->getRequest(); if ($request->getMethod() == 'POST') { $form->bindRequest($request); if ($form->isValid()) { return $this->redirect($this->generateUrl('DjebbzBlogBundle_contact')); } } return $this->render('DjebbzBlogBundle:Page:contact.html.twig', array( 'form' => $form->createView() )); } }
Add whitespace after description in phpdoc and fix classname used
<?php namespace EventCentric\EventStore; use EventCentric\Contracts\Contract; use EventCentric\EventStore\EventStream; use EventCentric\Identifiers\Identifier; use EventCentric\Persistence\Persistence; /** * A history of all DomainEvents that have happened in the system. */ final class EventStore { /** * @var Persistence */ private $persistence; /** * @param Persistence $persistence */ public function __construct(Persistence $persistence) { $this->persistence = $persistence; } /** * Creates a new stream. * * @param Contract $streamContract * @param $streamId * @return EventStream */ public function createStream(Contract $streamContract, Identifier $streamId) { return EventStream::create($this->persistence, $streamContract, $streamId); } /** * Queries the persistence to open a stream. If there was no stream, a new stream is created. Prefer using * createStream when you know there is no stream yet. * * @param Contract $streamContract * @param Identifier $streamId * @return EventStream */ public function openOrCreateStream(Contract $streamContract, Identifier $streamId) { return EventStream::open($this->persistence, $streamContract, $streamId); } }
<?php namespace EventCentric\EventStore; use EventCentric\Contracts\Contract; use EventCentric\EventStore\EventStream; use EventCentric\Identifiers\Identifier; use EventCentric\Persistence\Persistence; /** * A history of all DomainEvents that have happened in the system. */ final class EventStore { /** * @var \EventCentric\Persistence\Persistence */ private $persistence; public function __construct(Persistence $persistence) { $this->persistence = $persistence; } /** * Creates a new stream. * @param Contract $streamContract * @param $streamId * @return EventStream */ public function createStream(Contract $streamContract, Identifier $streamId) { return EventStream::create($this->persistence, $streamContract, $streamId); } /** * Queries the persistence to open a stream. If there was no stream, a new stream is created. Prefer using * createStream when you know there is no stream yet. * @param Contract $streamContract * @param Identifier $streamId * @return EventStream */ public function openOrCreateStream(Contract $streamContract, Identifier $streamId) { return EventStream::open($this->persistence, $streamContract, $streamId); } }
Update for the last changes in the API
// Allows to get the video of the url through the api_url (optional) function BaseVideoInfo(url, api_url) { this.url = url || 'null'; this.api_url = api_url || "https://youtube-dl.appspot.com/api/info"; } BaseVideoInfo.prototype = { log: function () { console.log("VideoInfo:\n\t=> URL: " + this.url + "\n\t=> API URL: " + this.api_url); }, // Get the info of the url get_info: function () { $.getJSON( this.api_url, {'url': this.url}, this.process_video_info ).error(this.api_call_failed); }, // This function will be called when the video data is received process_video_info: function (data) { console.error("Nothing to be done with the data"); }, api_call_failed: function (jqXHR, textStatus, errorThrown) { console.error("Error on the api call"); } };
// Allows to get the video of the url through the api_url (optional) function BaseVideoInfo(url, api_url) { this.url = url || 'null'; this.api_url = api_url || "https://youtube-dl.appspot.com/api/"; } BaseVideoInfo.prototype = { log: function () { console.log("VideoInfo:\n\t=> URL: " + this.url + "\n\t=> API URL: " + this.api_url); }, // Get the info of the url get_info: function () { $.getJSON( this.api_url, {'url': this.url}, this.process_video_info ).error(this.api_call_failed); }, // This function will be called when the video data is received process_video_info: function (data) { console.error("Nothing to be done with the data"); }, api_call_failed: function (jqXHR, textStatus, errorThrown) { console.error("Error on the api call"); } };
Make sha256 and sha512 sink names correspond to their commandline arguments
import hashlib from digestive.io import Sink class HashDigest(Sink): def __init__(self, name, digest): super().__init__(name) self._digest = digest def update(self, data): self._digest.update(data) def digest(self): return self._digest.hexdigest() class MD5(HashDigest): def __init__(self): super().__init__('md5', hashlib.md5()) class SHA1(HashDigest): def __init__(self): super().__init__('sha1', hashlib.sha1()) class SHA256(HashDigest): def __init__(self): super().__init__('sha256', hashlib.sha256()) class SHA512(HashDigest): def __init__(self): super().__init__('sha512', hashlib.sha512())
import hashlib from digestive.io import Sink class HashDigest(Sink): def __init__(self, name, digest): super().__init__(name) self._digest = digest def update(self, data): self._digest.update(data) def digest(self): return self._digest.hexdigest() class MD5(HashDigest): def __init__(self): super().__init__('md5', hashlib.md5()) class SHA1(HashDigest): def __init__(self): super().__init__('sha1', hashlib.sha1()) class SHA256(HashDigest): def __init__(self): super().__init__('sha2-256', hashlib.sha256()) class SHA512(HashDigest): def __init__(self): super().__init__('sha2-512', hashlib.sha512())
Clear command registry BEFORE each test.
import unittest from nymms import registry from nymms.resources import Command, MonitoringGroup from weakref import WeakValueDictionary class TestRegistry(unittest.TestCase): def setUp(self): # Ensure we have a fresh registry before every test Command.registry.clear() def test_empty_registry(self): self.assertEqual(Command.registry, WeakValueDictionary()) def test_register_object(self): # First test it's empty self.assertEqual(Command.registry, WeakValueDictionary()) # Add a command command = Command('test_command', '/bin/true') # verify that there is only a single command in the registry self.assertEqual(len(Command.registry), 1) # Verify that the registered command is the same as command self.assertIs(Command.registry[command.name], command) def test_duplicate_register(self): # add a command print Command.registry Command('test_command', '/bin/true') with self.assertRaises(registry.DuplicateEntryError): Command('test_command', '/bin/true') def test_invalid_resource_register(self): with self.assertRaises(TypeError): Command.registry['test'] = MonitoringGroup('test_group')
import unittest from nymms import registry from nymms.resources import Command, MonitoringGroup from weakref import WeakValueDictionary class TestRegistry(unittest.TestCase): def tearDown(self): # Ensure we have a fresh registry after every test Command.registry.clear() def test_empty_registry(self): self.assertEqual(Command.registry, WeakValueDictionary()) def test_register_object(self): # First test it's empty self.assertEqual(Command.registry, WeakValueDictionary()) # Add a command command = Command('test_command', '/bin/true') # verify that there is only a single command in the registry self.assertEqual(len(Command.registry), 1) # Verify that the registered command is the same as command self.assertIs(Command.registry[command.name], command) def test_duplicate_register(self): # add a command Command('test_command', '/bin/true') with self.assertRaises(registry.DuplicateEntryError): Command('test_command', '/bin/true') def test_invalid_resource_register(self): with self.assertRaises(TypeError): Command.registry['test'] = MonitoringGroup('test_group')
Make it possible to set session secret using environment variables
const express = require('express'); const session = require('express-session'); const SequelizeStore = require('connect-session-sequelize')(session.Store); const logger = require('./logging'); const auth = require('./auth'); const db = require('./models/postgresql'); // Initialize express const app = express(); // Set up session store using database connection const store = new SequelizeStore({ db: db.sequelize }); const sessionSecret = process.env.SDF_SESSION_STORE_SECRET || 'super secret'; // Set up session store app.use(session({ secret: sessionSecret, store, resave: true, saveUninitialized: true, })); store.sync(); if (process.env.PRODUCTION) { // Register dist path for static files in prod const staticDir = './dist'; logger.info(`Serving staticfiles from ${staticDir}`); app.use('/assets/', express.static(staticDir)); app.get(/^(?!\/(log(in|out)|auth))/, (req, res) => res.sendFile('index.html', { root: staticDir })); } module.exports = async () => auth(app);
const express = require('express'); const session = require('express-session'); const SequelizeStore = require('connect-session-sequelize')(session.Store); const logger = require('./logging'); const auth = require('./auth'); const db = require('./models/postgresql'); // Initialize express const app = express(); // Set up session store using database connection const store = new SequelizeStore({ db: db.sequelize }); // Set up session store app.use(session({ secret: 'super secret', store, resave: true, saveUninitialized: true, })); store.sync(); if (process.env.PRODUCTION) { // Register dist path for static files in prod const staticDir = './dist'; logger.info(`Serving staticfiles from ${staticDir}`); app.use('/assets/', express.static(staticDir)); app.get(/^(?!\/(log(in|out)|auth))/, (req, res) => res.sendFile('index.html', { root: staticDir })); } module.exports = async () => auth(app);
Initialize method with this.options to pass position to client-side
define(function(require, exports, module) { var _ = require('underscore'); var $ = require('jquery'); var Backbone = require('backbone'); var GenderTpl = require('text!templates/gender.html'); var CharacterGenderView = Backbone.View.extend({ tagName: 'li', className: 'media', template: _.template(GenderTpl), events: { 'click #female': 'female', 'click #male': 'male' }, initialize: function(options) { this.options = options || {}; }, render: function () { var data = { model: this.model.toJSON(), position: this.options.position }; this.$el.html(this.template(data)); return this; }, female: function() { var self = this; self.$el.remove(); $.post('/api/gender', { characterId: this.model.get('characterId'), gender: 'female' }, function(data) { return false; }); }, male: function() { var self = this; self.$el.remove(); $.post('/api/gender', { characterId: this.model.get('characterId'), gender: 'male' }, function(data) { return false; }); } }); return CharacterGenderView; });
define(function(require, exports, module) { var _ = require('underscore'); var $ = require('jquery'); var Backbone = require('backbone'); var GenderTpl = require('text!templates/gender.html'); var CharacterGenderView = Backbone.View.extend({ tagName: 'li', className: 'media', template: _.template(GenderTpl), events: { 'click #female': 'female', 'click #male': 'male' }, render: function () { var data = { model: this.model.toJSON(), position: this.options.position }; this.$el.html(this.template(data)); return this; }, female: function() { var self = this; self.$el.remove(); $.post('/api/gender', { characterId: this.model.get('characterId'), gender: 'female' }, function(data) { return false; }); }, male: function() { var self = this; self.$el.remove(); $.post('/api/gender', { characterId: this.model.get('characterId'), gender: 'male' }, function(data) { return false; }); } }); return CharacterGenderView; });
Remove code in comment that was used for constructing call
class MCDirComponentController { /*@ngInject*/ constructor(mcFileOpsDialogs) { this.mcFileOpsDialogs = mcFileOpsDialogs; this.selected = false; } onSelected(selected) { this.selected = selected; } renameDirectory() { this.mcFileOpsDialogs.renameDirectory(this.dir.data.name).then(name => this.onRenameDir({newDirName: name})); } createDirectory() { this.mcFileOpsDialogs.createDirectory(this.dir.data.name).then(name => this.onCreateDir({createDirName: name})); } uploadFiles() { this.onUploadFiles(); } } angular.module('materialscommons').component('mcDir', { templateUrl: 'app/project/files/components/dir/mc-dir.html', controller: MCDirComponentController, bindings: { dir: '<', onRenameDir: '&', onCreateDir: '&', onUploadFiles: '&' } });
class MCDirComponentController { /*@ngInject*/ constructor(mcFileOpsDialogs) { this.mcFileOpsDialogs = mcFileOpsDialogs; this.selected = false; } onSelected(selected) { this.selected = selected; } renameDirectory() { this.mcFileOpsDialogs.renameDirectory(this.dir.data.name).then(name => this.onRenameDir({newDirName: name})); } createDirectory() { this.mcFileOpsDialogs.createDirectory(this.dir.data.name).then(name => this.onCreateDir({createDirName: name})); } uploadFiles() { this.onUploadFiles(); } } // projectFileTreeAPI.renameProjectDir(ctrl.projectId, ctrl.file.data.id, ctrl.file.data.name) // .then( angular.module('materialscommons').component('mcDir', { templateUrl: 'app/project/files/components/dir/mc-dir.html', controller: MCDirComponentController, bindings: { dir: '<', onRenameDir: '&', onCreateDir: '&', onUploadFiles: '&' } });
Update publish for desktop script
const fs = require('fs'); const glob = require('glob'); const path = require('path'); const rimraf = require('rimraf'); const workspaceRoot = path.join(__dirname, '..'); const desktopUpdatesPath = path.join(workspaceRoot, '..', 'toolkit-for-ynab-gh-pages', 'desktop-updates'); // Clear out the directory and create it clean. rimraf.sync(desktopUpdatesPath); fs.mkdirSync(desktopUpdatesPath); // Copy the extension over first. const filesToCopy = glob.sync(path.join(workspaceRoot, 'dist/toolkit-for-ynab-v*.zip')); if (filesToCopy.length !== 1) { throw new Error(`There must be precisely one zip file to copy. Found ${filesToCopy.length}!`); } fs.copyFileSync(filesToCopy[0], path.join(desktopUpdatesPath, 'toolkitforynab_desktop.zip')); // And now we can copy over the manifest too. fs.copyFileSync( path.join(workspaceRoot, 'dist', 'extension', 'manifest.json'), path.join(desktopUpdatesPath, 'manifest.json') );
const fs = require('fs'); const glob = require('glob'); const path = require('path'); const rimraf = require('rimraf'); const workspaceRoot = path.join(__dirname, '..'); const desktopUpdatesPath = path.join(workspaceRoot, '..', 'toolkit-for-ynab-gh-pages', 'desktop-updates'); // Clear out the directory and create it clean. rimraf.sync(desktopUpdatesPath); fs.mkdirSync(desktopUpdatesPath); // Copy the extension over first. const filesToCopy = glob.sync(path.join(workspaceRoot, 'dist/*.zip')); if (filesToCopy.length !== 1) { throw new Error(`There must be precisely one zip file to copy. Found ${filesToCopy.length}!`); } fs.copyFileSync(filesToCopy[0], path.join(desktopUpdatesPath, 'toolkitforynab_desktop.zip')); // And now we can copy over the manifest too. fs.copyFileSync( path.join(workspaceRoot, 'dist', 'extension', 'manifest.json'), path.join(desktopUpdatesPath, 'manifest.json') );
Fix building static media on Django 1.11. Our wrapper script for building static media attempted to honor the exit code of the `collectstatic` management command, passing it along to `sys.exit()` so that we wouldn't have a failure show up as a successful result. However, exit codes are never returned. Instead, we were always getting `None` back, which Python helpfully converts to an exit code of 0. Any failure would have been an explicit `sys.exit(1)` or a raised exception. So what we were doing was pointless. On Django 1.11, though, we actually got a result back: The result of `stdout`. We were then passing this to `sys.exit()`, which Python was converting to an exit code of 1, resulting in the command always failing. We now just exit normally without trying to be clever and helpful, letting Django do its own thing. Testing Done: Tested building static media on Django 1.6 and 1.11. Reviewed at https://reviews.reviewboard.org/r/10605/
#!/usr/bin/env python from __future__ import unicode_literals import os import sys scripts_dir = os.path.abspath(os.path.dirname(__file__)) # Source root directory sys.path.insert(0, os.path.abspath(os.path.join(scripts_dir, '..', '..'))) # Script config directory sys.path.insert(0, os.path.join(scripts_dir, 'conf')) from reviewboard.dependencies import django_version import __main__ __main__.__requires__ = ['Django' + django_version] import pkg_resources from django.core.management import call_command if __name__ == '__main__': os.putenv('FORCE_BUILD_MEDIA', '1') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reviewboard.settings') # This will raise a CommandError or call sys.exit(1) on failure. call_command('collectstatic', interactive=False, verbosity=2)
#!/usr/bin/env python from __future__ import unicode_literals import os import sys scripts_dir = os.path.abspath(os.path.dirname(__file__)) # Source root directory sys.path.insert(0, os.path.abspath(os.path.join(scripts_dir, '..', '..'))) # Script config directory sys.path.insert(0, os.path.join(scripts_dir, 'conf')) from reviewboard.dependencies import django_version import __main__ __main__.__requires__ = ['Django' + django_version] import pkg_resources from django.core.management import call_command if __name__ == '__main__': os.putenv('FORCE_BUILD_MEDIA', '1') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reviewboard.settings') ret = call_command('collectstatic', interactive=False, verbosity=2) sys.exit(ret)
Add console.log to test to find out travis problem
var _ = require('lodash'); var assert = require("assert"); var exec = require('child_process').exec; describe('githours', function() { describe('cli', function() { it('should output json', function(done) { exec('node index.js', function(err, stdout, stderr) { if (err !== null) { throw new Error(stderr); } console.log('output json', stdout); var work = JSON.parse(stdout); assert.notEqual(work.total.hours.length, 0); assert.notEqual(work.total.commits.length, 0); done(); }); }); }); });
var _ = require('lodash'); var assert = require("assert"); var exec = require('child_process').exec; describe('githours', function() { describe('cli', function() { it('should output json', function(done) { exec('node index.js', function(err, stdout, stderr) { if (err !== null) { throw new Error(stderr); } var work = JSON.parse(stdout); assert.notEqual(work.total.hours.length, 0); assert.notEqual(work.total.commits.length, 0); done(); }); }); }); });
Remove diamond usage. IntelliJ plugins needs java 6 and this feature is not supported
package com.github.pedrovgs.androidwifiadb.adb; import com.github.pedrovgs.androidwifiadb.Device; import java.util.LinkedList; import java.util.List; public class ADBParser { public List<Device> parseGetDevicesOutput(String adbDevicesOutput) { List<Device> devices = new LinkedList<Device>(); String[] splittedOutput = adbDevicesOutput.split("\\n"); for (String line : splittedOutput) { String[] deviceLine = line.split("\\t"); if (deviceLine.length == 2) { String id = deviceLine[0]; if (id.contains(".")) { continue; } String name = deviceLine[1]; Device device = new Device(name, id); devices.add(device); } } return devices; } public String parseGetDeviceIp(String ipInfoOutput) { String[] splittedOutput = ipInfoOutput.split("\\n"); int end = splittedOutput[1].indexOf("/"); int start = splittedOutput[1].indexOf("t"); return splittedOutput[1].substring(start + 2, end); } }
package com.github.pedrovgs.androidwifiadb.adb; import com.github.pedrovgs.androidwifiadb.Device; import java.util.LinkedList; import java.util.List; public class ADBParser { public List<Device> parseGetDevicesOutput(String adbDevicesOutput) { List<Device> devices = new LinkedList<>(); String[] splittedOutput = adbDevicesOutput.split("\\n"); for (String line : splittedOutput) { String[] deviceLine = line.split("\\t"); if (deviceLine.length == 2) { String id = deviceLine[0]; if (id.contains(".")) { continue; } String name = deviceLine[1]; Device device = new Device(name, id); devices.add(device); } } return devices; } public String parseGetDeviceIp(String ipInfoOutput) { String[] splittedOutput = ipInfoOutput.split("\\n"); int end = splittedOutput[1].indexOf("/"); int start = splittedOutput[1].indexOf("t"); return splittedOutput[1].substring(start + 2, end); } }
Resolve the authenticated user out of the IoC.
<?php namespace Illuminate\Auth; use Illuminate\Support\ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->registerUserResolver(); $this->app->bindShared('auth', function($app) { // Once the authentication service has actually been requested by the developer // we will set a variable in the application indicating such. This helps us // know that we need to set any queued cookies in the after event later. $app['auth.loaded'] = true; return new AuthManager($app); }); $this->app->bindShared('auth.driver', function($app) { return $app['auth']->driver(); }); } /** * Register a resolver for the authenticated user. * * @return void */ protected function registerUserResolver() { $this->app->bind('Illuminate\Contracts\Auth\User', function($app) { return $app['auth']->user(); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['auth', 'auth.driver', 'Illuminate\Contracts\Auth\User']; } }
<?php namespace Illuminate\Auth; use Illuminate\Support\ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->app->bindShared('auth', function($app) { // Once the authentication service has actually been requested by the developer // we will set a variable in the application indicating such. This helps us // know that we need to set any queued cookies in the after event later. $app['auth.loaded'] = true; return new AuthManager($app); }); $this->app->bindShared('auth.driver', function($app) { return $app['auth']->driver(); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['auth', 'auth.driver']; } }
Use arrow functions instead of `function` keyword
'use strict'; const debug = require('debug')('calendar:routes:common'); module.exports = { sendAppropriateResponse : (req, res, output) => { if (req.accepts('html')) { debug('sending html output'); res.send(output.text.replace(/(?:\r\n|\r|\n)/g, '<br />')); return; } if (req.accepts('text')) { debug('sending text output'); res.send(output.text); return; } if (req.accepts('json')) { debug('sending json output'); res.send(output.json); return; } res.type('txt').send(output.text); } };
'use strict'; const debug = require('debug')('calendar:routes:common'); module.exports = { sendAppropriateResponse : function (req, res, output) { if (req.accepts('html')) { debug('sending html output'); res.send(output.text.replace(/(?:\r\n|\r|\n)/g, '<br />')); return; } if (req.accepts('text')) { debug('sending text output'); res.send(output.text); return; } if (req.accepts('json')) { debug('sending json output'); res.send(output.json); return; } res.type('txt').send(output.text); } };
Revert "Converting tabs to spaces." This reverts commit aca5ea78363bed0e3a6b9d7993755022690a06a4.
describe("Simple tests examples", function() { it("should detect true", function() { assert.equal(true, true); }); it("should increments values", function() { var mike = 0; assert.equal(mike++ === 0, true); assert.equal(mike === 1, true); }); it("should increments values (improved)", function() { var mike = 0; assert.equal(mike++, 0); assert.equal(mike, 1); }); }); describe("Tests with before/after hooks", function() { var a = 0; beforeEach(function() { a++; }); afterEach(function() { a = 0 }); it("should increment value", function() { assert.equal(a, 1); }); it("should reset after each test", function() { assert.equal(a, 1); }); }); describe("Async tests", function() { it("should wait timer", function(done) { setTimeout(function() { assert.equal(true, true); done(); }, 500); }); });
describe("Simple tests examples", function () { it("should fail", function () { assert.equal(false, false); }); it("should detect true", function () { assert.equal(true, true); }); it("should increments values", function () { let mike = 0; assert.equal(mike++ === 0, true); assert.equal(mike === 1, true); }); it("should increments values (improved)", function () { let mike = 0; assert.equal(mike++, 0); assert.equal(mike, 1); }); }); describe("Tests with before/after hooks", function () { let a = 0; beforeEach(function () { a++; }); afterEach(function () { a = 0 }); it("should increment value", function () { assert.equal(a, 1); }); it("should reset after each test", function () { assert.equal(a, 1); }); }); describe("Async tests", function () { it("should wait timer", function (done) { setTimeout(function () { assert.equal(true, true); done(); }, 500); }); });
Add basic heroku production settings
import os import dj_database_url from painindex.settings.settings_base import * # This file is NOT part of our repo. It contains sensitive settings like secret key # and db setup. from env import * DEBUG = False TEMPLATE_DEBUG = False # Apps used specifically for production INSTALLED_APPS += ( 'gunicorn', ) # These people will get error emails in production ADMINS = ( ('Xan', 'xan.vong@gmail.com'), ) # Set this to match the domains of the production site. ALLOWED_HOSTS = [ 'www.thepainindex.com', 'thepainindex.com', 'http://still-taiga-5292.herokuapp.com', 'localhost' ] ################### # Heroku settings # ################### # See https://devcenter.heroku.com/articles/getting-started-with-django DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Heroku instructions allow all hosts. # If I have a problem, try this. # ALLOWED_HOSTS = ['*'] STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static') )
import os from painindex.settings.settings_base import * # This file is NOT part of our repo. It contains sensitive settings like secret key # and db setup. from env import * DEBUG = False TEMPLATE_DEBUG = False # Apps used specifically for production INSTALLED_APPS += ( 'gunicorn', ) # Configure production emails. # These people will get error emails in production ADMINS = ( ('Xan', 'xan.vong@gmail.com'), ) # Set this to match the domains of the production site. ALLOWED_HOSTS = [ 'www.thepainindex.com', 'thepainindex.com', 'http://still-taiga-5292.herokuapp.com', 'localhost' ] # Define place my static files will be collected and served from. # See https://docs.djangoproject.com/en/1.6/ref/settings/#std:setting-STATIC_ROOT # STATIC_ROOT = "" # MEDIA_ROOT = ""
Add EOL to tokens JSON file
const fs = require("fs"); const objectEquals = require("./objectEquals"); const { DEFAULT_TOKENS_FILENAME } = require("../lib/constants"); const tokensManager = function tokensManager (filename = DEFAULT_TOKENS_FILENAME) { const tokens = (function init () { try { return JSON.parse(fs.readFileSync(filename, { encoding: "utf-8" })); } catch (err) { if (err.code === "ENOENT") return []; else throw err; } })(); const persistTokens = () => fs.writeFileSync(filename, JSON.stringify(tokens, null, 2) + "\n", { encoding: "utf-8" }); const exists = function exists (token) { return tokens.some(t => objectEquals(t, token)); }; const add = function add (token) { if (!exists(token)) { tokens.push(token); persistTokens(); } }; const clear = function clear () { tokens.splice(0); persistTokens(); }; const remove = function remove (token) { tokens.splice(tokens.indexOf(token), 1); persistTokens(); }; return { add, clear, exists, remove, size: () => tokens.length }; }; module.exports = tokensManager;
const fs = require("fs"); const objectEquals = require("./objectEquals"); const { DEFAULT_TOKENS_FILENAME } = require("../lib/constants"); const tokensManager = function tokensManager (filename = DEFAULT_TOKENS_FILENAME) { const tokens = (function init () { try { return JSON.parse(fs.readFileSync(filename, { encoding: "utf-8" })); } catch (err) { if (err.code === "ENOENT") return []; else throw err; } })(); const persistTokens = () => fs.writeFileSync(filename, JSON.stringify(tokens, null, 2), { encoding: "utf-8" }); const exists = function exists (token) { return tokens.some(t => objectEquals(t, token)); }; const add = function add (token) { if (!exists(token)) { tokens.push(token); persistTokens(); } }; const clear = function clear () { tokens.splice(0); persistTokens(); }; const remove = function remove (token) { tokens.splice(tokens.indexOf(token), 1); persistTokens(); }; return { add, clear, exists, remove, size: () => tokens.length }; }; module.exports = tokensManager;
Use unpacking for simpler code
CHILDREN = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred", "Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"] PLANTS = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"} class Garden(object): def __init__(self, garden, students=CHILDREN): self.students = sorted(students) row1, row2 = garden.split() patches = [row1[i:i+2] + row2[i:i+2] for i in range(0,2*len(self.students),2)] self._garden = {s: [PLANTS[ch] for ch in p] for s, p in zip(self.students, patches)} def plants(self, student): return self._garden[student]
CHILDREN = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred", "Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"] PLANTS = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"} class Garden(object): def __init__(self, garden, students=CHILDREN): self.students = sorted(students) rows = garden.split() patches = [rows[0][i:i+2] + rows[1][i:i+2] for i in range(0,2*len(self.students),2)] self._garden = {s: [PLANTS[ch] for ch in p] for s, p in zip(self.students, patches)} def plants(self, student): return self._garden[student]
Allow girder to show load errors in more cases. If girder is installed but requirements of large_image are not, the plugin would report as enabled but not be functional. This checks if girder is available, and, if so, allows girder to report errors. Eventually, it will be nice to separate large_image without girder from the necessary girder parts to make this easier to manage. For now, this should make diagnosis easier. As a simple test, when everything works under girder, uninstall a required module (cachetools, for instance), and restart girder. Before, no error was reported. With this change, the missing module is reported.
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### try: import girder # This should include all of the explicitly required Girder plugins. import girder.plugins.worker except ImportError: # If our import failed because either girder or a girder plugin is # unavailable, log it and start anyway (we may be running in a girder-less # environment). import logging as logger logger.getLogger().setLevel(logger.INFO) logger.debug('Girder is unavailable. Run as a girder plugin for girder ' 'access.') girder = None else: # if girder is available, and we fail to import anything else, girder will # show the failure from .base import load # noqa
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### try: from .base import * # noqa except ImportError as exc: # If our import failed because either girder or a girder plugin is # unavailable, log it and start anyway (we may be running in a girder-less # environment). import logging as logger logger.getLogger().setLevel(logger.INFO) logger.debug('Girder is unavailable. Run as a girder plugin for girder ' 'access.') girder = None
Add support for UStream recorded schema
<?php /** * Ustream.php * * @package Providers * @author Michael Pratt <pratt@hablarmierda.net> * @link http://www.michael-pratt.com/ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Embera\Providers; /** * The ustream.tv|com Provider * @link http://ustream.tv */ class Ustream extends \Embera\Adapters\Service { /** inline {@inheritdoc} */ protected $apiUrl = 'http://www.ustream.tv/oembed'; /** inline {@inheritdoc} */ protected function validateUrl() { $this->url->stripLastSlash(); $this->url->invalidPattern('ustream\.(?:com|tv)/(?:explore|howto|upcomming|our-company|services|premium-membership|search)$'); return (preg_match('~ustream\.(?:com|tv)/channel/(?:[\w\d\-_]+)$~i', $this->url) || preg_match('~ustream\.(?:com|tv)/recorded/(?:[\w\d\-_]+)$~i', $this->url) || preg_match('~ustream\.(?:com|tv)/(?:[\w\d\-_]+)$~i', $this->url)); } }
<?php /** * Ustream.php * * @package Providers * @author Michael Pratt <pratt@hablarmierda.net> * @link http://www.michael-pratt.com/ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Embera\Providers; /** * The ustream.tv|com Provider * @link http://ustream.tv */ class Ustream extends \Embera\Adapters\Service { /** inline {@inheritdoc} */ protected $apiUrl = 'http://www.ustream.tv/oembed'; /** inline {@inheritdoc} */ protected function validateUrl() { $this->url->stripLastSlash(); $this->url->invalidPattern('ustream\.(?:com|tv)/(?:explore|howto|upcomming|our-company|services|premium-membership|search)$'); return (preg_match('~ustream\.(?:com|tv)/channel/(?:[\w\d\-_]+)$~i', $this->url) || preg_match('~ustream\.(?:com|tv)/(?:[\w\d\-_]+)$~i', $this->url)); } } ?>
Move jshint and jscs into default build pipeline
'use strict'; var gulp = require('gulp'), batch = require('gulp-batch'), concat = require('gulp-concat'), ignore = require('gulp-ignore'), jshint = require('gulp-jshint'), jscs = require('gulp-jscs'), watch = require('gulp-watch'), path = require('path'); var dist = 'dist/hypermedia.js'; gulp.task('default', function () { var distDir = path.dirname(dist); return gulp.src('src/*.js') // jshint .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')) // jscs .pipe(jscs()) .pipe(jscs.reporter()) .pipe(jscs.reporter('fail')) // build .pipe(ignore.exclude('*.spec.js')) .pipe(concat(path.basename(dist))) .pipe(gulp.dest(distDir)); }); gulp.task('watch', function () { gulp.start('default'); watch('src/**', batch(function (events, done) { gulp.start('default', done); })); });
'use strict'; var gulp = require('gulp'), batch = require('gulp-batch'), concat = require('gulp-concat'), ignore = require('gulp-ignore'), jshint = require('gulp-jshint'), watch = require('gulp-watch'), path = require('path'); var dist = 'dist/hypermedia.js'; gulp.task('default', ['jshint'], function(){ var distDir = path.dirname(dist); return gulp.src('src/*.js') .pipe(ignore.exclude('*.spec.js')) .pipe(concat(path.basename(dist))) .pipe(gulp.dest(distDir)); }); gulp.task('watch', function () { gulp.start('default'); watch('src/**', batch(function (events, done) { gulp.start('default', done); })); }); gulp.task('jshint', function () { return gulp.src(['src/*.js']) .pipe(jshint('./.jshintrc')) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); });
Fix 3 char hex support
/** * Convert string array to int array and returns it sorted. */ function sortIntArray(arr) { var intArr = arr.map(Number); return intArr.sort(function(a, b) { return a - b; }); } /** * Decide if hex color needs black or white text color to match. * Modified, Credit to @(http://stackoverflow.com/a/12043228/2741279) */ function getLumColor(hex) { var c = hex.substring(1); // strip # // Convert 3 character hex to 6 character hex if (c.length === 3) { c = c[0] + c[0] + c[1] + c[1] + c[2] + c[2]; } var rgb = parseInt(c, 16), // convert rrggbb to decimal r = (rgb >> 16) & 0xff, // extract red g = (rgb >> 8) & 0xff, // extract green b = (rgb >> 0) & 0xff, // extract blue luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709 if (luma < 100) { return "#DDDDDD"; } else { return "#222222"; } }
/** * Convert string array to int array and returns it sorted. */ function sortIntArray(arr) { var intArr = arr.map(Number); return intArr.sort(function(a, b) { return a - b; }); } /** * Decide if hex color needs black or white text color to match. * Modified, Credit to @(http://stackoverflow.com/a/12043228/2741279) */ function getLumColor(hex) { var c = hex.substring(1), // strip # rgb = parseInt(c, 16), // convert rrggbb to decimal r = (rgb >> 16) & 0xff, // extract red g = (rgb >> 8) & 0xff, // extract green b = (rgb >> 0) & 0xff, // extract blue luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709 if (luma < 100) { return "#DDDDDD"; } else { return "#222222"; } }
Rename parameters from photo to gif to get more meaningful names
// URLs grom telegram const TELEGRAM_BASE_URL = 'https://api.telegram.org'; const TELEGRAM_MESSAGE_GIF_ENDPOINT = '/sendVideo'; const DEFAULT_GIF_URL = 'http://gph.is/1KuNTVa'; // URLs from giphy const {GIPHY_PUBLIC_API_KEY} = require('./variables'); const GIPHY_BASE_URL = 'http://api.giphy.com'; const GIPHY_API_KEY_SUFIX = 'api_key=' + GIPHY_PUBLIC_API_KEY; const GIPHY_SEARCH_ENDPOINT = '/v1/gifs/search'; module.exports = { // Giphy GIPHY_BASE_URL, GIPHY_API_KEY_SUFIX, GIPHY_SEARCH_ENDPOINT, // Telegram TELEGRAM_BASE_URL, TELEGRAM_MESSAGE_GIF_ENDPOINT, DEFAULT_GIF_URL }
// URLs grom telegram const TELEGRAM_BASE_URL = 'https://api.telegram.org'; const TELEGRAM_MESSAGE_PHOTO_ENDPOINT = '/sendPhoto'; const DEFAULT_PHOTO_URL = 'http://media.salemwebnetwork.com/cms/CROSSCARDS/17343-im-sorry-pug.jpg'; // URLs from giphy const {GIPHY_PUBLIC_API_KEY} = require('./variables'); const GIPHY_BASE_URL = 'http://api.giphy.com'; const GIPHY_API_KEY_SUFIX = 'api_key=' + GIPHY_PUBLIC_API_KEY; const GIPHY_SEARCH_ENDPOINT = '/v1/gifs/search'; module.exports = { // Giphy GIPHY_BASE_URL, GIPHY_API_KEY_SUFIX, GIPHY_SEARCH_ENDPOINT, // Telegram TELEGRAM_BASE_URL, TELEGRAM_MESSAGE_PHOTO_ENDPOINT, DEFAULT_PHOTO_URL }
Add note on TODO for handling quotes via API
import React, { Component } from 'react'; import Promise from 'bluebird'; import FontAwesome from 'react-fontawesome'; import quotes from './quotes.json'; import styles from './jumboQuote.css'; class JumboQuote extends Component { constructor(props) { super(props); this.state = { quote: {} }; } componentDidMount() { // TODO: Pull this from an API with fetch // (kylemh: recommend axios if using promises) source: https://daveceddia.com/ajax-requests-in-react/ Promise.try( () => quotes.quotes[Math.floor(Math.random() * quotes.quotes.length)] ).then((quote) => { this.setState({ quote }); }); } render() { return ( <div className={styles.quotes}> <h4 className={styles.quoteBody}> <FontAwesome name="quote-left" className={styles.quoteIcon} /> {this.state.quote.body} <FontAwesome name="quote-right" className={styles.quoteIcon} /> </h4> <h5 className={styles.quoteAuthor}>{this.state.quote.author} </h5> </div> ); } } export default JumboQuote;
import React, { Component } from 'react'; import Promise from 'bluebird'; import FontAwesome from 'react-fontawesome'; import quotes from './quotes.json'; import styles from './jumboQuote.css'; class JumboQuote extends Component { constructor(props) { super(props); this.state = { quote: {} }; } componentDidMount() { // TODO: Pull this from an API with fetch Promise.try( () => quotes.quotes[Math.floor(Math.random() * quotes.quotes.length)] ).then((quote) => { this.setState({ quote }); }); } render() { return ( <div className={styles.quotes}> <h4 className={styles.quoteBody}> <FontAwesome name="quote-left" className={styles.quoteIcon} /> {this.state.quote.body} <FontAwesome name="quote-right" className={styles.quoteIcon} /> </h4> <h5 className={styles.quoteAuthor}>{this.state.quote.author} </h5> </div> ); } } export default JumboQuote;
Replace global var with threading.local
# -*- coding: utf-8 -*- import threading import six from django.core.handlers.wsgi import WSGIHandler tld = threading.local() def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500): """Function to override django.views.debug.technical_500_response. Django's convert_exception_to_response() wrapper is called on each 'Middleware' object to avoid leaking exceptions. If and uncaught exception is raised, the wrapper calls technical_500_response() to create a response for django's debug view. Runserver_plus overrides the django debug view's technical_500_response() function to allow for an enhanced WSGI debugger view to be displayed. However, because Django calls convert_exception_to_response() on each object in the stack of Middleware objects, re-raising an error quickly pollutes the traceback displayed. Runserver_plus only needs needs traceback frames relevant to WSGIHandler Middleware objects, so only store the traceback if it is for a WSGIHandler. If an exception is not raised here, Django eventually throws an error for not getting a valid response object for its debug view. """ # Store the most recent tb for WSGI requests. The class can be found in the second frame of the tb if isinstance(tb.tb_next.tb_frame.f_locals['self'], WSGIHandler): tld.wsgi_tb = tb elif tld.wsgi_tb: tb = tld.wsgi_tb six.reraise(exc_type, exc_value, tb)
# -*- coding: utf-8 -*- import six from django.core.handlers.wsgi import WSGIHandler wsgi_tb = None def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500): """Function to override django.views.debug.technical_500_response. Django's convert_exception_to_response wrapper is called on each 'Middleware' object to avoid leaking exceptions. The wrapper eventually calls technical_500_response to create a response for an error view. Runserver_plus overrides the django debug view's technical_500_response function with this to allow for an enhanced WSGI debugger view to be displayed. However, because Django calls convert_exception_to_response on each object in the stack of Middleware objects, re-raising an error quickly pollutes the traceback displayed. Runserver_plus only needs needs traceback frames relevant to WSGIHandler Middleware objects, so only raise the traceback if it is for a WSGIHandler. If an exception is not raised here, Django eventually throws an error for not getting a valid response object for its debug view. """ global wsgi_tb # After an uncaught exception is raised the class can be found in the second frame of the tb if isinstance(tb.tb_next.tb_frame.f_locals['self'], WSGIHandler): wsgi_tb = tb six.reraise(exc_type, exc_value, tb) else: six.reraise(exc_type, exc_value, wsgi_tb)
Make source_details column an index
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddSourceDetailsColumnToPosts extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->string('source_details')->after('source')->index()->nullable()->comment('Extra details about the post source, like newsletter ID'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { $table->dropColumn('source_details'); }); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddSourceDetailsColumnToPosts extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->string('source_details')->after('source')->nullable()->comment('Extra details about the post source, like newsletter ID'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { $table->dropColumn('source_details'); }); } }
Modify command line tool parameters
package main import ( "github.com/esimov/diagram/io" "github.com/esimov/diagram/ui" "github.com/esimov/diagram/canvas" "math/rand" "time" "flag" "log" "os" ) var ( source = flag.String("in", "", "Source") destination = flag.String("out", "", "Destination") ) func main() { rand.Seed(time.Now().UTC().UnixNano()) // Generate diagram directly with command line tool. if len(os.Args) > 1 { flag.Parse() input := string(io.ReadFile(*source)) if err := canvas.DrawDiagram(input, *destination); err != nil { log.Fatal("Error on converting the ascii art to hand drawn diagrams!") } } else { ui.InitApp() } }
package main import ( "github.com/esimov/diagram/io" "github.com/esimov/diagram/ui" "github.com/esimov/diagram/canvas" "math/rand" "time" "flag" "log" "os" ) var ( source = flag.String("source", "", "Source") destination = flag.String("destination", "", "Destination") ) func main() { rand.Seed(time.Now().UTC().UnixNano()) // Generate diagram directly with command line tool. if len(os.Args) > 1 { flag.Parse() input := string(io.ReadFile(*source)) if err := canvas.DrawDiagram(input, *destination); err != nil { log.Fatal("Error on converting the ascii art to hand drawn diagrams!") } } else { ui.InitApp() } }
Send back a mimetype for JSON response.
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data), mimetype="application/json") def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data}), mimetype="application/json")
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data)) def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data}))
Use correct order of arguments of pgettext
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager 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 Affero General Public License from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('As in "email subject"', 'Subject')) body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager 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 Affero General Public License from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('Subject', 'As in "email subject"')) body = CharField(widget=Textarea, label=pgettext('Content', 'As in "content of an email"'))
Deploy logger and log levels
var cluster = require('cluster'), nconf = require('nconf'), winston = require('winston'); nconf.file({ file: './gebo.json' }); var logLevel = nconf.get('logLevel'); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true }) ] }); /** * The clustering stuff is courtesy of Rowan Manning * http://rowanmanning.com/posts/node-cluster-and-express/ * 2014-2-28 */ if (cluster.isMaster) { require('strong-cluster-express-store').setup(); // Count the machine's CPUs var cpuCount = require('os').cpus().length; // Create a worker for each CPU for (var i = 0; i < cpuCount; i += 1) { cluster.fork(); } // Listen for dying workers cluster.on('exit', function (worker) { // Replace the dead worker, // we're not sentimental if (logLevel === 'trace') logger.warn('Worker ' + worker.id + ' died :('); cluster.fork(); }); } else { /** * Run node demo.js */ var gebo = require('./index')(); gebo.start(); if (logLevel === 'trace') logger.info('Worker ' + cluster.worker.id + ' running!'); }
var cluster = require('cluster'); /** * The clustering stuff is courtesy of Rowan Manning * http://rowanmanning.com/posts/node-cluster-and-express/ * 2014-2-28 */ if (cluster.isMaster) { require('strong-cluster-express-store').setup(); // Count the machine's CPUs var cpuCount = require('os').cpus().length; // Create a worker for each CPU for (var i = 0; i < cpuCount; i += 1) { cluster.fork(); } // Listen for dying workers cluster.on('exit', function (worker) { // Replace the dead worker, // we're not sentimental console.log('Worker ' + worker.id + ' died :('); cluster.fork(); }); } else { /** * Run node demo.js */ var gebo = require('./index')(); gebo.start(); console.log('Worker ' + cluster.worker.id + ' running!'); }
Remove extra forward slash after navbar home_url()
<header class="banner navbar navbar-default navbar-static-top" role="banner"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a> </div> <nav class="collapse navbar-collapse" role="navigation"> <?php if (has_nav_menu('primary_navigation')) : wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav navbar-nav')); endif; ?> </nav> </div> </header>
<header class="banner navbar navbar-default navbar-static-top" role="banner"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo esc_url(home_url('/')); ?>/"><?php bloginfo('name'); ?></a> </div> <nav class="collapse navbar-collapse" role="navigation"> <?php if (has_nav_menu('primary_navigation')) : wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav navbar-nav')); endif; ?> </nav> </div> </header>
BUGFIX: Fix bug in request pattern that caused broken setup
<?php namespace Sandstorm\UserManagement\Security; use TYPO3\Flow\Mvc\ActionRequest; use TYPO3\Flow\Mvc\RequestInterface; use TYPO3\Flow\Security\RequestPatternInterface; /** * A request pattern that can detect and match "frontend" and "backend" mode */ class NeosRequestPattern implements RequestPatternInterface { const AREA_BACKEND = 'backend'; const AREA_FRONTEND = 'frontend'; /** * @var array */ protected $options; /** * @param array $options */ public function __construct(array $options) { $this->options = $options; } /** * Matches a \TYPO3\Flow\Mvc\RequestInterface against its set pattern rules * * @param RequestInterface $request The request that should be matched * @return boolean TRUE if the pattern matched, FALSE otherwise */ public function matchRequest(RequestInterface $request) { $shouldMatchBackend = ($this->options['area'] === self::AREA_FRONTEND) ? false : true; if (!$request instanceof ActionRequest) { return false; } $requestPath = $request->getHttpRequest()->getUri()->getPath(); $requestPathMatchesBackend = substr($requestPath, 0, 5) === '/neos' || substr($requestPath, 0, 6) === '/setup' || strpos($requestPath, '@') !== false; return $shouldMatchBackend === $requestPathMatchesBackend; } }
<?php namespace Sandstorm\UserManagement\Security; use TYPO3\Flow\Mvc\ActionRequest; use TYPO3\Flow\Mvc\RequestInterface; use TYPO3\Flow\Security\RequestPatternInterface; /** * A request pattern that can detect and match "frontend" and "backend" mode */ class NeosRequestPattern implements RequestPatternInterface { const AREA_BACKEND = 'backend'; const AREA_FRONTEND = 'frontend'; /** * @var array */ protected $options; /** * @param array $options */ public function __construct(array $options) { $this->options = $options; } /** * Matches a \TYPO3\Flow\Mvc\RequestInterface against its set pattern rules * * @param RequestInterface $request The request that should be matched * @return boolean TRUE if the pattern matched, FALSE otherwise */ public function matchRequest(RequestInterface $request) { $shouldMatchBackend = ($this->options['area'] === self::AREA_FRONTEND) ? false : true; if (!$request instanceof ActionRequest) { return false; } $requestPath = $request->getHttpRequest()->getUri()->getPath(); $requestPathMatchesBackend = substr($requestPath, 0, 5) === '/neos' || strpos($requestPath, '@') !== false; return $shouldMatchBackend === $requestPathMatchesBackend; } }
Revert "Load org inside location" This reverts commit d2c28437309a2df5a0ea9641f4619ca32fa4910f.
import React, { Component } from 'react' import globalConfig from '../../config' import { fetchLocation, fetchOrganization } from '../../core/firebaseRestAPI' import Layout from '../../components/Layout' import Loading from '../../components/Loading' import Location from '../../components/Location' export default class LocationPage extends Component { constructor(props) { super(props) this.state = { location: null, organization: null, } } componentDidMount() { const match = this.props.route.pattern.exec(window.location.pathname) const locationId = match[1] fetchLocation(locationId) .then(location => { this.setState({ location }) }) fetchOrganization(location.organizationId) .then(organization => { this.setState({ organization }) }) } componentDidUpdate() { const { location } = this.state document.title = location ? location.name : globalConfig.title } render() { const { location, organization } = this.state return ( <Layout> {(location && organization) ? <Location location={location} organization={organization} /> : <Loading /> } </Layout> ) } }
import React, { Component } from 'react' import globalConfig from '../../config' import { fetchLocation, fetchOrganization } from '../../core/firebaseRestAPI' import Layout from '../../components/Layout' import Loading from '../../components/Loading' import Location from '../../components/Location' export default class LocationPage extends Component { constructor(props) { super(props) this.state = { location: null, organization: null, } } componentDidMount() { const match = this.props.route.pattern.exec(window.location.pathname) const locationId = match[1] fetchLocation(locationId) .then(location => { this.setState({ location }) fetchOrganization(location.organizationId) .then(organization => { this.setState({ organization }) }) }) } componentDidUpdate() { const { location } = this.state document.title = location ? location.name : globalConfig.title } render() { const { location, organization } = this.state console.log(location) console.log(organization) return ( <Layout> {(location && organization) ? <Location location={location} organization={organization} /> : <Loading /> } </Layout> ) } }
Remove devices array from the Port JSON representation. The array was never populated with device data, it was only added to maintain compatability with the old REST API. Change-Id: Id89e9732c1ae229b7accc13b97283b8e000cd3ae
package net.onrc.onos.core.topology.serializers; import java.io.IOException; import net.onrc.onos.core.topology.Port; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.SerializerProvider; import org.codehaus.jackson.map.ser.std.SerializerBase; import org.openflow.util.HexString; public class PortSerializer extends SerializerBase<Port> { public PortSerializer() { super(Port.class); } @Override public void serialize(Port port, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("state", "ACTIVE"); jsonGenerator.writeStringField("dpid", HexString.toHexString(port.getDpid())); jsonGenerator.writeNumberField("number", port.getNumber()); jsonGenerator.writeStringField("desc", port.getDescription()); jsonGenerator.writeEndObject(); } }
package net.onrc.onos.core.topology.serializers; import java.io.IOException; import net.onrc.onos.core.topology.Port; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.SerializerProvider; import org.codehaus.jackson.map.ser.std.SerializerBase; import org.openflow.util.HexString; public class PortSerializer extends SerializerBase<Port> { public PortSerializer() { super(Port.class); } @Override public void serialize(Port port, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("state", "ACTIVE"); jsonGenerator.writeStringField("dpid", HexString.toHexString(port.getDpid())); jsonGenerator.writeNumberField("number", port.getNumber()); jsonGenerator.writeStringField("desc", port.getDescription()); jsonGenerator.writeArrayFieldStart("devices"); jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); } }
Edit path and external evaluation
from pygraphc.misc.LKE import * from pygraphc.evaluation.ExternalEvaluation import * # set input and output path dataset_path = '/home/hudan/Git/labeled-authlog/dataset/Hofstede2014/dataset1_perday/' groundtruth_file = dataset_path + 'Dec 1.log.labeled' analyzed_file = 'Dec 1.log' OutputPath = '/home/hudan/Git/pygraphc/result/misc/' prediction_file = OutputPath + 'Dec 1.log.perline' para = Para(path=dataset_path, logname=analyzed_file, save_path=OutputPath) # run LKE method myparser = LKE(para) time = myparser.main_process() clusters = myparser.get_clusters() original_logs = myparser.logs # perform evaluation ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file) # get evaluation of clustering performance ar = ExternalEvaluation.get_adjusted_rand(groundtruth_file, prediction_file) ami = ExternalEvaluation.get_adjusted_mutual_info(groundtruth_file, prediction_file) nmi = ExternalEvaluation.get_normalized_mutual_info(groundtruth_file, prediction_file) h = ExternalEvaluation.get_homogeneity(groundtruth_file, prediction_file) c = ExternalEvaluation.get_completeness(groundtruth_file, prediction_file) v = ExternalEvaluation.get_vmeasure(groundtruth_file, prediction_file) # print evaluation result print ar, ami, nmi, h, c, v print ('The running time of LKE is', time)
from pygraphc.misc.LKE import * from pygraphc.evaluation.ExternalEvaluation import * # set input and output path ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/Hofstede2014/dataset1/' + ip_address standard_file = standard_path + 'auth.log.anon.labeled' analyzed_file = 'auth.log.anon' prediction_file = 'lke-result-' + ip_address + '.txt' OutputPath = './results' para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath) # run LKE method myparser = LKE(para) time = myparser.main_process() clusters = myparser.get_clusters() original_logs = myparser.logs # perform evaluation ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file) homogeneity_completeness_vmeasure = ExternalEvaluation.get_homogeneity_completeness_vmeasure(standard_file, prediction_file) # print evaluation result print homogeneity_completeness_vmeasure print ('The running time of LKE is', time)
Fix lp:1302500 by evaluating an empty context to avoid error
openerp.web_context_tunnel = function(instance) { instance.web.form.FormWidget.prototype.build_context = function() { var v_context = false; var fields_values = false; // instead of using just the attr context, we merge any attr starting with context for (var key in this.node.attrs) { if (key.substring(0, 7) === "context") { if (!v_context) { fields_values = this.field_manager.build_eval_context(); v_context = new instance.web.CompoundContext(this.node.attrs[key]).set_eval_context(fields_values); } else { v_context = new instance.web.CompoundContext(this.node.attrs[key], v_context).set_eval_context(fields_values); } } } if (!v_context) { v_context = (this.field || {}).context || {}; v_context = new instance.web.CompoundContext(v_context).set_eval_context(false); } return v_context; }; }; // vim:et fdc=0 fdl=0:
openerp.web_context_tunnel = function(instance) { instance.web.form.FormWidget.prototype.build_context = function() { var v_context = false; var fields_values = false; // instead of using just the attr context, we merge any attr starting with context for (var key in this.node.attrs) { if (key.substring(0, 7) === "context") { if (!v_context) { fields_values = this.field_manager.build_eval_context(); v_context = new instance.web.CompoundContext(this.node.attrs[key]).set_eval_context(fields_values); } else { v_context = new instance.web.CompoundContext(this.node.attrs[key], v_context).set_eval_context(fields_values); } } } if (!v_context) { v_context = (this.field || {}).context || {}; } return v_context; }; }; // vim:et fdc=0 fdl=0:
Remove delivery from depends as useless
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014-15 Agile Business Group sagl # (<http://www.agilebg.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Stock move description", 'version': '1.0', 'category': 'Warehouse Management', 'author': "Agile Business Group, Odoo Community Association (OCA)", 'website': 'http://www.agilebg.com', 'license': 'AGPL-3', 'depends': [ 'stock_account', ], 'data': [ 'security/stock_security.xml', 'stock_config_settings_view.xml', 'stock_move_view.xml', ], 'test': [ 'test/stock_move_description.yml', ], 'installable': True }
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014-15 Agile Business Group sagl # (<http://www.agilebg.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Stock move description", 'version': '1.0', 'category': 'Warehouse Management', 'author': "Agile Business Group, Odoo Community Association (OCA)", 'website': 'http://www.agilebg.com', 'license': 'AGPL-3', 'depends': [ 'stock_account', 'delivery', ], 'data': [ 'security/stock_security.xml', 'stock_config_settings_view.xml', 'stock_move_view.xml', ], 'test': [ 'test/stock_move_description.yml', ], 'installable': True }
Add back in test of 2010 solution
import vcproj.solution import tempfile, filecmp import pytest @pytest.fixture(scope="session") def test_sol(): return vcproj.solution.parse('vcproj/tests/test_solution/test.sln') def test_project_files(test_sol): assert list(test_sol.project_files()) == ['test\\test.vcxproj', 'lib1\\lib1.vcxproj', 'lib2\\lib2.vcxproj'] def test_dependencies(test_sol): assert list(test_sol.dependencies('test')) == ['lib1', 'lib2'] def test_project_names(test_sol): assert list(test_sol.project_names()) == ['test', 'lib1', 'lib2'] def test_set_dependencies(test_sol): test_sol.set_dependencies('lib1', ['lib2']) assert list(test_sol.dependencies('lib1')) == ['lib2'] def test_write(): s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln') temp = tempfile.NamedTemporaryFile() temp.close() s.write(temp.name) assert filecmp.cmp('vcproj/tests/test_solution/test.sln', temp.name)
import vcproj.solution import tempfile, filecmp import pytest @pytest.fixture(scope="session") def test_sol(): return vcproj.solution.parse('vcproj/tests/test_solution/vc15sol/vc15sol.sln') def test_all_projects(test_sol): projects = test_sol.project_names() len(list(projects)) == 59 def test_project_names(test_sol): projects = test_sol.project_names() assert 'Helper' in projects assert 'MDraw' in projects def test_project_files(test_sol): proj_files = list(test_sol.project_files()) assert 'PrivateLib\\PrivateLib.vcxproj' in proj_files assert 'Helper\\Helper.vcxproj' in proj_files assert 'Resource\\Resource.vcxproj' in proj_files def test_dependencies(test_sol): deps = list(test_sol.dependencies('DXHHTest')) assert deps == ['Public', 'MDraw'] def test_set_dependencies(): s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln') s.set_dependencies('lib1', ['lib2']) assert list(s.dependencies('lib1')) == ['lib2'] def test_write(): s = vcproj.solution.parse('vcproj/tests/test_solution/test.sln') temp = tempfile.NamedTemporaryFile() temp.close() s.write(temp.name) assert filecmp.cmp('vcproj/tests/test_solution/test.sln', temp.name)
Update server site for osmlive reports
<?php function startsWith($haystack, $needle) { $length = strlen($needle); return (substr($haystack, 0, $length) === $needle); } $c = new Memcached(); $c->addServer("localhost", 11211); foreach($c->getAllKeys() as $key) { if(startsWith($key, "qreport_")) { $time_start = microtime(true); $query = substr($key, strlen("qreport_")) ; echo "====== QUERY $query ======\n"; echo file_get_contents("http://builder.osmand.net/reports/query_report?".$query."&force=true"); $time_end = microtime(true); $time = $time_end - $time_start; echo "\n====== DONE $time seconds ======\n"; } } var_dump( $c->getAllKeys() ); ?>
<?php function startsWith($haystack, $needle) { $length = strlen($needle); return (substr($haystack, 0, $length) === $needle); } $c = new Memcached(); $c->addServer("localhost", 11211); foreach($c->getAllKeys() as $key) { if(startsWith($key, "qreport_")) { $time_start = microtime(true); $query = substr($key, strlen("qreport_")) ; echo "====== QUERY $query ======\n"; echo file_get_contents("http://builder.osmand.net/reports/query_report?".$query."&force=true"); $time_end = microtime(true); $time = $time_end - $time_start; echo "\n====== DONE $time seconds ======\n"; } } // var_dump( $c->getAllKeys() ); ?>
Make s.effify handle empty msg
module.exports = { effify: (message, _, msg) => { if (!msg) { message.channel.send('Provide some text to effify.'); } else { message.channel.send(effify(msg)); } function effify(str) { const dict = { 'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u', 'ï': 'i', 'ü': 'u', }; return str.replace(/[aeiouáéíóúü]/gi, char => ( `${char}f${dict[char.toLowerCase()] || char.toLowerCase()}` )); } }, };
module.exports = { effify: (message, _, msg) => { const effify = (str) => { const dict = { 'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u', 'ï': 'i', 'ü': 'u', }; return str.replace(/[aeiouáéíóúü]/gi, char => ( `${char}f${dict[char.toLowerCase()] || char.toLowerCase()}` )); }; message.channel.send(effify(msg)); }, };
Update author & use Color's new GH repo
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name="clrsvsim", version="0.1.0", description="Color Genomics Structural Variant Simulator", author="Color", author_email="dev@color.com", url="https://github.com/color/clrsvsim", packages=["clrsvsim"], install_requires=[ "cigar>=0.1.3", "numpy>=1.10.1", "preconditions>=0.1", "pyfasta>=0.5.2", "pysam>=0.10.0", ], tests_require=[ # NOTE: `mock` is not actually needed in Python 3. # `unittest.mock` can be used instead. "mock>=2.0.0", "nose>=1.3.7", ], license="Apache-2.0", )
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name="clrsvsim", version="0.1.0", description="Color Genomics Structural Variant Simulator", author="Color Genomics", author_email="dev@color.com", url="https://github.com/ColorGenomics/clrsvsim", packages=["clrsvsim"], install_requires=[ "cigar>=0.1.3", "numpy>=1.10.1", "preconditions>=0.1", "pyfasta>=0.5.2", "pysam>=0.10.0", ], tests_require=[ # NOTE: `mock` is not actually needed in Python 3. # `unittest.mock` can be used instead. "mock>=2.0.0", "nose>=1.3.7", ], license="Apache-2.0", )
Add security_group_rule to objects registry This adds the security_group_rule module to the objects registry, which allows a service to make sure that all of its objects are registered before any could be received over RPC. We don't really have a test for any of these because of the nature of how they're imported. Refactoring this later could provide some incremental steps to making this more testable. Change-Id: Ie96021f3cdeac6addab21c42a14cd8f136eb0b27 Closes-Bug: #1264816
# Copyright 2013 IBM Corp. # # 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. def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.dns_domain') __import__('nova.objects.instance') __import__('nova.objects.instance_info_cache') __import__('nova.objects.security_group') __import__('nova.objects.migration') __import__('nova.objects.quotas') __import__('nova.objects.virtual_interface') __import__('nova.objects.network') __import__('nova.objects.block_device') __import__('nova.objects.fixed_ip') __import__('nova.objects.floating_ip') __import__('nova.objects.security_group_rule')
# Copyright 2013 IBM Corp. # # 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. def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.dns_domain') __import__('nova.objects.instance') __import__('nova.objects.instance_info_cache') __import__('nova.objects.security_group') __import__('nova.objects.migration') __import__('nova.objects.quotas') __import__('nova.objects.virtual_interface') __import__('nova.objects.network') __import__('nova.objects.block_device') __import__('nova.objects.fixed_ip') __import__('nova.objects.floating_ip')
Add owner to projects model.
package com.asana.models; import com.google.gson.annotations.SerializedName; import java.util.Collection; import com.google.api.client.util.DateTime; public class Project { public String id; public String name; public String notes; public String color; @SerializedName("archived") public boolean isArchived; @SerializedName("public") public boolean isPublic; public Collection<User> followers; public Collection<User> members; public Team team; public Workspace workspace; @SerializedName("created_at") public DateTime createdAt; @SerializedName("modified_at") public DateTime modifiedAt; public User owner; public Project() { //no-arg constructor } // constructor with id arg provided for convenience public Project(String id) { this.id = id; } }
package com.asana.models; import com.google.gson.annotations.SerializedName; import java.util.Collection; import com.google.api.client.util.DateTime; public class Project { public String id; public String name; public String notes; public String color; @SerializedName("archived") public boolean isArchived; @SerializedName("public") public boolean isPublic; public Collection<User> followers; public Collection<User> members; public Team team; public Workspace workspace; @SerializedName("created_at") public DateTime createdAt; @SerializedName("modified_at") public DateTime modifiedAt; public Project() { //no-arg constructor } // constructor with id arg provided for convenience public Project(String id) { this.id = id; } }
Fix version string format for development versions
"""EditorConfig version tools Provides ``join_version`` and ``split_version`` classes for converting __version__ strings to VERSION tuples and vice versa. """ import re __all__ = ['join_version', 'split_version'] _version_re = re.compile(r'^(\d+)\.(\d+)\.(\d+)(\..*)?$', re.VERBOSE) def join_version(version_tuple): """Return a string representation of version from given VERSION tuple""" version = "%s.%s.%s" % version_tuple[:3] if version_tuple[3] != "final": version += "-%s" % version_tuple[3] return version def split_version(version): """Return VERSION tuple for given string representation of version""" match = _version_re.search(version) if not match: return None else: split_version = list(match.groups()) if split_version[3] is None: split_version[3] = "final" split_version = map(int, split_version[:3]) + split_version[3:] return tuple(split_version)
"""EditorConfig version tools Provides ``join_version`` and ``split_version`` classes for converting __version__ strings to VERSION tuples and vice versa. """ import re __all__ = ['join_version', 'split_version'] _version_re = re.compile(r'^(\d+)\.(\d+)\.(\d+)(\..*)?$', re.VERBOSE) def join_version(version_tuple): """Return a string representation of version from given VERSION tuple""" version = "%s.%s.%s" % version_tuple[:3] if version_tuple[3] != "final": version += ".%s" % version_tuple[3] return version def split_version(version): """Return VERSION tuple for given string representation of version""" match = _version_re.search(version) if not match: return None else: split_version = list(match.groups()) if split_version[3] is None: split_version[3] = "final" split_version = map(int, split_version[:3]) + split_version[3:] return tuple(split_version)
Fix persistence issues not tracking the correct mutations
import Vue from "vue"; import Vuex, {Store} from "vuex"; import state from "./state"; import * as mutations from "./mutations"; import * as getters from "./getters"; import * as actions from "./actions"; import {persistencePlugin, i18nPlugin} from "./plugins"; Vue.use(Vuex); export default new Store({ strict: process.env.NODE_ENV !== "production", state, mutations, getters, actions, plugins: [ persistencePlugin({ prefix: "sulcalc", saveOn: { importPokemon: "sets.custom", toggleSmogonSets: "enabledSets.smogon", togglePokemonPerfectSets: "enabledSets.pokemonPerfect", toggleCustomSets: "enabledSets.custom", toggleLongRolls: "longRolls", toggleFractions: "fractions" } }), i18nPlugin() ] });
import Vue from "vue"; import Vuex, {Store} from "vuex"; import state from "./state"; import * as mutations from "./mutations"; import * as getters from "./getters"; import * as actions from "./actions"; import {persistencePlugin, i18nPlugin} from "./plugins"; Vue.use(Vuex); export default new Store({ strict: process.env.NODE_ENV !== "production", state, mutations, getters, actions, plugins: [ persistencePlugin({ prefix: "sulcalc", saveOn: { addCustomSets: "sets.custom", setSmogonSets: "enabledSets.smogon", setPokemonPerfectSets: "enabledSets.pokemonPerfect", setCustomSets: "enabledSets.custom", setLongRolls: "longRolls", setFractions: "fractions" } }), i18nPlugin() ] });
Add handler for unavailable files
var nunjucks = require('nunjucks'); var minify = require('html-minifier').minify; var FileSystemLoader = nunjucks.FileSystemLoader; var defaultMinifyOpts = { removeComments: true, collapseWhitespace: true, minifyJS: true, minifyCSS: true, ignoreCustomFragments: [/{%.*?%}/, /{{.*?}}/] }; var FileMinifyLoader = FileSystemLoader.extend({ init: function(searchPaths, opts) { this.minifyOpts = opts.minify || defaultMinifyOpts; if (!this.minifyOpts.ignoreCustomFragments) { this.minifyOpts.ignoreCustomFragments = defaultMinifyOpts.ignoreCustomFragments; } FileSystemLoader.prototype.init.call(this, searchPaths, opts); }, getSource: function(name) { var result = FileSystemLoader.prototype.getSource.call(this, name); if (!result) return null; result.src = minify(result.src, this.minifyOpts); return result; } }); module.exports = FileMinifyLoader;
var nunjucks = require('nunjucks'); var minify = require('html-minifier').minify; var FileSystemLoader = nunjucks.FileSystemLoader; var defaultMinifyOpts = { removeComments: true, collapseWhitespace: true, minifyJS: true, minifyCSS: true, ignoreCustomFragments: [/{%.*?%}/, /{{.*?}}/] }; var FileMinifyLoader = FileSystemLoader.extend({ init: function(searchPaths, opts) { this.minifyOpts = opts.minify || defaultMinifyOpts; if (!this.minifyOpts.ignoreCustomFragments) { this.minifyOpts.ignoreCustomFragments = defaultMinifyOpts.ignoreCustomFragments; } FileSystemLoader.prototype.init.call(this, searchPaths, opts); }, getSource: function(name) { var result = FileSystemLoader.prototype.getSource.call(this, name); result.src = minify(result.src, this.minifyOpts); return result; } }); module.exports = FileMinifyLoader;
Add hide alert action creator
export function changeLocation(location) { return { type: 'CHANGE_LOCATION', location }; } export function changeUnitType(unitType) { return { type: 'CHANGE_UNIT_TYPE', unitType }; } export function setAlert({type, message}) { return { type: 'SET_ALERT', alert: { type, message } }; } export function hideAlert() { return { type: 'SET_ALERT', alert: {} }; } export function setTooltip({x, y, contentElement, originTarget, title}) { return { type: 'SET_TOOLTIP', tooltip: { x, y, contentElement, originTarget, title } }; } export function hideTooltip() { return { type: 'SET_TOOLTIP', tooltip: {} }; }
export function changeLocation(location) { return { type: 'CHANGE_LOCATION', location }; } export function changeUnitType(unitType) { return { type: 'CHANGE_UNIT_TYPE', unitType }; } export function setAlert({type, message}) { return { type: 'SET_ALERT', alert: { type, message } }; } export function setTooltip({x, y, contentElement, originTarget, title}) { return { type: 'SET_TOOLTIP', tooltip: { x, y, contentElement, originTarget, title } }; } export function hideTooltip() { return { type: 'SET_TOOLTIP', tooltip: {} }; }
Fix for jQuery version of isLoading()
/*! * Ladda for jQuery * http://lab.hakim.se/ladda * MIT licensed * * Copyright (C) 2015 Hakim El Hattab, http://hakim.se */ (function( Ladda, $ ) { if ($ === undefined) return console.error( 'jQuery required for Ladda.jQuery' ); var arr = []; $ = $.extend( $, { ladda: function( arg ) { if( arg === 'stopAll' ) Ladda.stopAll(); } }); $.fn = $.extend( $.fn, { ladda: function( arg ) { var args = arr.slice.call( arguments, 1 ); if( arg === 'bind' ) { args.unshift( $( this ).selector ); Ladda.bind.apply( Ladda, args ); } else if ( arg === 'isLoading' ) { var ladda = $(this).data( 'ladda' ); return ladda.isLoading(); } else { $( this ).each( function() { var $this = $( this ), ladda; if( arg === undefined ) $this.data( 'ladda', Ladda.create( this ) ); else { ladda = $this.data( 'ladda' ); ladda[arg].apply( ladda, args ); } }); } return this; } }); }( this.Ladda, this.jQuery ));
/*! * Ladda for jQuery * http://lab.hakim.se/ladda * MIT licensed * * Copyright (C) 2015 Hakim El Hattab, http://hakim.se */ (function( Ladda, $ ) { if ($ === undefined) return console.error( 'jQuery required for Ladda.jQuery' ); var arr = []; $ = $.extend( $, { ladda: function( arg ) { if( arg === 'stopAll' ) Ladda.stopAll(); } }); $.fn = $.extend( $.fn, { ladda: function( arg ) { var args = arr.slice.call( arguments, 1 ); if( arg === 'bind' ) { args.unshift( $( this ).selector ); Ladda.bind.apply( Ladda, args ); } else { $( this ).each( function() { var $this = $( this ), ladda; if( arg === undefined ) $this.data( 'ladda', Ladda.create( this ) ); else { ladda = $this.data( 'ladda' ); ladda[arg].apply( ladda, args ); } }); } return this; } }); }( this.Ladda, this.jQuery ));
Add exclamation mark to the proposal console log
(function() { var LiveApi = window['binary-live-api'].LiveApi; var api = new LiveApi(); binary_visual.login = function login(token, callback){ api.authorize(token).then(function(value){ callback(value); }, function (reason){ console.log('Error: ' + reason.message); }); }; binary_visual.startTrade = function startTrade(options, callback){ /*api.events.on('tick', callback); api.subscribeToTicks(options.symbol).then(function(value){ console.log('Subscribed to tick for symbol:', value); }, function(reason){ console.log('Error: ' + reason.message); });*/ }; binary_visual.getPriceForProposal = function getPriceForProposal(options){ api.subscribeToPriceForContractProposal(options).then(function(value){ console.log('Proposal Accepted!\nID:', value.proposal.id); }, function(reason){ console.log('Error: ' + reason.message); }); }; })();
(function() { var LiveApi = window['binary-live-api'].LiveApi; var api = new LiveApi(); binary_visual.login = function login(token, callback){ api.authorize(token).then(function(value){ callback(value); }, function (reason){ console.log('Error: ' + reason.message); }); }; binary_visual.startTrade = function startTrade(options, callback){ /*api.events.on('tick', callback); api.subscribeToTicks(options.symbol).then(function(value){ console.log('Subscribed to tick for symbol:', value); }, function(reason){ console.log('Error: ' + reason.message); });*/ }; binary_visual.getPriceForProposal = function getPriceForProposal(options){ api.subscribeToPriceForContractProposal(options).then(function(value){ console.log('Proposal Accepted\nID:', value.proposal.id); }, function(reason){ console.log('Error: ' + reason.message); }); }; })();
Use pflag and glog packages in go server code This is per gmarek's recommendation.
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "flag" "fmt" "net/http" "github.com/golang/glog" "github.com/spf13/pflag" ) var ( argPort = pflag.Int("port", 8080, "The port to listen to for incomming HTTP requests") ) func main() { pflag.CommandLine.AddGoFlagSet(flag.CommandLine) pflag.Parse() glog.Info("Starting HTTP server on port ", *argPort) defer glog.Flush(); // Run a HTTP server that serves static files from current directory. // TODO(bryk): Disable directory listing. http.Handle("/", http.FileServer(http.Dir("./"))) glog.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *argPort), nil)) }
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "flag" "fmt" "log" "net/http" ) var ( argPort = flag.Int("port", 8080, "The port to listen to for incomming HTTP requests") ) func main() { flag.Parse() log.Print("Starting HTTP server on port ", *argPort) // Run a HTTP server that serves static files from current directory. // TODO(bryk): Disable directory listing. http.Handle("/", http.FileServer(http.Dir("./"))) err := http.ListenAndServe(fmt.Sprintf(":%d", *argPort), nil) if err != nil { log.Fatal("HTTP server error: ", err) } }
Remove message logic from player controller
define([ 'Backbone', 'text!templates/project-page/playerTemplate.html' ], function( Backbone, playerTemplate ){ var PlayersController = Backbone.View.extend({ template: _.template(playerTemplate), initialize: function(){ this.collection.off(); this.collection.on('add remove', this.render, this); this.options.project.on('change', this.render, this); }, render: function(){ this.$('.list').html(''); var template = this.template; var project = this.options.project.get('name'); var players = this.collection.where({project: project}); var $list = this.$('.list'); _.each(players, function(player){ $list.append(template({player: player.get('email')})); }); //Display last message this.options.socket.message.trigger('change'); } }); return PlayersController; });
define([ 'Backbone', 'text!templates/project-page/playerTemplate.html' ], function( Backbone, playerTemplate ){ var PlayersController = Backbone.View.extend({ template: _.template(playerTemplate), initialize: function(){ this.collection.off(); this.options.message.off(); this.collection.on('add remove', this.render, this); this.options.project.on('change', this.render, this); this.options.message.on('change', this.showMessage, this); }, showMessage: function(){ var message = this.options.message.get('message'); this.$('.js-message').text(message); }, render: function(){ this.$('.list').html(''); var template = this.template; var project = this.options.project.get('name'); var players = this.collection.where({project: project}); var $list = this.$('.list'); _.each(players, function(player){ $list.append(template({player: player.get('email')})); }); } }); return PlayersController; });
i18n: Fix reference error for localstorage.
// commonjs code goes here import i18next from 'i18next'; import localstorage from './localstorage'; window.i18n = i18next; i18next.init({ lng: 'lang', resources: { lang: { translation: page_params.translation_data, }, }, nsSeparator: false, keySeparator: false, interpolation: { prefix: "__", suffix: "__", }, returnEmptyString: false, // Empty string is not a valid translation. }); // garbage collect all old-style i18n translation maps in localStorage. $(function () { if (!localstorage.supported()) { return; } // this collects all localStorage keys that match the format of: // i18next:dddddddddd:w+ => 1484902202:en // these are all language translation strings. var translations = Object.keys(localStorage).filter(function (key) { return /^i18next:\d{10}:\w+$/.test(key); }); // remove cached translations of older versions. translations.forEach(function (translation_key) { localStorage.removeItem(translation_key); }); return this; });
// commonjs code goes here import i18next from 'i18next'; window.i18n = i18next; i18next.init({ lng: 'lang', resources: { lang: { translation: page_params.translation_data, }, }, nsSeparator: false, keySeparator: false, interpolation: { prefix: "__", suffix: "__", }, returnEmptyString: false, // Empty string is not a valid translation. }); // garbage collect all old-style i18n translation maps in localStorage. $(function () { if (!localstorage.supported()) { return; } // this collects all localStorage keys that match the format of: // i18next:dddddddddd:w+ => 1484902202:en // these are all language translation strings. var translations = Object.keys(localStorage).filter(function (key) { return /^i18next:\d{10}:\w+$/.test(key); }); // remove cached translations of older versions. translations.forEach(function (translation_key) { localStorage.removeItem(translation_key); }); return this; });
Remove @Override annotation from 1.7 added method
package org.stagemonitor.core.instrument; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; import org.stagemonitor.core.Stagemonitor; /** * This is not a real Driver, it is just used to attach the stagemonitor agent as early in the lifecycle as possible. * Because the earlier the agent is attached, the less classes have to be retransformed, which is a expensive operation. * * Some application server as wildfly load all Driver implementations with a ServiceLoader at startup and even * before ServletContainerInitializer classes are loaded. */ public class StagemonitorRuntimeAgentAttacherDriver implements Driver { static { Stagemonitor.init(); } @Override public Connection connect(String url, Properties info) throws SQLException { return null; } @Override public boolean acceptsURL(String url) throws SQLException { return false; } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } }
package org.stagemonitor.core.instrument; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; import org.stagemonitor.core.Stagemonitor; /** * This is not a real Driver, it is just used to attach the stagemonitor agent as early in the lifecycle as possible. * Because the earlier the agent is attached, the less classes have to be retransformed, which is a expensive operation. * * Some application server as wildfly load all Driver implementations with a ServiceLoader at startup and even * before ServletContainerInitializer classes are loaded. */ public class StagemonitorRuntimeAgentAttacherDriver implements Driver { static { Stagemonitor.init(); } @Override public Connection connect(String url, Properties info) throws SQLException { return null; } @Override public boolean acceptsURL(String url) throws SQLException { return false; } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } }
Fix error of applying dask twice
import dask.array as da import h5py import clodius.tiles.hitile as hghi import numpy as np import os.path as op import tempfile def test_hitile(): array_size = int(1e6) chunk_size = 2**19 data = np.random.random((array_size,)) with tempfile.TemporaryDirectory() as td: output_file = op.join(td, 'blah.hitile') hghi.array_to_hitile( data, output_file, zoom_step=6, chunks=(chunk_size,) ) with h5py.File(output_file, 'r') as f: (means, mins, maxs) = hghi.get_data(f, 0, 0) # print("means, mins:", means[:10], mins[:10], maxs[:10])
import dask.array as da import h5py import clodius.tiles.hitile as hghi import numpy as np import os.path as op import tempfile def test_hitile(): array_size = int(1e6) chunk_size = 2**19 data = da.from_array(np.random.random((array_size,)), chunks=(chunk_size,)) with tempfile.TemporaryDirectory() as td: output_file = op.join(td, 'blah.hitile') hghi.array_to_hitile(data, output_file, zoom_step=6) with h5py.File(output_file, 'r') as f: (means, mins, maxs) = hghi.get_data(f, 0, 0) # print("means, mins:", means[:10], mins[:10], maxs[:10])
Purge style loader from webpack config
import path from 'path' import webpack from 'webpack' const { NODE_ENV } = process.env const production = NODE_ENV === 'production' const plugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV) }) ] let extension = '.js' if (production) { plugins.push(new webpack.optimize.UglifyJsPlugin()) extension = '.min.js' } module.exports = [ { entry: [ 'babel-polyfill', 'whatwg-fetch', path.join(__dirname, 'src', 'browser', 'index.js') ], output: { path: path.join(__dirname, 'dist'), filename: `bundle${extension}` }, plugins, module: { loaders: [ { test: /.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' } ] } } ]
import path from 'path' import webpack from 'webpack' const { NODE_ENV } = process.env const production = NODE_ENV === 'production' const plugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV) }) ] let extension = '.js' if (production) { plugins.push(new webpack.optimize.UglifyJsPlugin()) extension = '.min.js' } module.exports = [ { entry: [ 'babel-polyfill', 'whatwg-fetch', path.join(__dirname, 'src', 'browser', 'index.js') ], output: { path: path.join(__dirname, 'dist'), filename: `bundle${extension}` }, plugins, module: { loaders: [ { test: /.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' } ] } } ]
Rewrite Disqus to use the new scope selection system
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://disqus.com/' docs_url = 'http://disqus.com/api/docs/' category = 'Social' # URLs to interact with the API authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/' access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/' api_domain = 'disqus.com' available_permissions = [ (None, 'read data on your behalf'), ('write', 'read and write data on your behalf'), ('admin', 'read and write data on your behalf and moderate your forums'), ] permissions_widget = 'radio' bearer_type = token_uri def get_scope_string(self, scopes): # Disqus doesn't follow the spec on this point return ','.join(scopes) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/3.0/users/details.json') return r.json[u'response'][u'id']
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://disqus.com/' docs_url = 'http://disqus.com/api/docs/' category = 'Social' # URLs to interact with the API authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/' access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/' api_domain = 'disqus.com' available_permissions = [ (None, 'read data on your behalf'), ('write', 'write data on your behalf'), ('admin', 'moderate your forums'), ] bearer_type = token_uri def get_scope_string(self, scopes): # Disqus doesn't follow the spec on this point return ','.join(scopes) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/3.0/users/details.json') return r.json[u'response'][u'id']
Add starting anchor to regular expression.
package sqlancer.common; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class DBMSCommon { private static final Pattern sqlancerIndexPattern = Pattern.compile("^i\\d+"); private DBMSCommon() { } public static String createTableName(int nr) { return String.format("t%d", nr); } public static String createColumnName(int nr) { return String.format("c%d", nr); } public static String createIndexName(int nr) { return String.format("i%d", nr); } public static boolean matchesIndexName(String indexName) { Matcher matcher = sqlancerIndexPattern.matcher(indexName); return matcher.matches(); } }
package sqlancer.common; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class DBMSCommon { private static final Pattern sqlancerIndexPattern = Pattern.compile("i\\d+"); private DBMSCommon() { } public static String createTableName(int nr) { return String.format("t%d", nr); } public static String createColumnName(int nr) { return String.format("c%d", nr); } public static String createIndexName(int nr) { return String.format("i%d", nr); } public static boolean matchesIndexName(String indexName) { Matcher matcher = sqlancerIndexPattern.matcher(indexName); return matcher.matches(); } }
Simplify test code for jcasc support
package com.cloudbees.plugins.deployer.casc; import com.cloudbees.plugins.deployer.DeployNowColumn; import hudson.model.View; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import java.util.stream.StreamSupport; public class ConfigurationAsCodeTest { @Rule public JenkinsConfiguredWithCodeRule r = new JenkinsConfiguredWithCodeRule(); @Test @ConfiguredWithCode("view-configuration.yml") public void shouldBeAbleToConfigureAView() throws Exception { final View view = r.jenkins.getView("view-with-deployNowColumn"); Assert.assertNotNull(view); Assert.assertTrue( StreamSupport.stream(view.getColumns().spliterator(), false) .anyMatch( item -> item instanceof DeployNowColumn ) ); } }
package com.cloudbees.plugins.deployer.casc; import com.cloudbees.plugins.deployer.DeployNowColumn; import hudson.model.View; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; public class ConfigurationAsCodeTest { @Rule public JenkinsConfiguredWithCodeRule r = new JenkinsConfiguredWithCodeRule(); @Test @ConfiguredWithCode("view-configuration.yml") public void shouldBeAbleToConfigureAView() throws Exception { final View view = r.jenkins.getView("view-with-deployNowColumn"); Assert.assertNotNull(view); MatcherAssert.assertThat(view.getColumns(), Matchers.hasItem(Matchers.instanceOf(DeployNowColumn.class)) ); } }
Move Flickr over to its newly-secured API domain
import foauth.providers class Flickr(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.flickr.com/' docs_url = 'http://www.flickr.com/services/api/' category = 'Pictures' # URLs to interact with the API request_token_url = 'http://www.flickr.com/services/oauth/request_token' authorize_url = 'http://www.flickr.com/services/oauth/authorize' access_token_url = 'http://www.flickr.com/services/oauth/access_token' api_domain = 'api.flickr.com' available_permissions = [ (None, 'access your public and private photos'), ('write', 'upload, edit and replace your photos'), ('delete', 'upload, edit, replace and delete your photos'), ] permissions_widget = 'radio' def get_authorize_params(self, redirect_uri, scopes): params = super(Flickr, self).get_authorize_params(redirect_uri, scopes) params['perms'] = scopes[0] or 'read' return params def get_user_id(self, key): url = u'/services/rest/?method=flickr.people.getLimits' url += u'&format=json&nojsoncallback=1' r = self.api(key, self.api_domain, url) return r.json()[u'person'][u'nsid']
import foauth.providers class Flickr(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.flickr.com/' docs_url = 'http://www.flickr.com/services/api/' category = 'Pictures' # URLs to interact with the API request_token_url = 'http://www.flickr.com/services/oauth/request_token' authorize_url = 'http://www.flickr.com/services/oauth/authorize' access_token_url = 'http://www.flickr.com/services/oauth/access_token' api_domain = 'secure.flickr.com' available_permissions = [ (None, 'access your public and private photos'), ('write', 'upload, edit and replace your photos'), ('delete', 'upload, edit, replace and delete your photos'), ] permissions_widget = 'radio' def get_authorize_params(self, redirect_uri, scopes): params = super(Flickr, self).get_authorize_params(redirect_uri, scopes) params['perms'] = scopes[0] or 'read' return params def get_user_id(self, key): url = u'/services/rest/?method=flickr.people.getLimits' url += u'&format=json&nojsoncallback=1' r = self.api(key, self.api_domain, url) return r.json()[u'person'][u'nsid']
Replace jQuery with pure Javascript
/** * Tatoeba Project, free collaborative creation of multilingual corpuses project * Copyright (C) 2010 HO Ngoc Phuong Trang <tranglich@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Polyfill for IE */ if (window.NodeList && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; } var addAudio = function () { document.querySelectorAll('.audioAvailable').forEach(function(elem) { elem.addEventListener('click', function(event) { var audioURL = event.target.getAttribute('href'); var audio = new Audio(audioURL); audio.play(); }); }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', addAudio); } else { addAudio(); }
/** * Tatoeba Project, free collaborative creation of multilingual corpuses project * Copyright (C) 2010 HO Ngoc Phuong Trang <tranglich@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ $(document).ready(function () { $(document).watch('addrule', function () { $('.audioAvailable').off(); $('.audioAvailable').click(function () { var audioURL = $(this).attr('href'); var audio = new Audio(audioURL); audio.play(); }); }); });
Change build directory to `dist`
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: './src/index.js', output: { filename: 'bundle.js', path: path.join(__dirname, 'dist'), }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }, { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: 'src/index.html', }), ], devServer: { contentBase: path.join(__dirname, 'dist'), }, };
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: './src/index.js', output: { filename: 'bundle.js', path: path.join(__dirname, 'public'), }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }, { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: 'src/index.html', }), ], devServer: { contentBase: path.join(__dirname, 'public'), }, };
Extend base settings for test settings. Don't use live cache backend for tests.
from ._base import * # DJANGO ###################################################################### ALLOWED_HOSTS = ('*', ) CSRF_COOKIE_SECURE = False # Don't require HTTPS for CSRF cookie SESSION_COOKIE_SECURE = False # Don't require HTTPS for session cookie DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
from ._develop import * # DJANGO ###################################################################### DATABASES['default'].update({ 'TEST': { 'NAME': DATABASES['default']['NAME'], # See: https://docs.djangoproject.com/en/1.7/ref/settings/#serialize 'SERIALIZE': False, }, }) INSTALLED_APPS += ( 'fluent_pages.pagetypes.fluentpage', 'icekit.tests', ) ROOT_URLCONF = 'icekit.tests.urls' TEMPLATES_DJANGO['DIRS'].insert( 0, os.path.join(BASE_DIR, 'icekit', 'tests', 'templates')), # ICEKIT ###################################################################### # RESPONSE_PAGE_PLUGINS = ['ImagePlugin', ] # HAYSTACK #################################################################### # HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', # }, # } # TRAVIS ###################################################################### if 'TRAVIS' in os.environ: NOSE_ARGS.remove('--with-progressive')
Update test to use example json
// Package flight_test package flight_test import ( "log" "net/http/httptest" "testing" "github.com/blue-jay/blueprint/lib/env" "github.com/blue-jay/blueprint/lib/flight" ) // TestRace tests for race conditions. func TestRace(t *testing.T) { for i := 0; i < 100; i++ { go func() { // Load the configuration file config, err := env.LoadConfig("../../env.json.example") if err != nil { t.Fatal(err) } // Set up the session cookie store config.Session.SetupConfig() // Set up the views config.View.SetTemplates(config.Template.Root, config.Template.Children) // Store the view in flight flight.StoreConfig(*config) // Test the context retrieval w := httptest.NewRecorder() r := httptest.NewRequest("GET", "http://localhost/foo", nil) c := flight.Context(w, r) c.Config.Asset.Folder = "foo" log.Println(c.Config.Asset.Folder) c.View.BaseURI = "bar" log.Println(c.View.BaseURI) }() } }
// Package flight_test package flight_test import ( "log" "net/http/httptest" "testing" "github.com/blue-jay/blueprint/lib/env" "github.com/blue-jay/blueprint/lib/flight" ) // TestRace tests for race conditions. func TestRace(t *testing.T) { for i := 0; i < 100; i++ { go func() { // Load the configuration file config, err := env.LoadConfig("../../env.json") if err != nil { t.Fatal(err) } // Set up the session cookie store config.Session.SetupConfig() // Set up the views config.View.SetTemplates(config.Template.Root, config.Template.Children) // Store the view in flight flight.StoreConfig(*config) // Test the context retrieval w := httptest.NewRecorder() r := httptest.NewRequest("GET", "http://localhost/foo", nil) c := flight.Context(w, r) c.Config.Asset.Folder = "foo" log.Println(c.Config.Asset.Folder) c.View.BaseURI = "bar" log.Println(c.View.BaseURI) }() } }
Add number of objects for 3D layers
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Link } from 'routes'; // Redux import { connect } from 'react-redux'; // Components import Legend from 'components/app/pulse/Legend'; function LayerCard(props) { const { layerActive, layerPoints } = props.pulse; const className = classNames({ 'c-layer-card': true, '-hidden': layerActive === null }); const datasetId = (layerActive !== null) ? layerActive.attributes.dataset : null; return ( <div className={className}> <h2>{layerActive && layerActive.attributes.name}</h2> <p>{layerActive && layerActive.attributes.description}</p> {layerPoints && layerPoints.length > 0 && <p>Number of objects: {layerPoints.length}</p> } <Legend layerActive={layerActive} className={{ color: '-dark' }} /> { datasetId && <Link route={'explore_detail'} params={{ id: datasetId }} > <a className="link_button" >Explore the data</a> </Link> } </div> ); } LayerCard.propTypes = { // PROPS pulse: PropTypes.object }; const mapStateToProps = state => ({ pulse: state.pulse }); export default connect(mapStateToProps, null)(LayerCard);
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Legend from 'components/app/pulse/Legend'; import { Link } from 'routes'; function LayerCard(props) { const { layerActive } = props; const className = classNames({ 'c-layer-card': true, '-hidden': layerActive === null }); const datasetId = (layerActive !== null) ? layerActive.attributes.dataset : null; return ( <div className={className}> <h2>{layerActive && layerActive.attributes.name}</h2> <p>{layerActive && layerActive.attributes.description}</p> <Legend layerActive={layerActive} className={{ color: '-dark' }} /> { datasetId && <Link route={'explore_detail'} params={{ id: datasetId }} > <a className="link_button" >Explore the data</a> </Link> } </div> ); } LayerCard.propTypes = { // PROPS layerActive: PropTypes.object }; export default LayerCard;
Check whether the style's cover photo exists during upgrade to 5.4
<?php /** * Generates the WebP variant for cover photos of styles. * * @author Alexander Ebert * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core */ use wcf\data\style\StyleEditor; use wcf\data\style\StyleList; use wcf\system\package\SplitNodeException; $styleList = new StyleList(); $styleList->readObjects(); foreach ($styleList as $style) { if (!$style->coverPhotoExtension) { continue; } if (\file_exists($style->getCoverPhotoLocation(true))) { continue; } $styleEditor = new StyleEditor($style); // If the cover photo does not exist ... if (!\file_exists($style->getCoverPhotoLocation(false))) { // ... then the database information is wrong and we clear the cover photo. $styleEditor->update([ 'coverPhotoExtension' => '', ]); continue; } $result = $styleEditor->createCoverPhotoVariant(); if ($result === null) { continue; } // Queue the script again to prevent running into a timeout. throw new SplitNodeException(); }
<?php /** * Generates the WebP variant for cover photos of styles. * * @author Alexander Ebert * @copyright 2001-2021 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core */ use wcf\data\style\StyleEditor; use wcf\data\style\StyleList; use wcf\system\package\SplitNodeException; $styleList = new StyleList(); $styleList->readObjects(); foreach ($styleList as $style) { if (!$style->coverPhotoExtension) { continue; } if (\file_exists($style->getCoverPhotoLocation(true))) { continue; } $styleEditor = new StyleEditor($style); $result = $styleEditor->createCoverPhotoVariant(); if ($result === null) { continue; } // Queue the script again to prevent running into a timeout. throw new SplitNodeException(); }
Move the list class to the div
'use strict'; var Component = require('../../ui/Component'); var $$ = Component.$$; var ListHtmlConverter = require('./ListHTMLConverter'); var ListItemComponent = require('./ListItemComponent'); var ListComponent = Component.extend({ displayName: "ListComponent", initialize: function() { this.doc = this.props.doc; this.doc.getEventProxy('path').connect(this, [this.props.node.id, 'items'], this.onItemsChanged); this.doc.getEventProxy('path').connect(this, [this.props.node.id, 'ordered'], this.onOrderChanged); }, dispose: function() { this.doc.getEventProxy('path').disconnect(this); this.doc = null; }, render: function() { var elem = ListHtmlConverter.render(this.props.node, { createListElement: function(list) { var tagName = list.ordered ? 'ol' : 'ul'; return $$(tagName) .attr('data-id', list.id); }, renderListItem: function(item) { return $$(ListItemComponent, {node: item}); } }); return $$('div').addClass('sc-list').append(elem); }, onItemsChanged: function() { this.rerender(); }, onOrderChanged: function() { this.rerender(); } }); module.exports = ListComponent;
'use strict'; var Component = require('../../ui/Component'); var $$ = Component.$$; var ListHtmlConverter = require('./ListHTMLConverter'); var ListItemComponent = require('./ListItemComponent'); var ListComponent = Component.extend({ displayName: "ListComponent", initialize: function() { this.doc = this.props.doc; this.doc.getEventProxy('path').connect(this, [this.props.node.id, 'items'], this.onItemsChanged); this.doc.getEventProxy('path').connect(this, [this.props.node.id, 'ordered'], this.onOrderChanged); }, dispose: function() { this.doc.getEventProxy('path').disconnect(this); this.doc = null; }, render: function() { var elem = ListHtmlConverter.render(this.props.node, { createListElement: function(list) { var tagName = list.ordered ? 'ol' : 'ul'; return $$(tagName) .attr('data-id', list.id) .addClass('sc-list'); }, renderListItem: function(item) { return $$(ListItemComponent, {node: item}); } }); return $$('div').append(elem); }, onItemsChanged: function() { this.rerender(); }, onOrderChanged: function() { this.rerender(); } }); module.exports = ListComponent;
FIX formatting on meet markdown
const MySql = require("./MySql.js"); const entities = require("entities"); class Meet{ constructor(obj){ Object.keys(obj).forEach(k=>this[k]=entities.decodeHTML(obj[k])); } asMarkdown(){ return `[${this.post_title}](${this.guid}) _${this.meet_start_time}_`; } } Meet.fromObjArray = function(objArray){ return objArray.map(o=>new Meet(o)); }; function getAllMeets(){ return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`) .then(results=>Meet.fromObjArray(results.results)); } function getUpcomingMeets(){ return MySql.query(` SELECT CAST(meta_value AS DATE) AS meet_start_time, wp_posts.* FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE() `).then(results=>Meet.fromObjArray(results.results)); } module.exports = {getAllMeets,getUpcomingMeets};
const MySql = require("./MySql.js"); const entities = require("entities"); class Meet{ constructor(obj){ Object.keys(obj).forEach(k=>this[k]=entities.decodeHTML(obj[k])); } asMarkdown(){ return `*${this.post_title}* ${this.meet_start_time}\n${this.guid}`; } } Meet.fromObjArray = function(objArray){ return objArray.map(o=>new Meet(o)); }; function getAllMeets(){ return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`) .then(results=>Meet.fromObjArray(results.results)); } function getUpcomingMeets(){ return MySql.query(` SELECT CAST(meta_value AS DATE) AS meet_start_time, wp_posts.* FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE() `).then(results=>Meet.fromObjArray(results.results)); } module.exports = {getAllMeets,getUpcomingMeets};
Add future as required package (for Python2)
from setuptools import setup setup(name='mathprogbasepy', version='0.1.1', author='Bartolomeo Stellato', description='Low level interface for mathematical programming solvers.', url='http://github.com/bstellato/mathprogbasepy/', package_dir={'mathprogbasepy': 'mathprogbasepy'}, install_requires=["numpy >= 1.7", "scipy >= 0.13.2", "future"], license='Apache 2.0', packages=['mathprogbasepy', 'mathprogbasepy.quadprog', 'mathprogbasepy.quadprog.solvers', 'mathprogbasepy.unittests'])
from setuptools import setup setup(name='mathprogbasepy', version='0.1.1', author='Bartolomeo Stellato', description='Low level interface for mathematical programming solvers.', url='http://github.com/bstellato/mathprogbasepy/', package_dir={'mathprogbasepy': 'mathprogbasepy'}, install_requires=["numpy >= 1.7", "scipy >= 0.13.2"], license='Apache 2.0', packages=['mathprogbasepy', 'mathprogbasepy.quadprog', 'mathprogbasepy.quadprog.solvers', 'mathprogbasepy.unittests'])
Add a route for retrieval of device ID
"use strict"; let { getInternetStatus, getLastRefresh, getNumberOfUsersConnected, getSystemMemory, getSystemSpace, getSystemCpu, getSystemVersion, getDeviceID } = require("../controllers/dashboard.controller") const { saveTelemetryData } = require('../middlewares/telemetry.middleware.js'); module.exports = app => { app.get("/dashboard/system/internetStatus", getInternetStatus); app.get("/dashboard/system/lastRefresh", getLastRefresh); app.get("/dashboard/system/usersConnected", getNumberOfUsersConnected); app.get("/dashboard/system/memory", getSystemMemory); app.get("/dashboard/system/space", getSystemSpace); app.get("/dashboard/system/cpu", getSystemCpu); app.get("/dashboard/system/version", getSystemVersion); app.get("/dashboard/system/deviceID", getDeviceID); }
"use strict"; let { getInternetStatus, getLastRefresh, getNumberOfUsersConnected, getSystemMemory, getSystemSpace, getSystemCpu, getSystemVersion } = require("../controllers/dashboard.controller") const { saveTelemetryData } = require('../middlewares/telemetry.middleware.js'); module.exports = app => { app.get("/dashboard/system/internetStatus", getInternetStatus); app.get("/dashboard/system/lastRefresh", getLastRefresh); app.get("/dashboard/system/usersConnected", getNumberOfUsersConnected); app.get("/dashboard/system/memory", getSystemMemory); app.get("/dashboard/system/space", getSystemSpace); app.get("/dashboard/system/cpu", getSystemCpu); app.get("/dashboard/system/version", getSystemVersion); }
Return null when Firefox is not found on Windows
var osx = process.platform === 'darwin' var win = process.platform === 'win32' var other = !osx && !win var fs = require('fs') if (other) { try { module.exports = require('which').sync('firefox') } catch (_) { module.exports = null } } else if (osx) { var regPath = '/Applications/Firefox.app/Contents/MacOS/firefox' var altPath = require('userhome')(regPath.slice(1)) module.exports = fs.existsSync(regPath) ? regPath : altPath } else { var suffix = '\\Mozilla Firefox\\firefox.exe' module.exports = [ process.env.LOCALAPPDATA , process.env.PROGRAMFILES , process.env['PROGRAMFILES(X86)'] ].reduce(function (existing, prefix) { var exe = prefix + suffix return existing || fs.existsSync(exe) ? exe : null }, null) }
var osx = process.platform === 'darwin' var win = process.platform === 'win32' var other = !osx && !win var fs = require('fs') if (other) { try { module.exports = require('which').sync('firefox') } catch (_) { module.exports = null } } else if (osx) { var regPath = '/Applications/Firefox.app/Contents/MacOS/firefox' var altPath = require('userhome')(regPath.slice(1)) module.exports = fs.existsSync(regPath) ? regPath : altPath } else { var suffix = '\\Mozilla Firefox\\firefox.exe'; var prefixes = [ process.env.LOCALAPPDATA , process.env.PROGRAMFILES , process.env['PROGRAMFILES(X86)'] ] for (var i = 0; i < prefixes.length; i++) { var exe = prefixes[i] + suffix if (fs.existsSync(exe)) { module.exports = exe break } } module.exports = module.exports || null }
Add `polymorphic` to `INSTALLED_APPS`, and also `MessageMiddlware` (because Django wants it).
""" Test settings for ``polymorphic_auth`` app. """ AUTH_USER_MODEL = 'polymorphic_auth.User' POLYMORPHIC_AUTH = { 'DEFAULT_CHILD_MODEL': 'polymorphic_auth_email.EmailUser', } DATABASES = { 'default': { 'ATOMIC_REQUESTS': True, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'polymorphic_auth', } } DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django_nose', 'polymorphic', 'polymorphic_auth', 'polymorphic_auth.tests', 'polymorphic_auth.usertypes.email', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'polymorphic_auth.tests.urls' SECRET_KEY = 'secret-key' STATIC_URL = '/static/' TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
""" Test settings for ``polymorphic_auth`` app. """ AUTH_USER_MODEL = 'polymorphic_auth.User' POLYMORPHIC_AUTH = { 'DEFAULT_CHILD_MODEL': 'polymorphic_auth_email.EmailUser', } DATABASES = { 'default': { 'ATOMIC_REQUESTS': True, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'polymorphic_auth', } } DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django_nose', 'polymorphic_auth', 'polymorphic_auth.tests', 'polymorphic_auth.usertypes.email', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'polymorphic_auth.tests.urls' SECRET_KEY = 'secret-key' STATIC_URL = '/static/' TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
[native] Replace now-missing thread create icon https://github.com/oblador/react-native-vector-icons/issues/823 IonIcons removed `ios-create-outline` for some reason
// @flow import type { Navigate } from '../navigation/route-names'; import * as React from 'react'; import { StyleSheet } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import PropTypes from 'prop-types'; import { ComposeThreadRouteName } from '../navigation/route-names'; import Button from '../components/button.react'; type Props = {| navigate: Navigate, |}; class ComposeThreadButton extends React.PureComponent<Props> { static propTypes = { navigate: PropTypes.func.isRequired, }; render() { return ( <Button onPress={this.onPress} androidBorderlessRipple={true}> <Icon name="pencil-plus-outline" size={26} style={styles.composeButton} color="#036ABB" /> </Button> ); } onPress = () => { this.props.navigate({ routeName: ComposeThreadRouteName, params: {}, }); } } const styles = StyleSheet.create({ composeButton: { paddingHorizontal: 10, }, }); export default ComposeThreadButton;
// @flow import type { Navigate } from '../navigation/route-names'; import * as React from 'react'; import { StyleSheet } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; import PropTypes from 'prop-types'; import { ComposeThreadRouteName } from '../navigation/route-names'; import Button from '../components/button.react'; type Props = {| navigate: Navigate, |}; class ComposeThreadButton extends React.PureComponent<Props> { static propTypes = { navigate: PropTypes.func.isRequired, }; render() { return ( <Button onPress={this.onPress} androidBorderlessRipple={true}> <Icon name="ios-create-outline" size={30} style={styles.composeButton} color="#036AFF" /> </Button> ); } onPress = () => { this.props.navigate({ routeName: ComposeThreadRouteName, params: {}, }); } } const styles = StyleSheet.create({ composeButton: { paddingHorizontal: 10, }, }); export default ComposeThreadButton;
Fix typo in reservation delete modal selector
import { createSelector } from 'reselect'; import ActionTypes from 'constants/ActionTypes'; import ModalTypes from 'constants/ModalTypes'; import modalIsOpenSelectorFactory from 'selectors/factories/modalIsOpenSelectorFactory'; import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory'; const toDeleteSelector = (state) => state.ui.reservation.toDelete; const resourcesSelector = (state) => state.data.resources; const reservationDeleteModalSelector = createSelector( modalIsOpenSelectorFactory(ModalTypes.DELETE_RESERVATION), requestIsActiveSelectorFactory(ActionTypes.API.RESERVATION_DELETE_REQUEST), resourcesSelector, toDeleteSelector, ( deleteReservationModalIsOpen, isDeletingReservations, resources, reservationsToDelete ) => { return { isDeletingReservations, reservationsToDelete, resources, show: deleteReservationModalIsOpen, }; } ); export default reservationDeleteModalSelector;
import { createSelector } from 'reselect'; import ActionTypes from 'constants/ActionTypes'; import ModalTypes from 'constants/ModalTypes'; import modalIsOpenSelectorFactory from 'selectors/factories/modalIsOpenSelectorFactory'; import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory'; const toDeleteSelector = (state) => state.ui.reservation.toDelete; const resourcesSelector = (state) => state.data.resources; const reservationDeleteModalSelector = createSelector( modalIsOpenSelectorFactory(ModalTypes.DELETE_RESERVATION), requestIsActiveSelectorFactory(ActionTypes.API.RESERVATIONS_DELETE_REQUEST), resourcesSelector, toDeleteSelector, ( deleteReservationModalIsOpen, isDeletingReservations, resources, reservationsToDelete ) => { return { isDeletingReservations, reservationsToDelete, resources, show: deleteReservationModalIsOpen, }; } ); export default reservationDeleteModalSelector;
Send help if command not recognised
package qbot import ( "strings" "github.com/doozr/guac" "github.com/doozr/jot" "github.com/doozr/qbot/command" "github.com/doozr/qbot/queue" "github.com/doozr/qbot/util" ) // MessageHandler handles an incoming message event. type MessageHandler func(queue.Queue, guac.MessageEvent) (queue.Queue, error) // CommandMap is a dictionary of command strings to functions. type CommandMap map[string]command.Command // CreateMessageHandler creates a message handler that calls a command function. func CreateMessageHandler(commands CommandMap, notify Notifier) MessageHandler { return func(oq queue.Queue, m guac.MessageEvent) (q queue.Queue, err error) { text := strings.Trim(m.Text, " \t\r\n") var response command.Notification cmd, args := util.StringPop(text) cmd = strings.ToLower(cmd) jot.Printf("message dispatch: message %s with cmd %s and args %v", m.Text, cmd, args) fn, ok := commands[cmd] if !ok { fn, ok = commands["help"] if !ok { q = oq return } } q, response = fn(oq, m.Channel, m.User, args) err = notify(response) return } }
package qbot import ( "strings" "github.com/doozr/guac" "github.com/doozr/jot" "github.com/doozr/qbot/command" "github.com/doozr/qbot/queue" "github.com/doozr/qbot/util" ) // MessageHandler handles an incoming message event. type MessageHandler func(queue.Queue, guac.MessageEvent) (queue.Queue, error) // CommandMap is a dictionary of command strings to functions. type CommandMap map[string]command.Command // CreateMessageHandler creates a message handler that calls a command function. func CreateMessageHandler(commands CommandMap, notify Notifier) MessageHandler { return func(oq queue.Queue, m guac.MessageEvent) (q queue.Queue, err error) { text := strings.Trim(m.Text, " \t\r\n") var response command.Notification cmd, args := util.StringPop(text) cmd = strings.ToLower(cmd) jot.Printf("message dispatch: message %s with cmd %s and args %v", m.Text, cmd, args) fn, ok := commands[cmd] if !ok { q = oq return } q, response = fn(oq, m.Channel, m.User, args) err = notify(response) return } }
Add command to seed database
#!/usr/bin/env python import os from app import create_app, db from app.models import User, Role, Permission from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role, Permission=Permission) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def seed(): """Seed the database.""" Role.insert_roles() @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app, db from app.models import User, Role, Permission from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role, Permission=Permission) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
Fix exception string for missing project
import sys import pytoml as toml from proppy.exceptions import InvalidCommand, InvalidConfiguration from proppy.proposal import Proposal from proppy.render import to_pdf def main(filename): if not filename.endswith('.toml'): raise InvalidCommand("You must use a TOML file as input") with open(filename, 'rb') as f: print("Parsing %s" % filename) config = toml.load(f) theme = config.get('theme') if not theme: raise InvalidConfiguration("Missing theme in TOML file") if not config.get('customer'): raise InvalidConfiguration("Missing customer in TOML file") if not config.get('project'): raise InvalidConfiguration("Missing project in TOML file") proposal = Proposal(config) if proposal.is_valid(): print("Valid proposal, saving it.") to_pdf(theme, proposal) print("Proposal rendered and saved.") else: # show errors and do nothing proposal.print_errors() def run_main(): if len(sys.argv) != 2: raise InvalidCommand("Invalid number of arguments") main(sys.argv[1]) if __name__ == '__main__': run_main()
import sys import pytoml as toml from proppy.exceptions import InvalidCommand, InvalidConfiguration from proppy.proposal import Proposal from proppy.render import to_pdf def main(filename): if not filename.endswith('.toml'): raise InvalidCommand("You must use a TOML file as input") with open(filename, 'rb') as f: print("Parsing %s" % filename) config = toml.load(f) theme = config.get('theme') if not theme: raise InvalidConfiguration("Missing theme in TOML file") if not config.get('customer'): raise InvalidConfiguration("Missing customer in TOML file") if not config.get('project'): raise InvalidConfiguration("Missing customer in TOML file") proposal = Proposal(config) if proposal.is_valid(): print("Valid proposal, saving it.") to_pdf(theme, proposal) print("Proposal rendered and saved.") else: # show errors and do nothing proposal.print_errors() def run_main(): if len(sys.argv) != 2: raise InvalidCommand("Invalid number of arguments") main(sys.argv[1]) if __name__ == '__main__': run_main()
Support configuration via query params
var ngAnnotate = require('ng-annotate'); var utils = require('loader-utils'); var SourceMapConsumer = require('source-map').SourceMapConsumer; var SourceMapGenerator = require('source-map').SourceMapGenerator; function isEmpty(obj) { return Object.keys(obj).length === 0; } function getOptions(sourceMapEnabled) { var defaults = { add: true }; var options = this.query ? utils.parseQuery(this.query) : defaults; if (sourceMapEnabled && options.sourcemap === undefined) { var filename = utils.getCurrentRequest(this); options.sourcemap = {inline: false, inFile: filename, sourceRoot: filename}; } return options; } module.exports = function(source, sm) { var sourceMapEnabled = this.sourceMap; this.cacheable && this.cacheable(); var res = ngAnnotate(source, getOptions.call(this, sourceMapEnabled)); var mergeMap; if (sourceMapEnabled && sm) { var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sm)); if (res.map) { generator.applySourceMap(new SourceMapConsumer(res.map), filename); mergeMap = generator.toString(); } else { mergeMap = sm; } } this.callback(null, res.src || source, mergeMap); };
var ngAnnotate = require('ng-annotate'); var utils = require('loader-utils'); var SourceMapConsumer = require('source-map').SourceMapConsumer; var SourceMapGenerator = require('source-map').SourceMapGenerator; module.exports = function(source, sm) { this.cacheable && this.cacheable(); var filename = utils.getCurrentRequest(this); var res = ngAnnotate(source, { add: true, sourcemap: {inline: false, inFile: filename, sourceRoot: filename} } ); var mergeMap; if (sm) { var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sm)); if (res.map) { generator.applySourceMap(new SourceMapConsumer(res.map), filename); mergeMap = generator.toString(); } else { mergeMap = sm; } } this.callback(null, res.src || source, mergeMap); };
Fix missing quote after version number.
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "fastly", version = "0.0.2", author = "Fastly?", author_email="support@fastly.com", description = ("Fastly python API"), license = "dunno", keywords = "fastly api", url = "https://github.com/fastly/fastly-py", packages=find_packages(), long_description=read('README'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved??? :: BSD License???", ], entry_points = { 'console_scripts': [ 'purge_service = fastly.scripts.purge_service:purge_service', 'purge_key = fastly.scripts.purge_key:purge_key', 'purge_url = fastly.scripts.purge_url:purge_url', ] }, )
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "fastly", version = "0.0.2, author = "Fastly?", author_email="support@fastly.com", description = ("Fastly python API"), license = "dunno", keywords = "fastly api", url = "https://github.com/fastly/fastly-py", packages=find_packages(), long_description=read('README'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved??? :: BSD License???", ], entry_points = { 'console_scripts': [ 'purge_service = fastly.scripts.purge_service:purge_service', 'purge_key = fastly.scripts.purge_key:purge_key', 'purge_url = fastly.scripts.purge_url:purge_url', ] }, )
Upgrade map from 3.0 to 3.25
/* @flow */ import React from 'react'; import { GoogleMap } from 'react-google-maps'; import ScriptjsLoader from 'react-google-maps/lib/async/ScriptjsLoader'; import { latLon } from '../../../types/map'; type Props = { spanFullPage: ?boolean, defaultCenter: latLon, }; /** @class Map */ function Map(props : Props) { const containerElement = ( <div style={{ height: '200px', ...(props.spanFullPage ? { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, height: '100%', width: '100%' } : {}), }} /> ); const googleMapElement = ( <GoogleMap defaultZoom={15} defaultCenter={props.defaultCenter} /> ); return ( <ScriptjsLoader hostname={'maps.googleapis.com'} pathname={'/maps/api/js'} query={{ key: process.env.GOOGLE_MAPS_API_KEY, v: '3.25', }} loadingElement={ <div /> } containerElement={containerElement} googleMapElement={googleMapElement} /> ); } export default Map;
/* @flow */ import React from 'react'; import { GoogleMap } from 'react-google-maps'; import ScriptjsLoader from 'react-google-maps/lib/async/ScriptjsLoader'; import { latLon } from '../../../types/map'; type Props = { spanFullPage: ?boolean, defaultCenter: latLon, }; /** @class Map */ function Map(props : Props) { const containerElement = ( <div style={{ height: '200px', ...(props.spanFullPage ? { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, height: '100%', width: '100%' } : {}), }} /> ); const googleMapElement = ( <GoogleMap defaultZoom={15} defaultCenter={props.defaultCenter} /> ); return ( <ScriptjsLoader hostname={'maps.googleapis.com'} pathname={'/maps/api/js'} query={{ key: process.env.GOOGLE_MAPS_API_KEY, v: '3.0' }} loadingElement={ <div /> } containerElement={containerElement} googleMapElement={googleMapElement} /> ); } export default Map;
Make the search hit the first tab I know I know, the modal shouldn't know the specifics of the tabs.
/** * @fileoverview Describes a search modal view */ define([ 'text!templates/search.html', 'backbone', 'underscore', 'lib/jquery.hotkeys' ], function(searchTemplate) { return Backbone.View.extend({ events: { 'keyup .search-query': 'search', 'submit form': 'noop' }, hide: function() { this.trigger('search', null); this.$('input').animate({ right: '-450px' }, 'fast', function() { $(this).val(''); }); }, initialize: function() { $(document).bind('click', _.bind(this.hide, this)); $(document).bind('keydown', '/', _.bind(this.show, this)); }, noop: function() { return false; }, render: function(collection) { this.$el.html(_.template(searchTemplate)); return this; }, show: function() { $('.nav-tabs a:first').tab('show'); this.$('input').animate({ right: '10px' }, 'fast', function() { $(this).focus(); }); }, search: function() { this.trigger('search', this.$('input').val().trim().toLowerCase()); } }); });
/** * @fileoverview Describes a search modal view */ define([ 'text!templates/search.html', 'backbone', 'underscore', 'lib/jquery.hotkeys' ], function(searchTemplate) { return Backbone.View.extend({ events: { 'keyup .search-query': 'search', 'submit form': 'noop' }, hide: function() { this.trigger('search', null); this.$('input').animate({ right: '-450px' }, 'fast', function() { $(this).val(''); }); }, initialize: function() { $(document).bind('click', _.bind(this.hide, this)); $(document).bind('keydown', '/', _.bind(this.show, this)); }, noop: function() { return false; }, render: function(collection) { this.$el.html(_.template(searchTemplate)); return this; }, show: function() { this.$('input').animate({ right: '10px' }, 'fast', function() { $(this).focus(); }); }, search: function() { this.trigger('search', this.$('input').val().trim().toLowerCase()); } }); });
Change default value for waittime for flush
package com.inmobi.messaging.consumer.databus; import com.inmobi.databus.FSCheckpointProvider; /** * Configuration properties and their default values for {@link DatabusConsumer} */ public interface DatabusConsumerConfig { public static final String queueSizeConfig = "databus.consumer.buffer.size"; public static final int DEFAULT_QUEUE_SIZE = 5000; public static final String waitTimeForFlushConfig = "databus.consumer.waittime.forcollectorflush"; public static final long DEFAULT_WAIT_TIME_FOR_FLUSH = 5000; // 5 second public static final String databusConfigFileKey = "databus.conf"; public static final String DEFAULT_DATABUS_CONFIG_FILE = "databus.xml"; public static final String databusClustersConfig = "databus.consumer.clusters"; public static final String databusChkProviderConfig = "databus.consumer.chkpoint.provider.classname"; public static final String DEFAULT_CHK_PROVIDER = FSCheckpointProvider.class .getName(); public static final String checkpointDirConfig = "databus.consumer.checkpoint.dir"; public static final String DEFAULT_CHECKPOINT_DIR = "."; }
package com.inmobi.messaging.consumer.databus; import com.inmobi.databus.FSCheckpointProvider; /** * Configuration properties and their default values for {@link DatabusConsumer} */ public interface DatabusConsumerConfig { public static final String queueSizeConfig = "databus.consumer.buffer.size"; public static final int DEFAULT_QUEUE_SIZE = 5000; public static final String waitTimeForFlushConfig = "databus.consumer.waittime.forcollectorflush"; public static final long DEFAULT_WAIT_TIME_FOR_FLUSH = 1000; // 1 second public static final String databusConfigFileKey = "databus.conf"; public static final String DEFAULT_DATABUS_CONFIG_FILE = "databus.xml"; public static final String databusClustersConfig = "databus.consumer.clusters"; public static final String databusChkProviderConfig = "databus.consumer.chkpoint.provider.classname"; public static final String DEFAULT_CHK_PROVIDER = FSCheckpointProvider.class .getName(); public static final String checkpointDirConfig = "databus.consumer.checkpoint.dir"; public static final String DEFAULT_CHECKPOINT_DIR = "."; }
Update test for new API
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from cryptography.hazmat.bindings import utils def test_create_modulename(): cdef_source = "cdef sources go here" source = "source code" name = utils._create_modulename(cdef_source, source, "2.7") assert name == "_Cryptography_cffi_bcba7f4bx4a14b588" name = utils._create_modulename(cdef_source, source, "3.2") assert name == "_Cryptography_cffi_a7462526x4a14b588"
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from cryptography.hazmat.bindings import utils def test_create_modulename(): cdef_sources = ["cdef sources go here"] source = "source code" name = utils._create_modulename(cdef_sources, source, "2.7") assert name == "_Cryptography_cffi_bcba7f4bx4a14b588" name = utils._create_modulename(cdef_sources, source, "3.2") assert name == "_Cryptography_cffi_a7462526x4a14b588"
Update column if it exists, create new column if not
<?php use Migrations\AbstractMigration; class ReorganizeTranslationTable extends AbstractMigration { /** * Change Method. * * More information on this method is available here: * http://docs.phinx.org/en/latest/migrations.html#the-change-method * @return void */ public function change() { $table = $this->table('language_translations'); if ($table->hasColumn('is_active')) { $table->removeColumn('is_active'); } if ($table->hasColumn('code')) { $table->removeColumn('code'); } if ($table->hasColumn('language_id')) { $table->changeColumn('language_id', 'string', [ 'limit' => 36, 'null' => false, ]); } else { $table->addColumn('language_id', 'string', [ 'limit' => 36, 'null' => false, ]); } $table->save(); } }
<?php use Migrations\AbstractMigration; class ReorganizeTranslationTable extends AbstractMigration { /** * Change Method. * * More information on this method is available here: * http://docs.phinx.org/en/latest/migrations.html#the-change-method * @return void */ public function change() { $table = $this->table('language_translations'); if ($table->hasColumn('is_active')) { $table->removeColumn('is_active'); } if ($table->hasColumn('code')) { $table->removeColumn('code'); } $table->addColumn('language_id', 'string', [ 'limit' => 36, 'null' => false, ]); $table->save(); } }
Change the default query service name.
/* * Copyright (C) 2016 to the original authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.fabric8.spring.cloud.kubernetes.zipkin; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("spring.cloud.kubernetes.zipkin.discovery") public class KubernetesZipkinDiscoveryProperties { private boolean enabled = true; private String serviceName = "zipkin-query"; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getServiceName() { return serviceName; } }
/* * Copyright (C) 2016 to the original authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.fabric8.spring.cloud.kubernetes.zipkin; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("spring.cloud.kubernetes.zipkin.discovery") public class KubernetesZipkinDiscoveryProperties { private boolean enabled = true; private String serviceName = "zipkin-query-api"; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getServiceName() { return serviceName; } }
Fix request property and response properties
var Request = require('./request'); var Helpers = require('../../helpers'); var _ = require('lodash'); var Media = require('./media'); var Account = require('./account'); module.exports = function(session, inSingup) { return new Request(session) .setMethod('POST') .setResource('discoverAyml') .generateUUID() .setData({ phone_id: Helpers.generateUUID(), in_signup: inSingup ? 'true' : 'false', module: 'discover_people' }) .send() .then(function(json) { var items = _.property('suggested_users.suggestions')(json) || []; return _.map(items, function(item) { return { account: new Account(session, item.user), mediaIds: item.media_ids } }) }) };
var Request = require('./request'); var Helpers = require('../../helpers'); var _ = require('lodash'); var Media = require('./media'); var Account = require('./account'); module.exports = function(session, inSingup) { return new Request(session) .setMethod('POST') .setResource('discoverAyml') .generateUUID() .setData({ phone_id: Helpers.generateUUID(), in_singup: inSingup ? 'true' : 'false', module: 'ayml_recommended_users' }) .send() .then(function(json) { var groups = _.first(json.groups || []); var items = groups.items || []; return _.map(items, function(item) { return { account: new Account(session, item.user), mediaIds: item.media_ids } }) }) };
Align the method signature with subclasses
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import abc import six @six.add_metaclass(abc.ABCMeta) class ParserInterface(object): @abc.abstractmethod def parse(self, device, text): # pragma: no cover pass @six.add_metaclass(abc.ABCMeta) class AbstractParser(ParserInterface): def __init__(self): self._clear() @abc.abstractproperty def _tc_subcommand(self): # pragma: no cover pass @abc.abstractmethod def _clear(self): # pragma: no cover pass @staticmethod def _to_unicode(text): try: return text.decode("ascii") except AttributeError: return text
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import abc import six @six.add_metaclass(abc.ABCMeta) class ParserInterface(object): @abc.abstractmethod def parse(self, text): # pragma: no cover pass @six.add_metaclass(abc.ABCMeta) class AbstractParser(ParserInterface): def __init__(self): self._clear() @abc.abstractproperty def _tc_subcommand(self): # pragma: no cover pass @abc.abstractmethod def _clear(self): # pragma: no cover pass @staticmethod def _to_unicode(text): try: return text.decode("ascii") except AttributeError: return text
Remove redundant code breaking tests
/* Clearing variables */ import { getPositionIn, getPositionOut } from './offsetCalculator'; import getInlineOption from './getInlineOption'; const prepare = function($elements, options) { $elements.forEach((el, i) => { const mirror = getInlineOption(el.node, 'mirror', options.mirror); const once = getInlineOption(el.node, 'once', options.once); const id = getInlineOption(el.node, 'id'); const customClassNames = options.useClassNames && el.node.getAttribute('data-aos'); const animatedClassNames = [ options.animatedClassName, ...(customClassNames && customClassNames.split(' ')) ].filter(className => typeof className === 'string'); if (options.initClassName) { el.node.classList.add(options.initClassName); } el.position = { in: getPositionIn(el.node, options.offset), out: mirror && getPositionOut(el.node, options.offset) }; el.options = { once, mirror, animatedClassNames, id }; }); return $elements; }; export default prepare;
/* Clearing variables */ import { getPositionIn, getPositionOut } from './offsetCalculator'; import getInlineOption from './getInlineOption'; const prepare = function($elements, options) { $elements.forEach((el, i) => { const mirror = getInlineOption(el.node, 'mirror', options.mirror); const once = getInlineOption(el.node, 'once', options.once); const id = getInlineOption(el.node, 'id'); const customClassNames = options.useClassNames && el.node.getAttribute('data-aos'); const animatedClassNames = [ options.animatedClassName, ...(customClassNames && customClassNames.split(' ')) ].filter(className => typeof className === 'string'); if (options.initClassName) { el.node.classList.add(options.initClassName); } el.position = { in: getPositionIn(el.node, options.offset), out: mirror && getPositionOut(el.node, options.offset) }; el.data = el.node.getAttributeNames().reduce((acc, attr) => { return Object.assign({}, acc, { [attr]: el.node.getAttribute(attr) }); }, {}); el.options = { once, mirror, animatedClassNames, id }; }); return $elements; }; export default prepare;
Add serializable state middleware by default
import { createStore, compose, applyMiddleware, combineReducers } from 'redux' import { composeWithDevTools } from 'redux-devtools-extension' import thunk from 'redux-thunk' import createImmutableStateInvariantMiddleware from 'redux-immutable-state-invariant' import createSerializableStateInvariantMiddleware from './serializableStateInvariantMiddleware' import isPlainObject from './isPlainObject' const IS_PRODUCTION = process.env.NODE_ENV === 'production' export function getDefaultMiddleware(isProduction = IS_PRODUCTION) { let middlewareArray = [thunk] if (!isProduction) { middlewareArray = [ createImmutableStateInvariantMiddleware(), thunk, createSerializableStateInvariantMiddleware() ] } return middlewareArray } export function configureStore(options = {}) { const { reducer, middleware = getDefaultMiddleware(), devTools = true, preloadedState, enhancers = [] } = options let rootReducer if (typeof reducer === 'function') { rootReducer = reducer } else if (isPlainObject(reducer)) { rootReducer = combineReducers(reducer) } else { throw new Error( 'Reducer argument must be a function or an object of functions that can be passed to combineReducers' ) } const middlewareEnhancer = applyMiddleware(...middleware) const storeEnhancers = [middlewareEnhancer, ...enhancers] let finalCompose = devTools ? composeWithDevTools : compose const composedEnhancer = finalCompose(...storeEnhancers) const store = createStore(rootReducer, preloadedState, composedEnhancer) return store }
import { createStore, compose, applyMiddleware, combineReducers } from 'redux' import { composeWithDevTools } from 'redux-devtools-extension' import thunk from 'redux-thunk' import immutableStateInvariant from 'redux-immutable-state-invariant' import isPlainObject from './isPlainObject' const IS_PRODUCTION = process.env.NODE_ENV === 'production' export function getDefaultMiddleware(isProduction = IS_PRODUCTION) { const middlewareArray = [thunk] if (!isProduction) { middlewareArray.unshift(immutableStateInvariant()) } return middlewareArray } export function configureStore(options = {}) { const { reducer, middleware = getDefaultMiddleware(), devTools = true, preloadedState, enhancers = [] } = options let rootReducer if (typeof reducer === 'function') { rootReducer = reducer } else if (isPlainObject(reducer)) { rootReducer = combineReducers(reducer) } else { throw new Error( 'Reducer argument must be a function or an object of functions that can be passed to combineReducers' ) } const middlewareEnhancer = applyMiddleware(...middleware) const storeEnhancers = [middlewareEnhancer, ...enhancers] let finalCompose = devTools ? composeWithDevTools : compose const composedEnhancer = finalCompose(...storeEnhancers) const store = createStore(rootReducer, preloadedState, composedEnhancer) return store }
Update long_description for PyPI description integration
from authy import __version__ from setuptools import setup, find_packages # to install authy type the following command: # python setup.py install with open('README.md') as f: long_description = f.read() setup( name="authy", version=__version__, description="Authy API Client", author="Authy Inc", author_email="dev-support@authy.com", url="http://github.com/authy/authy-python", keywords=["authy", "two factor", "authentication"], install_requires=["requests>=2.2.1", "simplejson>=3.4.0", "six>=1.8.0"], packages=find_packages(), classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Security" ], long_description=long_description, long_description_content_type='text/markdown' )
from authy import __version__ from setuptools import setup, find_packages # to install authy type the following command: # python setup.py install # setup( name="authy", version=__version__, description="Authy API Client", author="Authy Inc", author_email="dev-support@authy.com", url="http://github.com/authy/authy-python", keywords=["authy", "two factor", "authentication"], install_requires=["requests>=2.2.1", "simplejson>=3.4.0", "six>=1.8.0"], packages=find_packages(), classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Security" ], long_description="""\ Authy API Client for Python """ )
Increase appengine-vm-runtime version field to 0.65
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from setuptools import find_packages from setuptools import setup setup( name='appengine-vm-runtime', version='0.65', description='Python Managed VMs Runtime', url='https://github.com/GoogleCloudPlatform/appengine-python-vm-runtime', author='Google', license='Apache License 2.0', include_package_data=True, packages=find_packages('.'), install_requires=[ 'appengine-compat', 'Werkzeug>=0.10' ] )
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from setuptools import find_packages from setuptools import setup setup( name='appengine-vm-runtime', version='0.64', description='Python Managed VMs Runtime', url='https://github.com/GoogleCloudPlatform/appengine-python-vm-runtime', author='Google', license='Apache License 2.0', include_package_data=True, packages=find_packages('.'), install_requires=[ 'appengine-compat', 'Werkzeug>=0.10' ] )
Remove a resolved TODO - trace file formats now standardized.
""" This module contains the methods for the ``openxc-dump`` command line program. `main` is executed when ``openxc-dump`` is run, and all other callables in this module are internal only. """ from __future__ import absolute_import import argparse import time from openxc.formats.json import JsonFormatter from .common import device_options, configure_logging, select_device def receive(message, **kwargs): message['timestamp'] = time.time() print(JsonFormatter.serialize(message)) def parse_options(): parser = argparse.ArgumentParser( description="View a raw OpenXC data stream", parents=[device_options()]) parser.add_argument("--corrupted", action="store_true", dest="show_corrupted", default=False, help="don't suppress corrupted messages from output") arguments = parser.parse_args() return arguments def main(): configure_logging() arguments = parse_options() source_class, source_kwargs = select_device(arguments) source = source_class(receive, **source_kwargs) source.start() while True: import time time.sleep(5)
""" This module contains the methods for the ``openxc-dump`` command line program. `main` is executed when ``openxc-dump`` is run, and all other callables in this module are internal only. """ from __future__ import absolute_import import argparse import time from openxc.formats.json import JsonFormatter from .common import device_options, configure_logging, select_device def receive(message, **kwargs): message['timestamp'] = time.time() # TODO update docs on trace file format print(JsonFormatter.serialize(message)) def parse_options(): parser = argparse.ArgumentParser( description="View a raw OpenXC data stream", parents=[device_options()]) parser.add_argument("--corrupted", action="store_true", dest="show_corrupted", default=False, help="don't suppress corrupted messages from output") arguments = parser.parse_args() return arguments def main(): configure_logging() arguments = parse_options() source_class, source_kwargs = select_device(arguments) source = source_class(receive, **source_kwargs) source.start() while True: import time time.sleep(5)
Add logging of command failure when not generate err
package main import ( "bufio" "fmt" "log" "os" "os/exec" ) func executeCmd(command string, args ...string) { cmd := exec.Command(command, args...) cmdReader, err := cmd.StdoutPipe() if err != nil { log.Fatal(os.Stderr, "Error creating StdoutPipe for Cmd", err) } defer cmdReader.Close() scanner := bufio.NewScanner(cmdReader) go func() { for scanner.Scan() { fmt.Printf("%s\n", scanner.Text()) } }() err = cmd.Start() if err != nil { log.Fatal(os.Stderr, "Error starting Cmd", err) } err = cmd.Wait() // go generate command will fail when no generate command find. if err != nil { if err.Error() != "exit status 1" { log.Println(err) } // log.Fatal(os.Stderr, "Error waiting for Cmd", err) } }
package main import ( "bufio" "fmt" "log" "os" "os/exec" ) func executeCmd(command string, args ...string) { cmd := exec.Command(command, args...) cmdReader, err := cmd.StdoutPipe() if err != nil { log.Fatal(os.Stderr, "Error creating StdoutPipe for Cmd", err) } defer cmdReader.Close() scanner := bufio.NewScanner(cmdReader) go func() { for scanner.Scan() { fmt.Printf("%s\n", scanner.Text()) } }() err = cmd.Start() if err != nil { log.Fatal(os.Stderr, "Error starting Cmd", err) } err = cmd.Wait() // go generate command will fail when no generate command find. // if err != nil { // log.Fatal(os.Stderr, "Error waiting for Cmd", err) // } }
Refactor Optimize with registered components.
/** * Optimize module initialization. * * Site Kit by Google, 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 * * https://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. */ /** * WordPress dependencies */ import domReady from '@wordpress/dom-ready'; import { addFilter } from '@wordpress/hooks'; /** * Internal dependencies */ import './datastore'; import Data from 'googlesitekit-data'; import { SetupMain as OptimizeSetup } from './components/setup'; import { SettingsEdit, SettingsView } from './components/settings'; import { fillFilterWithComponent } from '../../util'; import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants'; /** * Add component to the setup wizard. */ addFilter( 'googlesitekit.ModuleSetup-optimize', 'googlesitekit.OptimizeModuleSetupWizard', fillFilterWithComponent( OptimizeSetup ) ); domReady( () => { Data.dispatch( CORE_MODULES ).registerModule( 'optimize', { settingsEditComponent: SettingsEdit, settingsViewComponent: SettingsView, } ); } );
/** * Optimize module initialization. * * Site Kit by Google, 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 * * https://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. */ /** * WordPress dependencies */ import { addFilter } from '@wordpress/hooks'; /** * Internal dependencies */ import './datastore'; import { SetupMain as OptimizeSetup } from './components/setup'; import { SettingsMain as OptimizeSettings } from './components/settings'; import { fillFilterWithComponent } from '../../util'; /** * Add components to the settings page. */ addFilter( 'googlesitekit.ModuleSettingsDetails-optimize', 'googlesitekit.OptimizeModuleSettingsDetails', fillFilterWithComponent( OptimizeSettings ) ); /** * Add component to the setup wizard. */ addFilter( 'googlesitekit.ModuleSetup-optimize', 'googlesitekit.OptimizeModuleSetupWizard', fillFilterWithComponent( OptimizeSetup ) );
Make loggability regex groups non-capturing - captured groups have a performance overhead, which we seem to have been impacted by through the addition of this nested group when it comes to its use in imports calculations - we never actually attempt any matches with the pattern, only test it against strings, so there's no need for us to have the capturing functionality - adding `?:` to the start of a group makes in non-capturing
export const PAUSE_STORAGE_KEY = 'is-logging-paused' export function isLoggable({ url }) { // Just remember http(s) pages, ignoring data uris, newtab, ... const loggableUrlPattern = /^https?:\/\/\w+(?:[-/.#=$^@&%?+(),]\w*\/?(?:[-/.#=$^@&:%?+(),]\w*\/?)*)*$/ const urlEndings = ['.svg', '.jpg', '.png', '.jpeg', '.gif'] // Ignore all pages that are image files for (const urlEnding of urlEndings) { if (url.endsWith(urlEnding)) { return false } } return loggableUrlPattern.test(url) } export const getPauseState = async () => { const state = (await browser.storage.local.get(PAUSE_STORAGE_KEY))[ PAUSE_STORAGE_KEY ] switch (state) { case 0: case 1: return true case 2: default: return false } }
export const PAUSE_STORAGE_KEY = 'is-logging-paused' export function isLoggable({ url }) { // Just remember http(s) pages, ignoring data uris, newtab, ... const loggableUrlPattern = /^https?:\/\/\w+([-/.#=$^@&%?+(),]\w*\/?([-/.#=$^@&:%?+(),]\w*\/?)*)*$/ const urlEndings = ['.svg', '.jpg', '.png', '.jpeg', '.gif'] // Ignore all pages that are image files for (const urlEnding of urlEndings) { if (url.endsWith(urlEnding)) { return false } } return loggableUrlPattern.test(url) } export const getPauseState = async () => { const state = (await browser.storage.local.get(PAUSE_STORAGE_KEY))[ PAUSE_STORAGE_KEY ] switch (state) { case 0: case 1: return true case 2: default: return false } }