text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update test to match updated fuction
package plex import ( "testing" ) func TestCreateURI(t *testing.T) { type args struct { server Host path string } tests := []struct { name string args args want string }{ {"Test SSL", args{server: Host{Name: "Test SSL", Hostname: "localhost", Port: 2121, Ssl: true}, path: "test"}, "https://localhost:2121/test"}, {"Test HTTP", args{server: Host{Name: "Test HTTP", Hostname: "servername", Port: 1515, Ssl: false}, path: "new"}, "http://servername:1515/new"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := CreateURI(tt.args.server, tt.args.path); got != tt.want { t.Errorf("CreateURI() = %v, want %v", got, tt.want) } }) } }
package plex import ( "testing" ) func TestCreateURI(t *testing.T) { type args struct { server Host path string token string } tests := []struct { name string args args want string }{ {"Test SSL", args{server: Host{Name: "Test SSL", Hostname: "localhost", Port: 2121, Ssl: true}, path: "test", token: "123456"}, "https://localhost:2121/test?X-Plex-Token=123456"}, {"Test HTTP", args{server: Host{Name: "Test HTTP", Hostname: "servername", Port: 1515, Ssl: false}, path: "new", token: "789456"}, "http://servername:1515/new?X-Plex-Token=789456"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := CreateURI(tt.args.server, tt.args.path, tt.args.token); got != tt.want { t.Errorf("CreateURI() = %v, want %v", got, tt.want) } }) } }
Add debug for incoming messages
var config = require('./config'); var http = require('http'); var bot = require('./modules/bot.js'); var tg = require('./modules/telegram/telegramAPI'); tg.setupWebhook(); http.createServer(function (req, res) { var body = ''; req.on('data', function(chunk) { body += chunk; }); req.on('end', function() { if (req.url === config.BOT_WEBHOOK_PATH) { res.writeHead(200); try { body = JSON.parse(body); } catch (e) { console.log(`Bad JSON: ${e.message}`); return; }; if (process.env.DEBUG === '1') { console.log(body); }; bot.verifyRequest(body); } else { res.writeHead(401); } res.end(); }); }).listen(config.SERVER_PORT);
var config = require('./config'); var http = require('http'); var bot = require('./modules/bot.js'); var tg = require('./modules/telegram/telegramAPI'); tg.setupWebhook(); http.createServer(function (req, res) { var body = ''; req.on('data', function(chunk) { body += chunk; }); req.on('end', function() { if (req.url === config.BOT_WEBHOOK_PATH) { res.writeHead(200); try { body = JSON.parse(body); } catch (e) { console.log(`Bad JSON: ${e.message}`); return; }; bot.verifyRequest(body); } else { res.writeHead(401); } res.end(); }); }).listen(config.SERVER_PORT);
Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module. This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__. Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca Closes-Bug:#1604247 Change-Id: Iee9e0348c005e88c535f4da33cf98149a8c1b19d
""" HTTPS Transport Adapter for python-requests, that allows configuration of SSL version""" # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # @author: Sanju Abraham, Juniper Networks, OpenContrail from requests.adapters import HTTPAdapter try: # This is required for RDO, which installs both python-requests # and python-urllib3, but symlinks python-request's internally packaged # urllib3 to the site installed one. from requests.packages.urllib3.poolmanager import PoolManager except ImportError: # Fallback to standard installation methods from urllib3.poolmanager import PoolManager class SSLAdapter(HTTPAdapter): '''An HTTPS Transport Adapter that can be configured with SSL/TLS version.''' HTTPAdapter.__attrs__.extend(['ssl_version']) def __init__(self, ssl_version=None, **kwargs): self.ssl_version = ssl_version self.poolmanager = None super(SSLAdapter, self).__init__(**kwargs) def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=self.ssl_version)
""" HTTPS Transport Adapter for python-requests, that allows configuration of SSL version""" # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # @author: Sanju Abraham, Juniper Networks, OpenContrail from requests.adapters import HTTPAdapter try: # This is required for RDO, which installs both python-requests # and python-urllib3, but symlinks python-request's internally packaged # urllib3 to the site installed one. from requests.packages.urllib3.poolmanager import PoolManager except ImportError: # Fallback to standard installation methods from urllib3.poolmanager import PoolManager class SSLAdapter(HTTPAdapter): '''An HTTPS Transport Adapter that can be configured with SSL/TLS version.''' def __init__(self, ssl_version=None, **kwargs): self.ssl_version = ssl_version self.poolmanager = None super(SSLAdapter, self).__init__(**kwargs) def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=self.ssl_version)
Add abstination back to allow filters
package in.twizmwaz.cardinal.module.modules.filter.type.old; import in.twizmwaz.cardinal.module.ModuleCollection; import in.twizmwaz.cardinal.module.modules.filter.FilterModule; import in.twizmwaz.cardinal.module.modules.filter.FilterState; import in.twizmwaz.cardinal.module.modules.filter.parsers.ChildrenFilterParser; import static in.twizmwaz.cardinal.module.modules.filter.FilterState.*; public class AllowFilter extends FilterModule { private final ModuleCollection<FilterModule> children; public AllowFilter(final ChildrenFilterParser parser) { super(parser.getName()); this.children = parser.getChildren(); } @Override public FilterState evaluate(final Object... objects) { boolean abstain = true; for (FilterModule child : children) { if (child.evaluate(objects).equals(DENY)) return DENY; if (!child.evaluate(objects).equals(ABSTAIN)) abstain = false; } if (abstain) return ABSTAIN; return ALLOW; } }
package in.twizmwaz.cardinal.module.modules.filter.type.old; import in.twizmwaz.cardinal.module.ModuleCollection; import in.twizmwaz.cardinal.module.modules.filter.FilterModule; import in.twizmwaz.cardinal.module.modules.filter.FilterState; import in.twizmwaz.cardinal.module.modules.filter.parsers.ChildrenFilterParser; import static in.twizmwaz.cardinal.module.modules.filter.FilterState.*; public class AllowFilter extends FilterModule { private final ModuleCollection<FilterModule> children; public AllowFilter(final ChildrenFilterParser parser) { super(parser.getName()); this.children = parser.getChildren(); } @Override public FilterState evaluate(final Object... objects) { for (FilterModule child : children) { if (child.evaluate(objects).equals(DENY)) return DENY; if (child.evaluate(objects).equals(ALLOW)) return ALLOW; } return ABSTAIN; } }
Fix url path for homepage for sitemap
import rmc.shared.constants as c import rmc.models as m import mongoengine as me import os FILE_DIR = os.path.dirname(os.path.realpath(__file__)) HTML_DIR = os.path.join(FILE_DIR, 'html') me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT) def write(file_path, content): ensure_dir(file_path) with open(file_path, 'w') as f: f.write(content) def ensure_dir(file_path): d = os.path.dirname(file_path) if not os.path.exists(d): os.makedirs(d) def generate_urls(): urls = [] # Home page urls.append('') # Course pages for course in m.Course.objects: course_id = course.id urls.append('course/' + course_id) return urls
import rmc.shared.constants as c import rmc.models as m import mongoengine as me import os FILE_DIR = os.path.dirname(os.path.realpath(__file__)) HTML_DIR = os.path.join(FILE_DIR, 'html') me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT) def write(file_path, content): ensure_dir(file_path) with open(file_path, 'w') as f: f.write(content) def ensure_dir(file_path): d = os.path.dirname(file_path) if not os.path.exists(d): os.makedirs(d) def generate_urls(): urls = [] # Home page urls.append('/') # Course pages for course in m.Course.objects: course_id = course.id urls.append('course/' + course_id) return urls
Remove Unused config imported from openedoo_project, pylint.
from openedoo_project import db class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
from openedoo_project import db from openedoo_project import config class Setting(db.Model): __tablename__ = 'module_employee_site_setting' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.Text) def serialize(self): return { 'id': self.id, 'name': self.name } def get_existing_name(self): setting = self.query.limit(1).first() return setting def update(self, data): setting = self.get_existing_name() setting.name = data['name'] return db.session.commit()
Change port back to 6666
var express = require('express'); var https = require('https'); var logger = require('./logger'); var security = require('./security'); var db = require('./db'); var app = configureExpressApp(); initializeMongo(initializeRoutes); startServer(security, app); function configureExpressApp() { var app = express(); app.use(express.json()); app.use(express.urlencoded()); app.use(genericErrorHandler); return app; function genericErrorHandler(err, req, res, next) { res.status(500); res.json({ error: "Please check if your request is correct" }); } } function initializeMongo(onSuccessCallback) { db.initialize(function(err, _db) { if(err) throw err; // interrupt when can't connect onSuccessCallback(_db); }); } function initializeRoutes(db) { ['./daily_stats_routes', './instance_run_routes'].forEach(function(routes) { require(routes)(app, logger, db); }); } function startServer(security, app) { var port = 6666; var httpsServer = https.createServer(security.credentials, app); httpsServer.listen(port); console.log("Codebrag stats server started on port", port); return httpsServer; }
var express = require('express'); var https = require('https'); var logger = require('./logger'); var security = require('./security'); var db = require('./db'); var app = configureExpressApp(); initializeMongo(initializeRoutes); startServer(security, app); function configureExpressApp() { var app = express(); app.use(express.json()); app.use(express.urlencoded()); app.use(genericErrorHandler); return app; function genericErrorHandler(err, req, res, next) { res.status(500); res.json({ error: "Please check if your request is correct" }); } } function initializeMongo(onSuccessCallback) { db.initialize(function(err, _db) { if(err) throw err; // interrupt when can't connect onSuccessCallback(_db); }); } function initializeRoutes(db) { ['./daily_stats_routes', './instance_run_routes'].forEach(function(routes) { require(routes)(app, logger, db); }); } function startServer(security, app) { var port = 3000; var httpsServer = https.createServer(security.credentials, app); httpsServer.listen(port); console.log("Codebrag stats server started on port", port); return httpsServer; }
Revert "Ship all of our examples in the API update tarball." This reverts commit 4162114707f69bcfb6ecea95d7bdf4c080b4b168. (imported from commit a4d68bc2a68209bed8e00e6d58dd5f5d3a3187f9)
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=["bin/humbug-send"], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', glob.glob('examples/*'))] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=glob.glob("bin/*"), )
Return [] from serialize so that files can be added. - Use Ember.get so that POJOs can be used instead of Ember.Object instances
import Ember from 'ember'; import DS from 'ember-data'; const { get, isNone } = Ember; const keys = Object.keys || Ember.keys; export default DS.Transform.extend({ deserialize: function(serialized) { if (isNone(serialized)) { return []; } return keys(serialized).map(function (attachmentName) { return Ember.Object.create({ name: attachmentName, content_type: serialized[attachmentName]['content_type'], data: serialized[attachmentName]['data'], stub: serialized[attachmentName]['stub'], length: serialized[attachmentName]['length'], digest: serialized[attachmentName]['digest'] }); }); }, serialize: function(deserialized) { if (!Ember.isArray(deserialized)) { return null; } return deserialized.reduce(function (acc, attachment) { const serialized = { content_type: get(attachment, 'content_type'), }; if (get(attachment, 'stub')) { serialized.stub = true; serialized.length = get(attachment, 'length'); serialized.digest = get(attachment, 'digest'); } else { serialized.data = get(attachment, 'data'); } acc[get(attachment, 'name')] = serialized; return acc; }, {}); } });
import Ember from 'ember'; import DS from 'ember-data'; const { isNone } = Ember; const keys = Object.keys || Ember.keys; export default DS.Transform.extend({ deserialize: function(serialized) { if (isNone(serialized)) { return []; } return keys(serialized).map(function (attachmentName) { return Ember.Object.create({ name: attachmentName, content_type: serialized[attachmentName]['content_type'], data: serialized[attachmentName]['data'], stub: serialized[attachmentName]['stub'], length: serialized[attachmentName]['length'], digest: serialized[attachmentName]['digest'] }); }); }, serialize: function(deserialized) { if (!Ember.isArray(deserialized)) { return null; } return deserialized.reduce(function (acc, attachment) { const serialized = { content_type: attachment.get('content_type'), }; if (attachment.get('stub')) { serialized.stub = true; serialized.length = attachment.get('length'); serialized.digest = attachment.get('digest'); } else { serialized.data = attachment.get('data'); } acc[attachment.get('name')] = serialized; return acc; }, {}); } });
Fix closing shade mode equalizer
import React from "react"; import { connect } from "react-redux"; import Volume from "../Volume"; import Balance from "../Balance"; import { segment } from "../../utils"; import { closeWindow, toggleEqualizerShadeMode } from "../../actionCreators"; const EqualizerShade = props => { const { volume, balance } = props; const classes = ["left", "center", "right"]; const eqVolumeClassName = segment(0, 100, volume, classes); const eqBalanceClassName = segment(-100, 100, balance, classes); return ( <div className="draggable" onDoubleClick={props.toggleEqualizerShadeMode} style={{ width: "100%", height: "100%" }} > <div id="equalizer-shade" onClick={props.toggleEqualizerShadeMode} /> <div id="equalizer-close" onClick={props.closeWindow} /> <Volume id="equalizer-volume" className={eqVolumeClassName} /> <Balance id="equalizer-balance" className={eqBalanceClassName} /> </div> ); }; const mapDispatchToProps = { closeWindow: () => closeWindow("equalizer"), toggleEqualizerShadeMode }; const mapStateToProps = state => ({ volume: state.media.volume, balance: state.media.balance }); export default connect( mapStateToProps, mapDispatchToProps )(EqualizerShade);
import React from "react"; import { connect } from "react-redux"; import Volume from "../Volume"; import Balance from "../Balance"; import { segment } from "../../utils"; import { closeWindow, toggleEqualizerShadeMode } from "../../actionCreators"; const EqualizerShade = props => { const { volume, balance } = props; const classes = ["left", "center", "right"]; const eqVolumeClassName = segment(0, 100, volume, classes); const eqBalanceClassName = segment(-100, 100, balance, classes); return ( <div className="draggable" onDoubleClick={props.toggleEqualizerShadeMode} style={{ width: "100%", height: "100%" }} > <div id="equalizer-shade" onClick={props.toggleEqualizerShadeMode} /> <div id="equalizer-close" onClick={props.closeEqualizerWindow} /> <Volume id="equalizer-volume" className={eqVolumeClassName} /> <Balance id="equalizer-balance" className={eqBalanceClassName} /> </div> ); }; const mapDispatchToProps = { closeWindow: () => closeWindow("equalizer"), toggleEqualizerShadeMode }; const mapStateToProps = state => ({ volume: state.media.volume, balance: state.media.balance }); export default connect( mapStateToProps, mapDispatchToProps )(EqualizerShade);
Fix integration test for Python 2.6
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # import boto from boto.compat import unittest class DirectConnectTest(unittest.TestCase): """ A very basic test to make sure signatures and basic calls work. """ def test_basic(self): conn = boto.connect_directconnect() response = conn.describe_connections() self.assertTrue(response) self.assertTrue('connections' in response) self.assertIsInstance(response['connections'], list)
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # import boto from unittest import TestCase class DirectConnectTest(TestCase): """ A very basic test to make sure signatures and basic calls work. """ def test_basic(self): conn = boto.connect_directconnect() response = conn.describe_connections() self.assertTrue(response) self.assertTrue('connections' in response) self.assertIsInstance(response['connections'], list)
Add better exception to viewer resolver
from django.contrib.auth import get_user_model from graphene import AbstractType, Field, String from users.jwt_util import get_token_user_id from .definitions import Viewer class UserQueries(AbstractType): viewer = Field(Viewer) @staticmethod def resolve_viewer(self, args, context, info): users = get_user_model() try: token_user_id = get_token_user_id(args, context) user = users.objects.get(id=token_user_id) return Viewer( id=0, user=user ) except users.DoesNotExist: return Viewer( id=0, user=get_user_model()( id=0, email="" ) )
from django.contrib.auth import get_user_model from graphene import AbstractType, Field, String from users.jwt_util import get_token_user_id from .definitions import Viewer class UserQueries(AbstractType): viewer = Field(Viewer) @staticmethod def resolve_viewer(self, args, context, info): try: token_user_id = get_token_user_id(args, context) user = get_user_model().objects.get(id=token_user_id) print(user) return Viewer( id=0, user=user ) except BaseException: return Viewer( id=0, user=get_user_model()( id=0, email="" ) )
Remove unix dependent shebang from a js file
'use strict'; import * as bus from './bus'; import * as ble from './ble'; import * as serial from './serial'; import * as enocean from './enocean'; let url; let user; let password; if (process.env.WS_URL) { url = process.env.WS_URL; } if (!url) { console.error('WS_URL is missing'); process.exit(1); } if (url.indexOf('ws') !== 0 || url.indexOf(':') < 0) { console.error('Invalid WS_URL'); process.exit(2); } if (process.env.WS_USER) { user = process.env.WS_USER; } if (process.env.WS_PASSWORD) { password = process.env.WS_USER; } console.log(`connecting to ${url}`); if (user || password) { console.log(`The given credentials will be used for authentication: user=${user}`); } bus.start(url, user, password).then(() => { return ble.start(bus); }).then(() => { return serial.start(bus); }).then(() => { return enocean.start(bus); }).catch(e => { console.error('[ERROR]:', e); if (e instanceof Error) { console.error(e.stack); } process.exit(3); });
#!/usr/bin/env node 'use strict'; import * as bus from './bus'; import * as ble from './ble'; import * as serial from './serial'; import * as enocean from './enocean'; let url; let user; let password; if (process.env.WS_URL) { url = process.env.WS_URL; } if (!url) { console.error('WS_URL is missing'); process.exit(1); } if (url.indexOf('ws') !== 0 || url.indexOf(':') < 0) { console.error('Invalid WS_URL'); process.exit(2); } if (process.env.WS_USER) { user = process.env.WS_USER; } if (process.env.WS_PASSWORD) { password = process.env.WS_USER; } console.log(`connecting to ${url}`); if (user || password) { console.log(`The given credentials will be used for authentication: user=${user}`); } bus.start(url, user, password).then(() => { return ble.start(bus); }).then(() => { return serial.start(bus); }).then(() => { return enocean.start(bus); }).catch(e => { console.error('[ERROR]:', e); if (e instanceof Error) { console.error(e.stack); } process.exit(3); });
Template: Add error checking of api_result
(function (env) { "use strict"; env.ddg_spice_<: $lia_name :> = function(api_result){ // Validate the response (customize for your Spice) if (!api_result || api_result.error) { return Spice.failed('<: $lia_name :>'); } // Render the response Spice.add({ id: "<: $lia_name :>", // Customize these properties name: "AnswerBar title", data: api_result, meta: { sourceName: "Example.com", sourceUrl: 'http://example.com/url/to/details/' + api_result.name }, templates: { group: 'your-template-group', options: { content: Spice.<: $lia_name :>.content, moreAt: true } } }); }; }(this));
(function (env) { "use strict"; env.ddg_spice_<: $lia_name :> = function(api_result){ // Validate the response (customize for your Spice) if (api_result.error) { return Spice.failed('<: $lia_name :>'); } // Render the response Spice.add({ id: "<: $lia_name :>", // Customize these properties name: "AnswerBar title", data: api_result, meta: { sourceName: "Example.com", sourceUrl: 'http://example.com/url/to/details/' + api_result.name }, templates: { group: 'your-template-group', options: { content: Spice.<: $lia_name :>.content, moreAt: true } } }); }; }(this));
Make LCD behave a bit better
function Messages(clear, empty, firstMessage, displayMessage, displayMessageLong) { this.messages = []; this.clear = clear; this.empty = empty; this.firstMessage = firstMessage; this.displayMessage = displayMessage; this.displayMessageLong = displayMessageLong; } Messages.prototype.hasMessages = function () { return this.messages.length > 0; } Messages.prototype.showMessage = function () { var message = this.messages[0]; var display = message.length > 16 ? this.displayMessageLong : this.displayMessage; this.clear(); setImmediate(function() { display(message); }); } Messages.prototype.nextMessage = function () { if (this.messages.length < 1) return; this.messages.splice(0, 1); if (this.messages.length > 0) this.showMessage(); else { this.clear(); this.empty(); } } Messages.prototype.receive = function (message) { var firstMessage = this.messages.length === 0; this.messages.push(message); if (firstMessage) { this.firstMessage(); this.showMessage(); } } module.exports = Messages;
function Messages(clear, empty, firstMessage, displayMessage, displayMessageLong) { this.messages = []; this.clear = clear; this.empty = empty; this.firstMessage = firstMessage; this.displayMessage = displayMessage; this.displayMessageLong = displayMessageLong; } Messages.prototype.hasMessages = function () { return this.messages.length > 0; } Messages.prototype.showMessage = function () { var message = this.messages[0]; var display = message.length > 16 ? this.displayMessageLong : this.displayMessage; this.clear(); display(message); } Messages.prototype.nextMessage = function () { if (this.messages.length < 1) return; this.messages.splice(0, 1); if (this.messages.length > 0) this.showMessage(); else { this.clear(); this.empty(); } } Messages.prototype.receive = function (message) { var firstMessage = this.messages.length === 0; this.messages.push(message); if (firstMessage) { this.firstMessage(); this.showMessage(); } } module.exports = Messages;
Create reducer: Move dispatched action type into the dedicated variable
import { Iterable, fromJS } from 'immutable'; const defaultArgs = { initialState: {} }; /** * Create reducer * @description Shorthand function to create a new reducer. By default, always returns the state * in case it was not modified by any action. * @param {Object} initialState - Initial state of the reducer. * @param {Object} actions - Subscribed actions (format: { actionType: fn() } ). * @return {Function} Reducer function. */ export function createReducer(args = defaultArgs) { let { initialState, actions } = args; if (!actions) { throw Error(`Shorthand reducer should have {actions} property specified, but received: ${actions}.`); } return (state, action) => { const dispatchedType = action.type; /* Duplicate the state for further changes */ let newState = state || initialState; /* Enforce immutable state */ if (!Iterable.isIterable(newState)) { newState = fromJS(newState); } /* Iterate through each specified action */ actions.forEach((expectedAction) => { const expectedType = expectedAction.type; const isRegExp = (expectedType instanceof RegExp); /* Determine if dispatched action type is expected */ const shouldActionPass = isRegExp ? expectedType.test(dispatchedType) : expectedType.includes(dispatchedType); /* Mutate the state once dispatched action type is expected */ if (shouldActionPass) { newState = expectedAction.reducer(newState, fromJS(action)); } }); /* Return a new state */ return newState; }; }
import { Iterable, fromJS } from 'immutable'; const defaultArgs = { initialState: {} }; /** * Create reducer * @description Shorthand function to create a new reducer. By default, always returns the state * in case it was not modified by any action. * @param {Object} initialState - Initial state of the reducer. * @param {Object} actions - Subscribed actions (format: { actionType: fn() } ). * @return {Function} Reducer function. */ export function createReducer(args = defaultArgs) { let { initialState, actions } = args; if (!actions) { throw Error(`Shorthand reducer should have {actions} property specified, but received: ${actions}.`); } return (state, action) => { /* Duplicate the state for further changes */ let newState = state || initialState; /* Enforce immutable state */ if (!Iterable.isIterable(newState)) { newState = fromJS(newState); } /* Iterate through each specified action */ actions.forEach((expectedAction) => { const expectedType = expectedAction.type; const isRegExp = (expectedType instanceof RegExp); /* Determine if dispatched action type is expected */ const shouldActionPass = isRegExp ? expectedType.test(action.type) : expectedType.includes(action.type); /* Mutate the state once dispatched action type is expected */ if (shouldActionPass) { newState = expectedAction.reducer(newState, fromJS(action)); } }); /* Return a new state */ return newState; }; }
Update cmd/notify with new API (Display not Show)
package main import ( "flag" "fmt" "os" "github.com/ciarand/notify" ) var ( text *string title *string subtitle *string sound *string ) func init() { text = flag.String("text", "", "The required text for the notification") title = flag.String("title", "", "The required title of the notification") subtitle = flag.String("subtitle", "", "An optional subtitle for the notification") sound = flag.String("sound", "", "An optional sound name to play") } func main() { flag.Parse() if len(os.Args) == 1 { flag.Usage() return } if *title == "" { dief("Title cannot be blank") } if *text == "" { dief("Text cannot be blank") } n := notify.NewSubtitledNotificationWithSound(*title, *subtitle, *text, *sound) if err := n.Display(); err != nil { dief("Error showing notification: %s", err) } } func dief(s string, args ...interface{}) { fmt.Printf(s+"\n", args...) os.Exit(1) }
package main import ( "flag" "fmt" "os" "github.com/ciarand/notify" ) var ( text *string title *string subtitle *string sound *string ) func init() { text = flag.String("text", "", "The required text for the notification") title = flag.String("title", "", "The required title of the notification") subtitle = flag.String("subtitle", "", "An optional subtitle for the notification") sound = flag.String("sound", "", "An optional sound name to play") } func main() { flag.Parse() if len(os.Args) == 1 { flag.Usage() return } if *title == "" { dief("Title cannot be blank") } if *text == "" { dief("Text cannot be blank") } n := notify.NewSubtitledNotificationWithSound(*title, *subtitle, *text, *sound) if err := notify.Show(n); err != nil { dief("Error showing notification: %s", err) } } func dief(s string, args ...interface{}) { fmt.Printf(s+"\n", args...) os.Exit(1) }
Stop processing after trailing slash handler has redirected.
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details. 'use strict'; /** * @description * This handler registers itself as an Express middleware that * redirects all requests with a trailing slash. * This ensures that content items have a single URL. */ var PreventTrailingSlashRouteHandler = { service: 'middleware', feature: 'prevent-trailing-slash', routePriority: 0, scope: 'shell', register: function registerTrailingSlashMiddleware(scope, context) { context.expressApp.register(PreventTrailingSlashRouteHandler.routePriority, function bindTrailingSlashMiddleware(app) { app.get('*', function trailingSlashMiddleware(request, response, next) { var p = request.path; if (p.length > 1 && p[p.length - 1] === '/') { response.redirect(301, p.substr(0, p.length - 1)); return; } next(); }); }); } }; module.exports = PreventTrailingSlashRouteHandler;
// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details. 'use strict'; /** * @description * This handler registers itself as an Express middleware that * redirects all requests with a trailing slash. * This ensures that content items have a single URL. */ var PreventTrailingSlashRouteHandler = { service: 'middleware', feature: 'prevent-trailing-slash', routePriority: 0, scope: 'shell', register: function registerTrailingSlashMiddleware(scope, context) { context.expressApp.register(PreventTrailingSlashRouteHandler.routePriority, function bindTrailingSlashMiddleware(app) { app.get('*', function trailingSlashMiddleware(request, response, next) { var p = request.path; if (p.length > 1 && p[p.length - 1] === '/') { response.redirect(301, p.substr(0, p.length - 1)); } next(); }); }); } }; module.exports = PreventTrailingSlashRouteHandler;
Fix issue with Javascript compilation
const get = require('lodash.get'); const forEach = require('lodash.foreach'); const defaultsDeep = require('lodash.defaultsdeep'); const loaderUtils = require('loader-utils'); const parse = require('./parse').default; const defaultOptions = require('./options'); /** * ComponentOne Loader * @param {string} content */ module.exports = function (content) { let output = ''; const cb = this.async(); const parts = parse(content); const options = defaultsDeep(loaderUtils.getOptions(this), defaultOptions); const resource = loaderUtils.getRemainingRequest(this); forEach(parts, (part, tag) => { forEach(part, (code, type) => { if (options.map.hasOwnProperty(type)) { output += getRequire(this, options, tag, type, resource); } }); }); cb(null, output); } /** * Return full require() statement for given resource and type * @param {object} context * @param {object} options * @param {string} tag * @param {string} type * @param {string} resource * @returns {string} */ function getRequire(context, options, tag, type, resource) { const url = loaderUtils.stringifyRequest(context, '!' + options.map[type] + require.resolve('./select-loader.js') + '?tag=' + tag + '&type=' + type + '!' + resource) const prefix = tag === 'script' ? 'module.exports = ' : ''; return `${prefix}require(${url});\r\n`; }
const get = require('lodash.get'); const forEach = require('lodash.foreach'); const defaultsDeep = require('lodash.defaultsdeep'); const loaderUtils = require('loader-utils'); const parse = require('./parse').default; const defaultOptions = require('./options'); /** * ComponentOne Loader * @param {string} content */ module.exports = function (content) { let output = ''; const cb = this.async(); const parts = parse(content); const options = defaultsDeep(loaderUtils.getOptions(this), defaultOptions); const resource = loaderUtils.getRemainingRequest(this); forEach(parts, (part, tag) => { forEach(part, (code, type) => { if (options.map.hasOwnProperty(type)) { output += getRequire(this, options, tag, type, resource); } }); }); cb(null, output); } /** * Return full require() statement for given resource and type * @param {object} context * @param {object} options * @param {string} tag * @param {string} type * @param {string} resource * @returns {string} */ function getRequire(context, options, tag, type, resource) { let url = loaderUtils.stringifyRequest(context, '!' + options.map[type] + require.resolve('./select-loader.js') + '?tag=' + tag + '&type=' + type + '!' + resource) return `require(${url});\r\n`; }
Use bodyParser() and remove x-powered-by
var fs = require('fs'), log = require('./log'), express = require('express'), app = express(), config = require('./config'); pluginRoot = './plugins'; app.use(express.bodyParser()); app.disable('x-powered-by'); log.info('[app]', 'Scanning for plugins.'); fs.readdirSync(pluginRoot).forEach(function(folder) { var pluginPath = pluginRoot + '/' + folder; log.verbose('[app]', 'Scanning folder ' + pluginPath); var files = fs.readdirSync(pluginPath); if (files.indexOf('index.js') > -1) { try { var plugin = require(pluginPath); log.info('[app]', 'Initializing ' + plugin.name() + ' v' + plugin.version()); plugin.init(app); } catch(e) { log.error('[app]', e.stack); } } else { log.error('[app]', 'Missing index.js in ' + pluginPath); } }); try { app.listen(config.port); log.info('[app]', 'Server listening at port ' + config.port); } catch(e) { log.error('[app]', e.stack); }
var fs = require('fs'), log = require('./log'), express = require('express'), app = express(), config = require('./config'); pluginRoot = './plugins'; log.info('[app]', 'Scanning for plugins.'); fs.readdirSync(pluginRoot).forEach(function(folder) { var pluginPath = pluginRoot + '/' + folder; log.verbose('[app]', 'Scanning folder ' + pluginPath); var files = fs.readdirSync(pluginPath); if (files.indexOf('index.js') > -1) { try { var plugin = require(pluginPath); log.info('[app]', 'Initializing ' + plugin.name() + ' v' + plugin.version()); plugin.init(app); } catch(e) { log.error('[app]', e.stack); } } else { log.error('[app]', 'Missing index.js in ' + pluginPath); } }); try { app.listen(config.port); log.info('[app]', 'Server listening at port ' + config.port); } catch(e) { log.error('[app]', e.stack); }
Fix return type of fowarded secure livedoc handler in Sample App
package org.example.shelf.controller; import org.hildan.livedoc.core.annotations.ApiResponseBodyType; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasic; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasicUser; import org.hildan.livedoc.core.model.doc.Livedoc; import org.hildan.livedoc.springmvc.controller.JsonLivedocController; import org.hildan.livedoc.springmvc.converter.LivedocMessageConverter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @ApiAuthBasic(testUsers = { @ApiAuthBasicUser(username = "testuser", password = "password") }) @Controller @RequestMapping("/secure") public class SecureDocController { /** * This endpoint is an example of authenticated jsondoc endpoint. * <p> * It simply forwards to the {@link JsonLivedocController} added by livedoc-springboot, but requires authentication. * * @return the Livedoc documentation in the form of a JSON body */ @GetMapping(value = "/jsondoc", produces = LivedocMessageConverter.APPLICATION_LIVEDOC) @ApiResponseBodyType(Livedoc.class) // the String is a forward, Livedoc can't know that public String jsondoc() { return "forward:/jsondoc"; } }
package org.example.shelf.controller; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasic; import org.hildan.livedoc.core.annotations.auth.ApiAuthBasicUser; import org.hildan.livedoc.springmvc.controller.JsonLivedocController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @ApiAuthBasic(testUsers = { @ApiAuthBasicUser(username = "testuser", password = "password") }) @Controller @RequestMapping("/secure") public class SecureDocController { /** * This endpoint is an example of authenticated jsondoc endpoint. * <p> * It simply forwards to the {@link JsonLivedocController} added by livedoc-springboot, but requires authentication. * * @return the Livedoc documentation in the form of a JSON body */ @GetMapping("/jsondoc") public String jsondoc() { return "forward:/jsondoc"; } }
Make TemporaryStorage backend's location less random.
import os import shutil import tempfile from django.core.files.storage import FileSystemStorage """ Temporary Storage class for test. Copied from Smiley Chris' Easy Thumbnails test package https://github.com/SmileyChris/easy-thumbnails/blob/master/easy_thumbnails/test.py """ class TemporaryStorage(FileSystemStorage): """ A storage class useful for tests that uses a temporary location to store all files and provides a method to remove this location when it is finished with. """ def __init__(self, *args, **kwargs): """ Create the temporary location. """ self.temporary_location = os.path.join(tempfile.gettempdir(), 'thumbs_test') super(TemporaryStorage, self).__init__(location=self.temporary_location, *args, **kwargs) def delete_temporary_storage(self): """ Delete the temporary directory created during initialisation. This storage class should not be used again after this method is called. """ temporary_location = getattr(self, 'temporary_location', None) if temporary_location: shutil.rmtree(temporary_location)
import tempfile import shutil from django.core.files.storage import FileSystemStorage """ Temporary Storage class for test. Copied from Smiley Chris' Easy Thumbnails test package https://github.com/SmileyChris/easy-thumbnails/blob/master/easy_thumbnails/test.py """ class TemporaryStorage(FileSystemStorage): """ A storage class useful for tests that uses a temporary location to store all files and provides a method to remove this location when it is finished with. """ def __init__(self, location=None, *args, **kwargs): """ Create the temporary location. """ if location is None: location = tempfile.mkdtemp() self.temporary_location = location super(TemporaryStorage, self).__init__(location=location, *args, **kwargs) def delete_temporary_storage(self): """ Delete the temporary directory created during initialisation. This storage class should not be used again after this method is called. """ temporary_location = getattr(self, 'temporary_location', None) if temporary_location: shutil.rmtree(temporary_location)
Fix sidenav on full-index page
--- --- $(document).ready(function() { 'use strict'; // Navbar // ======================================================= const header = $('.header'); const navbar = $('.navbar-profile'); const range = 64; // Height of navbar $(window).on('scroll', function() { let scrollTop = $(this).scrollTop(); let height = header.outerHeight(); let offset = height / 2; let calc = 1 - (scrollTop - offset + range) / range; header.css({ 'opacity': calc }); if (calc > '1') { header.css({ 'opacity': 1 }); navbar.addClass('affix-top'); navbar.removeClass('affix'); } else if ( calc < '0' ) { header.css({ 'opacity': 0 }); navbar.addClass('affix'); navbar.removeClass('affix-top'); } }); // Materialize components // ======================================================= window.onload = function() { $('.sidenav').sidenav(); $('.tooltipped:not(.v-tooltipped)').tooltip(); // :not ensures Vue handles relevant initiation for Vue-controlled elements $('.collapsible').collapsible({ 'accordion': false, }); }; });
--- --- $(document).ready(function() { 'use strict'; // Navbar // ======================================================= const header = $('.header'); const navbar = $('.navbar-profile'); const range = 64; // Height of navbar $(window).on('scroll', function() { let scrollTop = $(this).scrollTop(); let height = header.outerHeight(); let offset = height / 2; let calc = 1 - (scrollTop - offset + range) / range; header.css({ 'opacity': calc }); if (calc > '1') { header.css({ 'opacity': 1 }); navbar.addClass('affix-top'); navbar.removeClass('affix'); } else if ( calc < '0' ) { header.css({ 'opacity': 0 }); navbar.addClass('affix'); navbar.removeClass('affix-top'); } }); // Materialize components // ======================================================= window.onload = function() { $('.tooltipped:not(.v-tooltipped)').tooltip(); // :not ensures Vue handles relevant initiation for Vue-controlled elements $('.collapsible').collapsible({ 'accordion': false, }); }; });
Fix deleting when not connected
<?php // give the name of php file associated with routename function getPhpFile($routeName='') { // read global var $app global $app; // check if page exists in file if(array_key_exists($routeName, $app['pages'])) { $file = $app['pages'][$routeName]; } else { throw new Exception("Error processing getPhpFile($routeName)", 1); } return $file; } // return actual routeName function getActualRoute() { // if route not defined if(!isset($_GET['p'])) { // equivalent to homepage $page = 'accueil'; } else { // given page $page = $_GET['p']; } return $page; } // redirect user to given routeName function redirect($routeName='') { // redirect to generate url redirectUrl(generateUrl($routeName)); } // redirect user to given routeName function redirectUrl($url) { // redirect to generate url header('Location:' . $url ); die("Redirected"); } // generate url by routeName function generateUrl($routeName=''){ $url = 'index.php'; if($routeName != '' && !is_null($routeName)){ // concate get variable $url = $url . '?p=' . $routeName; } return $url; }
<?php // give the name of php file associated with routename function getPhpFile($routeName='') { // read global var $app global $app; // check if page exists in file if(array_key_exists($routeName, $app['pages'])) { $file = $app['pages'][$routeName]; } else { throw new Exception("Error processing getPhpFile($routeName)", 1); } return $file; } // return actual routeName function getActualRoute() { // if route not defined if(!isset($_GET['p'])) { // equivalent to homepage $page = 'accueil'; } else { // given page $page = $_GET['p']; } return $page; } // redirect user to given routeName function redirect($routeName='') { // redirect to generate url redirectUrl(generateUrl($routeName)); } // redirect user to given routeName function redirectUrl($url) { // redirect to generate url header('Location:' . $url ); } // generate url by routeName function generateUrl($routeName=''){ $url = 'index.php'; if($routeName != '' && !is_null($routeName)){ // concate get variable $url = $url . '?p=' . $routeName; } return $url; }
Comment out the private library connection
package main import ( "github.com/henrylee2cn/pholcus/exec" _ "github.com/pholcus/spider_lib" // 此为公开维护的spider规则库 // _ "github.com/pholcus/spider_lib_pte" // 同样你也可以自由添加自己的规则库 ) func main() { // 设置运行时默认操作界面,并开始运行 // 运行软件前,可设置 -a_ui 参数为"web"、"gui"或"cmd",指定本次运行的操作界面 // 其中"gui"仅支持Windows系统 exec.DefaultRun("web") }
package main import ( "github.com/henrylee2cn/pholcus/exec" _ "github.com/pholcus/spider_lib" // 此为公开维护的spider规则库 _ "github.com/pholcus/spider_lib_pte" // 同样你也可以自由添加自己的规则库 ) func main() { // 设置运行时默认操作界面,并开始运行 // 运行软件前,可设置 -a_ui 参数为"web"、"gui"或"cmd",指定本次运行的操作界面 // 其中"gui"仅支持Windows系统 exec.DefaultRun("web") }
Allow specifying which unit-tests to run e.g. 0test ../0release.xml -- testrelease.TestRelease.testBinaryRelease
#!/usr/bin/env python import unittest, os, sys try: import coverage coverage.erase() coverage.start() except ImportError: coverage = None my_dir = os.path.dirname(sys.argv[0]) if not my_dir: my_dir = os.getcwd() testLoader = unittest.TestLoader() if len(sys.argv) > 1: alltests = testLoader.loadTestsFromNames(sys.argv[1:]) else: alltests = unittest.TestSuite() suite_names = [f[:-3] for f in os.listdir(my_dir) if f.startswith('test') and f.endswith('.py')] suite_names.remove('testall') suite_names.sort() for name in suite_names: m = __import__(name, globals(), locals(), []) t = testLoader.loadTestsFromModule(m) alltests.addTest(t) a = unittest.TextTestRunner(verbosity=2).run(alltests) if coverage: coverage.stop() else: print "Coverage module not found. Skipping coverage report." print "\nResult", a if not a.wasSuccessful(): sys.exit(1) if coverage: all_sources = [] def incl(d): for x in os.listdir(d): if x.endswith('.py'): all_sources.append(os.path.join(d, x)) incl('..') coverage.report(all_sources + ['../0publish'])
#!/usr/bin/env python import unittest, os, sys try: import coverage coverage.erase() coverage.start() except ImportError: coverage = None my_dir = os.path.dirname(sys.argv[0]) if not my_dir: my_dir = os.getcwd() sys.argv.append('-v') suite_names = [f[:-3] for f in os.listdir(my_dir) if f.startswith('test') and f.endswith('.py')] suite_names.remove('testall') suite_names.sort() alltests = unittest.TestSuite() for name in suite_names: m = __import__(name, globals(), locals(), []) alltests.addTest(m.suite) a = unittest.TextTestRunner(verbosity=2).run(alltests) if coverage: coverage.stop() else: print "Coverage module not found. Skipping coverage report." print "\nResult", a if not a.wasSuccessful(): sys.exit(1) if coverage: all_sources = [] def incl(d): for x in os.listdir(d): if x.endswith('.py'): all_sources.append(os.path.join(d, x)) incl('..') coverage.report(all_sources + ['../0publish'])
Fix a problem reported by Greg Ward and pointed out by John Machin when doing: return (need_quotes) and ('"%s"' % text) or (text) The following warning was generated: Using a conditional statement with a constant value ("%s") This was because even the stack wasn't modified after a BINARY_MODULO to say the value on the stack was no longer const.
'test checking constant conditions' # __pychecker__ = '' def func1(x): 'should not produce a warning' if 1: pass while 1: print x break assert x, 'test' return 0 def func2(x): 'should produce a warning' __pychecker__ = 'constant1' if 1: pass while 1: print x break return 0 def func3(x): 'should produce a warning' if 21: return 1 if 31: return 2 assert(x, 'test') assert(5, 'test') assert 5, 'test' if 'str': return 3 return 4 def func4(x): 'should not produce a warning' if x == 204 or x == 201 or 200 <= x < 300: x = 0 if x == 1: pass while x == 'str': print x break return 0 def func5(need_quotes, text): 'should not produce a warning' return (need_quotes) and ('"%s"' % text) or (text)
'test checking constant conditions' # __pychecker__ = '' def func1(x): 'should not produce a warning' if 1: pass while 1: print x break assert x, 'test' return 0 def func2(x): 'should produce a warning' __pychecker__ = 'constant1' if 1: pass while 1: print x break return 0 def func3(x): 'should produce a warning' if 21: return 1 if 31: return 2 assert(x, 'test') assert(5, 'test') assert 5, 'test' if 'str': return 3 return 4 def func4(x): 'should not produce a warning' if x == 204 or x == 201 or 200 <= x < 300: x = 0 if x == 1: pass while x == 'str': print x break return 0
Fix reference to linux-only struct
// +build !linux /* Copyright 2016 The Kubernetes Authors 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 cm import "fmt" type unsupportedCgroupManager struct{} // Make sure that unsupportedCgroupManager implements the CgroupManager interface var _ CgroupManager = &unsupportedCgroupManager{} func NewCgroupManager(_ interface{}) CgroupManager { return &unsupportedCgroupManager{} } func (m *unsupportedCgroupManager) Destroy(_ *CgroupConfig) error { return nil } func (m *unsupportedCgroupManager) Update(_ *CgroupConfig) error { return nil } func (m *unsupportedCgroupManager) Create(_ *CgroupConfig) error { return fmt.Errorf("Cgroup Manager is not supported in this build") }
// +build !linux /* Copyright 2016 The Kubernetes Authors 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 cm import "fmt" type unsupportedCgroupManager struct{} // Make sure that unsupportedCgroupManager implements the CgroupManager interface var _ CgroupManager = &unsupportedCgroupManager{} func NewCgroupManager(_ *cgroupSubsystems) CgroupManager { return &unsupportedCgroupManager{} } func (m *unsupportedCgroupManager) Destroy(_ *CgroupConfig) error { return nil } func (m *unsupportedCgroupManager) Update(_ *CgroupConfig) error { return nil } func (m *unsupportedCgroupManager) Create(_ *CgroupConfig) error { return fmt.Errorf("Cgroup Manager is not supported in this build") }
Add --quick option to mysqldump
import datetime from google.cloud import storage from invoke import task import os BUCKET_NAME = 'lekcije' @task def backup_mysql(ctx): mysqldump = os.getenv('MYSQLDUMP') if not mysqldump: mysqldump = './bin/mysqldump' user = os.getenv('MYSQL_USER') password = os.getenv('MYSQL_PASSWORD') host = os.getenv('MYSQL_HOST') port = os.getenv('MYSQL_PORT') database = os.getenv('MYSQL_DATABASE') dump_file = 'lekcije_' + datetime.datetime.now().strftime('%Y%m%d') + '.dump.bz2' ctx.run('{mysqldump} -u{user} -p{password} -h{host} -P{port} --no-tablespaces --quick {database} | bzip2 -9 > {dump_file}'.format(**locals())) client = storage.Client() bucket = client.get_bucket(BUCKET_NAME) new_blob = bucket.blob('backup/' + dump_file) new_blob.upload_from_filename(dump_file) delete_date = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y%m%d') delete_blob_name = 'backup/lekcije_' + delete_date + '.dump.bz2' delete_blob = bucket.get_blob(delete_blob_name) if delete_blob: delete_blob.delete()
import datetime from google.cloud import storage from invoke import task import os BUCKET_NAME = 'lekcije' @task def backup_mysql(ctx): mysqldump = os.getenv('MYSQLDUMP') if not mysqldump: mysqldump = './bin/mysqldump' user = os.getenv('MYSQL_USER') password = os.getenv('MYSQL_PASSWORD') host = os.getenv('MYSQL_HOST') port = os.getenv('MYSQL_PORT') database = os.getenv('MYSQL_DATABASE') dump_file = 'lekcije_' + datetime.datetime.now().strftime('%Y%m%d') + '.dump.bz2' ctx.run('{mysqldump} -u{user} -p{password} -h{host} -P{port} --no-tablespaces {database} | bzip2 -9 > {dump_file}'.format(**locals())) client = storage.Client() bucket = client.get_bucket(BUCKET_NAME) new_blob = bucket.blob('backup/' + dump_file) new_blob.upload_from_filename(dump_file) delete_date = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y%m%d') delete_blob_name = 'backup/lekcije_' + delete_date + '.dump.bz2' delete_blob = bucket.get_blob(delete_blob_name) if delete_blob: delete_blob.delete()
Make sure that we pass a CSRF cookie with value We need to pass a CSRF cookie when we make a GET request because otherwise Angular would have no way of grabing the CSRF.
"""ohmycommand URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.views.decorators.csrf import ensure_csrf_cookie from rest_framework.authtoken import views from apps.commands.urls import router urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', ensure_csrf_cookie(TemplateView.as_view(template_name='index.html'))), # API url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', views.obtain_auth_token) ]
"""ohmycommand URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from rest_framework.authtoken import views from apps.commands.urls import router urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='index.html')), # API url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', views.obtain_auth_token) ]
fix(transformers): Revert Enable async entity transforms This reverts commit 6dcad860e5fc67fabcebeee762aad42d06e029e9.
import Promise from 'bluebird' import { omit, defaults } from 'lodash/object' import * as defaultTransformers from './transformers' const spaceEntities = [ 'contentTypes', 'entries', 'assets', 'locales', 'webhooks' ] /** * Run transformer methods on each item for each kind of entity, in case there * is a need to transform data when copying it to the destination space */ export default function ( space, destinationSpace, customTransformers, entities = spaceEntities ) { const transformers = defaults(customTransformers, defaultTransformers) // TODO maybe we don't need promises here at all const newSpace = omit(space, ...entities) return Promise.reduce(entities, (newSpace, type) => { return Promise.map( space[type], (entity) => Promise.resolve({ original: entity, transformed: transformers[type](entity, destinationSpace[type]) }) ) .then((entities) => { newSpace[type] = entities return newSpace }) }, newSpace) }
import Promise from 'bluebird' import { omit, defaults } from 'lodash/object' import { partialRight } from 'lodash/partialRight' import * as defaultTransformers from './transformers' const spaceEntities = [ 'contentTypes', 'entries', 'assets', 'locales', 'webhooks' ] /** * Run transformer methods on each item for each kind of entity, in case there * is a need to transform data when copying it to the destination space */ export default function ( sourceSpace, destinationSpace, customTransformers, entities = spaceEntities ) { const transformers = defaults(customTransformers, defaultTransformers) const newSpace = omit(sourceSpace, ...entities) // Use bluebird collection methods to support async transforms. return Promise.reduce(entities, (newSpace, type) => { const transformer = transformers[type] const sourceEntities = sourceSpace[type] const destinationEntities = destinationSpace[type] const typeTransform = partialRight(applyTransformer, transformer, destinationEntities, destinationSpace) return Promise.map(sourceEntities, typeTransform).then((entities) => { newSpace[type] = entities return newSpace }) }, newSpace) } function applyTransformer (entity, transformer, destinationEntities, destinationSpace) { return Promise.props({ original: entity, transformed: transformer(entity, destinationEntities, destinationSpace) }) }
Increment enemy index after getting enemies
package engine.element; import java.util.ArrayList; import java.util.List; import engine.Endable; import engine.UpdateAndReturnable; /** * This class contains a wave, which is a set of enemies who are sent out from one spawn point. The * enemies may be sent all at once, randomly, or spaced evenly. * * @author Qian Wang * @author Bojia Chen * */ public class Wave extends GameElement implements UpdateAndReturnable, Endable { private List<List<String>> myEnemies; private double mySendRate; private int myEnemyIndex = 0; private int myTimer = 0; public Wave () { myEnemies = new ArrayList<>(); } @Override public boolean hasEnded () { return myEnemyIndex == myEnemies.size(); } @Override public List<String> update (int counter) { if (++myTimer == mySendRate && !hasEnded()) { myTimer = 0; return myEnemies.get(myEnemyIndex++); } return null; // No enemies to return } }
package engine.element; import java.util.ArrayList; import java.util.List; import engine.Endable; import engine.UpdateAndReturnable; /** * This class contains a wave, which is a set of enemies who are sent out from one spawn point. The * enemies may be sent all at once, randomly, or spaced evenly. * * @author Qian Wang * @author Bojia Chen * */ public class Wave extends GameElement implements UpdateAndReturnable, Endable { private List<List<String>> myEnemies; private double mySendRate; private int myEnemyIndex = 0; private int myTimer = 0; public Wave () { myEnemies = new ArrayList<>(); } @Override public boolean hasEnded () { return myEnemyIndex == myEnemies.size(); } @Override public List<String> update (int counter) { if (++myTimer == mySendRate && !hasEnded()) { myTimer = 0; return myEnemies.get(++myEnemyIndex); } return null; // No enemies to return } }
Change error message to local constant
#!/usr/bin/env python # encoding: utf-8 """Class to handle Exceptions relating to MoodleFUSE actions """ from functools import wraps from moodlefuse.core import config class MoodleFuseException(Exception): def __init__(self, debug_info): _EXCEPTION_REASON = "ERROR ENCOUNTERED: MoodleFUSE has encountered an error." self.message = _EXCEPTION_REASON + debug_info def __str__(self): return self.message def throws_moodlefuse_error(moodlefuse_error): def inner(f): def wrapped(*args): try: return f(*args) except Exception, e: if config['DEBUG'] is False: raise moodlefuse_error() else: raise e return wraps(f)(wrapped) return inner
#!/usr/bin/env python # encoding: utf-8 """Class to handle Exceptions relating to MoodleFUSE actions """ from functools import wraps from moodlefuse.core import config class MoodleFuseException(Exception): def __init__(self, debug_info): exception_reason = "ERROR ENCOUNTERED: MoodleFUSE has encountered an error." debug_info = debug_info self.message = exception_reason + debug_info def __str__(self): return self.message def throws_moodlefuse_error(moodlefuse_error): def inner(f): def wrapped(*args): try: return f(*args) except Exception, e: if config['DEBUG'] is False: raise moodlefuse_error() else: raise e return wraps(f)(wrapped) return inner
Use TO_HIRAGANA to get lemmas from Hiragana table.
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in TO_HIRA: self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, TO_HIRA, "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in FROM_HIRA.values(): self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, FROM_HIRA.values(), "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()
Rename statistics handler to be more specific
#!/usr/bin/env python import rospy import socket from statistics.msg import StatsD class StatsDHandler(): def __init__(self, statsd_host, statsd_port): self.statsd_target = (statsd_host, statsd_port) self.sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) def _send_msg(self, statsd_msg): self.sock.sendto(statsd_msg, self.statsd_target) def handle(self, msg): statsd_msg = 'display.{name}:{value}|{type}|@{rate}'.format( name=msg.name, value=msg.value, type=msg.type, rate=msg.rate ) print statsd_msg self._send_msg(statsd_msg) def listen(): rospy.init_node('statistics') statsd_host = rospy.get_param( '~statsd_host', 'lg-head' ) statsd_port = rospy.get_param( '~statsd_port', 8125 ) handler = StatsDHandler(statsd_host, statsd_port) rospy.Subscriber('statistics/render', StatsD, handler.handle) rospy.spin() if __name__=='__main__': listen()
#!/usr/bin/env python import rospy import socket from statistics.msg import StatsD class StatsHandler(): def __init__(self, statsd_host, statsd_port): self.statsd_target = (statsd_host, statsd_port) self.sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) def _send_msg(self, statsd_msg): self.sock.sendto(statsd_msg, self.statsd_target) def handle(self, msg): statsd_msg = 'display.{name}:{value}|{type}|@{rate}'.format( name=msg.name, value=msg.value, type=msg.type, rate=msg.rate ) print statsd_msg self._send_msg(statsd_msg) def listen(): rospy.init_node('statistics') statsd_host = rospy.get_param( '~statsd_host', 'lg-head' ) statsd_port = rospy.get_param( '~statsd_port', 8125 ) handler = StatsHandler(statsd_host, statsd_port) rospy.Subscriber('statistics/render', StatsD, handler.handle) rospy.spin() if __name__=='__main__': listen()
Fix issue with path variable
import os from setuptools import setup PACKAGE_VERSION = '0.3' def version(): def version_file(mode='r'): return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'version.txt'), mode) if os.getenv('TRAVIS'): with version_file('w') as verfile: verfile.write('{0}.{1}'.format(PACKAGE_VERSION, os.getenv('TRAVIS_BUILD_NUMBER'))) with version_file() as verfile: data = verfile.readlines() return data[0].strip() setup( name='osaapi', version=version(), author='apsliteteam, oznu', author_email='aps@odin.com', packages=['osaapi'], url='https://aps.odin.com', license='Apache License', description='A python client for the Odin Service Automation (OSA) and billing APIs.', long_description=open('README.md').read(), )
import os from setuptools import setup PACKAGE_VERSION = '0.3' def version(): def version_file(mode='r'): return open(os.path.join(os.path.dirname(os.path.abspath(__file__), 'version.txt')), mode) if os.getenv('TRAVIS'): with version_file('w') as verfile: verfile.write('{0}.{1}'.format(PACKAGE_VERSION, os.getenv('TRAVIS_BUILD_NUMBER'))) with version_file() as verfile: data = verfile.readlines() return data[0].strip() setup( name='osaapi', version=version(), author='apsliteteam, oznu', author_email='aps@odin.com', packages=['osaapi'], url='https://aps.odin.com', license='Apache License', description='A python client for the Odin Service Automation (OSA) and billing APIs.', long_description=open('README.md').read(), )
Remove hidden test as it is not being used
/* * ADR Reporting * Copyright (C) 2017 Divay Prakash * GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE) */ var dataUriTest; Modernizr.on('datauri', function(result) { dataUriTest = result.valueOf() && result.over32kb; var inputTest = Modernizr.input.max && Modernizr.input.min && Modernizr.input.placeholder && Modernizr.input.step; var inputTypesTest = Modernizr.inputtypes.date && Modernizr.inputtypes.email && Modernizr.inputtypes.number && Modernizr.inputtypes.range && Modernizr.inputtypes.tel; var mediaQueriesTest = Modernizr.mediaqueries; var placeholderTest = Modernizr.placeholder; var totalTest = dataUriTest && formValidationTest && hiddenTest && inputTest && inputTypesTest && mediaQueriesTest && placeholderTest; if (totalTest) document.getElementById('warning').style.display = 'none'; else document.getElementById('main-div').style.display = 'none'; });
/* * ADR Reporting * Copyright (C) 2017 Divay Prakash * GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE) */ var dataUriTest; Modernizr.on('datauri', function(result) { dataUriTest = result.valueOf() && result.over32kb; var hiddenTest = Modernizr.hidden; var inputTest = Modernizr.input.max && Modernizr.input.min && Modernizr.input.placeholder && Modernizr.input.step; var inputTypesTest = Modernizr.inputtypes.date && Modernizr.inputtypes.email && Modernizr.inputtypes.number && Modernizr.inputtypes.range && Modernizr.inputtypes.tel; var mediaQueriesTest = Modernizr.mediaqueries; var placeholderTest = Modernizr.placeholder; var totalTest = dataUriTest && formValidationTest && hiddenTest && inputTest && inputTypesTest && mediaQueriesTest && placeholderTest; if (totalTest) document.getElementById('warning').style.display = 'none'; else document.getElementById('main-div').style.display = 'none'; });
Allow todo creation by non logged-in users.
import { call, fork, put, select, take, takeEvery } from 'redux-saga/effects'; import { types, syncTodos, } from '../reducer/todos.actions'; import rsf from '../rsf'; function* syncTodosSaga() { const channel = yield call(rsf.channel, 'todos'); while(true) { const todos = yield take(channel); yield put(syncTodos( Object.keys(todos).map(key => ({ ...todos[key], id: key, })) )); } } function* saveNewTodo() { const user = yield select(state => state.login.user); const newTodo = yield select(state => state.todos.new); yield call(rsf.create, 'todos', { creator: user ? user.uid : null, done: false, label: newTodo, }); } function* setTodoStatus(action) { yield call(rsf.patch, `todos/${action.todoId}`, { done: action.done, }); } export default function* rootSaga() { yield fork(syncTodosSaga); yield [ takeEvery(types.TODOS.NEW.SAVE, saveNewTodo), takeEvery(types.TODOS.SET_STATUS, setTodoStatus), ]; }
import { call, fork, put, select, take, takeEvery } from 'redux-saga/effects'; import { types, syncTodos, } from '../reducer/todos.actions'; import rsf from '../rsf'; function* syncTodosSaga() { const channel = yield call(rsf.channel, 'todos'); while(true) { const todos = yield take(channel); yield put(syncTodos( Object.keys(todos).map(key => ({ ...todos[key], id: key, })) )); } } function* saveNewTodo() { const uid = yield select(state => state.login.user.uid); const newTodo = yield select(state => state.todos.new); yield call(rsf.create, 'todos', { creator: uid, done: false, label: newTodo, }); } function* setTodoStatus(action) { yield call(rsf.patch, `todos/${action.todoId}`, { done: action.done, }); } export default function* rootSaga() { yield fork(syncTodosSaga); yield [ takeEvery(types.TODOS.NEW.SAVE, saveNewTodo), takeEvery(types.TODOS.SET_STATUS, setTodoStatus), ]; }
Generalize print_tree to work with different number of columns.
from __future__ import print_function, unicode_literals from collections import namedtuple TreeNode = namedtuple('TreeNode', ['data', 'children']) def create_tree(node_children_mapping, start=0): subtree = [ TreeNode(child, create_tree(node_children_mapping, child["id"])) for child in node_children_mapping[start] ] return subtree def print_tree(node, depth=0, indent=4, exclude_fields=["id", "deprel", "xpostag", "feats", "head", "deps", "misc"]): assert isinstance(node, TreeNode), "node not TreeNode %s" % type(node) relevant_data = node.data.copy() map(lambda x: relevant_data.pop(x, None), exclude_fields) node_repr = " ".join([ "{key}:{value}".format(key=key, value=value) for key, value in relevant_data.items() ]) print(" " * indent * depth + "(deprel:{deprel}) {node_repr} [{idx}]".format( deprel=node.data["deprel"], node_repr=node_repr, idx=node.data["id"], )) for child in node.children: print_tree(child, depth + 1, indent=indent, exclude_fields=exclude_fields)
from __future__ import print_function, unicode_literals from collections import namedtuple TreeNode = namedtuple('TreeNode', ['data', 'children']) def create_tree(node_children_mapping, start=0): subtree = [ TreeNode(child, create_tree(node_children_mapping, child["id"])) for child in node_children_mapping[start] ] return subtree def print_tree(node, depth=0): assert isinstance(node, TreeNode), "node not TreeNode %s" % type(node) print("\t" * depth + "(deprel:{deprel}) form:{form}, tag:{tag} [{idx}]".format( deprel=node.data["deprel"], form=node.data["form"], tag=node.data["upostag"], idx=node.data["id"], )) for child in node.children: print_tree(child, depth + 1)
Revert fixtures changes from 27547f7
<?php /** * /core/app fixtures for mongodb app collection. */ namespace Graviton\I18nBundle\DataFixtures\MongoDB; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Graviton\I18nBundle\Document\Language; /** * Load Language data fixtures into mongodb * * @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors> * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link http://swisscom.ch */ class LoadLanguageData implements FixtureInterface { /** * {@inheritDoc} * * @param ObjectManager $manager Object Manager * * @return void */ public function load(ObjectManager $manager) { $enTag = new Language; $enTag->setId('en'); $enTag->setName('English'); $manager->persist($enTag); $manager->flush(); } }
<?php /** * /core/app fixtures for mongodb app collection. */ namespace Graviton\I18nBundle\DataFixtures\MongoDB; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Graviton\I18nBundle\Document\Language; /** * Load Language data fixtures into mongodb * * @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors> * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link http://swisscom.ch */ class LoadLanguageData implements FixtureInterface { /** * {@inheritDoc} * * @param ObjectManager $manager Object Manager * * @return void */ public function load(ObjectManager $manager) { $lang = new Language; $lang->setId('en'); $lang->setName('English'); $manager->persist($lang); $lang = new Language; $lang->setId('de'); $lang->setName('German'); $manager->persist($lang); $lang = new Language; $lang->setId('fr'); $lang->setName('French'); $manager->persist($lang); $manager->flush(); } }
Fix the bug webviews can not be loaded Webviews are not loaded after inserting a node which contains <webview> tags Contributed by yupingx.chen@intel.com BUG=222663 Review URL: https://chromiumcodereview.appspot.com/12465019 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@193320 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var forEach = require('utils').forEach; // Expose a function to watch the HTML tag creation via Mutation Observers. function watchForTag(tagName, cb) { if (!document.body) return; function findChildTags(queryNode) { forEach(queryNode.querySelectorAll(tagName), function(i, node) { cb(node); }); } // Query tags already in the document. findChildTags(document.body); // Observe the tags added later. var documentObserver = new WebKitMutationObserver(function(mutations) { forEach(mutations, function(i, mutation) { forEach(mutation.addedNodes, function(i, addedNode) { if (addedNode.tagName == tagName) { cb(addedNode); } findChildTags(addedNode); }); }); }); documentObserver.observe(document, {subtree: true, childList: true}); } exports.watchForTag = watchForTag;
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var forEach = require('utils').forEach; // Expose a function to watch the HTML tag creation via Mutation Observers. function watchForTag(tagName, cb) { if (!document.body) return; // Query tags already in the document. var nodes = document.body.querySelectorAll(tagName); for (var i = 0, node; node = nodes[i]; i++) { cb(node); } // Observe the tags added later. var documentObserver = new WebKitMutationObserver(function(mutations) { forEach(mutations, function(i, mutation) { for (var i = 0, addedNode; addedNode = mutation.addedNodes[i]; i++) { if (addedNode.tagName == tagName) { cb(addedNode); } } }); }); documentObserver.observe(document, {subtree: true, childList: true}); } exports.watchForTag = watchForTag;
Fix the admin creation command
from freeposte import manager, db from freeposte.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain(name=domain_name) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(domain) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
from freeposte import manager, db from freeposte.admin import models @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain(name=domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(domain) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
Fix ScheduleBackups and UnscheduleBackups not defaulting correctly
package lib import ( "github.com/BytemarkHosting/bytemark-client/lib/brain" "strconv" ) // CreateBackupSchedule creates a new backup schedule starting at the given date, with backups occuring every interval seconds func (c *bytemarkClient) CreateBackupSchedule(server VirtualMachineName, discLabel string, startDate string, interval int) (sched brain.BackupSchedule, err error) { err = c.validateVirtualMachineName(&server) if err != nil { return } r, err := c.BuildRequest("POST", BrainEndpoint, "/accounts/%s/groups/%s/virtual_machines/%s/discs/%s/backup_schedules", server.Account, server.Group, server.VirtualMachine, discLabel) if err != nil { return } inputSchedule := brain.BackupSchedule{ StartDate: startDate, Interval: interval, } _, _, err = r.MarshalAndRun(inputSchedule, &sched) return } // DeleteBackupSchedule deletes the given backup schedule func (c *bytemarkClient) DeleteBackupSchedule(server VirtualMachineName, discLabel string, id int) (err error) { err = c.validateVirtualMachineName(&server) if err != nil { return } r, err := c.BuildRequest("DELETE", BrainEndpoint, "/accounts/%s/groups/%s/virtual_machines/%s/discs/%s/backup_schedules/%s", server.Account, server.Group, server.VirtualMachine, discLabel, strconv.Itoa(id)) if err != nil { return } _, _, err = r.Run(nil, nil) return }
package lib import ( "github.com/BytemarkHosting/bytemark-client/lib/brain" "strconv" ) // CreateBackupSchedule creates a new backup schedule starting at the given date, with backups occuring every interval seconds func (c *bytemarkClient) CreateBackupSchedule(server VirtualMachineName, discLabel string, startDate string, interval int) (sched brain.BackupSchedule, err error) { r, err := c.BuildRequest("POST", BrainEndpoint, "/accounts/%s/groups/%s/virtual_machines/%s/discs/%s/backup_schedules", server.Account, server.Group, server.VirtualMachine, discLabel) if err != nil { return } inputSchedule := brain.BackupSchedule{ StartDate: startDate, Interval: interval, } _, _, err = r.MarshalAndRun(inputSchedule, &sched) return } // DeleteBackupSchedule deletes the given backup schedule func (c *bytemarkClient) DeleteBackupSchedule(server VirtualMachineName, discLabel string, id int) (err error) { r, err := c.BuildRequest("DELETE", BrainEndpoint, "/accounts/%s/groups/%s/virtual_machines/%s/discs/%s/backup_schedules/%s", server.Account, server.Group, server.VirtualMachine, discLabel, strconv.Itoa(id)) if err != nil { return } _, _, err = r.Run(nil, nil) return }
Allow using consul index from a single response when polling for health
package com.outbrain.ob1k.consul; import com.outbrain.ob1k.Service; import com.outbrain.ob1k.concurrent.ComposableFuture; import com.outbrain.ob1k.http.TypedResponse; import java.util.List; /** * A programmatic API that maps to the /v1/health/* consul REST API * * @author Eran Harel */ public interface ConsulHealth extends Service { ComposableFuture<List<HealthInfoInstance>> filterDcLocalHealthyInstances(final String service, final String filterTag); ComposableFuture<TypedResponse<List<HealthInfoInstance>>> pollHealthyInstances(final String service, final String filterTag, final long index); ComposableFuture<List<HealthInfoInstance>> getInstancesHealth(final String service, final String dc); ComposableFuture<List<HealthInfoInstance.Check>> getInstancesChecks(final String service, final String dc); ComposableFuture<List<HealthInfoInstance.Check>> getInstancesAtState(final States state, final String dc); enum States { ANY, UNKNOWN, PASSING, WARNING, CRITICAL; @Override public String toString() { return name().toLowerCase(); } } }
package com.outbrain.ob1k.consul; import com.outbrain.ob1k.Service; import com.outbrain.ob1k.concurrent.ComposableFuture; import java.util.List; /** * A programmatic API that maps to the /v1/health/* consul REST API * * @author Eran Harel */ public interface ConsulHealth extends Service { ComposableFuture<List<HealthInfoInstance>> filterDcLocalHealthyInstances(final String service, final String filterTag); ComposableFuture<List<HealthInfoInstance>> pollHealthyInstances(final String service, final String filterTag, final long index); ComposableFuture<List<HealthInfoInstance>> getInstancesHealth(final String service, final String dc); ComposableFuture<List<HealthInfoInstance.Check>> getInstancesChecks(final String service, final String dc); ComposableFuture<List<HealthInfoInstance.Check>> getInstancesAtState(final States state, final String dc); enum States { ANY, UNKNOWN, PASSING, WARNING, CRITICAL; @Override public String toString() { return name().toLowerCase(); } } }
Add missing tick to upgrade message
import fs from "fs"; import path from "path"; import logger from "./cliLogger"; import readFileSyncStrip from "./readFileSyncStrip"; import { compareVersions } from "./utils"; module.exports = function updateLastVersionUsed(gluestickVersion, withWarnings=true) { // Check version in .gluestick file const gluestickDotFile = path.join(process.cwd(), ".gluestick"); let fileContents = readFileSyncStrip(gluestickDotFile); // We won't know how old this version is, it might have still have the 'DO NOT MODIFY' header fileContents = fileContents.replace("DO NOT MODIFY", ""); if (!fileContents.length) { fileContents = "{}"; } const project = JSON.parse(fileContents); const needsUpdate = compareVersions(gluestickVersion, project.version || "") === -1; if (withWarnings && needsUpdate) { logger.warn("This project is configured to work with versions >= " + project.version + " Please upgrade your global `gluestick` module with `sudo npm install gluestick -g`"); process.exit(1); return; } // Update version in dot file const newContents = JSON.stringify({version: gluestickVersion}); fs.writeFileSync(gluestickDotFile, newContents); };
import fs from "fs"; import path from "path"; import logger from "./cliLogger"; import readFileSyncStrip from "./readFileSyncStrip"; import { compareVersions } from "./utils"; module.exports = function updateLastVersionUsed(gluestickVersion, withWarnings=true) { // Check version in .gluestick file const gluestickDotFile = path.join(process.cwd(), ".gluestick"); let fileContents = readFileSyncStrip(gluestickDotFile); // We won't know how old this version is, it might have still have the 'DO NOT MODIFY' header fileContents = fileContents.replace("DO NOT MODIFY", ""); if (!fileContents.length) { fileContents = "{}"; } const project = JSON.parse(fileContents); const needsUpdate = compareVersions(gluestickVersion, project.version || "") === -1; if (withWarnings && needsUpdate) { logger.warn("This project is configured to work with versions >= " + project.version + " Please upgrade your global `gluestick` module with `sudo npm install gluestick -g"); process.exit(1); return; } // Update version in dot file const newContents = JSON.stringify({version: gluestickVersion}); fs.writeFileSync(gluestickDotFile, newContents); };
Remove non-ascii-chars in BBP name
"""Compute pi.""" from decimal import Decimal, getcontext import argparse import itertools class ComputePi: """Compute pi to a specific precision using multiple algorithms.""" @staticmethod def BBP(precision): """Compute pi using the Bailey-Borwein-Plouffe formula.""" getcontext().prec = precision + 20 pi = Decimal(0) for k in itertools.count(): term = (Decimal(4)/(8*k+1) - Decimal(2)/(8*k+4) - Decimal(1)/(8*k+5) - Decimal(1)/(8*k+6)) term /= Decimal(16)**k pi += term if term < Decimal(10)**(-precision-10): break pi = str(pi)[:-19] return pi if __name__ == '__main__': parser = argparse.ArgumentParser(description='Calculates pi.') parser.add_argument('--precision', type=int, default=100, help='The desired precision of pi (default: 100 digits)') args = parser.parse_args() pi_computer = ComputePi() print(pi_computer.BBP(args.precision))
"""Compute pi.""" from decimal import Decimal, getcontext import argparse import itertools class ComputePi: """Compute pi to a specific precision using multiple algorithms.""" @staticmethod def BBP(precision): """Compute pi using the Bailey–Borwein–Plouffe formula.""" getcontext().prec = precision + 20 pi = Decimal(0) for k in itertools.count(): term = (Decimal(4)/(8*k+1) - Decimal(2)/(8*k+4) - Decimal(1)/(8*k+5) - Decimal(1)/(8*k+6)) term /= Decimal(16)**k pi += term if term < Decimal(10)**(-precision-10): break pi = str(pi)[:-19] return pi if __name__ == '__main__': parser = argparse.ArgumentParser(description='Calculates pi.') parser.add_argument('--precision', type=int, default=100, help='The desired precision of pi (default: 100 digits)') args = parser.parse_args() pi_computer = ComputePi() print(pi_computer.BBP(args.precision))
Remove method of creating global Def
/** * Created by ChengFuLin on 2015/5/12. */ var Def = require('./def'), Scope = require('./scope'); /** * Constructor of DefFactory * @constructor */ function DefFactory() { 'use strict'; } /** * Creator of Def object * @param from * @param type * @param range * @param scope * @returns {Def} * @throws {Error} when a value is invalid */ DefFactory.prototype.create = function (from, type, range, scope) { 'use strict'; return new Def(from, type, range, scope); }; /** * Creator of parameter definition * @param functionScope * @param type * @param range Should be equal to var of parameter's * @returns {*|Def} * @throws {Error} when a value of Def is invalid */ DefFactory.prototype.createParamDef = function (functionScope, type, range) { 'use strict'; return new Def(functionScope.getCFG()[0], type, range, functionScope.getScope()); }; /** * Singleton * @type {DefFactory} */ var factory = new DefFactory(); module.exports = factory;
/** * Created by ChengFuLin on 2015/5/12. */ var Def = require('./def'), Scope = require('./scope'); /** * Constructor of DefFactory * @constructor */ function DefFactory() { 'use strict'; } /** * Creator of Def object * @param from * @param type * @param range * @param scope * @returns {Def} * @throws {Error} when a value is invalid */ DefFactory.prototype.create = function (from, type, range, scope) { 'use strict'; return new Def(from, type, range, scope); }; /** * Creator of global definition * @param type * @param range * @returns {Def} * @throws {Error} when a value is invalid */ DefFactory.prototype.createGlobalDef = function (type, range) { 'use strict'; return new Def(0, type, range, Scope.GLOBAL_SCOPE); }; /** * Creator of parameter definition * @param functionScope * @param type * @param range Should be equal to var of parameter's * @returns {*|Def} * @throws {Error} when a value of Def is invalid */ DefFactory.prototype.createParamDef = function (functionScope, type, range) { 'use strict'; return new Def(functionScope.getCFG()[0].cfgId, type, range, functionScope.getScope()); }; /** * Singleton * @type {DefFactory} */ var factory = new DefFactory(); module.exports = factory;
Add Pinback URL for the verification process
const Report = require('./Report'); const Notification = require('./Notification'); async function Reporter( request, reply ) { // Params https://sites.google.com/a/webpagetest.org/docs/advanced-features/webpagetest-restful-apis const base = process.env.BASE || 'http://localhost:8080'; const result = await new Report({ k: process.env.WEB_PAGE_TEST_KEY || '', // k means KEY url: request.query.site, pingback: `${base}/verification/?hipchat=${request.query.hipchat}`, }).run(); // Set error as default. let notificationOpts = { status: 'Error', description: `There was an error proccesing ${request.query.site}`, room: request.query.hipchat, url: request.query.site, } // Update notificationOptions if was a success if ( 'statusCode' in result && result.statusCode === 200 ) { let notificationOpts = Object.assign({}, notificationOpts, { status: 'Started', description: 'Your web page performance test has started.', url: result.data.userUrl, }); } const notificationResult = await Notification(notificationOpts); return reply(notificationResult); } module.exports = Reporter;
const Report = require('./Report'); const Notification = require('./Notification'); async function Reporter( request, reply ) { const result = await new Report({ k: process.env.WEB_PAGE_TEST_KEY || '', url: request.query.site, }).run(); // Set error as default. let notificationOptions = { status: 'Error', description: `There was an error proccesing ${request.query.site}`, room: request.query.hipchat, url: request.query.site, } // Update notificationOptions if was a success if ( 'statusCode' in result && result.statusCode === 200 ) { notificationOptions = Object.assign({}, notificationOptions, { status: 'Started', description: 'Your web page performance test has started.', url: result.data.userUrl, }); } const notificationResult = await Notification(notificationOptions); return reply(notificationResult); } module.exports = Reporter;
Fix index names in migrations This can be reverted when we upgrade to Laravel 5.7.
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Flarum\Database\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Builder; return [ 'up' => function (Builder $schema) { $schema->table('discussions', function (Blueprint $table) use ($schema) { $table->index(['is_sticky', 'created_at']); Migration::fixIndexNames($schema, $table); }); }, 'down' => function (Builder $schema) { $schema->table('discussions', function (Blueprint $table) use ($schema) { $table->dropIndex(['is_sticky', 'created_at']); Migration::fixIndexNames($schema, $table); }); } ];
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Builder; return [ 'up' => function (Builder $schema) { $schema->table('discussions', function (Blueprint $table) { $table->index(['is_sticky', 'created_at']); }); }, 'down' => function (Builder $schema) { $schema->table('discussions', function (Blueprint $table) { $table->dropIndex(['is_sticky', 'created_at']); }); } ];
Use different notification messages when the tab is focused, unfocused, closed
self.addEventListener('push', function(event) { event.waitUntil(clients.matchAll().then(function(clientList) { var focused = false; for (var i = 0; i < clientList.length; i++) { if (clientList[i].focused) { focused = true; break; } } var notificationMessage; if (focused) { notificationMessage = 'You\'re still here, thanks!'; } else if (clientList.length > 0) { notificationMessage = 'You haven\'t closed the page, click here to focus it!'; } else { notificationMessage = 'You have closed the page, click here to re-open it!'; } return self.registration.showNotification('ServiceWorker Cookbook', { body: notificationMessage, }); })); }); self.addEventListener('notificationclick', function(event) { event.waitUntil(clients.matchAll().then(function(clientList) { if (clientList.length > 0) { return clientList[0].focus(); } else { return clients.openWindow('./push-clients/index.html'); } })); });
self.addEventListener('push', function(event) { event.waitUntil(clients.matchAll().then(function(clientList) { var focused = false; for (var i = 0; i < clientList.length; i++) { if (clientList[i].focused) { focused = true; break; } } return self.registration.showNotification('ServiceWorker Cookbook', { body: focused ? 'You\'re still here, thanks!' : 'Click me, please!', }); })); }); self.addEventListener('notificationclick', function(event) { event.waitUntil(clients.matchAll().then(function(clientList) { if (clientList.length > 0) { return clientList[0].focus(); } else { return clients.openWindow('./push-clients/index.html'); } })); });
Add EnhancedListView project to licenses list.
package com.levibostian.pantrypirate.model; import com.levibostian.pantrypirate.vo.License; import java.util.ArrayList; public class LicensesModel { private ArrayList<License> mLicenses; public LicensesModel() { mLicenses = new ArrayList<License>(); setUpLicenses(); } private void setUpLicenses() { mLicenses.add(new License("Android-RobotoTextView", "https://github.com/johnkil/Android-RobotoTextView")); mLicenses.add(new License("Tomáš Procházka ImageView", "https://gist.github.com/tprochazka/5486822")); mLicenses.add(new License("ListViewAnimations", "https://github.com/nhaarman/ListViewAnimations")); mLicenses.add(new License("EnhancedListView", "https://github.com/timroes/EnhancedListView")); } public ArrayList<License> getLicenses() { return mLicenses; } public License getLicense(int position) { return mLicenses.get(position); } }
package com.levibostian.pantrypirate.model; import com.levibostian.pantrypirate.vo.License; import java.util.ArrayList; public class LicensesModel { private ArrayList<License> mLicenses; public LicensesModel() { mLicenses = new ArrayList<License>(); setUpLicenses(); } private void setUpLicenses() { mLicenses.add(new License("Android-RobotoTextView", "https://github.com/johnkil/Android-RobotoTextView")); mLicenses.add(new License("Tomáš Procházka ImageView", "https://gist.github.com/tprochazka/5486822")); mLicenses.add(new License("ListViewAnimations", "https://github.com/nhaarman/ListViewAnimations")); } public ArrayList<License> getLicenses() { return mLicenses; } public License getLicense(int position) { return mLicenses.get(position); } }
Remove parameters from save methods
package edu.chl.proton.model; /** * @author Stina Werme * Created by stinawerme on 01/05/17. */ public class File extends FileSystemEntity { //private Document document; public File(String name) { this.setName(name); } public File(String name, Folder parentFolder) { this.setName(name); parentFolder.addFile(this); } //protected Document getDocument() { // return this.document; //} //protected void setDocument(Document document) { // this.document = document; //} // What should be saved? Shouldn't this be in document? protected void save() { } protected boolean isSaved() { return true; } }
package edu.chl.proton.model; /** * @author Stina Werme * Created by stinawerme on 01/05/17. */ public class File extends FileSystemEntity { //private Document document; public File(String name) { this.setName(name); } public File(String name, Folder parentFolder) { this.setName(name); parentFolder.addFile(this); } //protected Document getDocument() { // return this.document; //} //protected void setDocument(Document document) { // this.document = document; //} // What should be saved? Shouldn't this be in document? protected void save(File file) { } protected boolean isSaved(File file) { return true; } }
[Security] Fix http basic authentication entry point
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Http\EntryPoint; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; /** * BasicAuthenticationEntryPoint starts an HTTP Basic authentication. * * @author Fabien Potencier <fabien@symfony.com> */ class BasicAuthenticationEntryPoint implements AuthenticationEntryPointInterface { private $realmName; public function __construct($realmName) { $this->realmName = $realmName; } public function start(Request $request, AuthenticationException $authException = null) { $response = new Response(); $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName)); $response->setStatusCode(401, $authException ? $authException->getMessage() : null); return $response; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Http\EntryPoint; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; /** * BasicAuthenticationEntryPoint starts an HTTP Basic authentication. * * @author Fabien Potencier <fabien@symfony.com> */ class BasicAuthenticationEntryPoint implements AuthenticationEntryPointInterface { private $realmName; public function __construct($realmName) { $this->realmName = $realmName; } public function start(Request $request, AuthenticationException $authException = null) { $response = new Response(); $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName)); $response->setStatusCode(401, $authException->getMessage()); return $response; } }
Switch to JSON containing database.tar.gz
from ..utils.data_utils import get_file import json import tarfile def load_data(path='peptone_dspp.tar.gz'): """Loads the MNIST dataset. # Arguments path: path where to cache the dataset locally (relative to ~/.keras/datasets). # Returns Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. """ path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true') tar = tarfile.open(path, "r:gz") #print("Open archive at {}".format(path)) for member in tar.getmembers(): f = tar.extractfile(member) if f is None: continue #print("Load json {}".format(f)) database = json.load(f) break X, Y = database['X'], database['Y'] f.close() return (X, Y)
from ..utils.data_utils import get_file import numpy as np import cPickle as pickle import tarfile def load_data(path='peptone_dspp.tar.gz'): """Loads the MNIST dataset. # Arguments path: path where to cache the dataset locally (relative to ~/.keras/datasets). # Returns Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. """ path = get_file(path, origin='https://github.com/PeptoneInc/dspp-data/blob/master/database.tar.gz?raw=true') tar = tarfile.open(path, "r:gz") #print("Open archive at {}".format(path)) for member in tar.getmembers(): f = tar.extractfile(member) if f is None: continue database = pickle.load(f) break X, Y = database['X'], database['Y'] f.close() return (X, Y)
Add hidden files (.*) to forever watch ignore patterns
#!/usr/bin/env node var forever = require('forever-monitor'); // TODO: Use official forever repo as dependency once // ignorePattern bug has been fixed var server = new forever.Monitor('server.js', { options: process.argv.slice(2), watch: true, watchIgnorePatterns: ['.*/**', 'public/**', 'views/**'], watchDirectory: '.' }); server.on('watch:restart', function(info) { console.error(' restarting script because ' + info.file + ' changed'); }); server.on('restart', function() { console.error(' (time ' + server.times + ')'); }); server.on('exit:code', function(code) { if (code) { console.error(' script exited with code ' + code); } }); server.on('exit', function() { console.log('server.js exiting'); }); server.start();
#!/usr/bin/env node var forever = require('forever-monitor'); // TODO: Use official forever repo as dependency once // ignorePattern bug has been fixed var server = new forever.Monitor('server.js', { options: process.argv.slice(2), watch: true, watchIgnorePatterns: ['public/**', 'views/**'], watchDirectory: '.' }); server.on('watch:restart', function(info) { console.error(' restarting script because ' + info.file + ' changed'); }); server.on('restart', function() { console.error(' (time ' + server.times + ')'); }); server.on('exit:code', function(code) { if (code) { console.error(' script exited with code ' + code); } }); server.on('exit', function() { console.log('server.js exiting'); }); server.start();
Fix url to point to repository.
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "ideone", version = "0.0.1", author = "Joe Schafer", author_email = "joe@jschaf.com", url = "http://github.com/jschaf/ideone-api/", description = "A Python binding to the Ideone API.", license = "BSD", keywords = "API ideone codepad", packages = ['ideone'], long_description=read('README.rst'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], install_requires=['suds',] )
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "ideone", version = "0.0.1", author = "Joe Schafer", author_email = "joe@jschaf.com", url = "http://github.com/jschaf", description = "A Python binding to the Ideone API.", license = "BSD", keywords = "API ideone codepad", packages = ['ideone'], long_description=read('README.rst'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], install_requires=['suds',] )
Update files, Alura, Design Patterns em PHP, Aula 9
<?php date_default_timezone_set("Brazil/East"); function carregaClasse($nomeClasse) { require $nomeClasse.".php"; } spl_autoload_register("carregaClasse"); $geradorDeNotas = new NotaFiscalBuilder(); $geradorDeNotas->comEmpresa("Alura"); $geradorDeNotas->comCnpj("1234"); $geradorDeNotas->addItem(new Item("Tijolo", 250)); $geradorDeNotas->addItem(new Item("Cimento 1kg", 250)); $geradorDeNotas->addItem(new Item("Cimento 1kg", 250)); $geradorDeNotas->addItem(new Item("Cimento 1kg", 250)); $geradorDeNotas->comObservacao("Tijolos amarelos"); $geradorDeNotas->naData(); // acoes $geradorDeNotas->addAcao(new Impressora()); $geradorDeNotas->addAcao(new NotaFiscalDAO()); $geradorDeNotas->addAcao(new EnviadorDeSMS()); $notaFiscal = $geradorDeNotas->build(); echo "<pre>"; var_dump($notaFiscal); ?>
<?php date_default_timezone_set("Brazil/East"); require "AcoesAoGerarNota.php"; require "NotaFiscal.php"; require "Item.php"; require "NotaFiscalBuilder.php"; require "Impressora.php"; require "NotaFiscalDAO.php"; require "EnviadorDeSMS.php"; $geradorDeNotas = new NotaFiscalBuilder(); $geradorDeNotas->comEmpresa("Alura"); $geradorDeNotas->comCnpj("1234"); $geradorDeNotas->addItem(new Item("Tijolo", 250)); $geradorDeNotas->addItem(new Item("Cimento 1kg", 250)); $geradorDeNotas->addItem(new Item("Cimento 1kg", 250)); $geradorDeNotas->addItem(new Item("Cimento 1kg", 250)); $geradorDeNotas->comObservacao("Tijolos amarelos"); $geradorDeNotas->naData(); // acoes $geradorDeNotas->addAcao(new Impressora()); $geradorDeNotas->addAcao(new NotaFiscalDAO()); $geradorDeNotas->addAcao(new EnviadorDeSMS()); $notaFiscal = $geradorDeNotas->build(); echo "<pre>"; var_dump($notaFiscal); ?>
Make sure inventory item is completely loaded
import Ember from "ember"; export default Ember.Mixin.create({ /** * For use with the inventory-type ahead. When an inventory item is selected, resolve the selected * inventory item into an actual model object and set is as inventoryItem. */ inventoryItemChanged: function() { var selectedInventoryItem = this.get('selectedInventoryItem'); if (!Ember.isEmpty(selectedInventoryItem)) { selectedInventoryItem.id = selectedInventoryItem._id.substr(10); this.store.find('inventory', selectedInventoryItem._id.substr(10)).then(function(item) { item.reload().then(function() { this.set('inventoryItem', item); Ember.run.once(this, function(){ this.get('model').validate(); }); }.bind(this), function(err) { console.log("ERROR reloading inventory item", err); }); }.bind(this)); } }.observes('selectedInventoryItem'), });
import Ember from "ember"; export default Ember.Mixin.create({ /** * For use with the inventory-type ahead. When an inventory item is selected, resolve the selected * inventory item into an actual model object and set is as inventoryItem. */ inventoryItemChanged: function() { var selectedInventoryItem = this.get('selectedInventoryItem'); if (!Ember.isEmpty(selectedInventoryItem)) { selectedInventoryItem.id = selectedInventoryItem._id.substr(10); this.store.find('inventory', selectedInventoryItem._id.substr(10)).then(function(item) { this.set('inventoryItem', item); Ember.run.once(this, function(){ this.get('model').validate(); }); }.bind(this)); } }.observes('selectedInventoryItem'), });
Use lxml instead of elementtree.
#!/usr/bin/env python from xml.dom import minidom import lxml.etree as ET import xmltodict def add(k, parent=None, txt=None, attrs=None): if parent is None: handle = ET.Element(k) else: handle = ET.SubElement(parent, k) if txt: handle.text = unicode(txt) try: for k, v in attrs.iteritems(): handle.attrib[k] = v except AttributeError: pass return handle def etree2xml(e, encoding='UTF-8'): return ET.tostring(e, encoding=encoding) if encoding else ET.tostring(e) def pretty(xml=None, fn=None): if fn is not None: xml = minidom.parse(fn) elif not isinstance(xml, minidom.Document): xml = minidom.parseString(xml) return xml.toprettyxml(indent=' ') def xml_fn_to_json(fn): fh = open(fn, 'r') json = xmltodict.parse(fh.read()) return json
#!/usr/bin/env python from xml.dom import minidom import xml.etree.ElementTree as ET import xmltodict def add(k, parent=None, txt=None, attrs=None): if parent is None: handle = ET.Element(k) else: handle = ET.SubElement(parent, k) if txt: handle.text = unicode(txt) try: for k, v in attrs.iteritems(): handle.attrib[k] = v except AttributeError: pass return handle def etree2xml(e, encoding='UTF-8'): return ET.tostring(e, encoding=encoding) if encoding else ET.tostring(e) def pretty(xml=None, fn=None): if fn is not None: xml = minidom.parse(fn) elif not isinstance(xml, minidom.Document): xml = minidom.parseString(xml) return xml.toprettyxml(indent=' ') def xml_fn_to_json(fn): fh = open(fn, 'r') json = xmltodict.parse(fh.read()) return json
Support @ColumnName on Constructor params.
package com.hubspot.rosetta.jackson; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.cfg.MapperConfig; import com.fasterxml.jackson.databind.introspect.AnnotatedField; import com.fasterxml.jackson.databind.introspect.AnnotatedMember; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.introspect.AnnotatedParameter; import com.hubspot.rosetta.ColumnName; public class RosettaNamingStrategy extends PropertyNamingStrategy { private static final long serialVersionUID = 1L; @Override public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) { return convert(field, defaultName); } @Override public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod getter, String defaultName) { return convert(getter, defaultName); } @Override public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod setter, String defaultName) { return convert(setter, defaultName); } @Override public String nameForConstructorParameter(MapperConfig<?> config, AnnotatedParameter param, String defaultName) { return convert(param, defaultName); } private String convert(AnnotatedMember member, String defaultName) { ColumnName ann = member.getAnnotation(ColumnName.class); if (ann != null) { return ann.value(); } return defaultName; } }
package com.hubspot.rosetta.jackson; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.cfg.MapperConfig; import com.fasterxml.jackson.databind.introspect.AnnotatedField; import com.fasterxml.jackson.databind.introspect.AnnotatedMember; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.hubspot.rosetta.ColumnName; public class RosettaNamingStrategy extends PropertyNamingStrategy { private static final long serialVersionUID = 1L; @Override public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) { return convert(field, defaultName); } @Override public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod getter, String defaultName) { return convert(getter, defaultName); } @Override public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod setter, String defaultName) { return convert(setter, defaultName); } private String convert(AnnotatedMember member, String defaultName) { ColumnName ann = member.getAnnotation(ColumnName.class); if (ann != null) { return ann.value(); } return defaultName; } }
Remove last good URL for tryserver.chromium The expected behavior of this change is that the tryserver master no longer tries to resolve revisions to LKGR when trying jobs. BUG=372499, 386667 Review URL: https://codereview.chromium.org/394653002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@283469 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = 8028 slave_port = 8128 master_port_alt = 8228 try_job_port = 8328 # Select tree status urls and codereview location. reply_to = 'chrome-troopers+tryserver@google.com' base_app_url = 'https://chromium-status.appspot.com' tree_status_url = base_app_url + '/status' store_revisions_url = base_app_url + '/revisions' last_good_url = None last_good_blink_url = None svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' buildbot_url = 'http://build.chromium.org/p/tryserver.chromium/'
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class TryServer(Master.Master4): project_name = 'Chromium Try Server' master_port = 8028 slave_port = 8128 master_port_alt = 8228 try_job_port = 8328 # Select tree status urls and codereview location. reply_to = 'chrome-troopers+tryserver@google.com' base_app_url = 'https://chromium-status.appspot.com' tree_status_url = base_app_url + '/status' store_revisions_url = base_app_url + '/revisions' last_good_url = base_app_url + '/lkgr' last_good_blink_url = 'http://blink-status.appspot.com/lkgr' svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try' buildbot_url = 'http://build.chromium.org/p/tryserver.chromium/'
Change style variables role name
import {resolveRoles} from '@sanity/resolver' import isPlainObject from 'lodash/isPlainObject' import merge from 'lodash/merge' let resolving = false const waiting = [] const roleName = 'variables:@sanity/base/theme' function getStyleVariables(basePath) { if (resolving) { return new Promise((resolve, reject) => { waiting.push({resolve, reject}) }) } resolving = true return resolveRoles({basePath}) .then(result => { const role = result.fulfilled[roleName] || [] const implementations = role.map(impl => { const implementer = require(impl.path) const implementation = implementer.__esModule && implementer.default || implementer if (!isPlainObject(implementation)) { throw new Error( `Plugin "${impl.plugin}" implemented "${roleName}", but did not export a plain object` ) } return implementation }) const res = merge({}, ...implementations) while (waiting.length) { waiting.shift().resolve(res) } resolving = false return res }) .catch(err => { while (waiting.length) { waiting.shift().reject(err) } resolving = false }) } export default getStyleVariables
import {resolveRoles} from '@sanity/resolver' import isPlainObject from 'lodash/isPlainObject' import merge from 'lodash/merge' let resolving = false const waiting = [] const roleName = 'variables:@sanity/base/style' function getStyleVariables(basePath) { if (resolving) { return new Promise((resolve, reject) => { waiting.push({resolve, reject}) }) } resolving = true return resolveRoles({basePath}) .then(result => { const role = result.fulfilled[roleName] || [] const implementations = role.map(impl => { const implementer = require(impl.path) const implementation = implementer.__esModule && implementer.default || implementer if (!isPlainObject(implementation)) { throw new Error( `Plugin "${impl.plugin}" implemented "${roleName}", but did not export a plain object` ) } return implementation }) const res = merge({}, ...implementations) while (waiting.length) { waiting.shift().resolve(res) } resolving = false return res }) .catch(err => { while (waiting.length) { waiting.shift().reject(err) } resolving = false }) } export default getStyleVariables
Change services number in test
from hamcrest import * from nose.tools import nottest from test.features import BrowserTest class test_create_pages(BrowserTest): def test_about_page(self): self.browser.visit("http://0.0.0.0:8000/high-volume-services/" "by-transactions-per-year/descending") assert_that(self.browser.find_by_css('h1').text, is_('High-volume services')) def test_home_page(self): self.browser.visit("http://0.0.0.0:8000/home") headlines = self.browser.find_by_css('.headline') departments = headlines[0].text services = headlines[1].text transactions = headlines[2].text assert_that(departments, contains_string('16')) assert_that(services, contains_string('658')) assert_that(transactions, contains_string('1.31bn')) @nottest def test_all_services(self): self.browser.visit("http://0.0.0.0:8000/all-services") assert_that(self.browser.find_by_css('h1').text, is_("All Services")) assert_that(self.browser.find_by_css('#navigation .current').text, is_("All services"))
from hamcrest import * from nose.tools import nottest from test.features import BrowserTest class test_create_pages(BrowserTest): def test_about_page(self): self.browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending") assert_that(self.browser.find_by_css('h1').text, is_('High-volume services')) def test_home_page(self): self.browser.visit("http://0.0.0.0:8000/home") headlines = self.browser.find_by_css('.headline') departments = headlines[0].text services = headlines[1].text transactions = headlines[2].text assert_that(departments, contains_string('16')) assert_that(services, contains_string('654')) assert_that(transactions, contains_string('1.31bn')) @nottest def test_all_services(self): self.browser.visit("http://0.0.0.0:8000/all-services") assert_that(self.browser.find_by_css('h1').text, is_("All Services")) assert_that(self.browser.find_by_css('#navigation .current').text, is_("All services"))
Fix incorrect override function signatures
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Console\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; abstract class SilentEnabledCommand extends Command { public function info($string, $verbosity = null) { if (!$this->option('silent')) { parent::info($string); } } public function comment($string, $verbosity = null) { if (!$this->option('silent')) { parent::comment($string); } } public function getOptions() { return [ ['silent', null, InputOption::VALUE_NONE, 'Silence the output from the function', null], ]; } }
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Console\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; abstract class SilentEnabledCommand extends Command { public function info($string) { if (!$this->option('silent')) { parent::info($string); } } public function comment($string) { if (!$this->option('silent')) { parent::comment($string); } } public function getOptions() { return [ ['silent', null, InputOption::VALUE_NONE, 'Silence the output from the function', null], ]; } }
Remove unnecessary call to PartitionConfig
from .config import PartitionConfig PROXY_APP = 'sql_proxy_accessors' SQL_ACCESSORS_APP = 'sql_accessors' FORM_PROCESSING_GROUP = 'form_processing' PROXY_GROUP = 'proxy' MAIN_GROUP = 'main' class PartitionRouter(object): def __init__(self): self.config = PartitionConfig() def allow_migrate(self, db, app_label, model=None, **hints): if app_label == PROXY_APP: return (db in self.config.dbs_by_group(PROXY_GROUP) or db in self.config.dbs_by_group(FORM_PROCESSING_GROUP)) elif app_label == SQL_ACCESSORS_APP: return db in self.config.dbs_by_group(FORM_PROCESSING_GROUP) else: return db in self.config.dbs_by_group(MAIN_GROUP) class MonolithRouter(object): def allow_migrate(self, db, app_label, model=None, **hints): return app_label != PROXY_APP
from .config import PartitionConfig PROXY_APP = 'sql_proxy_accessors' SQL_ACCESSORS_APP = 'sql_accessors' FORM_PROCESSING_GROUP = 'form_processing' PROXY_GROUP = 'proxy' MAIN_GROUP = 'main' class PartitionRouter(object): def __init__(self): self.config = PartitionConfig() def allow_migrate(self, db, app_label, model=None, **hints): if app_label == PROXY_APP: return (db in self.config.dbs_by_group(PROXY_GROUP) or db in self.config.dbs_by_group(FORM_PROCESSING_GROUP)) elif app_label == SQL_ACCESSORS_APP: return db in self.config.dbs_by_group(FORM_PROCESSING_GROUP) else: return db in self.config.dbs_by_group(MAIN_GROUP) class MonolithRouter(object): def __init__(self): self.config = PartitionConfig() def allow_migrate(self, db, app_label, model=None, **hints): return app_label != PROXY_APP
Update package version to 2.0.0-beta.2
#!/usr/bin/env python3 # coding=utf-8 from setuptools import setup # Get long description (used on PyPI project page) def get_long_description(): with open('README.md', 'r') as readme_file: return readme_file.read() setup( name='alfred-workflow-packager', version='2.0.0b2', description='A CLI utility for packaging and exporting Alfred workflows', long_description=get_long_description(), long_description_content_type='text/markdown', url='https://github.com/caleb531/alfred-workflow-packager', author='Caleb Evans', author_email='caleb@calebevans.me', license='MIT', keywords='alfred workflow package export', packages=['awp'], package_data={ 'awp': ['data/config-schema.json'] }, install_requires=[ 'jsonschema >= 4, < 5' ], entry_points={ 'console_scripts': [ 'awp=awp.main:main' ] } )
#!/usr/bin/env python3 # coding=utf-8 from setuptools import setup # Get long description (used on PyPI project page) def get_long_description(): with open('README.md', 'r') as readme_file: return readme_file.read() setup( name='alfred-workflow-packager', version='2.0.0b1', description='A CLI utility for packaging and exporting Alfred workflows', long_description=get_long_description(), long_description_content_type='text/markdown', url='https://github.com/caleb531/alfred-workflow-packager', author='Caleb Evans', author_email='caleb@calebevans.me', license='MIT', keywords='alfred workflow package export', packages=['awp'], package_data={ 'awp': ['data/config-schema.json'] }, install_requires=[ 'jsonschema >= 4, < 5' ], entry_points={ 'console_scripts': [ 'awp=awp.main:main' ] } )
Add reference to user model and __unicode__() method to FacebookProfileModel
from django.db import models from django.contrib.auth.models import User class FacebookProfileModel(models.Model): ''' Abstract class to add to your profile model. NOTE: If you don't use this this abstract class, make sure you copy/paste the fields in. ''' user = models.OneToOneField(User) about_me = models.TextField(blank=True, null=True) facebook_id = models.IntegerField(blank=True, null=True) facebook_name = models.CharField(max_length=255, blank=True, null=True) facebook_profile_url = models.TextField(blank=True, null=True) website_url = models.TextField(blank=True, null=True) blog_url = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True, upload_to='profile_images') date_of_birth = models.DateField(blank=True, null=True) def __unicode__(self): return self.user.__unicode__() class Meta: abstract = True
from django.db import models class FacebookProfileModel(models.Model): ''' Abstract class to add to your profile model. NOTE: If you don't use this this abstract class, make sure you copy/paste the fields in. ''' about_me = models.TextField(blank=True, null=True) facebook_id = models.IntegerField(blank=True, null=True) facebook_name = models.CharField(max_length=255, blank=True, null=True) facebook_profile_url = models.TextField(blank=True, null=True) website_url = models.TextField(blank=True, null=True) blog_url = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True, upload_to='profile_images') date_of_birth = models.DateField(blank=True, null=True) class Meta: abstract = True
Fix migration tree for journal 0035
# -*- coding: utf-8 -*- # Generated by Django 1.11.23 on 2019-11-03 20:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import journal.models class Migration(migrations.Migration): dependencies = [ ('journal', '0034_migrate_issue_types'), ('core', '0037_journal_xsl_files'), ] operations = [ migrations.AddField( model_name='journal', name='xsl', field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'), preserve_default=False, ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.23 on 2019-11-03 20:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import journal.models class Migration(migrations.Migration): dependencies = [ ('journal', '0034_migrate_issue_types'), ] operations = [ migrations.AddField( model_name='journal', name='xsl', field=models.ForeignKey(default=journal.models.default_xsl, on_delete=django.db.models.deletion.SET_DEFAULT, to='core.XSLFile'), preserve_default=False, ), ]
CC-3751: Remove db.php requirement in the upgrade script - added require_once of Propel
<?php /** * @package Airtime * @subpackage StorageServer * @copyright 2010 Sourcefabric O.P.S. * @license http://www.gnu.org/licenses/gpl.txt */ /* * In the future, most Airtime upgrades will involve just mutating the * data that is stored on the system. For example, The only data * we need to convert between versions is the database, /etc/airtime, and * /srv/airtime. Everything else is just executable files that can be removed/replaced * with new versions. */ function get_conf_location(){ $conf = parse_ini_file("/etc/airtime/airtime.conf", TRUE); $airtime_dir = $conf['general']['airtime_dir']; return $airtime_dir."/"."application/configs/conf.php"; } $conf_path = get_conf_location(); require_once $conf_path; set_include_path(__DIR__.'/../../../airtime_mvc/library' . PATH_SEPARATOR . get_include_path()); require_once 'propel/runtime/lib/Propel.php'; require_once 'common/UpgradeCommon.php'; require_once 'ConfFileUpgrade.php'; require_once 'DbUpgrade.php'; require_once 'MiscUpgrade.php'; UpgradeCommon::connectToDatabase(); UpgradeCommon::SetDefaultTimezone(); AirtimeConfigFileUpgrade::start(); AirtimeDatabaseUpgrade::start(); AirtimeMiscUpgrade::start();
<?php /** * @package Airtime * @subpackage StorageServer * @copyright 2010 Sourcefabric O.P.S. * @license http://www.gnu.org/licenses/gpl.txt */ /* * In the future, most Airtime upgrades will involve just mutating the * data that is stored on the system. For example, The only data * we need to convert between versions is the database, /etc/airtime, and * /srv/airtime. Everything else is just executable files that can be removed/replaced * with new versions. */ function get_conf_location(){ $conf = parse_ini_file("/etc/airtime/airtime.conf", TRUE); $airtime_dir = $conf['general']['airtime_dir']; return $airtime_dir."/"."application/configs/conf.php"; } $conf_path = get_conf_location(); require_once $conf_path; require_once 'common/UpgradeCommon.php'; require_once 'ConfFileUpgrade.php'; require_once 'DbUpgrade.php'; require_once 'MiscUpgrade.php'; UpgradeCommon::connectToDatabase(); UpgradeCommon::SetDefaultTimezone(); AirtimeConfigFileUpgrade::start(); AirtimeDatabaseUpgrade::start(); AirtimeMiscUpgrade::start();
Check for current window when getting active tab
'use strict'; // Connect to port and listen for messages. chrome.runtime.onConnect.addListener(function (port) { // Listen for message from devtools.js port.onMessage.addListener(function (message) { if (message.sender == 'drupal-template-helper-devtools' && message.message == 'current-tab-url') { // Get the current window. chrome.windows.getCurrent(function (window) { if (window) { // Get the current active tab. chrome.tabs.query({ 'active': true, 'windowId': window.id }, function (tabs) { // Send the url of the active tab to devtools.js if (tabs.length) { port.postMessage({ 'sender': 'drupal-template-helper-background', 'url': tabs[0].url }); } }); } }); } }); }); // Open Options page on browserAction click. chrome.browserAction.onClicked.addListener(function (tab) { if (chrome.runtime.openOptionsPage) { chrome.runtime.openOptionsPage(); } });
'use strict'; // Connect to port and listen for messages. chrome.runtime.onConnect.addListener(function (port) { // Listen for message from devtools.js port.onMessage.addListener(function (message) { if (message.sender == 'drupal-template-helper-devtools' && message.message == 'current-tab-url') { // Get the current active tab. chrome.tabs.query({ 'active': true }, function (tabs) { // Send the url of the active tab to devtools.js if (tabs.length) { port.postMessage({ 'sender': 'drupal-template-helper-background', 'url': tabs[0].url }); } }); } }); }); // Open Options page on browserAction click. chrome.browserAction.onClicked.addListener(function (tab) { if (chrome.runtime.openOptionsPage) { chrome.runtime.openOptionsPage(); } });
Revert "[Timeout] Fix an assert" This reverts commit 05f0fb77716297114043d52de3764289a1926752.
import signal class Timeout(Exception): """Context manager which wraps code in a timeout. If the timeout is exceeded, the context manager will be raised. Example usage: try: with Timeout(5): time.sleep(10) except Timeout: pass """ def __init__(self, duration): self.duration = duration def _handler(self, signum, frame): raise self def __enter__(self): self._old_handler = signal.signal(signal.SIGALRM, self._handler) old_alarm = signal.alarm(self.duration) if old_alarm: raise Exception("Timeout will not behave correctly in conjunction with other code that uses signal.alarm()") def __exit__(self, *exc_info): signal.alarm(0) # cancel any pending alarm my_handler = signal.signal(signal.SIGALRM, self._old_handler) assert my_handler is self._handler, "Wrong SIGALRM handler on __exit__, is something else messing with signal handlers?" def __str__(self): return "Exceeded timeout of {} seconds".format(self.duration)
import signal class Timeout(Exception): """Context manager which wraps code in a timeout. If the timeout is exceeded, the context manager will be raised. Example usage: try: with Timeout(5): time.sleep(10) except Timeout: pass """ def __init__(self, duration): self.duration = duration def _handler(self, signum, frame): raise self def __enter__(self): self._old_handler = signal.signal(signal.SIGALRM, self._handler) old_alarm = signal.alarm(self.duration) if old_alarm: raise Exception("Timeout will not behave correctly in conjunction with other code that uses signal.alarm()") def __exit__(self, *exc_info): signal.alarm(0) # cancel any pending alarm my_handler = signal.signal(signal.SIGALRM, self._old_handler) assert my_handler == self._handler, "Wrong SIGALRM handler on __exit__, is something else messing with signal handlers?" def __str__(self): return "Exceeded timeout of {} seconds".format(self.duration)
Drop `mock` and `nose` as package dependencies That `nose` is used as a test runner (and `mock` is used in those tests) has nothing to do with the package itself. Rather, these are just dependencies needed in order to *run tests.* Note that we're still pinning to very precise version numbers, for no particularly compelling reason. We'll fix that soon. (`version` number is not increased, since this commit won't be packaged & released).
try: from setuptools import setup except ImportError: from distutils.core import setup setup(name = "clrsvsim", version = "0.0.2", 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=[ '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.0.2", 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', 'mock==2.0.0', 'nose==1.3.7', 'numpy==1.10.1', 'preconditions==0.1', 'pyfasta==0.5.2', 'pysam==0.10.0', ], license = "Apache-2.0", )
Make data source module for hss division debug-only, until it is fixed
# -*- coding: utf-8 -*- from flask.ext.babel import gettext from ..division import Division from database_utils import init_db from ldap_utils import init_ldap from ipaddress import IPv4Network import user def init_context(app): init_db(app) init_ldap(app) division = Division( name='hss', display_name=gettext(u"Hochschulstraße"), user_class=user.User, mail_server=u"wh12.tu-dresden.de", subnets=[ IPv4Network(u'141.30.217.0/24'), # HSS 46 IPv4Network(u'141.30.234.0/25'), # HSS 46 IPv4Network(u'141.30.218.0/24'), # HSS 48 IPv4Network(u'141.30.215.128/25'), # HSS 48 IPv4Network(u'141.30.219.0/24'), # HSS 50 ], init_context=init_context, debug_only=True )
# -*- coding: utf-8 -*- from flask.ext.babel import gettext from ..division import Division from database_utils import init_db from ldap_utils import init_ldap from ipaddress import IPv4Network import user def init_context(app): init_db(app) init_ldap(app) division = Division( name='hss', display_name=gettext(u"Hochschulstraße"), user_class=user.User, mail_server=u"wh12.tu-dresden.de", subnets=[ IPv4Network(u'141.30.217.0/24'), # HSS 46 IPv4Network(u'141.30.234.0/25'), # HSS 46 IPv4Network(u'141.30.218.0/24'), # HSS 48 IPv4Network(u'141.30.215.128/25'), # HSS 48 IPv4Network(u'141.30.219.0/24'), # HSS 50 ], init_context=init_context )
Fix menu is not shown.
'use strict'; var app = require('app'); var BrowserWindow = require('browser-window'); var Menu = require('menu'); var mainWindow = null; var menu = Menu.buildFromTemplate([ { label: 'er', submenu: [ { label: 'About', role: 'about' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: function() { app.quit(); } } ] } ]); app.on('window-all-closed', function() { if (process.platform != 'darwin') { quit(); } }); app.on('ready', function() { Menu.setApplicationMenu(menu); mainWindow = new BrowserWindow({width: 800, height: 600, center: true}); mainWindow.loadURL('file://' + __dirname + '/index.html'); mainWindow.on('closed', function() { mainWindow = null; }); });
'use strict'; var app = require('app'); var BrowserWindow = require('browser-window'); var Menu = require('menu'); var mainWindow = null; var menu = Menu.buildFromTemplate([ { label: 'er', submenu: [ { label: 'About', role: 'about' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: function() { app.quit(); } } ] } ]); Menu.setApplicationMenu(menu); app.on('window-all-closed', function() { if (process.platform != 'darwin') { quit(); } }); app.on('ready', function() { mainWindow = new BrowserWindow({width: 800, height: 600, center: true}); mainWindow.loadURL('file://' + __dirname + '/index.html'); mainWindow.on('closed', function() { mainWindow = null; }); });
Reset range to be required in dynamic intr form
from django import forms from cyder.cydhcp.interface.dynamic_intr.models import (DynamicInterface, DynamicIntrKeyValue) from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.forms import RangeWizard class DynamicInterfaceForm(RangeWizard, UsabilityFormMixin): def __init__(self, *args, **kwargs): super(DynamicInterfaceForm, self).__init__(*args, **kwargs) self.fields.keyOrder = ['system', 'domain', 'mac', 'vrf', 'site', 'range', 'workgroup', 'dhcp_enabled', 'dns_enabled', 'ctnr'] self.fields['range'].required = True class Meta: model = DynamicInterface exclude = ('last_seen') class DynamicIntrKeyValueForm(forms.ModelForm): dynamic_interface = forms.ModelChoiceField( queryset=DynamicInterface.objects.all(), widget=forms.HiddenInput()) class Meta: model = DynamicIntrKeyValue exclude = ('is_option', 'is_statement', 'is_quoted',)
from django import forms from cyder.cydhcp.interface.dynamic_intr.models import (DynamicInterface, DynamicIntrKeyValue) from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.forms import RangeWizard class DynamicInterfaceForm(RangeWizard, UsabilityFormMixin): def __init__(self, *args, **kwargs): super(DynamicInterfaceForm, self).__init__(*args, **kwargs) self.fields.keyOrder = ['system', 'domain', 'mac', 'vrf', 'site', 'range', 'workgroup', 'dhcp_enabled', 'dns_enabled', 'ctnr'] class Meta: model = DynamicInterface exclude = ('last_seen') class DynamicIntrKeyValueForm(forms.ModelForm): dynamic_interface = forms.ModelChoiceField( queryset=DynamicInterface.objects.all(), widget=forms.HiddenInput()) class Meta: model = DynamicIntrKeyValue exclude = ('is_option', 'is_statement', 'is_quoted',)
Fix for OPTIONS method to an instance OPTIONS /track/1 TypeError: options() got an unexpected keyword argument 'track_id'
from flask import current_app as app, Response from flask.ext import restful from shiva.decorators import allow_origins class Resource(restful.Resource): def __new__(cls, *args, **kwargs): if app.config.get('CORS_ENABLED') is True: # Applies to all inherited resources cls.method_decorators = [allow_origins] return super(Resource, cls).__new__(cls, *args, **kwargs) # Without this the shiva.decorator.allow_origins method won't get called # when issuing an OPTIONS request. def options(self, *args, **kwargs): return JSONResponse() class JSONResponse(Response): """ A subclass of flask.Response that sets the Content-Type header by default to "application/json". """ def __init__(self, status=200, **kwargs): params = { 'headers': [], 'mimetype': 'application/json', 'response': '', 'status': status, } params.update(kwargs) super(JSONResponse, self).__init__(**params)
from flask import current_app as app, Response from flask.ext import restful from shiva.decorators import allow_origins class Resource(restful.Resource): def __new__(cls, *args, **kwargs): if app.config.get('CORS_ENABLED') is True: # Applies to all inherited resources cls.method_decorators = [allow_origins] return super(Resource, cls).__new__(cls, *args, **kwargs) # Without this the shiva.decorator.allow_origins method won't get called # when issuing an OPTIONS request. def options(self): return JSONResponse() class JSONResponse(Response): """ A subclass of flask.Response that sets the Content-Type header by default to "application/json". """ def __init__(self, status=200, **kwargs): params = { 'headers': [], 'mimetype': 'application/json', 'response': '', 'status': status, } params.update(kwargs) super(JSONResponse, self).__init__(**params)
Improve readability with newlines between reports.
/*jslint forin: true */ var log = console.log; exports.report = function(file, lint) { log("\n" + file); var options = [], key, value, i, len, pad, e; for (key in lint.options) { value = lint.options[key]; options.push(key + ": " + value); } log("/*jslint " + options.join(", ") + " */"); if (!lint.ok) { len = lint.errors.length; for (i=0; i<len; i++) { pad = '' + (i + 1); while (pad.length < 3) { pad = ' ' + pad; } e = lint.errors[i]; if (e) { log(pad + ' ' + e.line + ',' + e.character + ': ' + e.reason); log( ' ' + (e.evidence || '').replace(/^\s+|\s+$/, "")); } } } else { log("No errors found."); } return lint.ok; };
/*jslint forin: true */ var log = console.log; exports.report = function(file, lint) { log(file); var options = [], key, value, i, len, pad, e; for (key in lint.options) { value = lint.options[key]; options.push(key + ": " + value); } log("/*jslint " + options.join(", ") + " */"); if (!lint.ok) { len = lint.errors.length; for (i=0; i<len; i++) { pad = '' + (i + 1); while (pad.length < 3) { pad = ' ' + pad; } e = lint.errors[i]; if (e) { log(pad + ' ' + e.line + ',' + e.character + ': ' + e.reason); log( ' ' + (e.evidence || '').replace(/^\s+|\s+$/, "")); } } } else { log("ok!"); } return lint.ok; };
Add LICENSE to package data The LICENSE file isn't included with the version found on PyPI. Including it in the `package_data` argument passed to `setup` should fix this.
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup settings = dict() # Publish if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() settings.update( name='switches', version='0.1.0', description='Friendly Command Line Scripts', long_description=open('README.rst').read(), author='Andy Dirnberger', author_email='dirn@dirnonline.com', url='https://github.com/dirn/switches', py_modules=['switches'], package_data={'': ['LICENSE']}, include_package_data=True, license=open('LICENSE').read(), classifiers=( 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ), ) setup(**settings)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup settings = dict() # Publish if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() settings.update( name='switches', version='0.1.0', description='Friendly Command Line Scripts', long_description=open('README.rst').read(), author='Andy Dirnberger', author_email='dirn@dirnonline.com', url='https://github.com/dirn/switches', py_modules=['switches'], license=open('LICENSE').read(), classifiers=( 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ), ) setup(**settings)
Set correct type for setMatrixArrayType
/** * Common utilities * @module glMatrix */ // Configuration Constants export const EPSILON = 0.000001; export let ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array; export const RANDOM = Math.random; /** * Sets the type of array used when creating new vectors and matrices * * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array */ export function setMatrixArrayType(type) { ARRAY_TYPE = type; } const degree = Math.PI / 180; /** * Convert Degree To Radian * * @param {Number} a Angle in Degrees */ export function toRadian(a) { return a * degree; } /** * Tests whether or not the arguments have approximately the same value, within an absolute * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less * than or equal to 1.0, and a relative tolerance is used for larger values) * * @param {Number} a The first number to test. * @param {Number} b The second number to test. * @returns {Boolean} True if the numbers are approximately equal, false otherwise. */ export function equals(a, b) { return Math.abs(a - b) <= EPSILON*Math.max(1.0, Math.abs(a), Math.abs(b)); }
/** * Common utilities * @module glMatrix */ // Configuration Constants export const EPSILON = 0.000001; export let ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array; export const RANDOM = Math.random; /** * Sets the type of array used when creating new vectors and matrices * * @param {Type} type Array type, such as Float32Array or Array */ export function setMatrixArrayType(type) { ARRAY_TYPE = type; } const degree = Math.PI / 180; /** * Convert Degree To Radian * * @param {Number} a Angle in Degrees */ export function toRadian(a) { return a * degree; } /** * Tests whether or not the arguments have approximately the same value, within an absolute * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less * than or equal to 1.0, and a relative tolerance is used for larger values) * * @param {Number} a The first number to test. * @param {Number} b The second number to test. * @returns {Boolean} True if the numbers are approximately equal, false otherwise. */ export function equals(a, b) { return Math.abs(a - b) <= EPSILON*Math.max(1.0, Math.abs(a), Math.abs(b)); }
Move perm check for starring via reaction
const { Listener } = require('discord-akairo'); class MessageReactionAddListener extends Listener { constructor() { super('messageReactionAdd', { eventName: 'messageReactionAdd', emitter: 'client', category: 'client' }); } async exec(reaction, user) { if (user.id === this.client.user.id) return; if (!reaction.message.guild) return; if (reaction.emoji.name === '⭐') { const starboard = this.client.starboards.get(reaction.message.guild.id); const error = await starboard.add(reaction.message, user); if (error) { if (reaction.message.channel.permissionsFor(this.client.user).has('MANAGE_MESSAGES')) { await reaction.remove(user); } if (reaction.message.channel.permissionsFor(this.client.user).has('SEND_MESSAGES')) { reaction.message.channel.send(`${user} **::** ${error}`); } } } } } module.exports = MessageReactionAddListener;
const { Listener } = require('discord-akairo'); class MessageReactionAddListener extends Listener { constructor() { super('messageReactionAdd', { eventName: 'messageReactionAdd', emitter: 'client', category: 'client' }); } async exec(reaction, user) { if (user.id === this.client.user.id) return; if (!reaction.message.guild) return; if (reaction.emoji.name === '⭐') { if (!reaction.message.channel.permissionsFor(this.client.user).has('MANAGE_MESSAGES')) { reaction.message.channel.send(`${user} **::** I'm missing \`Manage Messages\` to star that message in this channel.`); return; } const starboard = this.client.starboards.get(reaction.message.guild.id); const error = await starboard.add(reaction.message, user); if (error) { await reaction.remove(user); if (reaction.message.channel.permissionsFor(this.client.user).has('SEND_MESSAGES')) { reaction.message.channel.send(`${user} **::** ${error}`); } } } } } module.exports = MessageReactionAddListener;
Use routeCount rather than routes (TDD)
module.exports = (function() { function chimneypot(opts) { if (!opts || !isOptionsValid(opts)) { throw new Error("Required options: port, path, secret"); } this.options = { port: opts.port, path: opts.path, secret: opts.secret }; this.routeCount = 0; } function isOptionsValid(opts) { if (opts.port === undefined || opts.path === undefined) { return false; } // Non numbers and non-integers if (Number(opts.port) !== opts.port || opts.port % 1 !== 0) { return false; } return true; } function route(path, callback) { } function listen() { if (this.routeCount === 0) { throw new Error("Routes must be applied before listening."); } } chimneypot.prototype = { constructor: chimneypot, route: route, listen: listen }; return chimneypot; })();
module.exports = (function() { function chimneypot(opts) { if (!opts || !isOptionsValid(opts)) { throw new Error("Required options: port, path, secret"); } this.options = { port: opts.port, path: opts.path, secret: opts.secret }; this.routes = {}; } function isOptionsValid(opts) { if (opts.port === undefined || opts.path === undefined) { return false; } // Non numbers and non-integers if (Number(opts.port) !== opts.port || opts.port % 1 !== 0) { return false; } return true; } function route(path, callback) { } function listen() { } chimneypot.prototype = { constructor: chimneypot, route: route, listen: listen }; return chimneypot; })();
Add TreeNode to fix compile error
package leetcode type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func sumNumbers(root *TreeNode) int { if root == nil { return 0 } else if root.Left == nil && root.Right == nil { return root.Val } else if root.Left == nil { return sum(root.Right, root.Val) } else if root.Right == nil { return sum(root.Left, root.Val) } return sum(root.Left, root.Val) + sum(root.Right, root.Val) } func sum(node *TreeNode, val int) int { newVal := val*10 + node.Val if node.Left == nil && node.Right == nil { return newVal } else if node.Left == nil { return sum(node.Right, newVal) } else if node.Right == nil { return sum(node.Left, newVal) } return sum(node.Left, newVal) + sum(node.Right, newVal) }
package leetcode /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func sumNumbers(root *TreeNode) int { if root == nil { return 0 } else if root.Left == nil && root.Right == nil { return root.Val } else if root.Left == nil { return sum(root.Right, root.Val) } else if root.Right == nil { return sum(root.Left, root.Val) } return sum(root.Left, root.Val) + sum(root.Right, root.Val) } func sum(node *TreeNode, val int) int { newVal := val*10 + node.Val if node.Left == nil && node.Right == nil { return newVal } else if node.Left == nil { return sum(node.Right, newVal) } else if node.Right == nil { return sum(node.Left, newVal) } return sum(node.Left, newVal) + sum(node.Right, newVal) }
Make { ident } const instead of let for closure
import { NativeModules, Platform } from 'react-native' const { RNBranch } = NativeModules export default async function createBranchUniversalObject(identifier, options = {}) { if (typeof identifier !== 'string') throw new Error('react-native-branch: identifier must be a string') const branchUniversalObject = { contentIndexingMode: 'private', canonicalIdentifier: identifier, ...options } const { ident } = await RNBranch.createUniversalObject(branchUniversalObject) return { showShareSheet(shareOptions = {}, linkProperties = {}, controlParams = {}) { shareOptions = { title: options.title || '', text: options.contentDescription || '', ...shareOptions, } linkProperties = { feature: 'share', channel: 'RNApp', ...linkProperties, } return RNBranch.showShareSheet(ident, shareOptions, linkProperties, controlParams) }, registerView() { return RNBranch.registerView(ident) }, generateShortUrl(linkProperties = {}, controlParams = {}) { return RNBranch.generateShortUrl(ident, linkProperties, controlParams) }, listOnSpotlight() { if (Platform.OS !== 'ios') return Promise.resolve() return RNBranch.listOnSpotlight(ident) }, release() { RNBranch.releaseUniversalObject(ident) } } }
import { NativeModules, Platform } from 'react-native' const { RNBranch } = NativeModules export default async function createBranchUniversalObject(identifier, options = {}) { if (typeof identifier !== 'string') throw new Error('react-native-branch: identifier must be a string') const branchUniversalObject = { contentIndexingMode: 'private', canonicalIdentifier: identifier, ...options } let { ident } = await RNBranch.createUniversalObject(branchUniversalObject) return { showShareSheet(shareOptions = {}, linkProperties = {}, controlParams = {}) { shareOptions = { title: options.title || '', text: options.contentDescription || '', ...shareOptions, } linkProperties = { feature: 'share', channel: 'RNApp', ...linkProperties, } return RNBranch.showShareSheet(ident, shareOptions, linkProperties, controlParams) }, registerView() { return RNBranch.registerView(ident) }, generateShortUrl(linkProperties = {}, controlParams = {}) { return RNBranch.generateShortUrl(ident, linkProperties, controlParams) }, listOnSpotlight() { if (Platform.OS !== 'ios') return Promise.resolve() return RNBranch.listOnSpotlight(ident) }, release() { RNBranch.releaseUniversalObject(ident) } } }
Store password in session after successful login.
#! coding: utf-8 from django.shortcuts import render_to_response, render from django.http import HttpResponseRedirect from django.contrib.auth import login from forms import LoginForm def index(request): return render_to_response('index.html', {}) def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = form.cleaned_data['user'] if user is not None and user.is_active: request.session['password'] = form.cleaned_data['password'] login(request, user) return HttpResponseRedirect('/') else: form = LoginForm() return render(request, 'login.html', { 'form': form, })
#! coding: utf-8 from django.shortcuts import render_to_response, render from django.http import HttpResponseRedirect from django.contrib.auth import login from forms import LoginForm def index(request): return render_to_response('index.html', {}) def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = form.cleaned_data['user'] if user is not None and user.is_active: login(request, user) return HttpResponseRedirect('/') else: form = LoginForm() return render(request, 'login.html', { 'form': form, })
Add `owner` filter to CaseES
from .es_query import HQESQuery from . import filters class CaseES(HQESQuery): index = 'cases' @property def builtin_filters(self): return [ opened_range, closed_range, is_closed, case_type, owner, ] + super(CaseES, self).builtin_filters def opened_range(gt=None, gte=None, lt=None, lte=None): return filters.date_range('opened_on', gt, gte, lt, lte) def closed_range(gt=None, gte=None, lt=None, lte=None): return filters.date_range('closed_on', gt, gte, lt, lte) def is_closed(closed=True): return filters.term('closed', closed) def case_type(type_): return filters.term('type.exact', type_) def owner(owner_id): return filters.term('owner_id', owner_id)
from .es_query import HQESQuery from . import filters class CaseES(HQESQuery): index = 'cases' @property def builtin_filters(self): return [ opened_range, closed_range, is_closed, case_type, ] + super(CaseES, self).builtin_filters def opened_range(gt=None, gte=None, lt=None, lte=None): return filters.date_range('opened_on', gt, gte, lt, lte) def closed_range(gt=None, gte=None, lt=None, lte=None): return filters.date_range('closed_on', gt, gte, lt, lte) def is_closed(closed=True): return filters.term('closed', closed) def case_type(type_): return filters.term('type.exact', type_)
js: Fix version check for win-x64
; (function (d, n) { 'use strict'; var os = n.platform.match(/(Win|Mac|Linux)/); var x = n.userAgent.match(/x86_64|Win64|WOW64/) || n.cpuClass === 'x64' ? 'x64' : 'x86'; var db = d.getElementById('home-downloadbutton'); if (!db) { return; } var version = db.dataset.version; var dlLocal = db.dataset.dlLocal; switch (os && os[1]) { case 'Mac': db.href += 'node-' + version + '.pkg'; db.innerText = dlLocal + ' OS X (x64)'; break; case 'Win': // Windows 64-bit files for 0.x.x need to be prefixed with 'x64/' db.href += (version[1] == '0' && x == 'x64' ? x + '/' : '') + 'node-' + version + '-' + x + '.msi'; db.innerText = dlLocal + ' Windows (' + x +')'; break; case 'Linux': db.href += 'node-' + version + '-linux-' + x + '.tar.gz'; db.innerText = dlLocal + ' Linux (' + x + ')'; break; } })(document, navigator);
; (function (d, n) { 'use strict'; var os = n.platform.match(/(Win|Mac|Linux)/); var x = n.userAgent.match(/x86_64|Win64|WOW64/) || n.cpuClass === 'x64' ? 'x64' : 'x86'; var db = d.getElementById('home-downloadbutton'); if (!db) { return; } var version = db.dataset.version; var dlLocal = db.dataset.dlLocal; switch (os && os[1]) { case 'Mac': db.href += 'node-' + version + '.pkg'; db.innerText = dlLocal + ' OS X (x64)'; break; case 'Win': db.href += (version[0] == '0' && x == 'x64' ? x + '/' : '') + 'node-' + version + '-' + x + '.msi'; db.innerText = dlLocal + ' Windows (' + x +')'; break; case 'Linux': db.href += 'node-' + version + '-linux-' + x + '.tar.gz'; db.innerText = dlLocal + ' Linux (' + x + ')'; break; } })(document, navigator);
Allow linear referencing on rings. Closes #286. Eliminating the assert is good for optimization reasons, too.
"""Linear referencing """ from shapely.topology import Delegating class LinearRefBase(Delegating): def _validate_line(self, ob): super(LinearRefBase, self)._validate(ob) if not ob.geom_type in ['LinearRing', 'LineString', 'MultiLineString']: raise TypeError("Only linear types support this operation") class ProjectOp(LinearRefBase): def __call__(self, this, other): self._validate_line(this) self._validate(other) return self.fn(this._geom, other._geom) class InterpolateOp(LinearRefBase): def __call__(self, this, distance): self._validate_line(this) return self.fn(this._geom, distance)
"""Linear referencing """ from shapely.topology import Delegating class LinearRefBase(Delegating): def _validate_line(self, ob): super(LinearRefBase, self)._validate(ob) try: assert ob.geom_type in ['LineString', 'MultiLineString'] except AssertionError: raise TypeError("Only linear types support this operation") class ProjectOp(LinearRefBase): def __call__(self, this, other): self._validate_line(this) self._validate(other) return self.fn(this._geom, other._geom) class InterpolateOp(LinearRefBase): def __call__(self, this, distance): self._validate_line(this) return self.fn(this._geom, distance)
Fix VueGwtPanel not being typed in the Demo app
package com.axellience.vuegwtdemo.client; import com.axellience.vuegwt.client.gwtextension.VueGwtPanel; import com.axellience.vuegwt.client.jsnative.Vue; import com.axellience.vuegwtdemo.client.components.counterwithtemplate.CounterWithTemplateComponent; import com.axellience.vuegwtdemo.client.components.todolist.TodoListComponent; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootPanel; /** * Entry point classes define <code>onModuleLoad()</code> */ public class VueGwtDemoApp implements EntryPoint { /** * This is the entry point method. */ public void onModuleLoad() { // Create a simple GWT panel containing a CounterWithTemplateComponent RootPanel .get("simpleCounterComponentContainer") .add(new VueGwtPanel<>(CounterWithTemplateComponent.class)); Vue.attach("#todoListComponentContainer", TodoListComponent.class); } }
package com.axellience.vuegwtdemo.client; import com.axellience.vuegwt.client.gwtextension.VueGwtPanel; import com.axellience.vuegwt.client.jsnative.Vue; import com.axellience.vuegwtdemo.client.components.counterwithtemplate.CounterWithTemplateComponent; import com.axellience.vuegwtdemo.client.components.todolist.TodoListComponent; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootPanel; /** * Entry point classes define <code>onModuleLoad()</code> */ public class VueGwtDemoApp implements EntryPoint { /** * This is the entry point method. */ public void onModuleLoad() { // Create a simple GWT panel containing a CounterWithTemplateComponent RootPanel .get("simpleCounterComponentContainer") .add(new VueGwtPanel(CounterWithTemplateComponent.class)); Vue.attach("#todoListComponentContainer", TodoListComponent.class); } }
Make migrations compatible with L53
<?php namespace PragmaRX\Sdk\Core\Migrations; use Illuminate\Database\Console\Migrations\RollbackCommand as IlluminateRollbackCommand; class RollbackCommand extends IlluminateRollbackCommand { use MigratableTrait; /** * Execute the console command. * * @return void */ public function fire() { if ( ! $this->confirmToProceed()) return; $this->migrator->setConnection($this->input->getOption('database')); $pretend = $this->input->getOption('pretend'); if (! isLaravel53()) { $this->requireServiceMigrations(); $this->migrator->rollback($pretend); } else { $this->migrator->rollback($this->getServicesMigrationPaths(), ['pretend' => $pretend]); } $this->cleanTemporaryDirectory(); // Once the migrator has run we will grab the note output and send it out to // the console screen, since the migrator itself functions without having // any instances of the OutputInterface contract passed into the class. foreach ($this->migrator->getNotes() as $note) { $this->output->writeln($note); } } }
<?php namespace PragmaRX\Sdk\Core\Migrations; use Illuminate\Database\Console\Migrations\RollbackCommand as IlluminateRollbackCommand; class RollbackCommand extends IlluminateRollbackCommand { use MigratableTrait; /** * Execute the console command. * * @return void */ public function fire() { if ( ! $this->confirmToProceed()) return; $this->migrator->setConnection($this->input->getOption('database')); $pretend = $this->input->getOption('pretend'); $this->requireServiceMigrations(); $this->migrator->rollback($pretend); $this->cleanTemporaryDirectory(); // Once the migrator has run we will grab the note output and send it out to // the console screen, since the migrator itself functions without having // any instances of the OutputInterface contract passed into the class. foreach ($this->migrator->getNotes() as $note) { $this->output->writeln($note); } } }
Add init from POST array
<?php /** * @license MIT * @author Igor Sorokin <dspbee@pivasic.com> */ namespace Dspbee\Bundle\Data; /** * Initialize class properties from array. * * Class TDataFilter * @package Dspbee\Core */ trait TDataInit { /** * Init class members. * * @param array $data */ public function initFromArray(array $data) { foreach ($data as $name => $value) { $method = 'set' . ucfirst($name); if (method_exists($this, $method)) { call_user_func_array([$this, $method], [$value]); } else { if (property_exists(get_called_class(), $name)) { $this->$name = $value; } } } } /** * Init class members from $_POST array. * * @param null $callback */ public function initFromPost($callback = null) { $input = $_POST; if (null !== $callback) { $input = array_map($callback, $input); } $this->initFromArray($input); } }
<?php /** * @license MIT * @author Igor Sorokin <dspbee@pivasic.com> */ namespace Dspbee\Bundle\Data; /** * Initialize class properties from array. * * Class TDataFilter * @package Dspbee\Core */ trait TDataInit { /** * Init class members. * * @param array $data */ public function initFromArray(array $data) { foreach ($data as $name => $value) { $method = 'set' . ucfirst($name); if (method_exists($this, $method)) { call_user_func_array([$this, $method], [$value]); } else { if (property_exists(get_called_class(), $name)) { $this->$name = $value; } } } } }
Move client creation/selection to an object to prepare for one day abstracting this.
// #TODO: change the whole `fieldspec` thing to just operate on the schema in place? // #TODO: clean up the Base.Schema methods // #TODO: chainable inserts and updates var _ = require('underscore') require('./ext-underscore.js'); const supported = { mysql: function (conf) { var mysql = require('mysql'); require('./ext-mysql-client.js'); return mysql.createClient(conf); } } var Hyde = function (conf) { if (conf) Hyde.initialize(conf); return Hyde; }; Hyde.Validators = require('./validators.js'); Hyde.Schema = require('./schema.js'); Hyde.Base = require('./base.js'); Hyde.initialize = function (conf) { var client = supported[conf.driver](conf); Hyde.DRIVER = Hyde.Base.prototype.driver = conf.driver; Hyde.Migration = Hyde.Base.Migration = require('./migration.js')(client); Hyde.client = Hyde.Base.client = Hyde.Base.prototype.client = client } module.exports = Hyde;
// #TODO: change the whole `fieldspec` thing to just operate on the schema in place? // #TODO: clean up the Base.Schema methods // #TODO: chainable inserts and updates var _ = require('underscore') require('./ext-underscore.js'); var Hyde = function (conf) { if (conf) Hyde.initialize(conf); return Hyde; }; Hyde.Validators = require('./validators.js'); Hyde.Schema = require('./schema.js'); Hyde.Base = require('./base.js'); Hyde.initialize = function (conf) { var mysql = require('mysql') , client = mysql.createClient(conf) // add some methods to the client prototype require('./ext-mysql-client.js'); Hyde.DRIVER = Hyde.Base.prototype.driver = conf.driver; Hyde.Migration = Hyde.Base.Migration = require('./migration.js')(client); Hyde.client = Hyde.Base.client = Hyde.Base.prototype.client = client } module.exports = Hyde;
Drop pagination for Timeline platforms
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Inertia\Inertia; use App\Models\Platform; class TimelineController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return Inertia::render('Timeline/Show', [ 'platforms' => Platform::orderBy('position')->get()->map(function ($platform) { return [ 'name' => $platform->name, 'color' => $platform->color, 'icon' => $platform->icon, 'legacy' => $platform->legacy, 'url' => route('front.timeline.show', $platform, false) ]; }), 'status' => session('status') ]); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Inertia\Inertia; use App\Models\Platform; class TimelineController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return Inertia::render('Timeline/Show', [ 'platforms' => Platform::orderBy('position')->paginate(50)->map(function ($platform) { return [ 'id' => $platform->id, 'name' => $platform->name, 'color' => $platform->color, 'icon' => $platform->icon, 'legacy' => $platform->legacy, 'url' => route('front.timeline.show', $platform, false) ]; }), 'status' => session('status') ]); } }
Add random on quizz list
var QuizzListView = Backbone.View.extend({ el: '#app', templateHandlebars: Handlebars.compile( $('#play-template-handlebars').html() ), remove: function() { this.$el.empty(); return this; }, shuffleArray: function (o){ for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; }, initialize: function() { console.log('Initialize in quizz view'); this.myQuizzCollection = new QuizzCollection(); var self = this; this.myQuizzCollection.fetch({ success: function(data) { // Shuffle the data and store it self.quizzList = self.shuffleArray(self.myQuizzCollection.toJSON()); self.render(); }, error: function(error) { console.log('Error while fetching quizz: ', error); } }); }, render: function() { this.$el.html( this.templateHandlebars(this.quizzList) ); } });
var QuizzListView = Backbone.View.extend({ el: '#app', templateHandlebars: Handlebars.compile( $('#play-template-handlebars').html() ), remove: function() { this.$el.empty(); return this; }, initialize: function() { console.log('Initialize in quizz view'); this.myQuizzCollection = new QuizzCollection(); var self = this; this.myQuizzCollection.fetch({ success: function(data) { self.render(); }, error: function(error) { console.log('Error while fetching quizz: ', error); } }); }, render: function() { this.$el.html( this.templateHandlebars(this.myQuizzCollection.toJSON()) ); } });
Remove underscore prefix to 'private' fields and methods
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Blink extends Component { constructor(props) { super(props); this.state = { isVisible: true, }; } componentDidMount() { this.animate(); } componentDidUpdate() { this.animate(); } componentWillUnmount() { clearInterval(this.blinkTimer); } render() { const { className, children, text } = this.props; const style = { visibility: this.state.isVisible ? 'visible' : 'hidden', }; return ( <div className={`ui-blink ${className}`}> <span ref="text" style={style}>{children}</span> </div> ); } animate() { clearInterval(this.blinkTimer); const { rate } = this.props; this.blinkTimer = setInterval(() => { this.setState({ isVisible: !this.state.isVisible, }); }, rate); } } Blink.propTypes = { rate: PropTypes.number, className: PropTypes.string, children: PropTypes.node, }; Blink.defaultProps = { rate: 1000, className: '', children: '', } export default Blink;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; class Blink extends Component { constructor(props) { super(props); } getInitialState() { return { isVisible: true, }; } componentDidMount() { this._animate(); } componentDidUpdate() { this._animate(); } componentWillUnmount() { clearInterval(this._blinkTimer); } render() { const { className, children, text } = this.props; const style = { visibility: this.state.isVisible ? 'visible' : 'hidden', }; return ( <div className={`ui-blink ${className}`}> <span ref="text" style={style}>{children}</span> </div> ); } _animate() { clearInterval(this._blinkTimer); const { rate } = this.props; this._blinkTimer = setInterval(() => { this.setState({ isVisible: !this.state.isVisible, }); }, rate); } } Blink.propTypes = { rate: PropTypes.number, className: PropTypes.string, children: PropTypes.node, }; Blink.defaultProps = { rate: 1000, className: '', children: '', } export default Blink;
Add button for _onPressAddStory to styles
import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableHighlight, } from 'react-native'; import I18n from 'react-native-i18n' class Profile extends Component{ _onPressAddStory(){ } render() { return ( <View style={styles.container}> <Text style={styles.title}>Smeagles {I18n.t('profile')}</Text> <Text style={styles.body}> {JSON.stringify(this.props.users)}</Text> <Text style={styles.body}> Temporary for styling Skeleton </Text> <TouchableHighlight onPress={this._onPressAddStory.bind(this)} style={styles.button}> <Text style={styles.buttonText}> Add Story </Text> </TouchableHighlight> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { marginTop: 25, fontSize: 20, alignSelf: 'center', margin: 40, }, body: { flex: 0.1, }, button: { height: 50, backgroundColor: '#48BBEC', alignSelf: 'stretch', marginTop: 10, justifyContent: 'center' }, buttonText: { textAlign: 'center', }, }); module.exports = Profile;
import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableHighlight, } from 'react-native'; import I18n from 'react-native-i18n' class Profile extends Component{ _onPressAddStory(){ } render() { return ( <View style={styles.container}> <Text style={styles.title}>Smeagles {I18n.t('profile')}</Text> <Text style={styles.body}> {JSON.stringify(this.props.users)}</Text> <Text style={styles.body}> Temporary for styling Skeleton </Text> <TouchableHighlight onPress={this._onPressAddStory.bind(this)} style={styles.button}> <Text style={styles.buttonText}> Add Story </Text> </TouchableHighlight> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { marginTop: 25, fontSize: 20, alignSelf: 'center', margin: 40, }, body: { flex: 0.1, } }); module.exports = Profile;
feat(client): Add syntax highlighting to challenge instructions
import React, { Fragment, Component } from 'react'; import Prism from 'prismjs'; import PropTypes from 'prop-types'; import './challenge-description.css'; const propTypes = { description: PropTypes.string, instructions: PropTypes.string, section: PropTypes.string }; class ChallengeDescription extends Component { componentDidMount() { // Just in case 'current' has not been created, though it should have been. if (this.instructionsRef.current) { Prism.highlightAllUnder(this.instructionsRef.current); } } constructor(props) { super(props); this.instructionsRef = React.createRef(); } render() { const { description, instructions, section } = this.props; return ( <div className={`challenge-instructions ${section}`} ref={this.instructionsRef} > <div dangerouslySetInnerHTML={{ __html: description }} /> {instructions && ( <Fragment> <hr /> <div dangerouslySetInnerHTML={{ __html: instructions }} /> </Fragment> )} <hr /> </div> ); } } ChallengeDescription.displayName = 'ChallengeDescription'; ChallengeDescription.propTypes = propTypes; export default ChallengeDescription;
import React, { Fragment } from 'react'; import PropTypes from 'prop-types'; import './challenge-description.css'; const propTypes = { description: PropTypes.string, instructions: PropTypes.string, section: PropTypes.string }; function ChallengeDescription({ description, instructions, section }) { return ( <div className={`challenge-instructions ${section}`}> <div dangerouslySetInnerHTML={{ __html: description }} /> {instructions && ( <Fragment> <hr /> <div dangerouslySetInnerHTML={{ __html: instructions }} /> </Fragment> )} <hr /> </div> ); } ChallengeDescription.displayName = 'ChallengeDescription'; ChallengeDescription.propTypes = propTypes; export default ChallengeDescription;
fix(shape): Migrate to new basic shape and cursor
import Shape from 'kittik-shape-basic'; /** * Implements rectangle shape with text support. * * @since 1.0.0 * @version 1.0.0 */ export default class Rectangle extends Shape { render(cursor) { let text = this.getText(); let width = this.getWidth(); let height = this.getHeight(); let x1 = this.getX(); let y1 = this.getY(); let x2 = x1 + width - 1; let y2 = y1 + height - 1; let background = this.getBackground(); let foreground = this.getForeground(); let filler = ' '.repeat(width); if (typeof background !== 'undefined') cursor.background(background); if (typeof foreground !== 'undefined') cursor.foreground(foreground); cursor.moveTo(x1, y1); while (y1 <= y2) { cursor.write(filler); cursor.moveTo(x1, ++y1); } cursor.moveTo(x1 + (width / 2 - text.length / 2), this.getY() + (height / 2)).write(text); return this; } }
import Shape from 'kittik-shape-basic'; /** * Implements rectangle shape with text support. * * @since 1.0.0 * @version 1.0.0 */ export default class Rectangle extends Shape { fill(cursor, options = {}) { let {x, y, width, height, symbol = ' ', background, foreground} = options; let filler = symbol.repeat(width + 1); if (typeof background !== 'undefined') cursor.background(background); if (typeof foreground !== 'undefined') cursor.foreground(foreground); cursor.moveTo(x, y); while (y <= height + y) { cursor.write(filler); cursor.moveTo(x, ++y); } return this; } render(cursor) { let text = this.getText(); let width = this.getWidth(); let height = this.getHeight(); let {x: x1, y: y1} = this.getPosition(); let {x2, y2} = {x2: width + x1 - 1, y2: height + y1 - 1}; let background = this.getBackground(); let foreground = this.getForeground(); this.fill(cursor, {x1, y1, x2, y2, background, foreground}); cursor.setPosition(x1 + (width / 2 - text.length / 2), y1 + (height / 2)).write(text); return this; } }
Delete FK before dropping instance_id column.
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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 sqlalchemy import * from sqlalchemy import Column, ForeignKeyConstraint, Integer, String from sqlalchemy import MetaData, Table meta = MetaData() # # Tables to alter # # instance_id = Column('instance_id', Integer()) instance_uuid = Column('instance_uuid', String(255)) def upgrade(migrate_engine): meta.bind = migrate_engine migrations = Table('migrations', meta, autoload=True) migrations.create_column(instance_uuid) if migrate_engine.name == "mysql": migrate_engine.execute("ALTER TABLE migrations DROP FOREIGN KEY " \ "`migrations_ibfk_1`;") migrations.c.instance_id.drop() def downgrade(migrate_engine): meta.bind = migrate_engine migrations = Table('migrations', meta, autoload=True) migrations.c.instance_uuid.drop() migrations.create_column(instance_id)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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 sqlalchemy import * from sqlalchemy import Column, Integer, String, MetaData, Table meta = MetaData() # # Tables to alter # # instance_id = Column('instance_id', Integer()) instance_uuid = Column('instance_uuid', String(255)) def upgrade(migrate_engine): meta.bind = migrate_engine migrations = Table('migrations', meta, autoload=True) migrations.create_column(instance_uuid) migrations.c.instance_id.drop() def downgrade(migrate_engine): meta.bind = migrate_engine migrations = Table('migrations', meta, autoload=True) migrations.c.instance_uuid.drop() migrations.create_column(instance_id)
Remove clearing of exception context when raising a new exception This syntax is only supported in Python 3.3 and up and is causing tests in Python 2.7 to fail.
from pkg_resources import DistributionNotFound, get_distribution, parse_version try: import psycopg2 # noqa: F401 except ImportError: raise ImportError( 'No module named psycopg2. Please install either ' 'psycopg2 or psycopg2-binary package for CPython ' 'or psycopg2cffi for Pypy.' ) for package in ['psycopg2', 'psycopg2-binary', 'psycopg2cffi']: try: if get_distribution(package).parsed_version < parse_version('2.5'): raise ImportError('Minimum required version for psycopg2 is 2.5') break except DistributionNotFound: pass else: raise ImportError( 'A module was found named psycopg2, ' 'but the version of it could not be checked ' 'as it was neither the Python package psycopg2, ' 'psycopg2-binary or psycopg2cffi.' ) __version__ = get_distribution('sqlalchemy-redshift').version from sqlalchemy.dialects import registry registry.register("redshift", "sqlalchemy_redshift.dialect", "RedshiftDialect") registry.register( "redshift.psycopg2", "sqlalchemy_redshift.dialect", "RedshiftDialect" )
from pkg_resources import DistributionNotFound, get_distribution, parse_version try: import psycopg2 # noqa: F401 except ImportError: raise ImportError( 'No module named psycopg2. Please install either ' 'psycopg2 or psycopg2-binary package for CPython ' 'or psycopg2cffi for Pypy.' ) from None for package in ['psycopg2', 'psycopg2-binary', 'psycopg2cffi']: try: if get_distribution(package).parsed_version < parse_version('2.5'): raise ImportError('Minimum required version for psycopg2 is 2.5') break except DistributionNotFound: pass else: raise ImportError( 'A module was found named psycopg2, ' 'but the version of it could not be checked ' 'as it was neither the Python package psycopg2, ' 'psycopg2-binary or psycopg2cffi.' ) __version__ = get_distribution('sqlalchemy-redshift').version from sqlalchemy.dialects import registry registry.register("redshift", "sqlalchemy_redshift.dialect", "RedshiftDialect") registry.register( "redshift.psycopg2", "sqlalchemy_redshift.dialect", "RedshiftDialect" )
Add X points to profile on task complete
<?php namespace SayAndDo\TaskBundle\Service; use Doctrine\ORM\EntityManager; use SayAndDo\TaskBundle\DependencyInjection\TaskPoints; use SayAndDo\TaskBundle\DependencyInjection\TaskStatus; use SayAndDo\TaskBundle\Entity\Task; class TaskService { protected $em; public function __construct(EntityManager $em) { $this->em = $em; } public function store($task) { $this->saveEntity($task); } private function saveEntity($entity) { $this->em->persist($entity); $this->em->flush(); } public function confirmTask(Task $task) { $task->setStatus(TaskStatus::STATUS_CONFIRMED); $this->store($task); } public function startTask(Task $task) { $task->setStatus(TaskStatus::STATUS_IN_PROGRESS); $this->store($task); } public function completeTask(Task $task) { $task->setStatus(TaskStatus::STATUS_DONE); $this->store($task); $task->getProfile()->setPoints($task->getProfile()->getPoints() + TaskPoints::FOR_FINISHED_TASK); $this->saveEntity($task->getProfile()); } }
<?php namespace SayAndDo\TaskBundle\Service; use Doctrine\ORM\EntityManager; use SayAndDo\TaskBundle\DependencyInjection\TaskStatus; use SayAndDo\TaskBundle\Entity\Task; class TaskService { protected $em; public function __construct(EntityManager $em) { $this->em = $em; } public function store($task) { $this->saveEntity($task); } private function saveEntity($entity) { $this->em->persist($entity); $this->em->flush(); } public function confirmTask(Task $task) { $task->setStatus(TaskStatus::STATUS_CONFIRMED); $this->store($task); } public function startTask(Task $task) { $task->setStatus(TaskStatus::STATUS_IN_PROGRESS); $this->store($task); } public function completeTask(Task $task) { $task->setStatus(TaskStatus::STATUS_DONE); $this->store($task); } }