text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Upgrade SQLAlchemy 1.1.6 => 1.2.0
from setuptools import setup setup( name='tangled.website', version='1.0a1.dev0', description='tangledframework.org', long_description=open('README.rst').read(), url='https://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.website/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=[ 'tangled', 'tangled.website', ], include_package_data=True, install_requires=[ 'tangled.auth>=0.1a3', 'tangled.session>=0.1a3', 'tangled.site>=1.0a5', 'SQLAlchemy>=1.2.0', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
from setuptools import setup setup( name='tangled.website', version='1.0a1.dev0', description='tangledframework.org', long_description=open('README.rst').read(), url='https://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.website/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=[ 'tangled', 'tangled.website', ], include_package_data=True, install_requires=[ 'tangled.auth>=0.1a3', 'tangled.session>=0.1a3', 'tangled.site>=1.0a5', 'SQLAlchemy>=1.1.6', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
Fix for bad db.json path?
'use strict'; const jsonServer = require('json-server'); const server = jsonServer.create(); const router = jsonServer.router('db.json'); const middlewares = jsonServer.defaults(); const { DB_FILE } = require('../constants'); const { updateJSON } = require('../update/update'); /** * Server file for json-server */ server.use(middlewares); server.all('/:year/export', async function ({ params }, UUresponse, next) { const { year } = params; await updateJSON({ year }); router.db.assign(require('require-uncached')(DB_FILE)).write(); next(); }); server.use(jsonServer.rewriter({ '/:year/export\\?*W=:week': '/export?W=:week' })); router.render = (UUrequest, response) => { const { data } = response.locals; if (Array.isArray(data) && data.length === 1) return response.jsonp(data[0]); response.jsonp(data); }; server.use(router); server.listen(3003, () => { console.log('JSON Server is running...'); });
'use strict'; const jsonServer = require('json-server'); const server = jsonServer.create(); const router = jsonServer.router('db.json'); const middlewares = jsonServer.defaults(); const { updateJSON } = require('../update/update'); /** * Server file for json-server */ server.use(middlewares); server.all('/:year/export', async function ({ params }, UUresponse, next) { const { year } = params; await updateJSON({ year }); router.db.assign(require('require-uncached')('./db.json')).write(); next(); }); server.use(jsonServer.rewriter({ '/:year/export\\?*W=:week': '/export?W=:week' })); router.render = (UUrequest, response) => { const { data } = response.locals; if (Array.isArray(data) && data.length === 1) return response.jsonp(data[0]); response.jsonp(data); }; server.use(router); server.listen(3003, () => { console.log('JSON Server is running...'); });
Use tooltip for background jobs info tooltip
/** * ownCloud * * @author Jakob Sack * @copyright 2012 Jakob Sack owncloud@jakobsack.de * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ // start worker once page has loaded $(document).ready(function(){ $.get( OC.webroot+'/cron.php' ); $('.section .icon-info').tooltip({ placement: 'right' }); });
/** * ownCloud * * @author Jakob Sack * @copyright 2012 Jakob Sack owncloud@jakobsack.de * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ // start worker once page has loaded $(document).ready(function(){ $.get( OC.webroot+'/cron.php' ); $('.section .icon-info').tipsy({gravity: 'w'}); });
Fix boolean parser, expecting -1 to become false
package org.col.parser; import com.google.common.collect.Lists; import org.junit.Test; import java.util.List; /** * */ public class BooleanParserTest extends ParserTestBase<Boolean> { public BooleanParserTest() { super(BooleanParser.PARSER); } @Test public void parse() throws Exception { assertParse(true, "true"); assertParse(true, "yes"); assertParse(true, " t "); assertParse(true, "T"); assertParse(true, "si"); assertParse(true, "ja"); assertParse(true, "oui"); assertParse(true, "wahr"); assertParse(false,"f"); assertParse(false,"f"); assertParse(false,"no"); assertParse(false,"nein"); assertParse(false, "-1"); } @Override List<String> additionalUnparsableValues() { return Lists.newArrayList("t ru e", "a", "2"); } }
package org.col.parser; import com.google.common.collect.Lists; import org.junit.Test; import java.util.List; /** * */ public class BooleanParserTest extends ParserTestBase<Boolean> { public BooleanParserTest() { super(BooleanParser.PARSER); } @Test public void parse() throws Exception { assertParse(true, "true"); assertParse(true, "-1-"); assertParse(true, "yes!"); assertParse(true, " t "); assertParse(true, "T"); assertParse(true, "si"); assertParse(true, "ja"); assertParse(true, "oui"); assertParse(true, "wahr"); assertParse(false,"f"); assertParse(false,"f"); assertParse(false,"no"); assertParse(false,"nein"); } @Override List<String> additionalUnparsableValues() { return Lists.newArrayList("t ru e", "a", "2"); } }
Convert reactions syslog to logger: timetracking
#!/usr/bin/python ###################################################################### # Cloud Routes Bridge # ------------------------------------------------------------------- # Actions Module ###################################################################### import stathat import time def action(**kwargs): ''' This method is called to action a reaction ''' logger = kwargs['logger'] updateStathat(kwargs['jdata'], logger) return True def updateStathat(jdata, logger): ''' This method will be called to update a stathat Statistic ''' ez_key = jdata['time_tracking']['ez_key'] stat_name = "[%s] End to End Monitor transaction time" % jdata[ 'time_tracking']['env'] value = time.time() - jdata['time_tracking']['control'] stathat.ez_value(ez_key, stat_name, value) line = "timetracker: Sent stat to StatHat for %s" % jdata['cid'] logger.info(line)
#!/usr/bin/python ###################################################################### # Cloud Routes Bridge # ------------------------------------------------------------------- # Actions Module ###################################################################### import stathat import time import syslog def action(**kwargs): ''' This method is called to action a reaction ''' updateStathat(kwargs['jdata']) return True def updateStathat(jdata): ''' This method will be called to update a stathat Statistic ''' ez_key = jdata['time_tracking']['ez_key'] stat_name = "[%s] End to End Monitor transaction time" % jdata[ 'time_tracking']['env'] value = time.time() - jdata['time_tracking']['control'] stathat.ez_value(ez_key, stat_name, value) line = "timetracker: Sent stat to StatHat for %s" % jdata['cid'] syslog.syslog(syslog.LOG_INFO, line)
Use Dispatcher contract instead of concrete implementation
<?php namespace Laracasts\Utilities\JavaScript; use Illuminate\Contracts\Events\Dispatcher; class LaravelViewBinder implements ViewBinder { /** * The event dispatcher implementation. * * @var Dispatcher */ private $event; /** * The name of the view to bind any * generated JS variables to. * * @var string */ private $views; /** * Create a new Laravel view binder instance. * * @param Dispatcher $event * @param string|array $views */ function __construct(Dispatcher $event, $views) { $this->event = $event; $this->views = str_replace('/', '.', (array) $views); } /** * Bind the given JavaScript to the view. * * @param string $js */ public function bind($js) { foreach ($this->views as $view) { $this->event->listen("composing: {$view}", function () use ($js) { echo "<script>{$js}</script>"; }); } } }
<?php namespace Laracasts\Utilities\JavaScript; use Illuminate\Events\Dispatcher; class LaravelViewBinder implements ViewBinder { /** * The event dispatcher implementation. * * @var Dispatcher */ private $event; /** * The name of the view to bind any * generated JS variables to. * * @var string */ private $views; /** * Create a new Laravel view binder instance. * * @param Dispatcher $event * @param string|array $views */ function __construct(Dispatcher $event, $views) { $this->event = $event; $this->views = str_replace('/', '.', (array) $views); } /** * Bind the given JavaScript to the view. * * @param string $js */ public function bind($js) { foreach ($this->views as $view) { $this->event->listen("composing: {$view}", function () use ($js) { echo "<script>{$js}</script>"; }); } } }
Add comment about timeout service stability
/* * Copyright 2015 Timothy Brooks * * 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 net.uncontended.precipice.timeout; import java.util.concurrent.TimeUnit; /** * Unstable and still in development. At this time, {@link TimeoutService} should be used. */ public class NewTimerService { private final long resolution; private final long startTime; public NewTimerService(long resolution, TimeUnit unit) { this.resolution = unit.toMillis(resolution); startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } public void schedule(Object task, long delay, TimeUnit unit) { } }
/* * Copyright 2015 Timothy Brooks * * 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 net.uncontended.precipice.timeout; import java.util.concurrent.TimeUnit; public class NewTimerService { private final long resolution; private final long startTime; public NewTimerService(long resolution, TimeUnit unit) { this.resolution = unit.toMillis(resolution); startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } public void schedule(Object task, long delay, TimeUnit unit) { } }
Stop ESLint complaining about localStorage
module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, extends: 'airbnb-base', // required to lint *.vue files plugins: [ 'html' ], // check if imports actually resolve 'settings': { 'import/resolver': { 'webpack': { 'config': 'build/webpack.base.conf.js' } } }, // add your custom rules here 'rules': { // don't require .vue extension when importing 'import/extensions': ['error', 'always', { 'js': 'never', 'vue': 'never' }], // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, 'no-console': process.env.NODE_ENV === 'production' ? 2 : 0 }, 'env': { 'browser': true } }
module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, extends: 'airbnb-base', // required to lint *.vue files plugins: [ 'html' ], // check if imports actually resolve 'settings': { 'import/resolver': { 'webpack': { 'config': 'build/webpack.base.conf.js' } } }, // add your custom rules here 'rules': { // don't require .vue extension when importing 'import/extensions': ['error', 'always', { 'js': 'never', 'vue': 'never' }], // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, 'no-console': process.env.NODE_ENV === 'production' ? 2 : 0 } }
Add CLI flag to allow not showing the preview window
package main import ( "flag" "go/build" "log" "math/rand" "time" "github.com/esimov/diagram/canvas" "github.com/esimov/diagram/io" "github.com/esimov/diagram/ui" "github.com/fogleman/imview" ) var defaultFontFile = build.Default.GOPATH + "/src/github.com/esimov/diagram" + "/font/gloriahallelujah.ttf" var ( source = flag.String("in", "", "Source") destination = flag.String("out", "", "Destination") fontpath = flag.String("font", defaultFontFile, "path to font file") preview = flag.Bool("preview", true, "Show the preview window") ) func main() { rand.Seed(time.Now().UTC().UnixNano()) flag.Parse() // If filenames specified on the commandline generate diagram directly with command line tool. if (*source != "") && (*destination != "") { input := string(io.ReadFile(*source)) err := canvas.DrawDiagram(input, *destination, *fontpath) if err != nil { log.Fatal("Error on converting the ascii art to hand drawn diagrams!") } else if *preview { image, _ := imview.LoadImage(*destination) view := imview.ImageToRGBA(image) imview.Show(view) } } else { ui.InitApp(*fontpath) } }
package main import ( "flag" "go/build" "log" "math/rand" "time" "github.com/esimov/diagram/canvas" "github.com/esimov/diagram/io" "github.com/esimov/diagram/ui" "github.com/fogleman/imview" ) var defaultFontFile = build.Default.GOPATH + "/src/github.com/esimov/diagram" + "/font/gloriahallelujah.ttf" var ( source = flag.String("in", "", "Source") destination = flag.String("out", "", "Destination") fontpath = flag.String("font", defaultFontFile, "path to font file") ) func main() { rand.Seed(time.Now().UTC().UnixNano()) flag.Parse() // If filenames specified on the commandline generate diagram directly with command line tool. if (*source != "") && (*destination != "") { input := string(io.ReadFile(*source)) err := canvas.DrawDiagram(input, *destination, *fontpath) if err != nil { log.Fatal("Error on converting the ascii art to hand drawn diagrams!") } else { image, _ := imview.LoadImage(*destination) view := imview.ImageToRGBA(image) imview.Show(view) } } else { ui.InitApp(*fontpath) } }
Add sprints and tasks relationships to project model
<?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Client; class Project extends Model { protected $fillable = [ 'name', 'description', 'client_id' ]; /** * The client that the project belongs to **/ public function client() { return $this->belongsTo('App\Client'); } /** * Returns the client object that the project belongs to if one exists or * a blank client object if none exists. * * @return \App\Client **/ public function getClient() { if (is_null($this->client)) { return new Client; } return $this->client; } /** * The sprints that belong to the project **/ public function sprints() { return $this->hasMany('App\Sprint'); } /** * The tasks that belong to the project **/ public function tasks() { return $this->hasMany('App\Task'); } }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Client; class Project extends Model { protected $fillable = [ 'name', 'description', 'client_id' ]; /** * The client that the project belongs to **/ public function client() { return $this->belongsTo('App\Client'); } /** * Returns the client object that the project belongs to if one exists or * a blank client object if none exists. * * @return \App\Client **/ public function getClient() { if (is_null($this->client)) { return new Client; } return $this->client; } }
Update to use <span> instead of <input> for non-modifiable text.
<!-- Sleep so users see the activity indicator --> <?php sleep(2); ?> <ul id="stats" title="Stats"> <li><a href="#usage">Usage</a></li> <li><a href="#battery">Battery</a></li> </ul> <div id="usage" title="Usage" class="panel"> <h2>Play Time</h2> <fieldset> <div class="row"> <label>Years</label> <span>2</span> </div> <div class="row"> <label>Months</label> <span>8</span> </div> <div class="row"> <label>Days</label> <span>27</span> </div> </fieldset> </div> <div id="battery" title="Battery" class="panel"> <h2>Better recharge soon!</h2> </div>
<!-- Sleep so users see the activity indicator --> <?php sleep(2); ?> <ul id="stats" title="Stats"> <li><a href="#usage">Usage</a></li> <li><a href="#battery">Battery</a></li> </ul> <div id="usage" title="Usage" class="panel"> <h2>Play Time</h2> <fieldset> <div class="row"> <label>Years</label> <input type="text" value="2"/> </div> <div class="row"> <label>Months</label> <input type="text" value="8"/> </div> <div class="row"> <label>Days</label> <input type="text" value="27"/> </div> </fieldset> </div> <div id="battery" title="Battery" class="panel"> <h2>Better recharge soon!</h2> </div>
Add dcterms.creator to find author name https://www.dublincore.org/specifications/dublin-core/dcmi-terms/#http://purl.org/dc/elements/1.1/creator
<?php declare(strict_types = 1); namespace Embed\Detectors; class AuthorName extends Detector { public function detect(): ?string { $oembed = $this->extractor->getOEmbed(); $metas = $this->extractor->getMetas(); return $oembed->str('author_name') ?: $metas->str( 'article:author', 'book:author', 'sailthru.author', 'lp.article:author', 'twitter:creator', 'dcterms.creator', ); } }
<?php declare(strict_types = 1); namespace Embed\Detectors; class AuthorName extends Detector { public function detect(): ?string { $oembed = $this->extractor->getOEmbed(); $metas = $this->extractor->getMetas(); return $oembed->str('author_name') ?: $metas->str( 'article:author', 'book:author', 'sailthru.author', 'lp.article:author', 'twitter:creator' ); } }
Reword the permissions for Disqus
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://disqus.com/' docs_url = 'http://disqus.com/api/docs/' category = 'Social' # URLs to interact with the API authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/' access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/' api_domain = 'disqus.com' available_permissions = [ (None, 'access your contact info'), ('write', 'access your contact info and add comments'), ('admin', 'access your contact info, and comments and moderate your forums'), ] permissions_widget = 'radio' bearer_type = token_uri def get_scope_string(self, scopes): # Disqus doesn't follow the spec on this point return ','.join(scopes) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/3.0/users/details.json') return r.json[u'response'][u'id']
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://disqus.com/' docs_url = 'http://disqus.com/api/docs/' category = 'Social' # URLs to interact with the API authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/' access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/' api_domain = 'disqus.com' available_permissions = [ (None, 'read data on your behalf'), ('write', 'read and write data on your behalf'), ('admin', 'read and write data on your behalf and moderate your forums'), ] permissions_widget = 'radio' bearer_type = token_uri def get_scope_string(self, scopes): # Disqus doesn't follow the spec on this point return ','.join(scopes) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/3.0/users/details.json') return r.json[u'response'][u'id']
Add root route for serving index.html
// BASE SETUP // ============================================================================= var express = require('express'); var server = express(); var port = process.env.PORT || 4000; var bodyParser = require('body-parser'); var router = express.Router(); var apiRouter = express.Router(); // BODY PARSER SETUP // ============================================================================= server.use(bodyParser.urlencoded({ extended: true })); server.use(bodyParser.json()); // SERVER ROUTES // ============================================================================= // Middleware router.use(function(req, res, next) { console.log('Connection detected: ' + req.method + ' on ' + req.url); next(); }); // Browser routes router.get('/', function(req, res) { // res.send('<h1>Welcome to The Ape Butler Server!</h1>'); }); server.use('/', express.static('client')); // server.use('/', express.static(path.join(__dirname, 'client'))); // Api Routes apiRouter.get('/', function(req, res) { res.send('<h1>Welcome to The Ape Butler API!</h1>'); }) server.use('/api', apiRouter); server.listen(port); console.log('The Butler Server is running on port: ' + port);
// BASE SETUP // ============================================================================= var express = require('express'); var server = express(); var port = process.env.PORT || 4000; var bodyParser = require('body-parser'); var router = express.Router(); var apiRouter = express.Router(); // BODY PARSER SETUP // ============================================================================= server.use(bodyParser.urlencoded({ extended: true })); server.use(bodyParser.json()); // SERVER ROUTES // ============================================================================= // Middleware router.use(function(req, res, next) { console.log('Connection detected: ' + req.method + ' on ' + req.url); next(); }); // Browser routes router.get('/', function(req, res) { res.send('<h1>Welcome to The Ape Butler Server!</h1>'); }); server.use('/', router); // Api Routes apiRouter.get('/', function(req, res) { res.send('<h1>Welcome to The Ape Butler API!</h1>'); }) server.use('/api', apiRouter); server.listen(port); console.log('The Butler Server is running on port: ' + port);
Fix and extend test conditions
import os from indra.statements import * from indra.sources import ctd from indra.sources.ctd.processor import CTDChemicalGeneProcessor HERE = os.path.dirname(os.path.abspath(__file__)) def test_statement_type_mapping(): st = CTDChemicalGeneProcessor.get_statement_types( 'decreases^phosphorylation', 'X', 'X decreases the phosphorylation of Y') assert set(st.values()) == {Dephosphorylation}, st st = CTDChemicalGeneProcessor.get_statement_types( 'decreases^reaction|increases^phosphorylation', 'X', 'X decreases the reaction [Z increases the phosphorylation of Y]') assert set(st.values()) == {Dephosphorylation}, st def test_chemical_gene(): fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv') cp = ctd.process_tsv(fname, 'chemical_gene') assert len(cp.statements) == 3, cp.statements assert isinstance(cp.statements[0], Dephosphorylation) assert cp.statements[0].enz.name == 'wortmannin' assert isinstance(cp.statements[1], Dephosphorylation) assert cp.statements[1].enz.name == 'YM-254890' assert isinstance(cp.statements[2], Phosphorylation) assert cp.statements[2].enz.name == 'zinc atom'
import os from indra.statements import * from indra.sources import ctd from indra.sources.ctd.processor import CTDChemicalGeneProcessor HERE = os.path.dirname(os.path.abspath(__file__)) def test_statement_type_mapping(): st = CTDChemicalGeneProcessor.get_statement_types( 'decreases^phosphorylation', 'X', 'X decreases the phosphorylation of Y') assert set(st.values()) == {Dephosphorylation}, st st = CTDChemicalGeneProcessor.get_statement_types( 'decreases^reaction|increases^phosphorylation', 'X', 'X decreases the reaction [Z increases the phosphorylation of Y]') assert set(st.values()) == {Dephosphorylation}, st def test_chemical_gene(): fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv') cp = ctd.process_tsv(fname, 'chemical_gene') assert len(cp.statements) == 4, cp.statements
Use columns from points source
'use strict'; var dot = require('dot'); dot.templateSettings.strip = false; var Node = require('../node'); var queryTemplate = dot.template([ 'WITH', '_cdb_analysis_points AS (', ' {{=it.pointsQuery}}', '),', '_cdb_analysis_polygons AS (', ' {{=it.polygonsQuery}}', ')', 'SELECT {{=it.pointsColumns}}', 'FROM _cdb_analysis_points JOIN _cdb_analysis_polygons', 'ON ST_Contains(_cdb_analysis_polygons.the_geom, _cdb_analysis_points.the_geom)' ].join('\n')); function query(it) { it.pointsColumns = it.columnNames.map(function(name) { return '_cdb_analysis_points.' + name; }).join(', '); return queryTemplate(it); } var TYPE = 'point-in-polygon'; var PARAMS = { points_source: Node.PARAM.NODE, polygons_source: Node.PARAM.NODE }; var PointInPolygon = Node.create(TYPE, PARAMS); module.exports = PointInPolygon; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; module.exports.create = require('./factory').create; PointInPolygon.prototype._getQuery = function() { return query({ pointsQuery: this.points_source.getQuery(), polygonsQuery: this.polygons_source.getQuery(), columnNames: this.points_source.getColumns() }); };
'use strict'; var dot = require('dot'); dot.templateSettings.strip = false; var Node = require('../node'); var queryTemplate = dot.template([ 'WITH', '_cdb_analysis_points AS (', ' {{=it.pointsQuery}}', '),', '_cdb_analysis_polygons AS (', ' {{=it.polygonsQuery}}', ')', 'SELECT {{=it.pointsColumns}}', 'FROM _cdb_analysis_points JOIN _cdb_analysis_polygons', 'ON ST_Contains(_cdb_analysis_polygons.the_geom, _cdb_analysis_points.the_geom)' ].join('\n')); function query(it) { it.pointsColumns = it.columnNames.map(function(name) { return '_cdb_analysis_points.' + name; }).join(', '); return queryTemplate(it); } var TYPE = 'point-in-polygon'; var PARAMS = { points_source: Node.PARAM.NODE, polygons_source: Node.PARAM.NODE }; var PointInPolygon = Node.create(TYPE, PARAMS); module.exports = PointInPolygon; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; module.exports.create = require('./factory').create; PointInPolygon.prototype._getQuery = function() { return query({ pointsQuery: this.points_source.getQuery(), polygonsQuery: this.polygons_source.getQuery(), columnNames: this.columns }); };
Make migration to fix Topic's attachments
from datetime import datetime from django.db import models class Topic(models.Model): name = models.CharField(max_length=100) description = models.TextField() attachment = models.ManyToManyField('attachments.Attachment') def __unicode__(self): return self.name class Protocol(models.Model): date = models.DateField(default=datetime.now) number = models.CharField(max_length=20, unique=True) scheduled_time = models.TimeField() start_time = models.TimeField() quorum = models.PositiveIntegerField() absent = models.PositiveIntegerField() attendents = models.ManyToManyField('members.User', related_name='protocols') topics = models.ManyToManyField(Topic) voted_for = models.PositiveIntegerField() voted_against = models.PositiveIntegerField() voted_abstain = models.PositiveIntegerField() information = models.TextField() attachments = models.ManyToManyField('attachments.Attachment') def __unicode__(self): return self.number
from datetime import datetime from django.db import models class Topic(models.Model): name = models.CharField(max_length=100) description = models.TextField() attachment = models.ManyToManyField(Attachment) def __unicode__(self): return self.name class Protocol(models.Model): date = models.DateField(default=datetime.now) number = models.CharField(max_length=20, unique=True) scheduled_time = models.TimeField() start_time = models.TimeField() quorum = models.PositiveIntegerField() absent = models.PositiveIntegerField() attendents = models.ManyToManyField('members.User', related_name='protocols') topics = models.ManyToManyField(Topic) voted_for = models.PositiveIntegerField() voted_against = models.PositiveIntegerField() voted_abstain = models.PositiveIntegerField() information = models.TextField() attachments = models.ManyToManyField('attachments.Attachment') def __unicode__(self): return self.number
Remove logging of 401 status codes
angular.module('juiceShop', [ 'ngRoute', 'ngCookies', 'ngTouch', 'ngAnimate', 'ui.bootstrap' ]); angular.module('juiceShop').factory('authInterceptor', ['$rootScope', '$q', '$cookieStore', function ($rootScope, $q, $cookieStore) { 'use strict'; return { request: function (config) { config.headers = config.headers || {}; if ($cookieStore.get('token')) { config.headers.Authorization = 'Bearer ' + $cookieStore.get('token'); } return config; }, response: function (response) { return response || $q.when(response); } }; }]); angular.module('juiceShop').config(['$httpProvider', function ($httpProvider) { 'use strict'; $httpProvider.interceptors.push('authInterceptor'); }]); angular.module('juiceShop').run(['$cookieStore', '$rootScope', function ($cookieStore, $rootScope) { 'use strict'; $rootScope.isLoggedIn = function () { return $cookieStore.get('token'); }; }]);
angular.module('juiceShop', [ 'ngRoute', 'ngCookies', 'ngTouch', 'ngAnimate', 'ui.bootstrap' ]); angular.module('juiceShop').factory('authInterceptor', ['$rootScope', '$q', '$cookieStore', function ($rootScope, $q, $cookieStore) { 'use strict'; return { request: function (config) { config.headers = config.headers || {}; if ($cookieStore.get('token')) { config.headers.Authorization = 'Bearer ' + $cookieStore.get('token'); } return config; }, response: function (response) { if (response.status === 401) { console.log('401: ' + response.statusText); } return response || $q.when(response); } }; }]); angular.module('juiceShop').config(['$httpProvider', function ($httpProvider) { 'use strict'; $httpProvider.interceptors.push('authInterceptor'); }]); angular.module('juiceShop').run(['$cookieStore', '$rootScope', function ($cookieStore, $rootScope) { 'use strict'; $rootScope.isLoggedIn = function () { return $cookieStore.get('token'); }; }]);
Increase log size to 10 MB
var config = { // Default server port port: 8080, // Base static path base: '/static', // Node handlers route routes: {}, // Now handlers list everyone: [ require('./handlers/task.js').everyone ], // MongoDB configuration mongo: { server: '127.0.0.1', port: 27017, serverOption: {}, databaseOption: {}, database: 'Scrum' }, // Log facility log: { appenders: [ { type: 'file', filename: 'scrum.log', maxLogSize: 10485760, backups: 3, pollInterval: 15 }, { type: 'console' } ], levels: { console: 'info' } } } exports.config = config;
var config = { // Default server port port: 8080, // Base static path base: '/static', // Node handlers route routes: {}, // Now handlers list everyone: [ require('./handlers/task.js').everyone ], // MongoDB configuration mongo: { server: '127.0.0.1', port: 27017, serverOption: {}, databaseOption: {}, database: 'Scrum' }, // Log facility log: { appenders: [ { type: 'file', filename: 'scrum.log', maxLogSize: 102400, backups: 3, pollInterval: 15 }, { type: 'console' } ], levels: { console: 'info' } } } exports.config = config;
Add a few methods used in admin.py
import json import os from elasticsearch import Elasticsearch from elasticsearch_dsl import Index from model import APIDoc _dirname = os.path.dirname(__file__) with open(os.path.join(_dirname, 'mapping.json'), 'r') as file: SMARTAPI_MAPPING = json.load(file) def exists(): return Index(APIDoc.Index.name).exists() def setup(): """ Setup Elasticsearch Index. Primary index with dynamic template. Secondary index with static mappings. """ if not exists(): APIDoc.init() elastic = Elasticsearch() elastic.indices.put_mapping( index=APIDoc.Index.name, body=SMARTAPI_MAPPING ) def delete(): Index(APIDoc.Index.name).delete() def reset(): if exists(): delete() setup() def refresh(): index = Index(APIDoc.Index.name) index.refresh()
import json import os from elasticsearch import Elasticsearch from elasticsearch_dsl import Index from model import APIDoc _dirname = os.path.dirname(__file__) with open(os.path.join(_dirname, 'mapping.json'), 'r') as file: SMARTAPI_MAPPING = json.load(file) def setup(): """ Setup Elasticsearch Index. Primary index with dynamic template. Secondary index with static mappings. """ if not Index(APIDoc.Index.name).exists(): APIDoc.init() elastic = Elasticsearch() elastic.indices.put_mapping( index=APIDoc.Index.name, body=SMARTAPI_MAPPING ) def reset(): index = Index(APIDoc.Index.name) if index.exists(): index.delete() setup() def refresh(): index = Index(APIDoc.Index.name) index.refresh()
Fix database upgrade from a new database This fixes the problem where running "mistral-db-manage upgrade heads" on a new database result in error with workflow_input_hash index does not exist. Change-Id: I560b2b78d11cd3fd4ae9c8606e4336e87b22ef27 Closes-Bug: #1519929
# Copyright 2015 OpenStack Foundation. # # 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. """cron_trigger_constraints Revision ID: 003 Revises: 002 Create Date: 2015-05-25 13:09:50.190136 """ # revision identifiers, used by Alembic. revision = '003' down_revision = '002' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column( 'cron_triggers_v2', sa.Column('first_execution_time', sa.DateTime(), nullable=True) ) op.create_unique_constraint( None, 'cron_triggers_v2', [ 'workflow_input_hash', 'workflow_name', 'pattern', 'project_id', 'workflow_params_hash', 'remaining_executions', 'first_execution_time' ] )
# Copyright 2015 OpenStack Foundation. # # 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. """cron_trigger_constraints Revision ID: 003 Revises: 002 Create Date: 2015-05-25 13:09:50.190136 """ # revision identifiers, used by Alembic. revision = '003' down_revision = '002' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column( 'cron_triggers_v2', sa.Column('first_execution_time', sa.DateTime(), nullable=True) ) op.drop_index('workflow_input_hash', table_name='cron_triggers_v2') op.drop_index('workflow_input_hash_2', table_name='cron_triggers_v2') op.create_unique_constraint( None, 'cron_triggers_v2', [ 'workflow_input_hash', 'workflow_name', 'pattern', 'project_id', 'workflow_params_hash', 'remaining_executions', 'first_execution_time' ] )
Return SplFileInfo objects instead of strings
<?php namespace Becklyn\AssetsBundle\Finder; use Symfony\Component\Finder\Finder; /** * Finds all template files in a given directory */ class TemplateFinder { /** * @param string $directory * * @return \SplFileInfo[] */ public function findInDirectory (string $directory) : array { $result = []; $finder = new Finder(); $finder ->in($directory) ->files() ->name('*.html.twig') ->contains('/{%\s+?(javascripts|stylesheets) /i') ->followLinks() ->ignoreUnreadableDirs(); /** @var \SplFileInfo $file */ foreach ($finder as $file) { $result[] = $file; } return $result; } }
<?php namespace Becklyn\AssetsBundle\Finder; use Symfony\Component\Finder\Finder; /** * Finds all template files in a given directory */ class TemplateFinder { /** * @param string $directory * * @return string[] */ public function findInDirectory (string $directory) : array { $result = []; $finder = new Finder(); $finder ->in($directory) ->files() ->name('*.html.twig') ->contains('/{%\s+?(javascripts|stylesheets) /i') ->followLinks() ->ignoreUnreadableDirs(); /** @var \SplFileInfo $file */ foreach ($finder as $file) { $result[] = $file->getPathname(); } return $result; } }
Remove usage of remove_undocumented from core parallel_for. remove_undocumented is causing issues with our pip tests. remove_undocumented is not used anywhere else in core TF code and we have a new mechanism for annotating the public TF API.
# Copyright 2018 The TensorFlow 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. # ============================================================================== """Ops for pfor, for_loop, jacobian.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.ops.parallel_for import * # pylint: disable=wildcard-import from tensorflow.python.ops.parallel_for.control_flow_ops import for_loop from tensorflow.python.ops.parallel_for.control_flow_ops import pfor from tensorflow.python.ops.parallel_for.gradients import batch_jacobian from tensorflow.python.ops.parallel_for.gradients import jacobian
# Copyright 2018 The TensorFlow 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. # ============================================================================== """Ops for pfor, for_loop, jacobian.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.ops.parallel_for import * # pylint: disable=wildcard-import from tensorflow.python.ops.parallel_for.control_flow_ops import for_loop from tensorflow.python.ops.parallel_for.control_flow_ops import pfor from tensorflow.python.ops.parallel_for.gradients import batch_jacobian from tensorflow.python.ops.parallel_for.gradients import jacobian from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = [ 'pfor', 'for_loop', 'jacobian', 'batch_jacobian', ] remove_undocumented(__name__, _allowed_symbols)
Delete unused res in dispatch/then function
// this component is depreciated and is now in Newsletter module export default { name: 'MyNewsletter', data () { return { user: { isSubscribed: false } } }, methods: { unsubscribe () { this.$store.dispatch('mailchimp/unsubscribe', this.$store.state.user.current.email).then(() => { this.user.isSubscribed = false }).catch(err => this.$emit('unsubscription-error', err) ) }, subscribe () { this.$store.dispatch('mailchimp/subscribe', this.$store.state.user.current.email).then(() => { this.user.isSubscribed = true }).catch(err => this.$emit('subscription-error', err) ) }, updateNewsletter () { if (this.user.isSubscribed) { this.subscribe() } else { this.unsubscribe() } this.exitSection() } } }
// this component is depreciated and is now in Newsletter module export default { name: 'MyNewsletter', data () { return { user: { isSubscribed: false } } }, methods: { unsubscribe () { this.$store.dispatch('mailchimp/unsubscribe', this.$store.state.user.current.email).then(res => { this.user.isSubscribed = false }).catch(err => this.$emit('unsubscription-error', err) ) }, subscribe () { this.$store.dispatch('mailchimp/subscribe', this.$store.state.user.current.email).then(res => { this.user.isSubscribed = true }).catch(err => this.$emit('subscription-error', err) ) }, updateNewsletter () { if (this.user.isSubscribed) { this.subscribe() } else { this.unsubscribe() } this.exitSection() } } }
Order exhibition by end date
from django.db import models class Exhibition(models.Model): title = models.CharField( "Название", max_length=1024 ) begin = models.DateField( "Дата начала" ) end = models.DateField( "Дата окончания" ) showroom = models.CharField( "Выставочный зал", max_length=1024 ) showroom_url = models.CharField( "Ссылка", blank=True, null=True, max_length=255 ) image = models.ImageField( "Картинка", blank=True, null=True, max_length=500, upload_to="images/exhibitions/" ) class Meta: ordering = ['-end'] verbose_name = 'Выставка' verbose_name_plural = 'Выставки' def save(self): if self.showroom_url: if self.showroom_url[:4] != 'http': self.showroom_url = 'http://' + self.showroom_url super(Exhibition, self).save() def __str__(self): return (self.title)
from django.db import models class Exhibition(models.Model): title = models.CharField( "Название", max_length=1024 ) begin = models.DateField( "Дата начала" ) end = models.DateField( "Дата окончания" ) showroom = models.CharField( "Выставочный зал", max_length=1024 ) showroom_url = models.CharField( "Ссылка", blank=True, null=True, max_length=255 ) image = models.ImageField( "Картинка", blank=True, null=True, max_length=500, upload_to="images/exhibitions/" ) class Meta: ordering = ['-begin'] verbose_name = 'Выставка' verbose_name_plural = 'Выставки' def save(self): if self.showroom_url: if self.showroom_url[:4] != 'http': self.showroom_url = 'http://' + self.showroom_url super(Exhibition, self).save() def __str__(self): return (self.title)
Add Hybrid\Auth::is() to check if user has a given role Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Hybrid; /** * Auth class * * @package Hybrid * @category Auth * @author Laravel Hybrid Development Team */ use \Auth as Laravel_Auth, \Event; class Auth extends Laravel_Auth { /** * Cached user to roles relationship * * @var array */ protected static $user_roles = null; /** * Get the current user's roles of the application. * * If the user is a guest, empty array should be returned. * * @static * @access public * @return array */ public static function roles() { $user = static::user(); $roles = array(); $user_id = 0; // only search for roles when user is logged if ( ! is_null($user)) $user_id = $user->id; if (is_null(static::$user_roles[$user_id])) { static::$user_roles[$user_id] = Event::until('hybrid.auth.roles', array($user, $roles)); } return static::$user_roles[$user_id]; } /** * Determine if current user has the given role * * @static * @access public * @param string $role * @return boolean */ public static function is($role) { $roles = static::roles(); return in_array($role, $roles); } }
<?php namespace Hybrid; /** * Auth class * * @package Hybrid * @category Auth * @author Laravel Hybrid Development Team */ use \Auth as Laravel_Auth, \Event; class Auth extends Laravel_Auth { protected static $user_roles = null; /** * Get the current user's roles of the application. * * If the user is a guest, empty array should be returned. * * @static * @access public * @return array */ public static function roles() { $user = static::user(); $roles = array(); $user_id = 0; // only search for roles when user is logged if ( ! is_null($user)) $user_id = $user->id; if (is_null(static::$user_roles[$user_id])) { static::$user_roles[$user_id] = Event::until('hybrid.auth.roles', array($user, $roles)); } return static::$user_roles[$user_id]; } }
XWIKI-7161: Add support for classifier in Maven/Aether repository handler Set proper dependency id
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.repository.aether.internal; import org.sonatype.aether.graph.Dependency; import org.xwiki.extension.AbstractExtensionDependency; public class AetherExtensionDependency extends AbstractExtensionDependency { private Dependency aetherDependency; public AetherExtensionDependency(Dependency aetherDependency) { super(AetherUtils.createExtensionId(aetherDependency.getArtifact()).getId(), aetherDependency.getArtifact() .getVersion()); } public Dependency getAetherDependency() { return this.aetherDependency; } }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.repository.aether.internal; import org.sonatype.aether.graph.Dependency; import org.xwiki.extension.AbstractExtensionDependency; public class AetherExtensionDependency extends AbstractExtensionDependency { private Dependency aetherDependency; public AetherExtensionDependency(Dependency aetherDependency) { super(aetherDependency.getArtifact().getGroupId() + ':' + aetherDependency.getArtifact().getArtifactId(), aetherDependency.getArtifact().getVersion()); } public Dependency getAetherDependency() { return this.aetherDependency; } }
Make handlers expr case insensitive
package bot import ( "regexp" ) type Bot struct { adapter Adapter Handlers map[*regexp.Regexp]func(msg *Message) } func New(adapter Adapter) *Bot { return &Bot{ adapter, map[*regexp.Regexp]func(msg *Message){}, } } func (b *Bot) Handle(expr string, handler func(msg *Message)) { b.Handlers[regexp.MustCompile(`(?i)`+expr)] = handler } func (b *Bot) Listen() { for { msg := b.adapter.Listen() for re, handler := range b.Handlers { if re.MatchString(msg.Text) { handler(msg) break } } } } func (b *Bot) Reply(msg *Message, text string) { b.adapter.Reply(msg, text) }
package bot import ( "regexp" ) type Bot struct { adapter Adapter Handlers map[*regexp.Regexp]func(msg *Message) } func New(adapter Adapter) *Bot { return &Bot{ adapter, map[*regexp.Regexp]func(msg *Message){}, } } func (b *Bot) Handle(expr string, handler func(msg *Message)) { b.Handlers[regexp.MustCompile(expr)] = handler } func (b *Bot) Listen() { for { msg := b.adapter.Listen() for expr, handler := range b.Handlers { if expr.MatchString(msg.Text) { handler(msg) break } } } } func (b *Bot) Reply(msg *Message, text string) { b.adapter.Reply(msg, text) }
Disable tooltip for short messages
package org.bitbucket.mlopatkin.android.logviewer; import org.apache.commons.lang3.StringEscapeUtils; public class ToolTippedCellRenderer extends PriorityColoredCellRenderer { @Override protected void setValue(Object value) { this.setToolTipText(formatStringToWidth(value.toString())); super.setValue(value); } private static final int MAX_WIDTH = Configuration.ui.tooltipMaxWidth(); private static String formatStringToWidth(String src) { if (src.length() <= MAX_WIDTH) { return null; } StringBuilder result = new StringBuilder("<html>"); int pos = 0; while (pos + MAX_WIDTH < src.length()) { String substr = StringEscapeUtils.escapeXml(src.substring(pos, pos + MAX_WIDTH)); result.append(substr).append("<br>"); pos += MAX_WIDTH; } result.append(StringEscapeUtils.escapeXml(src.substring(pos))); result.append("</html>"); return result.toString(); } }
package org.bitbucket.mlopatkin.android.logviewer; import org.apache.commons.lang3.StringEscapeUtils; public class ToolTippedCellRenderer extends PriorityColoredCellRenderer { @Override protected void setValue(Object value) { this.setToolTipText(formatStringToWidth(value.toString())); super.setValue(value); } private static final int MAX_WIDTH = Configuration.ui.tooltipMaxWidth(); private static String formatStringToWidth(String src) { if (src.length() <= MAX_WIDTH) { return src; } StringBuilder result = new StringBuilder("<html>"); int pos = 0; while (pos + MAX_WIDTH < src.length()) { String substr = StringEscapeUtils.escapeXml(src.substring(pos, pos + MAX_WIDTH)); result.append(substr).append("<br>"); pos += MAX_WIDTH; } result.append(StringEscapeUtils.escapeXml(src.substring(pos))); result.append("</html>"); return result.toString(); } }
Switch license from MIT to AGPL in plugin file
<?php /* Plugin Name: Castlegate IT WP Media File Sort Plugin URI: http://github.com/castlegateit/cgit-wp-media-file-sort Description: Allow media library to be sorted by file name. Version: 1.1 Author: Castlegate IT Author URI: http://www.castlegateit.co.uk/ License: AGPL */ if (!defined('ABSPATH')) { wp_die('Access denied'); } /** Add column to media library */ add_filter('manage_media_columns', function ($columns) { $columns['file_name'] = 'File name'; return $columns; }); /** Display file names in new media library column */ add_action('manage_media_custom_column', function ($name, $id) { $meta = wp_get_attachment_metadata($id); echo basename($meta['file']); }, 10, 2); /** Enable columns to be sorted by file name */ add_filter('manage_upload_sortable_columns', function ($columns) { $columns['file_name'] = 'name'; return $columns; });
<?php /* Plugin Name: Castlegate IT WP Media File Sort Plugin URI: http://github.com/castlegateit/cgit-wp-media-file-sort Description: Allow media library to be sorted by file name. Version: 1.1 Author: Castlegate IT Author URI: http://www.castlegateit.co.uk/ License: MIT */ if (!defined('ABSPATH')) { wp_die('Access denied'); } /** Add column to media library */ add_filter('manage_media_columns', function ($columns) { $columns['file_name'] = 'File name'; return $columns; }); /** Display file names in new media library column */ add_action('manage_media_custom_column', function ($name, $id) { $meta = wp_get_attachment_metadata($id); echo basename($meta['file']); }, 10, 2); /** Enable columns to be sorted by file name */ add_filter('manage_upload_sortable_columns', function ($columns) { $columns['file_name'] = 'name'; return $columns; });
feat(service): Add a new plugin type
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.plugin.api; /** * @author David BRASSELY (brasseld at gmail.com) */ public enum PluginType { POLICY, REPORTER, SERVICE; public static PluginType from(String sType) { for(PluginType pluginType : values()) { if (pluginType.name().equalsIgnoreCase(sType)) { return pluginType; } } throw new IllegalArgumentException("Invalid PolicyType: " + sType); } }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.plugin.api; /** * @author David BRASSELY (brasseld at gmail.com) */ public enum PluginType { POLICY, REPORTER; public static PluginType from(String sType) { for(PluginType pluginType : values()) { if (pluginType.name().equalsIgnoreCase(sType)) { return pluginType; } } throw new IllegalArgumentException("Invalid PolicyType: " + sType); } }
Add missing displayed event trigger in embed manager
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. var manager = require('./manager-base'); var EmbedManager = exports.EmbedManager = function() { manager.ManagerBase.call(this); }; EmbedManager.prototype = Object.create(manager.ManagerBase.prototype); EmbedManager.prototype.display_widget_state = function(models, el) { return this.set_state(models, { el: el, displayOnce: true }); }; EmbedManager.prototype.display_view = function(msg, view, options) { return Promise.resolve(view).then(function(view) { options.el.appendChild(view.el); view.trigger('displayed'); view.on('remove', function() { console.log('View removed', view); }); return view; }); }; EmbedManager.prototype._get_comm_info = function() { return Promise.resolve({}); }; EmbedManager.prototype.require_error = function(success_callback) { /** * Takes a requirejs success handler and returns a requirejs error handler * that attempts loading the module from npmcdn. */ return function(err) { var failedId = err.requireModules && err.requireModules[0]; if (failedId) { window.require(['https://npmcdn.com/' + failedId + '/dist/index.js'], success_callback); } else { throw err; } }; };
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. var manager = require('./manager-base'); var EmbedManager = exports.EmbedManager = function() { manager.ManagerBase.call(this); }; EmbedManager.prototype = Object.create(manager.ManagerBase.prototype); EmbedManager.prototype.display_widget_state = function(models, el) { return this.set_state(models, { el: el, displayOnce: true }); }; EmbedManager.prototype.display_view = function(msg, view, options) { return Promise.resolve(view).then(function(view) { options.el.appendChild(view.el); view.on('remove', function() { console.log('View removed', view); }); return view; }); }; EmbedManager.prototype._get_comm_info = function() { return Promise.resolve({}); }; EmbedManager.prototype.require_error = function(success_callback) { /** * Takes a requirejs success handler and returns a requirejs error handler * that attempts loading the module from npmcdn. */ return function(err) { var failedId = err.requireModules && err.requireModules[0]; if (failedId) { window.require(['https://npmcdn.com/' + failedId + '/dist/index.js'], success_callback); } else { throw err; } }; };
Patch from bus part 2
// @flow import type { ChooView } from "./app"; import type { ChooMiddleware } from "./app"; const app = require("choo")(); const html = require("choo/html"); const eventNames = require("./eventNames"); const defaultView = require("./views/embed/default"); const embedView = require("./views/embed/home"); const errorReducer = require("./reducers/error"); const chatReducer = require("./reducers/chat"); const apiReducer = require("./reducers/embed/api"); app.use(eventNames); app.use(apiReducer); app.use(errorReducer()); app.use(chatReducer); app.route("/videochat-client/embed.html/group/:groupId", embedView); app.route("/embed.html/group/:groupId", embedView); app.route("/group/:groupId", embedView); app.route("*", defaultView); if (typeof document === "undefined" || !document.body) { throw new Error("document.body is not here"); } document.body.appendChild(app.start());
// @flow import type { ChooView } from "./app"; import type { ChooMiddleware } from "./app"; const app = require("choo")(); const html = require("choo/html"); const eventNames = require("./eventNames"); const defaultView = require("./views/embed/default"); const embedView = require("./views/embed/home"); const errorReducer = require("./reducers/error"); const chatReducer = require("./reducers/chat"); const apiReducer = require("./reducers/embed/api"); app.use(eventNames); app.use(apiReducer); app.use(errorReducer()); app.use(chatReducer); app.route("/videochat-client/embed.html/group/:groupId", embedView); app.route("/group/:groupId", embedView); app.route("*", defaultView); if (typeof document === "undefined" || !document.body) { throw new Error("document.body is not here"); } document.body.appendChild(app.start());
Verify will now output all mismatches
import path from 'path'; import objectPath from 'object-path'; import Q from 'q'; import hashFile from './hashFile'; export default function verifyFiles(cwd, script, root) { const deferred = Q.defer(); const top = root ? objectPath.get(script, root) : script; const hashes = Object.keys(top.files); const errors = []; const next = () => { if (hashes.length === 0) { if (errors.length > 0) { deferred.reject(new Error(errors.map(err => err.message).join('\n'))); } else { deferred.resolve(); } return; } const hash = hashes.shift(); const file = top.files[hash]; hashFile(cwd, path.resolve(cwd, file), top.algorithm) .then(h => { if (hash !== h) { errors.push(new Error('Mismatch: ' + file)); } }) .catch(err => errors.push(err)) .finally(next); }; next(); return deferred.promise; }
import path from 'path'; import objectPath from 'object-path'; import Q from 'q'; import hashFile from './hashFile'; export default function verifyFiles(cwd, script, root) { const deferred = Q.defer(); const top = root ? objectPath.get(script, root) : script; const hashes = Object.keys(top.files); const next = () => { if (hashes.length === 0) { deferred.resolve(); return; } const hash = hashes.shift(); const file = top.files[hash]; hashFile(cwd, path.resolve(cwd, file), top.algorithm) .then(h => { if (hash !== h) { deferred.reject(new Error('Mismatch: ' + file)); } next(); }) .catch(deferred.reject); }; next(); return deferred.promise; }
Add get_messages, get_thread, and send_message url strings
module.exports = { URLS: { login: 'https://www.okcupid.com/login', rate: 'http://www.okcupid.com/quickmatch', visit_user: 'http://www.okcupid.com/profile/{username}', user_profile: 'http://www.okcupid.com/profile/{username}?okc_api=1', user_questions: 'http://www.okcupid.com/profile/{username}/questions?okc_api=1&low={low}', get_visitors: 'http://www.okcupid.com/visitors?okc_api=1', quickmatch: 'http://www.okcupid.com/quickmatch?okc_api=1', get_messages: 'https://www.okcupid.com/messages?okc_api=1', get_thread: 'https://www.okcupid.com/messages?okc_api=1&readmsg=true&threadid={thread_id}', // OAuth API like: 'https://www.okcupid.com/1/apitun/profile/{userid}/like', unlike: 'https://www.okcupid.com/1/apitun/profile/{userid}/unlike', send_message: 'https://www.okcupid.com/1/apitun/messages/send', } }
module.exports = { URLS: { login: 'https://www.okcupid.com/login', rate: 'http://www.okcupid.com/quickmatch', visit_user: 'http://www.okcupid.com/profile/{username}', user_profile: 'http://www.okcupid.com/profile/{username}?okc_api=1', user_questions: 'http://www.okcupid.com/profile/{username}/questions?okc_api=1&low={low}', get_visitors: 'http://www.okcupid.com/visitors?okc_api=1', quickmatch: 'http://www.okcupid.com/quickmatch?okc_api=1', // OAuth API like: 'https://www.okcupid.com/1/apitun/profile/{userid}/like', unlike: 'https://www.okcupid.com/1/apitun/profile/{userid}/unlike', } }
Edit a wording of breadcrums. :)
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\CttStaticdataDocsources */ $this->title = Yii::t('app/ctt_staticdata_docsource', 'Update Ctt Staticdata Docsources') . ': ' . $model->name; $this->params['breadcrumbs'][] = ['label' => Yii::t('app/ctt_staticdata_docsource', 'Ctt Staticdata Docsources'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('app/ctt_staticdata_docsource', 'Ctt Staticdata Countrys(Language List)'), 'url' => ['lang-list', 'id' => $model->id]]; $this->params['breadcrumbs'][] = Yii::t('app/frontend', 'Update'); ?> <div class="ctt-staticdata-docsources-update"> <?= $this->render('_form', [ 'title' => Html::encode($this->title), 'model' => $model, 'mode' => 'edit', ]) ?> </div>
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\CttStaticdataDocsources */ $this->title = Yii::t('app/ctt_staticdata_docsource', 'Update Ctt Staticdata Docsources') . ' ' . $model->name; $this->params['breadcrumbs'][] = ['label' => Yii::t('app/ctt_staticdata_docsource', 'Ctt Staticdata Docsources'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('app/ctt_staticdata_docsource', 'Ctt Staticdata Countrys(Language List)'), 'url' => ['lang-list', 'id' => $model->id]]; $this->params['breadcrumbs'][] = Yii::t('app/frontend', 'Update'); ?> <div class="ctt-staticdata-docsources-update"> <?= $this->render('_form', [ 'title' => Html::encode($this->title), 'model' => $model, 'mode' => 'edit', ]) ?> </div>
Add TokenMismatchException to dontReport array. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Testbench\Exceptions; use Exception; use Illuminate\Session\TokenMismatchException; use Illuminate\Validation\ValidationException; use Illuminate\Foundation\Testing\HttpException; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class ApplicationHandler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ AuthorizationException::class, HttpException::class, ModelNotFoundException::class, TokenMismatchException::class, ValidationException::class, ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * * @return void */ public function report(Exception $e) { parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { return parent::render($request, $e); } }
<?php namespace Orchestra\Testbench\Exceptions; use Exception; use Illuminate\Validation\ValidationException; use Illuminate\Foundation\Testing\HttpException; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class ApplicationHandler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ AuthorizationException::class, HttpException::class, ModelNotFoundException::class, ValidationException::class, ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * * @return void */ public function report(Exception $e) { parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { return parent::render($request, $e); } }
Fix bug with missing config value
<?php /** * This file is part of the P2SecurityBundle. * * (c) 2013 Philipp Boes <mostgreedy@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace P2\Bundle\SecurityBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * Class Configuration * @package P2\Bundle\SecurityBundle\DependencyInjection */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('p2_security'); $rootNode ->children() ->scalarNode('document')->cannotBeEmpty()->end() ->scalarNode('manager')->cannotBeEmpty()->end() ->scalarNode('encoder')->defaultValue('sha256')->end() ->end(); return $treeBuilder; } }
<?php /** * This file is part of the P2SecurityBundle. * * (c) 2013 Philipp Boes <mostgreedy@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace P2\Bundle\SecurityBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * Class Configuration * @package P2\Bundle\SecurityBundle\DependencyInjection */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('p2_security'); $rootNode ->children() ->scalarNode('manager')->cannotBeEmpty()->end() ->scalarNode('encoder')->defaultValue('sha256')->end() ->end(); return $treeBuilder; } }
Set scraping interval vased on NODE_ENV
// @flow const Rx = require('rxjs/Rx') const axios = require('axios') const _ = require('lodash') const event = require('../event') const INTERVAL = process.env.NODE_ENV == "production" ? 1000 * 60 * 60 : 1000 * 1 // 1 hour or 1 second const Source$ = Rx.Observable .interval(INTERVAL) .exhaustMap(() => Promise.all(['tt4179452', 'tt3530232', 'tt2575988'].map((id: string) => axios('https://tv-v2.api-fetch.website/show/' + id)))) .map(resps => resps.map(resp => resp.data)) .map(resps => resps.map(show => show.episodes.map(episode => Object.assign({}, episode, {title: show.title})))) .map(showEpisodes => _.flatten(showEpisodes)) .pairwise() .map(([a, b]) => _.differenceBy(b, a, 'tvdb_id')) .flatMap(episodes => episodes) .map(event.bind({}, "popcorn-time")) .publishReplay() .refCount() module.exports = Source$
// @flow const Rx = require('rxjs/Rx') const axios = require('axios') const _ = require('lodash') const event = require('../event') // const INTERVAL: number = 1000 * 60 * 60 * 1// 1 hour TODO: Move to config // const INTERVAL: number = 1000 * 60 * 2 // 2 minutes const INTERVAL: number = 1000 * 1 // 3 seconds const Source$ = Rx.Observable .interval(INTERVAL) .exhaustMap(() => Promise.all(['tt4179452', 'tt3530232', 'tt2575988'].map((id: string) => axios('https://tv-v2.api-fetch.website/show/' + id)))) .map(resps => resps.map(resp => resp.data)) .map(resps => resps.map(show => show.episodes.map(episode => Object.assign({}, episode, {title: show.title})))) .map(showEpisodes => _.flatten(showEpisodes)) .pairwise() .map(([a, b]) => _.differenceBy(b, a, 'tvdb_id')) .flatMap(episodes => episodes) .map(event.bind({}, "popcorn-time")) .publishReplay() .refCount() module.exports = Source$
Use Icecast-KH for all demo purposes.
<?php namespace App\Entity\Fixture; use App\Radio\Adapters; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use App\Entity; class Station extends AbstractFixture { public function load(ObjectManager $em) { $station = new Entity\Station; $station->setName('AzuraTest Radio'); $station->setDescription('A test radio station.'); $station->setFrontendType(Adapters::FRONTEND_ICECAST); $station->setBackendType(Adapters::BACKEND_LIQUIDSOAP); $station->setRadioBaseDir('/var/azuracast/stations/azuratest_radio'); $em->persist($station); $em->flush(); $this->addReference('station', $station); } }
<?php namespace App\Entity\Fixture; use App\Radio\Adapters; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use App\Entity; class Station extends AbstractFixture { public function load(ObjectManager $em) { $station = new Entity\Station; $station->setName('AzuraTest Radio'); $station->setDescription('A test radio station.'); $station->setFrontendType(Adapters::FRONTEND_SHOUTCAST); $station->setBackendType(Adapters::BACKEND_LIQUIDSOAP); $station->setRadioBaseDir('/var/azuracast/stations/azuratest_radio'); $em->persist($station); $em->flush(); $this->addReference('station', $station); } }
Fix typo in variable name
<?php include('vendor/autoload.php'); function get_content($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $string = curl_exec($ch); curl_close($ch); if (empty($string)) { return FALSE; } return $string; } if (!empty($_SERVER['HTTPS'])) { $api_url = 'https'; } else { $api_url = 'http'; } $api_url .= '://'; $api_url .= $_SERVER['SERVER_NAME']; define('API_URL', $api_url);
<?php include('vendor/autoload.php'); function get_content($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $string = curl_exec($ch); curl_close($ch); if (empty($string)) { return FALSE; } return $string; } if (!empty($SERVER['HTTPS'])) { $api_url = 'https'; } else { $api_url = 'http'; } $api_url .= '://'; $api_url .= $_SERVER['SERVER_NAME']; define('API_URL', $api_url);
Add a boards registering signal to allow the board manager to gather connected boards
__author__ = 'Will Hart' from blinker import signal # fired when a new web client device connects web_client_connected = signal('client_connected') # fired when a web client disconnects web_client_disconnected = signal('client_disconnected') # fired when a new TCP client device connects tcp_client_connected = signal('tcp_client_connected') # fired when a TCP client disconnects tcp_client_disconnected = signal('tcp_client_disconnected') # fired when a server TCP connection is established logger_connected = signal('logger_connected') # fired when a server TCP connection is closed logger_disconnected = signal('logger_disconnected') # fired when the expansion board receives a data row for processing # allows pre-processing of data data_line_received = signal('data_line_received') # fired when a variable is ready for entry into the database # allows post processing of data data_variable_decoded = signal('data_variable_decoded') # fired when a board has finished processing a data line data_line_processed = signal('data_line_processed') # called when an expansion board is registered expansion_board_registered = signal('expansion_board_registered') # called when expansion boards should be registered with the board manager registering_boards = signal('registering_boards')
__author__ = 'Will Hart' from blinker import signal # fired when a new web client device connects web_client_connected = signal('client_connected') # fired when a web client disconnects web_client_disconnected = signal('client_disconnected') # fired when a new TCP client device connects tcp_client_connected = signal('tcp_client_connected') # fired when a TCP client disconnects tcp_client_disconnected = signal('tcp_client_disconnected') # fired when a server TCP connection is established logger_connected = signal('logger_connected') # fired when a server TCP connection is closed logger_disconnected = signal('logger_disconnected') # fired when the client receives a data row for processing data_line_received = signal('data_line_received') # fired when a variable is ready for entry into the database data_variable_decoded = signal('data_variable_decoded') # fired when a board has finished processing a data line data_line_processed = signal('data_line_processed') # called when an expansion board is registered expansion_board_registered = signal('expansion_board_registered')
XCOMMONS-9: Move from Commons Logging/Log4J to SLF4J/Logback ** Fixed javadoc
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.component.logging; import junit.framework.TestCase; /** * Unit tests for {@link AbstractLogEnabled}. * * @version $Id$ * @since 1.8RC3 * @deprecated starting with 3.1M2 use {@link javax.inject.Inject} annotation to get injected a SLF4J Logger instead */ @Deprecated public class LoggerTest extends TestCase { public void testDefaultVoidLogger() { AbstractLogEnabled component = new AbstractLogEnabled() {}; assertEquals(VoidLogger.class.getName(), component.getLogger().getClass().getName()); } }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.component.logging; import junit.framework.TestCase; /** * Unit tests for {@link AbstractLogEnabled}. * * @version $Id$ * @since 1.8RC3 * @deprecated starting with 3.1M2 use {@link javax.inject.Inject} annotation to get injected a * {@link org.xwiki.logging.Logger} instead. */ @Deprecated public class LoggerTest extends TestCase { public void testDefaultVoidLogger() { AbstractLogEnabled component = new AbstractLogEnabled() {}; assertEquals(VoidLogger.class.getName(), component.getLogger().getClass().getName()); } }
Fix fragment instance not correctly assigned
package com.nkming.packageinfo; import android.app.ActivityManager; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.nkming.utils.graphic.BitmapCache; public class MainActivity extends ActionBarActivity implements SearchDialog.SearchDialogListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int heapMb = ((ActivityManager)getSystemService(ACTIVITY_SERVICE)) .getMemoryClass(); BitmapCache.init(heapMb * 1024 * 1024 / 4); setContentView(R.layout.activity_main); if (savedInstanceState == null) { mFrag = new MainFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.container, mFrag) .commit(); } else { mFrag = (MainFragment)getSupportFragmentManager().findFragmentById( R.id.container); } getSupportActionBar().setElevation(getResources().getDimension( R.dimen.toolbar_z)); } @Override public void onSearchRequest(AppFilter req) { mFrag.onSearchRequest(req); } private MainFragment mFrag; }
package com.nkming.packageinfo; import android.app.ActivityManager; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.nkming.utils.graphic.BitmapCache; public class MainActivity extends ActionBarActivity implements SearchDialog.SearchDialogListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int heapMb = ((ActivityManager)getSystemService(ACTIVITY_SERVICE)) .getMemoryClass(); BitmapCache.init(heapMb * 1024 * 1024 / 4); setContentView(R.layout.activity_main); if (savedInstanceState == null) { mFrag = new MainFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.container, mFrag) .commit(); } getSupportActionBar().setElevation(getResources().getDimension( R.dimen.toolbar_z)); } @Override public void onSearchRequest(AppFilter req) { mFrag.onSearchRequest(req); } private MainFragment mFrag; }
Replace reference to src/shared/ with shared/
import React from 'react' import PropTypes from 'prop-types' import {connect} from 'react-redux' import Notification from 'shared/components/Notification' const Notifications = ({notifications, inPresentationMode}) => <div className={`${inPresentationMode ? 'notification-center__presentation-mode' : 'notification-center'}`} > {notifications.map(n => <Notification key={n.id} notification={n} />)} </div> const {arrayOf, bool, number, shape, string} = PropTypes Notifications.propTypes = { notifications: arrayOf( shape({ id: string.isRequired, type: string.isRequired, message: string.isRequired, duration: number.isRequired, icon: string, }) ), inPresentationMode: bool, } const mapStateToProps = ({ notifications, app: {ephemeral: {inPresentationMode}}, }) => ({ notifications, inPresentationMode, }) export default connect(mapStateToProps, null)(Notifications)
import React from 'react' import PropTypes from 'prop-types' import {connect} from 'react-redux' import Notification from 'src/shared/components/Notification' const Notifications = ({notifications, inPresentationMode}) => <div className={`${inPresentationMode ? 'notification-center__presentation-mode' : 'notification-center'}`} > {notifications.map(n => <Notification key={n.id} notification={n} />)} </div> const {arrayOf, bool, number, shape, string} = PropTypes Notifications.propTypes = { notifications: arrayOf( shape({ id: string.isRequired, type: string.isRequired, message: string.isRequired, duration: number.isRequired, icon: string, }) ), inPresentationMode: bool, } const mapStateToProps = ({ notifications, app: {ephemeral: {inPresentationMode}}, }) => ({ notifications, inPresentationMode, }) export default connect(mapStateToProps, null)(Notifications)
Use AGG backend for generic visualization to avoid display dependency.
import numpy as np import matplotlib as mpl mpl.use('agg') import neurokernel.LPU.utils.visualizer as vis import networkx as nx nx.readwrite.gexf.GEXF.convert_bool = {'false':False, 'False':False, 'true':True, 'True':True} G = nx.read_gexf('./data/generic_lpu.gexf.gz') neu_out = [k for k,n in G.node.items() if n['name'][:3] == 'out'] V = vis.visualizer() V.add_LPU('./data/generic_input.h5', LPU='Sensory') V.add_plot({'type':'waveform','ids':[[0]]}, 'input_Sensory') V.add_LPU('generic_output_spike.h5', './data/generic_lpu.gexf.gz','Generic LPU') V.add_plot({'type':'raster','ids':{0:range(48,83)}, 'yticks':range(1,1+len(neu_out)),'yticklabels':range(len(neu_out))}, 'Generic LPU','Output') V._update_interval = 50 V.rows = 2 V.cols = 1 V.fontsize = 18 V.out_filename = 'output_generic.avi' V.codec = 'libtheora' V.dt = 0.0001 V.xlim = [0,1.0] V.run()
import numpy as np import neurokernel.LPU.utils.visualizer as vis import networkx as nx nx.readwrite.gexf.GEXF.convert_bool = {'false':False, 'False':False, 'true':True, 'True':True} G = nx.read_gexf('./data/generic_lpu.gexf.gz') neu_out = [k for k,n in G.node.items() if n['name'][:3] == 'out'] V = vis.visualizer() V.add_LPU('./data/generic_input.h5', LPU='Sensory') V.add_plot({'type':'waveform','ids':[[0]]}, 'input_Sensory') V.add_LPU('generic_output_spike.h5', './data/generic_lpu.gexf.gz','Generic LPU') V.add_plot({'type':'raster','ids':{0:range(48,83)}, 'yticks':range(1,1+len(neu_out)),'yticklabels':range(len(neu_out))}, 'Generic LPU','Output') V._update_interval = 50 V.rows = 2 V.cols = 1 V.fontsize = 18 V.out_filename = 'output_generic.avi' V.codec = 'libtheora' V.dt = 0.0001 V.xlim = [0,1.0] V.run()
Remove methods implementation that must be do in subclasses.
package org.codehaus.modello.metadata; /* * LICENSE */ import org.codehaus.modello.AbstractLogEnabled; import org.codehaus.modello.Model; import org.codehaus.modello.ModelClass; import org.codehaus.modello.ModelField; import org.codehaus.modello.ModelloException; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> * @version $Id$ */ public abstract class AbstractMetaDataPlugin extends AbstractLogEnabled implements MetaDataPlugin { public Map getModelMap( Model model, MetaData metaData ) throws ModelloException { return null; } public Map getClassMap( ModelClass clazz, MetaData metaData ) throws ModelloException { return null; } public Map getFieldMap( ModelField field, MetaData metaData ) throws ModelloException { return null; } }
package org.codehaus.modello.metadata; /* * LICENSE */ import org.codehaus.modello.AbstractLogEnabled; import org.codehaus.modello.Model; import org.codehaus.modello.ModelClass; import org.codehaus.modello.ModelField; import org.codehaus.modello.ModelloException; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> * @version $Id$ */ public abstract class AbstractMetaDataPlugin extends AbstractLogEnabled implements MetaDataPlugin { public MetaData getModelMetaData( Model model ) { return null; } public MetaData getClassMetaData( ModelClass clazz ) { return null; } public MetaData getFieldMetaData( ModelField field ) { return null; } public Map getModelMap( Model model, MetaData metaData ) throws ModelloException { return null; } public Map getClassMap( ModelClass clazz, MetaData metaData ) throws ModelloException { return null; } public Map getFieldMap( ModelField field, MetaData metaData ) throws ModelloException { return null; } }
Improve the uniqueness of Currency.is_default
from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=1) factor = models.DecimalField(_('factor'), max_digits=10, decimal_places=4, help_text=_('Specifies the difference of the currency to default one.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('The currency will be available.')) is_default = models.BooleanField(_('default'), default=False, help_text=_('Make this the default currency.')) class Meta: verbose_name = _('currency') verbose_name_plural = _('currencies') def __unicode__(self): return self.code def save(self, **kwargs): # Make sure the default currency is unique if self.is_default: Currency.objects.filter(is_default=True).update(is_default=False) super(Currency, self).save(**kwargs)
from django.db import models from django.utils.translation import gettext_lazy as _ class Currency(models.Model): code = models.CharField(_('code'), max_length=3) name = models.CharField(_('name'), max_length=35) symbol = models.CharField(_('symbol'), max_length=1) factor = models.DecimalField(_('factor'), max_digits=10, decimal_places=4, help_text=_('Specifies the difference of the currency to default one.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('The currency will be available.')) is_default = models.BooleanField(_('default'), default=False, help_text=_('Make this the default currency.')) class Meta: verbose_name = _('currency') verbose_name_plural = _('currencies') def __unicode__(self): return self.code def save(self, **kwargs): if self.is_default: try: default_currency = Currency.objects.get(is_default=True) except DoesNotExist: pass else: default_currency.is_default = False default_currency.save() super(Currency, self).save(**kwargs)
Update SQL query with "and communication is null"
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Akretion (http://www.akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## def migrate(cr, version): cr.execute( "UPDATE payment_line SET communication = communication2, " "communication2 = null " "FROM payment_order " "WHERE payment_line.order_id = payment_order.id " "AND payment_order.state in ('draft', 'open') " "AND payment_line.state = 'normal' " "AND communication is null" "AND communication2 is not null")
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Akretion (http://www.akretion.com/) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## def migrate(cr, version): cr.execute( "UPDATE payment_line SET communication = communication2, " "communication2 = null " "FROM payment_order " "WHERE payment_line.order_id = payment_order.id " "AND payment_order.state in ('draft', 'open') " "AND payment_line.state = 'normal' " "AND communication2 is not null")
Use different usernames for each test. by: Glenn, Giles
# Copyright (c) 2017 PythonAnywhere LLP. # All Rights Reserved # from urlparse import urljoin from mock import Mock from resolver_test import ResolverTestMixins import django from django.conf import settings from django.contrib.auth.models import AnonymousUser, User from django.http import HttpRequest class ResolverDjangoTestCase(django.test.TestCase, ResolverTestMixins): maxDiff = None usernumber = 0 class ResolverViewTestCase(ResolverDjangoTestCase): def setUp(self): global usernumber self.user = User.objects.create(username='cherie{}'.format(usernumber)) usernumber += 1 self.request = HttpRequest() self.request.session = Mock() self.request.user = self.user self.client.force_login(self.user) def assert_login_required(self, view_to_call): self.owner = self.request.user = AnonymousUser() self.request.get_full_path = lambda: "my_path" self.request.build_absolute_uri = lambda: "my_path" response = view_to_call() self.assertEquals(response.status_code, 302) self.assertEquals( response['Location'], urljoin(settings.LOGIN_URL, '?next=my_path') )
# Copyright (c) 2011 Resolver Systems Ltd. # All Rights Reserved # from urlparse import urljoin from mock import Mock from resolver_test import ResolverTestMixins import django from django.conf import settings from django.contrib.auth.models import AnonymousUser, User from django.http import HttpRequest class ResolverDjangoTestCase(django.test.TestCase, ResolverTestMixins): maxDiff = None class ResolverViewTestCase(ResolverDjangoTestCase): def setUp(self): self.user = User(username='cherie') self.user.save() self.request = HttpRequest() self.request.session = Mock() self.request.user = self.user self.client.force_login(self.user) def assert_login_required(self, view_to_call): self.owner = self.request.user = AnonymousUser() self.request.get_full_path = lambda: "my_path" self.request.build_absolute_uri = lambda: "my_path" response = view_to_call() self.assertEquals(response.status_code, 302) self.assertEquals( response['Location'], urljoin(settings.LOGIN_URL, '?next=my_path') )
Fix mock results are not in json format
import os from unittest.mock import patch from pytest import fixture with patch.dict(os.environ, AWSCOGNITO_DOMAIN='jupyterhub-test.auth.us-west-1.amazoncognito.com'): from ..awscognito import AWSCognitoAuthenticator, AWSCOGNITO_DOMAIN from .mocks import setup_oauth_mock def user_model(username): """Return a user model""" return { 'username': username, 'scope': 'basic', } def Authenticator(): return AWSCognitoAuthenticator() @fixture def awscognito_client(client): setup_oauth_mock(client, host=AWSCOGNITO_DOMAIN, access_token_path='/oauth2/token', user_path='/oauth2/userInfo' ) return client async def test_awscognito(awscognito_client): authenticator = Authenticator() handler = awscognito_client.handler_for_user(user_model('foo')) user_info = await authenticator.authenticate(handler) assert sorted(user_info) == ['auth_state', 'name'] name = user_info['name'] assert name == 'foo' auth_state = user_info['auth_state'] assert 'access_token' in auth_state assert 'awscognito_user' in auth_state
import os from unittest.mock import patch from pytest import fixture with patch.dict(os.environ, AWSCOGNITO_DOMAIN='jupyterhub-test.auth.us-west-1.amazoncognito.com'): from ..awscognito import AWSCognitoAuthenticator, AWSCOGNITO_DOMAIN from .mocks import setup_oauth_mock def user_model(username): """Return a user model""" return { 'username': username, 'scope': 'basic', } def Authenticator(): return AWSCognitoAuthenticator() @fixture def awscognito_client(client): setup_oauth_mock(client, host=AWSCOGNITO_DOMAIN, access_token_path='/oauth2/token', user_path='/oauth2/userInfo', token_request_style='json', ) return client async def test_awscognito(awscognito_client): authenticator = Authenticator() handler = awscognito_client.handler_for_user(user_model('foo')) user_info = await authenticator.authenticate(handler) assert sorted(user_info) == ['auth_state', 'name'] name = user_info['name'] assert name == 'foo' auth_state = user_info['auth_state'] assert 'access_token' in auth_state assert 'awscognito_user' in auth_state
Append instead of truncating log file
#! /usr/bin/env python # logger.py """Log the serial output from the Arduino to a text file. """ import sys import serial from datetime import datetime def log_serial(filename, device='/dev/ttyACM0', baud=9600): ser = serial.Serial(device, baud) outfile = open(filename, 'a') try: while True: line = ser.readline() now = datetime.now() print("%s, %s" % (now, line)) outfile.write("%s, %s" % (now, line)) except KeyboardInterrupt: print("Quitting!") outfile.close() if __name__ == '__main__': if len(sys.argv) < 2: print("Usage: logger.py <filename>") filename = sys.argv[1] log_serial(filename)
#! /usr/bin/env python # logger.py """Log the serial output from the Arduino to a text file. """ import sys import serial from datetime import datetime def log_serial(filename, device='/dev/ttyACM0', baud=9600): ser = serial.Serial(device, baud) outfile = open(filename, 'w') try: while True: line = ser.readline() now = datetime.now() print("%s, %s" % (now, line)) outfile.write("%s, %s" % (now, line)) except KeyboardInterrupt: print("Quitting!") outfile.close() if __name__ == '__main__': if len(sys.argv) < 2: print("Usage: logger.py <filename>") filename = sys.argv[1] log_serial(filename)
Fix world size and camera follow.
import Phaser from 'phaser' import Player from '../sprites/Player' import Curve from '../plugins/Curve' export default class extends Phaser.State { create () { this.game.world.enableBody = true this.game.physics.startSystem(Phaser.Physics.ARCADE) this.game.plugins.add(Curve, [50, 0, 0, 0, 50]) this.map = this.game.add.tilemap('earth_travel') this.map.addTilesetImage('lofi_environment_4x', 'tiles') // Add both the background and ground layers. We won't be doing anything // with the GroundLayer though this.backgroundLayer = this.map.createLayer('backgroundlayer') this.backgroundLayer.resizeWorld() // Add the sprite to the game and enable arcade physics on it var playerSpawnX = this.game.world.centerX / 2; this.player = new Player(this.game, playerSpawnX, this.game.world.centerY) this.world.add(this.player) // Make the camera follow the sprite this.game.camera.follow(this.player) } update () { if (this.player.x > this.world.width) { this.state.start('Fight') } } }
import Phaser from 'phaser' import Player from '../sprites/Player' import Curve from '../plugins/Curve' export default class extends Phaser.State { create () { this.game.world.enableBody = true this.game.physics.startSystem(Phaser.Physics.ARCADE) this.game.plugins.add(Curve, [50, 0, 0, 0, 50]) this.map = this.game.add.tilemap('earth_travel') this.map.addTilesetImage('lofi_environment_4x', 'tiles') // Add both the background and ground layers. We won't be doing anything // with the GroundLayer though this.backgroundLayer = this.map.createLayer('backgroundlayer') // Add the sprite to the game and enable arcade physics on it var playerSpawnX = this.game.world.centerX / 2; this.player = new Player(this.game, playerSpawnX, this.game.world.centerY) this.world.add(this.player) // Make the camera follow the sprite this.game.camera.follow(this.sprite) } update () { if (this.player.x > this.game.world.width) { this.state.start('Fight') } } }
Put dates in the past so that we have no chance of having them spontaneously fail.
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from unittest import TestCase from education.views import AbsenteeismForm from datetime import datetime class TestAbsenteeismForm(TestCase): def test_should_invalidate_empty_form(self): absenteeism_form = AbsenteeismForm(data={}) self.assertFalse(absenteeism_form.is_valid()) def test_should_validate_if_to_date_is_greater_than_from_date(self): absenteeism_form = AbsenteeismForm(data={'to_date':'12/12/2012', 'from_date':'12/14/2012'}) self.assertFalse(absenteeism_form.is_valid()) def test_should_get_cleaned_data_after_validation(self): absenteeism_form = AbsenteeismForm(data={'to_date':'12/21/2012', 'from_date':'12/14/2012', 'indicator':'all'}) self.assertTrue(absenteeism_form.is_valid()) self.assertEqual(datetime(2012,12,21), absenteeism_form.cleaned_data['to_date']) self.assertEqual(datetime(2012,12,14), absenteeism_form.cleaned_data['from_date']) self.assertEqual('all', absenteeism_form.cleaned_data['indicator'])
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from unittest import TestCase from education.views import AbsenteeismForm from datetime import datetime class TestAbsenteeismForm(TestCase): def test_should_invalidate_empty_form(self): absenteeism_form = AbsenteeismForm(data={}) self.assertFalse(absenteeism_form.is_valid()) def test_should_validate_if_to_date_is_greater_than_from_date(self): absenteeism_form = AbsenteeismForm(data={'to_date':'12/12/2013', 'from_date':'12/14/2013'}) self.assertFalse(absenteeism_form.is_valid()) def test_should_get_cleaned_data_after_validation(self): absenteeism_form = AbsenteeismForm(data={'to_date':'12/21/2013', 'from_date':'12/14/2013', 'indicator':'all'}) self.assertTrue(absenteeism_form.is_valid()) self.assertEqual(datetime(2013,12,21), absenteeism_form.cleaned_data['to_date']) self.assertEqual(datetime(2013,12,14), absenteeism_form.cleaned_data['from_date']) self.assertEqual('all', absenteeism_form.cleaned_data['indicator'])
Comment and toast delete tested
(function () { 'use strict'; angular .module('drinks', ['ngAnimate', 'toastr']) .controller('DrinksListController', DrinksListController); DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr']; function DrinksListController(DrinksService, $state, $scope, toastr) { var vm = this; vm.AddToMenu = AddToMenu; vm.mvOnMenu = mvOnMenu; vm.mvOffMenu = mvOffMenu; vm.drinks = DrinksService.query(); function AddToMenu(drink) { drink.$update(successCallback, errorCallback); function successCallback(res) { $state.go('drinks.list', { drinkId: res._id }); } function errorCallback(res) { vm.error = res.data.message; } } //Menu drink toggle notification via toastr function mvOnMenu(drink) { toastr.success( drink.drinkName + ' was added to tap!', { closeHtml: '<button></button>' } ); } function mvOffMenu(drink) { toastr.success( drink.drinkName + ' was removed from tap!' ); } } })();
(function () { 'use strict'; angular .module('drinks', ['ngAnimate', 'toastr']) .controller('DrinksListController', DrinksListController); DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr']; function DrinksListController(DrinksService, $state, $scope, toastr) { var vm = this; vm.AddToMenu = AddToMenu; vm.mvOnMenu = mvOnMenu; vm.mvOffMenu = mvOffMenu; vm.drinks = DrinksService.query(); function AddToMenu(drink) { drink.$update(successCallback, errorCallback); function successCallback(res) { $state.go('drinks.list', { drinkId: res._id }); } function errorCallback(res) { vm.error = res.data.message; } } function mvOnMenu(drink) { toastr.success(drink.drinkName + ' was added to tap!'); } function mvOffMenu(drink) { toastr.success(drink.drinkName + ' was removed from tap!'); } } })();
Update pyrax, and make it stop reverting if the version is too new Conflicts: setup.py
#!/usr/bin/env python import os from setuptools import setup, find_packages # Use the docstring of the __init__ file to be the description short_description = " ".join(__import__("cumulus").__doc__.splitlines()).strip() # Use part of the sphinx docs index for the long description doc_dir = os.path.join(os.path.dirname(__file__), "docs") index_filename = os.path.join(doc_dir, "index.rst") long_description = open(index_filename).read().split("split here", 1)[1] setup( name="django-cumulus", version=__import__("cumulus").get_version().replace(" ", "-"), packages=find_packages(), install_requires=[ "pyrax>=1.5.0", ], author="Rich Leland", author_email="rich@richleland.com", license="BSD", description=short_description, long_description=long_description, url="https://github.com/richleland/django-cumulus/", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ] )
#!/usr/bin/env python import os from setuptools import setup, find_packages # Use the docstring of the __init__ file to be the description short_description = " ".join(__import__("cumulus").__doc__.splitlines()).strip() # Use part of the sphinx docs index for the long description doc_dir = os.path.join(os.path.dirname(__file__), "docs") index_filename = os.path.join(doc_dir, "index.rst") long_description = open(index_filename).read().split("split here", 1)[1] setup( name="django-cumulus", version=__import__("cumulus").get_version().replace(" ", "-"), packages=find_packages(), install_requires=[ "pyrax==1.4.10", ], author="Rich Leland", author_email="rich@richleland.com", license="BSD", description=short_description, long_description=long_description, url="https://github.com/richleland/django-cumulus/", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ] )
Add correct path to live API
'use strict'; var API_BASE = 'http://178.62.207.54:3000/'; /** * @ngdoc overview * @name perceptionClientApp * @description * # perceptionClientApp * * Main module of the application. */ angular .module('perceptionClientApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch' ]) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/intro', { templateUrl: 'views/intro.html', controller: 'IntroCtrl' }) .when('/start', { templateUrl: 'views/start.html', controller: 'StartCtrl' }) .when('/instructions', { templateUrl: 'views/instructions.html', controller: 'InstructionsCtrl' }) .when('/experiment', { templateUrl: 'views/experiment.html', controller: 'ExperimentCtrl' }) .when('/thankyou', { templateUrl: 'views/thankyou.html', controller: 'ThankyouCtrl' }) .otherwise({ redirectTo: '/' }); });
'use strict'; var API_BASE = 'http://localhost:3000/'; /** * @ngdoc overview * @name perceptionClientApp * @description * # perceptionClientApp * * Main module of the application. */ angular .module('perceptionClientApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch' ]) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/intro', { templateUrl: 'views/intro.html', controller: 'IntroCtrl' }) .when('/start', { templateUrl: 'views/start.html', controller: 'StartCtrl' }) .when('/instructions', { templateUrl: 'views/instructions.html', controller: 'InstructionsCtrl' }) .when('/experiment', { templateUrl: 'views/experiment.html', controller: 'ExperimentCtrl' }) .when('/thankyou', { templateUrl: 'views/thankyou.html', controller: 'ThankyouCtrl' }) .otherwise({ redirectTo: '/' }); });
tests/memory: Disable test_object_size under CPython 3.8
import sys import weakref import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import floats, vectors class DummyVector: """A naïve representation of vectors.""" x: float y: float def __init__(self, x, y): self.x = float(x) self.y = float(y) @pytest.mark.skipif(sys.implementation.name != 'cpython', reason="PyPy optimises __slots__ automatically.") @pytest.mark.skipif(sys.implementation.version.minor > 7, reason="Pympler 0.6 is broken under Python 3.8. See pympler#74") @given(x=floats(), y=floats()) def test_object_size(x, y): """Check that Vector2 is 2 times smaller than a naïve version.""" from pympler.asizeof import asizeof as sizeof # type: ignore assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2 @given(v=vectors()) def test_weak_ref(v): """Check that weak references can be made to Vector2s.""" assert weakref.ref(v) is not None
import sys import weakref import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import floats, vectors class DummyVector: """A naïve representation of vectors.""" x: float y: float def __init__(self, x, y): self.x = float(x) self.y = float(y) @pytest.mark.skipif(sys.implementation.name != 'cpython', reason="PyPy optimises __slots__ automatically.") @given(x=floats(), y=floats()) def test_object_size(x, y): """Check that Vector2 is 2 times smaller than a naïve version.""" from pympler.asizeof import asizeof as sizeof # type: ignore assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2 @given(v=vectors()) def test_weak_ref(v): """Check that weak references can be made to Vector2s.""" assert weakref.ref(v) is not None
Add deprecation notice about random() helper
"use strict"; /*global nodeca, _*/ // stdlib var crypto = require('crypto'); // nodeca var HashTree = require('nlib').Support.HashTree; var JASON = require('nlib').Vendor.JASON; //////////////////////////////////////////////////////////////////////////////// var helpers = module.exports = {}; //////////////////////////////////////////////////////////////////////////////// // returns asset source helpers.asset_include = function asset_include(path) { var asset = nodeca.runtime.assets.environment.findAsset(path); return !asset ? "" : asset.toString(); }; // returns part or whole config helpers.config = function (part) { return !part ? nodeca.config : HashTree.get(nodeca.config, part); }; // crypto-strong random 128 bit string // TODO: Remove it once REALTIME_ID will be received by AJAX handshake helpers.random = function () { var rnd = crypto.randomBytes(16); return crypto.createHash('md5').update(rnd).digest('hex'); }; // returns link for the api path `name` helpers.link_to = function (name, params) { return nodeca.runtime.router.linkTo(name, params) || '#'; }; // nodeca reference helpers.nodeca = nodeca; // JSON alike serializer (but that treats RegExps, Function as they are) helpers.jason = JASON.stringify;
"use strict"; /*global nodeca, _*/ // stdlib var crypto = require('crypto'); // nodeca var HashTree = require('nlib').Support.HashTree; var JASON = require('nlib').Vendor.JASON; //////////////////////////////////////////////////////////////////////////////// var helpers = module.exports = {}; //////////////////////////////////////////////////////////////////////////////// // returns asset source helpers.asset_include = function asset_include(path) { var asset = nodeca.runtime.assets.environment.findAsset(path); return !asset ? "" : asset.toString(); }; // returns part or whole config helpers.config = function (part) { return !part ? nodeca.config : HashTree.get(nodeca.config, part); }; // crypto-strong random 128 bit string helpers.random = function () { var rnd = crypto.randomBytes(16); return crypto.createHash('md5').update(rnd).digest('hex'); }; // returns link for the api path `name` helpers.link_to = function (name, params) { return nodeca.runtime.router.linkTo(name, params) || '#'; }; // nodeca reference helpers.nodeca = nodeca; // JSON alike serializer (but that treats RegExps, Function as they are) helpers.jason = JASON.stringify;
Fix for BRCD_798 : align non-prorated services/plans with the per cycle limits/rates
<?php /** * @package Billing * @copyright Copyright (C) 2012 BillRun Technologies Ltd. All rights reserved. * @license GNU Affero General Public License Version 3; see LICENSE.txt */ /** * Calculates a monthly charge * * @package Plans * @since 5.2 */ class Billrun_Plans_Charge_Arrears_Notprorated_Month extends Billrun_Plans_Charge_Arrears_Month { /** * Get the price of the current plan. */ public function getPrice($quantity = 1) { $charges = array(); foreach ($this->price as $tariff) { $price = Billrun_Plan::getPriceByTariff($tariff, max(0, floor($this->startOffset+1)), floor($this->endOffset+1)); if (!empty($price)) { $charges[] = array('value' => $price['price'], 'cycle' => $tariff['from']); } } return $charges; } }
<?php /** * @package Billing * @copyright Copyright (C) 2012 BillRun Technologies Ltd. All rights reserved. * @license GNU Affero General Public License Version 3; see LICENSE.txt */ /** * Calculates a monthly charge * * @package Plans * @since 5.2 */ class Billrun_Plans_Charge_Arrears_Notprorated_Month extends Billrun_Plans_Charge_Arrears_Month { /** * Get the price of the current plan. */ public function getPrice($quantity = 1) { $charges = array(); foreach ($this->price as $tariff) { $price = Billrun_Plan::getPriceByTariff($tariff, max(0, floor($this->startOffset)), ceil($this->endOffset)); if (!empty($price)) { $charges[] = array('value' => $price['price'], 'cycle' => $tariff['from']); } } return $charges; } }
Use the correct JSON keys for School structs.
package hackedu import ( "encoding/json" "fmt" "net/http" "appengine" ) type School struct { Name string `json:"name,omitempty"` Location Location `json:"location,omitempty"` } type Location struct { Latitude float32 `json:"latitude,omitempty"` Longitude float32 `json:"longitude,omitempty"` } func Schools(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) austin := School{ Name: "Austin High School", Location: Location{ Latitude: 30.27382, Longitude: -97.76745, }, } thunderridge := School{ Name: "Thunderridge High School", Location: Location{ Latitude: 39.5347968, Longitude: -105.01200670000003, }, } schools := []School{austin, thunderridge} bytes, err := json.Marshal(schools) if err != nil { serveError(c, w, err) } fmt.Println(string(bytes)) w.Write(bytes) }
package hackedu import ( "encoding/json" "fmt" "net/http" "appengine" ) type School struct { Name string `json:"latitude,omitempty"` Location Location } type Location struct { Latitude float32 `json:"latitude,omitempty"` Longitude float32 `json:"longitude,omitempty"` } func Schools(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) austin := School{ Name: "Austin High School", Location: Location{ Latitude: 30.27382, Longitude: -97.76745, }, } thunderridge := School{ Name: "Thunderridge High School", Location: Location{ Latitude: 39.5347968, Longitude: -105.01200670000003, }, } schools := []School{austin, thunderridge} bytes, err := json.Marshal(schools) if err != nil { serveError(c, w, err) } fmt.Println(string(bytes)) w.Write(bytes) }
Refactor BraggTree test to use pytest-qt
from __future__ import absolute_import, print_function import pytest from addie.main import MainWindow from addie.rietveld.braggtree import BraggTree, BankRegexException @pytest.fixture def braggtree(): return BraggTree(None) def test_get_bank_id(qtbot, braggtree): """Test we can extract a bank id from bank workspace name""" target = 12345 bank_wksp_name = "Bank {} - 90.0".format(target) bank_id = braggtree._get_bank_id(bank_wksp_name) assert int(bank_id) == target def test_get_bank_id_exception(qtbot, braggtree): """Test for raised exception from a bad workspace name""" bad_ws = "Bank jkl 1 -- 90.0" with pytest.raises(BankRegexException) as e: braggtree._get_bank_id(bad_ws) def test_do_plot_ws_exception(qtbot, braggtree): """Test for raised exception from MainWindow==None""" with pytest.raises(NotImplementedError) as e: braggtree.do_plot_ws()
from __future__ import absolute_import, print_function import unittest from qtpy.QtWidgets import QApplication from addie.rietveld.braggtree import BraggTree, BankRegexException class BraggTreeTests(unittest.TestCase): def setUp(self): self.main_window = QApplication([]) def tearDown(self): self.main_window.quit() def test_get_bank_id(self): """Test we can extract a bank id from bank workspace name""" braggtree = BraggTree(None) target = 12345 bank_wksp_name = "Bank {} - 90.0".format(target) bank_id = braggtree._get_bank_id(bank_wksp_name) self.assertEqual(int(bank_id), target) def test_get_bank_id_exception(self): """Test for raised exception from a bad workspace name""" braggtree = BraggTree(None) bad_ws = "Bank jkl 1 -- 90.0" self.assertRaises(BankRegexException, braggtree._get_bank_id, bad_ws) def test_do_plot_ws_exception(self): """Test for raised exception from MainWindow==None""" braggtree = BraggTree(None) self.assertRaises(NotImplementedError, braggtree.do_plot_ws) if __name__ == '__main__': unittest.main() # pragma: no cover
Allow all heading to be added to the nav
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require highlight.pack //= require_tree . $(document).ready(function() { $('pre').each(function(i, el) { hljs.highlightBlock(el); }); $('code').each(function(i, el) { hljs.highlightBlock(el); }); $('.vivus-documentation').find('h1, h2, h3, h4, h5, h6').each(function(i, el) { $('#vivus-navigation ul').append("<li class=" + $(el).prop("tagName").toLowerCase() + "><a href='#" + $(el).text().toLowerCase().replace(/ /g, '-') + "'>" + $(el).text() + "</a></li>"); $(el).prepend("<a name='" + $(el).text().toLowerCase().replace(/ /g, '-') + "'></a>"); }) });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require highlight.pack //= require_tree . $(document).ready(function() { $('pre').each(function(i, el) { hljs.highlightBlock(el); }); $('code').each(function(i, el) { hljs.highlightBlock(el); }); $('.vivus-documentation h1').each(function(i, el) { $('#vivus-navigation ul').append("<li><a href='#" + $(el).text().toLowerCase().replace(/ /g, '-') + "'>" + $(el).text() + "</a></li>"); $(el).prepend("<a name='" + $(el).text().toLowerCase().replace(/ /g, '-') + "'></a>"); }) });
Fix responsive shit for the carousel
// NOVA JavaScript // Author: shadowfacts $(document).ready(function() { $(".nova-use-id").each(function (i) { $(this).text(i + 1); }) $('.nova-slider').slick({ centerMode: true, centerPadding: '60px', slidesToShow: 3, autoplay: true, autplaySpeed: 8000, appendArrows: '.nova-slider-controls', prevArrow: '<a href="javascript:void(0)" class="left" role="button"><span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span><span class="sr-only">Previous</span></a>', nextArrow: '<a href="javascript:void(0)" class="right" role="button"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span><span class="sr-only">Next</span></a>', responsive: [ { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 3 slidesToScroll: 1 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 3 slidesToScroll: 1 } } ] }); });
// NOVA JavaScript // Author: shadowfacts $(document).ready(function() { $(".nova-use-id").each(function (i) { $(this).text(i + 1); }) $('.nova-slider').slick({ centerMode: true, centerPadding: '60px', slidesToShow: 3, autoplay: true, autplaySpeed: 8000, appendArrows: '.nova-slider-controls', prevArrow: '<a href="javascript:void(0)" class="left" role="button"><span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span><span class="sr-only">Previous</span></a>', nextArrow: '<a href="javascript:void(0)" class="right" role="button"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span><span class="sr-only">Next</span></a>', responsive: [ { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 3 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 3 } } ] }); });
Fix teaser image for maps.
<?php global $wp_query; $slider_or_image = ''; $page_parent_image = function_exists('get_field') ? get_field('header_image', $wp_query->post->post_parent) : ''; $page_parent_animation = function_exists('get_field') ? get_field('show_vobe_animation', $wp_query->post->post_parent) : ''; $page_google_map = function_exists('get_field') ? get_field('show_google_map', $wp_query->post->post_parent) : ''; if ( $page_parent_image ) { $slider_or_image = wp_get_attachment_image( $page_parent_image, 'full' ); } else if ( is_front_page() ) { $slider_or_image = do_shortcode( '[responsive_slider]' ); } else if ( $page_parent_animation ) { $slider_or_image = get_template_part('templates/animation'); } else if ( $page_google_map ) { $options = $get_option('plugin_options'); $slider_or_image = $options['vobe_google_map_code']; } echo $slider_or_image; ?>
<?php global $wp_query; $slider_or_image = ''; $page_parent_image = function_exists('get_field') ? get_field('header_image', $wp_query->post->post_parent) : ''; $page_parent_animation = function_exists('get_field') ? get_field('show_vobe_animation', $wp_query->post->post_parent) : ''; $page_google_map = function_exists('get_field') ? get_field('show_google_map', $wp_query->post->post_parent) : ''; if ( $page_parent_image ) { $slider_or_image = wp_get_attachment_image( $page_parent_image, 'full' ); } else if ( is_front_page() ) { $slider_or_image = do_shortcode( '[responsive_slider]' ); } else if ( $page_parent_animation ) { $slider_or_image = get_template_part('templates/animation'); } else if ( $page_google_map ) { $slider_or_image = get_option('plugin_options')['vobe_google_map_code']; } echo $slider_or_image; ?>
Update class to get image description if available and use it as the update message.
import exifread import os class TweetS3Images(object): def __init__(self, twitter, s3_client): self._twitter = twitter self._s3_client = s3_client self._file = None def send_image(self, bucket, image_name, cleanup=False): temp_file = '/tmp/{}'.format(image_name) self._s3_client.download_file(bucket, image_name, temp_file) self._file = open(temp_file, 'rb') tags = exifread.process_file(self._file) status = self.get_image_description(tags, image_name) self._twitter.update_with_media(filename=image_name, status=status, file=self._file) if cleanup: self.cleanup(temp_file) def get_file(self): return self._file @staticmethod def cleanup(file_to_remove): os.remove(file_to_remove) @staticmethod def get_image_description(tags, image_name): if 'Image ImageDescription' in tags: status = tags['Image ImageDescription'].values else: status = 'New image {} brought to you by lambda-tweet'.format(image_name) return status
import exifread import os class TweetS3Images(object): def __init__(self, twitter, s3_client): self._twitter = twitter self._s3_client = s3_client self._file = None def send_image(self, bucket, image_name, cleanup=False): temp_file = '/tmp/{}'.format(image_name) self._s3_client.download_file(bucket, image_name, temp_file) self._file = open(temp_file, 'rb') status = 'New image {} brought to you by lambda-tweet'.format(image_name) tags = exifread.process_file(self._file) self._twitter.update_with_media(filename=image_name, status=status, file=self._file) if cleanup: self.cleanup(temp_file) def get_file(self): return self._file def cleanup(self, file): os.remove(file)
Use the version in the config file
__author__ = 'matt' import datetime import blockbuster blockbuster.app.debug = blockbuster.config.debug_mode blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.config.app_version + " " "@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====") blockbuster.bb_logging.logger.info( '================Time restriction disabled================') \ if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info( '================Time restriction enabled================') blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") if blockbuster.config.debug_mode: blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========") # This section only applies when you are running run.py directly if __name__ == '__main__': blockbuster.bb_logging.logger.info("Running http on port 5000") blockbuster.app.run(host='0.0.0.0', debug=True)
__author__ = 'matt' import datetime import blockbuster blockbuster.app.debug = blockbuster.config.debug_mode blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " @@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====") blockbuster.bb_logging.logger.info( '================Time restriction disabled================') \ if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info( '================Time restriction enabled================') blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") if blockbuster.config.debug_mode: blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========") # This section only applies when you are running run.py directly if __name__ == '__main__': blockbuster.bb_logging.logger.info("Running http on port 5000") blockbuster.app.run(host='0.0.0.0', debug=True)
Use PRAGMA synchronous=NORMAL instead of OFF, and set page_size to 4096.
import sqlite3 class SQLiteWrapper: def __init__(self, db): self.conn = sqlite3.connect(db) self.cursor = self.conn.cursor() self.cursor.execute("PRAGMA page_size=4096") self.cursor.execute("PRAGMA cache_size=-16000") self.cursor.execute("PRAGMA synchronous=NORMAL") self.conn.commit() def query(self, sql, params=None, iterator=False, fetch_one=False, multi=False, many_rows=None): try: with self.conn as conn: cursor = conn.cursor() if many_rows: cursor.executemany(sql, many_rows) return if multi: cursor.executescript(sql) if params is None and not multi: cursor.execute(sql) if params and not multi: cursor.execute(sql, params) if iterator: return cursor if fetch_one: return cursor.fetchone()[0] if not multi: return cursor.fetchall() except Exception as e: raise Exception('Error in executing query ' + sql + ': ' + format(e)) def close(self): self.conn.close()
import sqlite3 class SQLiteWrapper: def __init__(self, db): self.conn = sqlite3.connect(db) self.cursor = self.conn.cursor() self.cursor.execute("PRAGMA cache_size=-16000") self.cursor.execute("PRAGMA synchronous=OFF") self.conn.commit() def query(self, sql, params=None, iterator=False, fetch_one=False, multi=False, many_rows=None): try: with self.conn as conn: cursor = conn.cursor() if many_rows: cursor.executemany(sql, many_rows) return if multi: cursor.executescript(sql) if params is None and not multi: cursor.execute(sql) if params and not multi: cursor.execute(sql, params) if iterator: return cursor if fetch_one: return cursor.fetchone()[0] if not multi: return cursor.fetchall() except Exception as e: raise Exception('Error in executing query ' + sql + ': ' + format(e)) def close(self): self.conn.close()
Increase timeout for satrapy name lookups
from astropy.table import Table from astropy.coordinates import ICRS, name_resolve from astropy import units as u TABLE_NAME = 'feder_object_list.csv' MAX_SEP = 5 # arcsec # increase timeout so that the Travis builds succeed name_resolve.NAME_RESOLVE_TIMEOUT.set(30) def test_table_can_be_read_and_coords_good(): objs = Table.read(TABLE_NAME, format='ascii', delimiter=',') columns = ['object', 'ra', 'dec'] for col in columns: assert col in objs.colnames for row in objs: try: simbad_pos = ICRS.from_name(row['object']) except name_resolve.NameResolveError: continue table_pos = ICRS(row['ra'], row['dec'], unit=(u.hour, u.degree)) # CHANGE ASSERT TO IF/THEN, print name then assert 0 sep = table_pos.separation(simbad_pos).arcsec warn = '' if sep > MAX_SEP: warn = ('Bad RA/Dec for object {}, ' 'separation is {} arcsec'.format(row['object'], sep)) print (warn) assert len(warn) == 0
from astropy.table import Table from astropy.coordinates import ICRS, name_resolve from astropy import units as u TABLE_NAME = 'feder_object_list.csv' MAX_SEP = 5 # arcsec def test_table_can_be_read_and_coords_good(): objs = Table.read(TABLE_NAME, format='ascii', delimiter=',') columns = ['object', 'ra', 'dec'] for col in columns: assert col in objs.colnames for row in objs: try: simbad_pos = ICRS.from_name(row['object']) except name_resolve.NameResolveError: continue table_pos = ICRS(row['ra'], row['dec'], unit=(u.hour, u.degree)) # CHANGE ASSERT TO IF/THEN, print name then assert 0 sep = table_pos.separation(simbad_pos).arcsec warn = '' if sep > MAX_SEP: warn = ('Bad RA/Dec for object {}, ' 'separation is {} arcsec'.format(row['object'], sep)) print (warn) assert len(warn) == 0
Correct formatting bug when version contains pipe
'use strict'; var cvss = require('cvss'); module.exports = function (err, data, pkgPath) { if (err) { return err; } var pipeWrap = function (items) { return '|' + items.join('|') + '|'; }; var header = [ 'Severity', 'Title', 'Module', 'Installed', 'Patched', 'Include Path', 'More Info' ]; var rows = []; rows.push( pipeWrap(header) ); rows.push( pipeWrap( Array(header.length).fill('--') ) ); data.forEach( function (finding) { var advisory_number = finding.advisory.substr(finding.advisory.lastIndexOf('/')); var patched_versions = finding.patched_versions === '<0.0.0' ? 'None' : finding.patched_versions.replace(/\|\|/g, 'OR'); rows.push( pipeWrap([ cvss.getRating(finding.cvss_score), finding.title, finding.module, finding.version, patched_versions, '{nav ' + finding.path.join(' > ') + '}', '[[' + finding.advisory + '|nspa' + advisory_number + ']]' ]) ); }); return rows.join('\n'); };
'use strict'; var cvss = require('cvss'); module.exports = function (err, data, pkgPath) { if (err) { return 'Debug output: ' + JSON.stringify(Buffer.isBuffer(data) ? data.toString() : data) + '\n' + err; } var pipeWrap = function (items) { return '|' + items.join('|') + '|'; }; var header = ['Severity', 'Title', 'Module', 'Installed', 'Patched', 'Include Path', 'More Info']; var rows = []; rows.push( pipeWrap(header) ); rows.push( pipeWrap( Array(header.length).fill('--') ) ); data.forEach( function (finding) { var advisory_number = finding.advisory.substr(finding.advisory.lastIndexOf('/')); rows.push( pipeWrap( [cvss.getRating(finding.cvss_score), finding.title, finding.module, finding.version, finding.patched_versions === '<1.0.0' ? 'None' : finding.patched_versions, '{nav ' + finding.path.join(' > ') + '}', '[[' + finding.advisory + '|nspa' + advisory_number + ']]'] ) ); }); return rows.join('\n'); };
Fix bug with un-renamed Docker Hub username.
package main const dockerUnitTemplate = ` [Unit] Description={{.Name}} After=docker.service [Service] EnvironmentFile=/etc/environment User=core TimeoutStartSec=0 ExecStartPre=/usr/bin/docker pull {{.DockerHubUsername}}/{{.Name}}:{{.Version}} ExecStartPre=-/usr/bin/docker rm -f {{.Name}}-{{.Version}}-%i ExecStart=/usr/bin/docker run --name {{.Name}}-{{.Version}}-%i -p 3000 {{.DockerHubUsername}}/{{.Name}}:{{.Version}} ExecStartPost=/bin/sh -c "sleep 15; /usr/bin/etcdctl set /vulcand/upstreams/{{.Name}}/endpoints/{{.Name}}-{{.Version}}-%i http://$COREOS_PRIVATE_IPV4:$(echo $(/usr/bin/docker port {{.Name}}-{{.Version}}-%i 3000) | cut -d ':' -f 2)" ExecStop=/bin/sh -c "/usr/bin/etcdctl rm '/vulcand/upstreams/{{.Name}}/endpoints/{{.Name}}-{{.Version}}-%i' ; /usr/bin/docker rm -f {{.Name}}-{{.Version}}-%i" `
package main const dockerUnitTemplate = ` [Unit] Description={{.Name}} After=docker.service [Service] EnvironmentFile=/etc/environment User=core TimeoutStartSec=0 ExecStartPre=/usr/bin/docker pull mmmhm/{{.Name}}:{{.Version}} ExecStartPre=-/usr/bin/docker rm -f {{.Name}}-{{.Version}}-%i ExecStart=/usr/bin/docker run --name {{.Name}}-{{.Version}}-%i -p 3000 {{.DockerHubUsername}}/{{.Name}}:{{.Version}} ExecStartPost=/bin/sh -c "sleep 15; /usr/bin/etcdctl set /vulcand/upstreams/{{.Name}}/endpoints/{{.Name}}-{{.Version}}-%i http://$COREOS_PRIVATE_IPV4:$(echo $(/usr/bin/docker port {{.Name}}-{{.Version}}-%i 3000) | cut -d ':' -f 2)" ExecStop=/bin/sh -c "/usr/bin/etcdctl rm '/vulcand/upstreams/{{.Name}}/endpoints/{{.Name}}-{{.Version}}-%i' ; /usr/bin/docker rm -f {{.Name}}-{{.Version}}-%i" `
Remove FutureWarning for capi import
""" This module provides bindings to C functions defined by OpenMC shared library. When the :mod:`openmc` package is imported, the OpenMC shared library is automatically loaded. Calls to the OpenMC library can then be via functions or objects in the :mod:`openmc.capi` subpackage, for example: .. code-block:: python openmc.capi.init() openmc.capi.run() openmc.capi.finalize() """ from ctypes import CDLL import os import sys import pkg_resources # Determine shared-library suffix if sys.platform == 'darwin': _suffix = 'dylib' else: _suffix = 'so' if os.environ.get('READTHEDOCS', None) != 'True': # Open shared library _filename = pkg_resources.resource_filename( __name__, 'libopenmc.{}'.format(_suffix)) _dll = CDLL(_filename) else: # For documentation builds, we don't actually have the shared library # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur from unittest.mock import Mock _dll = Mock() from .error import * from .core import * from .nuclide import * from .material import * from .cell import * from .filter import * from .tally import * from .settings import settings
""" This module provides bindings to C functions defined by OpenMC shared library. When the :mod:`openmc` package is imported, the OpenMC shared library is automatically loaded. Calls to the OpenMC library can then be via functions or objects in the :mod:`openmc.capi` subpackage, for example: .. code-block:: python openmc.capi.init() openmc.capi.run() openmc.capi.finalize() """ from ctypes import CDLL import os import sys from warnings import warn import pkg_resources # Determine shared-library suffix if sys.platform == 'darwin': _suffix = 'dylib' else: _suffix = 'so' if os.environ.get('READTHEDOCS', None) != 'True': # Open shared library _filename = pkg_resources.resource_filename( __name__, 'libopenmc.{}'.format(_suffix)) _dll = CDLL(_filename) else: # For documentation builds, we don't actually have the shared library # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur try: from unittest.mock import Mock except ImportError: from mock import Mock _dll = Mock() from .error import * from .core import * from .nuclide import * from .material import * from .cell import * from .filter import * from .tally import * from .settings import settings warn("The Python bindings to OpenMC's C API are still unstable " "and may change substantially in future releases.", FutureWarning)
Check for change value before rendering
var _ = require('underscore'), supportedModuleTypes = ['kpi', 'single_timeseries']; function processTimeSeries(timeSeriesData) { var latestDatum = timeSeriesData[0], secondLatestDatum = timeSeriesData[1], textUpdate = []; textUpdate.push([ latestDatum.formatted_date_range, latestDatum.formatted_value ].join(' = ')); textUpdate.push([ secondLatestDatum.formatted_date_range, secondLatestDatum.formatted_value ].join(' = ')); if (latestDatum.formatted_change_from_previous && latestDatum.formatted_change_from_previous.change) { textUpdate.push([ 'Total change = ', latestDatum.formatted_change_from_previous.change ].join('')); } return textUpdate; } function getTextUpdate(module) { var textUpdate = [], timeSeriesUpdate; if (module['module-type'] === 'grouped_timeseries') { _.each(module.data, function (timeSeries) { textUpdate.push(timeSeries.label); timeSeriesUpdate = processTimeSeries(timeSeries.values); textUpdate = textUpdate.concat(timeSeriesUpdate); }); return textUpdate; } else { return processTimeSeries(module.data); } } module.exports = function (modules) { return _.filter(modules, function (module) { if (_.contains(supportedModuleTypes, module['module-type'])) { module.textUpdate = getTextUpdate(module); return true; } }); };
var _ = require('underscore'), supportedModuleTypes = ['kpi', 'single_timeseries']; function processTimeSeries(timeSeriesData) { var latestDatum = timeSeriesData[0], secondLatestDatum = timeSeriesData[1], textUpdate = []; textUpdate.push([latestDatum.formatted_date_range, latestDatum.formatted_value].join(' = ')); textUpdate.push([ secondLatestDatum.formatted_date_range, secondLatestDatum.formatted_value ].join(' = ')); textUpdate.push([ 'Total change = ', latestDatum.formatted_change_from_previous.change ].join('')); return textUpdate; } function getTextUpdate(module) { var textUpdate = [], timeSeriesUpdate; if (module['module-type'] === 'grouped_timeseries') { _.each(module.data, function (timeSeries) { textUpdate.push(timeSeries.label); timeSeriesUpdate = processTimeSeries(timeSeries.values); textUpdate = textUpdate.concat(timeSeriesUpdate); }); return textUpdate; } else { return processTimeSeries(module.data); } } module.exports = function (modules) { return _.filter(modules, function (module) { if (_.contains(supportedModuleTypes, module['module-type'])) { module.textUpdate = getTextUpdate(module); return true; } }); };
Add combination code to runner
package ir_course; /** * Created by martin on 4/9/14. */ public class SearchSuite { public static final String corpusPath = "corpus_part2.xml"; private static String[] defaults = {corpusPath}; public static final String BM25 = "bm25"; private static String[] bm25Standard = {corpusPath, BM25}; public static final String PORTER = "PORTER"; private static String[] bm25Porter = {corpusPath, BM25, PORTER}; private static String[] vsmPorter = {corpusPath, PORTER}; public static final String SIMPLE = "SIMPLE"; private static String[] vsmSimple = {corpusPath, SIMPLE}; private static String[] bm25Simple = {corpusPath, BM25, SIMPLE}; public static void main(String[] args) { LuceneSearchApp app = new LuceneSearchApp(); app.main(defaults); app.main(bm25Standard); app.main(bm25Porter); app.main(bm25Simple); app.main(vsmSimple); app.main(vsmPorter); runCombination(app, "BM25", defaults, bm25Standard, bm25Porter, bm25Simple, vsmSimple, vsmPorter); } public static void runCombination(LuceneSearchApp app, String label, String[]... tests) { for( String[] test : tests) { // TODO: print label here app.main(test); } } }
package ir_course; /** * Created by martin on 4/9/14. */ public class SearchSuite { public static final String corpusPath = "corpus_part2.xml"; private static String[] defaults = {corpusPath}; public static final String BM25 = "bm25"; private static String[] bm25Standard = {corpusPath, BM25}; public static final String PORTER = "PORTER"; private static String[] bm25Porter = {corpusPath, BM25, PORTER}; private static String[] vsmPorter = {corpusPath, PORTER}; public static final String SIMPLE = "SIMPLE"; private static String[] vsmSimple = {corpusPath, SIMPLE}; private static String[] bm25Simple = {corpusPath, BM25, SIMPLE}; public static void main(String[] args) { LuceneSearchApp app = new LuceneSearchApp(); app.main(defaults); app.main(bm25Standard); app.main(bm25Porter); app.main(bm25Simple); app.main(vsmSimple); app.main(vsmPorter); } }
Update feedparse() for PHP 5
<?php /* * Core functions. * * Don't forget to add own ones. */ // `encrypt` // // Encrypts `$str` in rot13. function encrypt($str) { echo str_rot13($str); } // `decrypt` // // Decrypts `$str` in rot13. Gives `$str` as output. function decrypt($str) { echo str_rot13(str_rot13($str)); } // `cfile` // // Checks for current file. Change the target class name if necessary. function cfile($file) { if (strpos($_SERVER['PHP_SELF'], $file)) { echo 'class="active"'; } } // `fcount` // // Counts number of files in a directory. function fcount($dir) { $i = 0; if ($handle = opendir($dir)) { while (($file = readdir($handle)) !== false) { if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) { $i++; } } } } // `feedparse` // // Parses RSS or Atom feeds. function feedparse($url) { $feed = fopen("$url", 'r'); $data = stream_get_contents($feed); fclose($feed); echo $data; } ?>
<?php /* * Core functions. * * Don't forget to add own ones. */ // `encrypt` // // Encrypts `$str` in rot13. function encrypt($str) { echo str_rot13($str); } // `decrypt` // // Decrypts `$str` in rot13. Gives `$str` as output. function decrypt($str) { echo str_rot13(str_rot13($str)); } // `cfile` // // Checks for current file. Change the target class name if necessary. function cfile($file) { if (strpos($_SERVER['PHP_SELF'], $file)) { echo 'class="active"'; } } // `fcount` // // Counts number of files in a directory. function fcount($dir) { $i = 0; if ($handle = opendir($dir)) { while (($file = readdir($handle)) !== false) { if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) { $i++; } } } } // `feedparse` // // Parses RSS or Atom feeds. function feedparse($url) { $feed = @fopen("$url", 'r'); if ($feed) { $data = ''; while (!feof($feed)) { $data .= fread($feed, 8192); } } fclose($feed); echo $data; } ?>
Use default username on startup
import DefaultConfig from 'anyware/lib/game-logic/config/default-config'; import GAMES from 'anyware/lib/game-logic/constants/games'; class Config extends DefaultConfig { constructor() { super(); this.CLIENT_CONNECTION_OPTIONS = { protocol: "wss", username: "anyware", password: "anyware", host: "broker.shiftr.io" }; this.diskUrls = { disk0: 'images/disk0.png', disk1: 'images/disk1.png', disk2: 'images/disk2.png' }; this.initialDiskPositions = { disk0: 90, disk1: 0, disk2: 270, }; this.projectionParameters = { scale: 1, translate: [0, 0], }; // this.GAMES_SEQUENCE = [ // GAMES.DISK, // GAMES.SIMON // ]; } // FIXME: Configure user colors here? How to communicate that to CSS? } export default new Config();
import DefaultConfig from 'anyware/lib/game-logic/config/default-config'; import GAMES from 'anyware/lib/game-logic/constants/games'; class Config extends DefaultConfig { constructor() { super(); this.username = "sculpture0"; this.CLIENT_CONNECTION_OPTIONS = { protocol: "wss", username: "anyware", password: "anyware", host: "broker.shiftr.io" }; this.diskUrls = { disk0: 'images/disk0.png', disk1: 'images/disk1.png', disk2: 'images/disk2.png' }; this.initialDiskPositions = { disk0: 90, disk1: 0, disk2: 270, }; this.projectionParameters = { scale: 1, translate: [0, 0], }; // this.GAMES_SEQUENCE = [ // GAMES.DISK, // GAMES.SIMON // ]; } // FIXME: Configure user colors here? How to communicate that to CSS? } export default new Config();
Update call method in test client
#!/usr/bin/env python # Echo client program import socket import sys from RemoteFunctionCaller import * from SocketNetworker import SocketNetworker HOST = 'localhost' # The remote host PORT = 8553 # The same port as used by the server s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except OSError as msg: s = None continue try: s.connect(sa) except OSError as msg: s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) nw = SocketNetworker(s) caller = RemoteFunctionCaller(nw) try: print(caller.SharedClientDataStore__set("test", "success")) print(caller.SharedClientDtaStore__get("test", default="failish")) except TimeoutError: print("Timed out.") nw.close()
#!/usr/bin/env python # Echo client program import socket import sys from RemoteFunctionCaller import * from SocketNetworker import SocketNetworker HOST = 'localhost' # The remote host PORT = 8553 # The same port as used by the server s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except OSError as msg: s = None continue try: s.connect(sa) except OSError as msg: s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) nw = SocketNetworker(s) caller = RemoteFunctionCaller(nw) try: caller.setData("test", "success") print(caller.getData("test", default="failish")) except TimeoutError: print("Timed out.") nw.close()
Rename funciton to match corresponding HTTP request
import requests import yaml def runLoop( config ): """ Runs indefinitely. On user input (card swipe), will gather the card number, send it to the server configured, and if it has been authorized, open the relay with a GPIO call. """ while True: swipe = input() cardNumber = swipe print( 'The last input was ' + cardNumber ) try: res = requestAuthorization( cardNumber, config ) except requests.exceptions.Timeout: print( "Server timeout!" ) continue if res['isAuthorized']: # open the relay here pass def requestAuthorization( cardNumber, config ): url = 'http://' + str( config['serverAddress'] ) + ':' + str( config['serverPort'] ) path = '/users/checkAuthorization' req = requests.get( url + path, { 'cardNumber': cardNumber, 'machineID': config['machineID'], 'machineType': config['machineType'] }, timeout=config['timeout'] ) return req.json() if __name__ == '__main__': # read and return a yaml file (called 'config.yaml' by default) and give it # back as a dictionary with open( 'config.yaml' ) as f: config = yaml.load( f ) # run the main loop runLoop( config )
import requests import yaml def runLoop( config ): """ Runs indefinitely. On user input (card swipe), will gather the card number, send it to the server configured, and if it has been authorized, open the relay with a GPIO call. """ while True: swipe = input() cardNumber = swipe print( 'The last input was ' + cardNumber ) try: res = queryServer( cardNumber, config ) except requests.exceptions.Timeout: print( "Server timeout!" ) continue if res['isAuthorized']: # open the relay here pass def queryServer( cardNumber, config ): url = 'http://' + str( config['serverAddress'] ) + ':' + str( config['serverPort'] ) req = requests.get( url, { 'cardNumber': cardNumber, 'machineID': config['machineID'], 'machineType': config['machineType'] }, timeout=config['timeout'] ) return req.json() if __name__ == '__main__': # read and return a yaml file (called 'config.yaml' by default) and give it # back as a dictionary with open( 'config.yaml' ) as f: config = yaml.load( f ) # run the main loop runLoop( config )
Use parameters for path resolution
/* @flow */ import Rule from '../Rule' import type { Phase } from '../types' function escapePath (filePath) { return filePath.replace(/\\/g, '\\\\') } export default class PatchSyncTeX extends Rule { static parameterTypes: Array<Set<string>> = [ new Set(['Knitr']), new Set(['SyncTeX']), new Set(['KnitrConcordance']) ] static phases: Set<Phase> = new Set(['finalize']) static description: string = 'Patches SyncTeX files if LaTeX document was generated by knitr so PDF reverse sync will work.' constructCommand () { const filePath = escapePath(this.firstParameter.filePath) const synctexPath = escapePath(this.secondParameter.filePath.replace(/\.synctex(\.gz)?$/i, '')) const lines = [ 'library(patchSynctex)', `patchSynctex('${filePath}',syncfile='${synctexPath}')`] return { args: ['Rscript', '-e', lines.join(';')], severity: 'warning' } } }
/* @flow */ import Rule from '../Rule' import type { Phase } from '../types' function escapePath (filePath) { return filePath.replace(/\\/g, '\\\\') } export default class PatchSyncTeX extends Rule { static parameterTypes: Array<Set<string>> = [ new Set(['KnitrConcordance']), new Set(['SyncTeX']) ] static phases: Set<Phase> = new Set(['finalize']) static description: string = 'Patches SyncTeX files if LaTeX document was generated by knitr so PDF reverse sync will work.' constructCommand () { const filePath = escapePath(this.filePath) const synctexPath = escapePath(this.resolvePath('$OUTDIR/$JOB')) const lines = [ 'library(patchSynctex)', `patchSynctex('${filePath}',syncfile='${synctexPath}')`] return { args: ['Rscript', '-e', lines.join(';')], severity: 'warning' } } }
Add new rules to default set.
/** * Copyright (C) 2011 Akiban Technologies Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses. */ package com.akiban.sql.optimizer.rule; import java.util.Arrays; import java.util.List; public class DefaultRules { /** These are the rules that get run for normal compilation. */ public static final List<BaseRule> DEFAULT_RULES = Arrays.asList( // These aren't singletons because someday they will have options. new ASTStatementLoader(), new AggregateMapper(), new ConstantFolder(), new OuterJoinPromoter(), new GroupJoinFinder(), new IndexPicker(), new NestedLoopMapper(), new BranchJoiner(), new SelectPreponer(), new MapFolder(), new OperatorAssembler() ); private DefaultRules() { } }
/** * Copyright (C) 2011 Akiban Technologies Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses. */ package com.akiban.sql.optimizer.rule; import java.util.Arrays; import java.util.List; public class DefaultRules { /** These are the rules that get run for normal compilation. */ public static final List<BaseRule> DEFAULT_RULES = Arrays.asList( // These aren't singletons because someday they will have options. new ASTStatementLoader(), new AggregateMapper(), new ConstantFolder(), new OuterJoinPromoter(), new GroupJoinFinder(), new IndexPicker(), new BranchJoiner(), new SelectPreponer(), new OperatorAssembler() ); private DefaultRules() { } }
Update the author name and bump version This new version should fix the problem of installing `typing`.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except Exception: return "" setup( name="todoist-python", version="8.1.3", packages=["todoist", "todoist.managers"], author="Doist Team", author_email="integrations@todoist.com", license="BSD", description="todoist-python - The official Todoist Python API library", long_description=read("README.md"), install_requires=[ "requests", "typing;python_version<'3.5'", ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Programming Language :: Python", ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except Exception: return "" setup( name="todoist-python", version="8.1.2", packages=["todoist", "todoist.managers"], author="Doist Team", author_email="info@todoist.com", license="BSD", description="todoist-python - The official Todoist Python API library", long_description=read("README.md"), install_requires=[ "requests", "typing;python_version<'3.5'", ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Programming Language :: Python", ), )
Fix extension to work with latest state changes Refs flarum/core#2156.
import { extend } from 'flarum/extend'; import DiscussionControls from 'flarum/utils/DiscussionControls'; import DiscussionPage from 'flarum/components/DiscussionPage'; import Button from 'flarum/components/Button'; export default function addLockControl() { extend(DiscussionControls, 'moderationControls', function(items, discussion) { if (discussion.canLock()) { items.add('lock', Button.component({ children: app.translator.trans(discussion.isLocked() ? 'flarum-lock.forum.discussion_controls.unlock_button' : 'flarum-lock.forum.discussion_controls.lock_button'), icon: 'fas fa-lock', onclick: this.lockAction.bind(discussion) })); } }); DiscussionControls.lockAction = function() { this.save({isLocked: !this.isLocked()}).then(() => { if (app.current.matches(DiscussionPage)) { app.current.get('stream').update(); } m.redraw(); }); }; }
import { extend } from 'flarum/extend'; import DiscussionControls from 'flarum/utils/DiscussionControls'; import DiscussionPage from 'flarum/components/DiscussionPage'; import Button from 'flarum/components/Button'; export default function addLockControl() { extend(DiscussionControls, 'moderationControls', function(items, discussion) { if (discussion.canLock()) { items.add('lock', Button.component({ children: app.translator.trans(discussion.isLocked() ? 'flarum-lock.forum.discussion_controls.unlock_button' : 'flarum-lock.forum.discussion_controls.lock_button'), icon: 'fas fa-lock', onclick: this.lockAction.bind(discussion) })); } }); DiscussionControls.lockAction = function() { this.save({isLocked: !this.isLocked()}).then(() => { if (app.current instanceof DiscussionPage) { app.current.stream.update(); } m.redraw(); }); }; }
Tweak wording in Salmon Run gear tweet
const TwitterPostBase = require('./TwitterPostBase'); const { captureSalmonRunGearScreenshot } = require('@/app/screenshots'); const { readData } = require('@/common/utilities'); const moment = require('moment-timezone'); class SalmonRunTweet extends TwitterPostBase { getKey() { return 'salmonrungear'; } getName() { return 'Salmon Run Gear'; } getRewardGear() { let timeline = readData('timeline.json'); return timeline.coop && timeline.coop.reward_gear; } getData() { let rewardGear = this.getRewardGear(); if (rewardGear.available_time == this.getDataTime()) return rewardGear; } getTestData() { return this.getRewardGear(); } getImage(data) { return captureSalmonRunGearScreenshot(data.available_time); } getText(data) { let monthName = moment.unix(data.available_time).tz('UTC').format('MMMM'); return `New Salmon Run reward gear has been posted! ${monthName}'s gear is the ${data.gear.name}. #salmonrun #splatoon2`; } } module.exports = SalmonRunTweet;
const TwitterPostBase = require('./TwitterPostBase'); const { captureSalmonRunGearScreenshot } = require('@/app/screenshots'); const { readData } = require('@/common/utilities'); const moment = require('moment-timezone'); class SalmonRunTweet extends TwitterPostBase { getKey() { return 'salmonrungear'; } getName() { return 'Salmon Run Gear'; } getRewardGear() { let timeline = readData('timeline.json'); return timeline.coop && timeline.coop.reward_gear; } getData() { let rewardGear = this.getRewardGear(); if (rewardGear.available_time == this.getDataTime()) return rewardGear; } getTestData() { return this.getRewardGear(); } getImage(data) { return captureSalmonRunGearScreenshot(data.available_time); } getText(data) { let monthName = moment.unix(data.available_time).tz('UTC').format('MMMM'); return `Next month's Salmon Run reward gear has been posted! ${monthName}'s gear is the ${data.gear.name}. #salmonrun #splatoon2`; } } module.exports = SalmonRunTweet;
Fix the test for FlagSeries
import React from 'react'; import { shallow } from 'enzyme'; import FlagSeries from '../../../src/components/FlagSeries/FlagSeries'; import Series from 'react-jsx-highcharts/src/components/Series'; describe('<FlagSeries />', function () { it('renders a <Series />', function () { const wrapper = shallow(<FlagSeries id="mySeries" />); expect(wrapper).to.have.type(Series); }); it('renders a <Series type="flags" />', function () { const wrapper = shallow(<FlagSeries id="mySeries" />); expect(wrapper).to.have.prop('type').equal('flags'); }); it('passes other props through to <Series />', function () { const wrapper = shallow(<FlagSeries id="myOtherSeries" data={[1, 2, 3, 4]} />); expect(wrapper).to.have.prop('data').eql([1, 2, 3, 4]); }); });
import React from 'react'; import { shallow } from 'enzyme'; import FlagSeries from '../../../src/components/FlagSeries/FlagSeries'; import Series from 'react-jsx-highcharts/src/components/Series'; describe('<FlagSeries />', function () { it('renders a <Series />', function () { const wrapper = shallow(<FlagSeries id="mySeries" />); expect(wrapper).to.have.type(Series); }); it('renders a <Series type="flag" />', function () { const wrapper = shallow(<FlagSeries id="mySeries" />); expect(wrapper).to.have.prop('type').equal('flag'); }); it('passes other props through to <Series />', function () { const wrapper = shallow(<FlagSeries id="myOtherSeries" data={[1, 2, 3, 4]} />); expect(wrapper).to.have.prop('data').eql([1, 2, 3, 4]); }); });
Use the same Gson instance
package com.thuytrinh.transactionviewer.app; import android.content.Context; import android.content.res.Resources; import android.util.Log; import com.google.gson.Gson; import com.thuytrinh.transactionviewer.api.MockRatesFetcher; import com.thuytrinh.transactionviewer.api.MockTransactionsFetcher; import com.thuytrinh.transactionviewer.api.RatesFetcher; import com.thuytrinh.transactionviewer.api.TransactionsFetcher; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.functions.Action1; @Module class AppModule { private final Context context; AppModule(Context context) { this.context = context; } @Provides Resources resources() { return context.getResources(); } @Provides @Singleton Gson gson() { return new Gson(); } @Provides TransactionsFetcher transactionsFetcher(Gson gson) { return new MockTransactionsFetcher(context.getAssets(), gson); } @Provides RatesFetcher ratesFetcher(Gson gson) { return new MockRatesFetcher(context.getAssets(), gson); } @Provides @Singleton Action1<Throwable> errorHandler() { return error -> Log.e(App.class.getSimpleName(), error.getMessage(), error); } }
package com.thuytrinh.transactionviewer.app; import android.content.Context; import android.content.res.Resources; import android.util.Log; import com.google.gson.Gson; import com.thuytrinh.transactionviewer.api.MockRatesFetcher; import com.thuytrinh.transactionviewer.api.MockTransactionsFetcher; import com.thuytrinh.transactionviewer.api.RatesFetcher; import com.thuytrinh.transactionviewer.api.TransactionsFetcher; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.functions.Action1; @Module class AppModule { private final Context context; AppModule(Context context) { this.context = context; } @Provides Resources resources() { return context.getResources(); } @Provides TransactionsFetcher transactionsFetcher() { return new MockTransactionsFetcher(context.getAssets(), new Gson()); } @Provides RatesFetcher ratesFetcher() { return new MockRatesFetcher(context.getAssets(), new Gson()); } @Provides @Singleton Action1<Throwable> errorHandler() { return error -> Log.e(App.class.getSimpleName(), error.getMessage(), error); } }
Use node command instead of running directly
((req) => { const { spawn } = req('child_process'); describe('Server Binary Test', () => { const config = req('./fixtures/karma_single.conf.js'); before(() => { config.files = config.files.concat([ 'tests/fixtures/src/*.js', 'tests/fixtures/tests/*.js', ]); }); it('Should run tests thru process spawn', function spawnTest(done) { this.timeout(3000); const pc = spawn('node', [req.resolve('../bin/server.js')], { stdio: ['pipe', 'inherit', 'pipe'], }); const err = []; pc.stderr.on('data', (data) => { err.push(data); }); pc.on('error', done); pc.on('close', (code, signal) => { if (code || (signal && signal.length) || err.length) { done(new Error( `Karma server exited with Code: ${code}, Signal: ${signal} STDERR: ${err.join('')}` )); return; } done(); }); pc.stdin.end(JSON.stringify(config)); }); }); })(require);
((req) => { const { spawn } = req('child_process'); describe('Server Binary Test', () => { const config = req('./fixtures/karma_single.conf.js'); before(() => { config.files = config.files.concat([ 'tests/fixtures/src/*.js', 'tests/fixtures/tests/*.js', ]); }); it('Should run tests thru process spawn', function spawnTest(done) { this.timeout(3000); const pc = spawn(req.resolve('../bin/server.js'), [], { stdio: ['pipe', 'inherit', 'pipe'], }); const err = []; pc.stderr.on('data', (data) => { err.push(data); }); pc.on('error', done); pc.on('close', (code, signal) => { if (code || (signal && signal.length) || err.length) { done(new Error( `Karma server exited with Code: ${code}, Signal: ${signal} STDERR: ${err.join('')}` )); return; } done(); }); pc.stdin.end(JSON.stringify(config)); }); }); })(require);
Use the right version of python-dateutils when using python 3.
from setuptools import setup import sys version = '2.0.0' if sys.version_info >= (3,): python_dateutils_version = 'python-dateutil>=2.0' else: python_dateutils_version = 'python-dateutil<2.0' setup(name='pyactiveresource', version=version, description='ActiveResource for Python', author='Shopify', author_email='developers@shopify.com', url='https://github.com/Shopify/pyactiveresource/', packages=['pyactiveresource', 'pyactiveresource/testing'], license='MIT License', test_suite='test', tests_require=[ python_dateutils_version, 'PyYAML', ], platforms=['any'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules'] )
from setuptools import setup version = '2.0.0' setup(name='pyactiveresource', version=version, description='ActiveResource for Python', author='Shopify', author_email='developers@shopify.com', url='https://github.com/Shopify/pyactiveresource/', packages=['pyactiveresource', 'pyactiveresource/testing'], license='MIT License', test_suite='test', tests_require=[ 'python-dateutil<2.0', # >= 2.0 is for python>=3.0 'PyYAML', ], platforms=['any'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules'] )
Fix division by two when decrypting (I was actually dividing by 2^e instead of just 2)
// Challenge 46 - RSA parity oracle // http://cryptopals.com/sets/6/challenges/46 package cryptopals import "math/big" type challenge46 struct { } type parityOracleServer struct { priv privateKey } func (server *parityOracleServer) isOdd(c *big.Int) bool { m := server.priv.decrypt(c) mod := big.NewInt(2) mod = mod.Mod(m, mod) return mod.Sign() > 0 } func (challenge46) DecryptRsaParityOracle(server *parityOracleServer, pub *publicKey, c *big.Int) *big.Int { low := big.NewInt(0) high := new(big.Int).Set(pub.n) candidate := new(big.Int).Set(c) two := big.NewInt(2) multiplier := pub.encrypt(two) for low.Cmp(high) < 0 { candidate = candidate.Mul(candidate, multiplier) candidate = candidate.Mod(candidate, pub.n) mid := new(big.Int).Add(low, high) mid = mid.Div(mid, two) if server.isOdd(candidate) { low = mid } else { high = mid } } return high }
// Challenge 46 - RSA parity oracle // http://cryptopals.com/sets/6/challenges/46 package cryptopals import "math/big" type challenge46 struct { } type parityOracleServer struct { priv privateKey } func (server *parityOracleServer) isOdd(c *big.Int) bool { m := server.priv.decrypt(c) mod := big.NewInt(2) mod = mod.Mod(m, mod) return mod.Sign() > 0 } func (challenge46) DecryptRsaParityOracle(server *parityOracleServer, pub *publicKey, c *big.Int) *big.Int { low := big.NewInt(0) high := new(big.Int).Set(pub.n) candidate := new(big.Int).Set(c) two := pub.encrypt(big.NewInt(2)) for low.Cmp(high) < 0 { candidate = candidate.Mul(candidate, two) candidate = candidate.Mod(candidate, pub.n) mid := new(big.Int).Add(low, high) mid = mid.Div(mid, two) if server.isOdd(candidate) { low = mid } else { high = mid } } return high }
Use helma/system.asJavaObject() to prevent allocating new java.lang.Strings in String.toBinary(). git-svn-id: fac99be8204c57f0935f741ea919b5bf0077cdf6@9703 688a9155-6ab5-4160-a077-9df41f55a9e9
var asJavaObject = require('helma/system').asJavaObject; var Binary = exports.Binary = function(bytes) { this.bytes = bytes; }; Binary.prototype.getLength = function() { return this.bytes.length; }; Binary.prototype.toString = function(encoding) { var jstr = encoding ? new java.lang.String(this.bytes, encoding) : new java.lang.String(this.bytes); return String(jstr); }; String.prototype.toBinary = function(encoding) { var bytes = encoding ? asJavaObject(this.toString()).getBytes(encoding) : asJavaObject(this.toString()).getBytes(); return new Binary(bytes); }; Binary.prototype.forEach = function(block) { block(this); }; Binary.prototype.toBinary = function() { return this; };
var Binary = exports.Binary = function(bytes) { this.bytes = bytes; }; Binary.prototype.getLength = function() { return this.bytes.length; }; Binary.prototype.toString = function(encoding) { var jstr = encoding ? new java.lang.String(this.bytes, encoding) : new java.lang.String(this.bytes); return String(jstr); }; String.prototype.toBinary = function(encoding) { var bytes = encoding ? new java.lang.String(this).getBytes(encoding) : new java.lang.String(this).getBytes(); return new Binary(bytes); }; Binary.prototype.forEach = function(block) { block(this); }; Binary.prototype.toBinary = function() { return this; };
Fix mock import for Python 3
"""Tests for github_webhook.webhook""" from __future__ import print_function import unittest try: from unittest.mock import Mock except ImportError: from mock import Mock from github_webhook.webhook import Webhook class TestWebhook(unittest.TestCase): def test_constructor(self): # GIVEN app = Mock() # WHEN webhook = Webhook(app) # THEN app.add_url_rule.assert_called_once_with( '/postreceive', view_func=webhook._postreceive, methods=['POST']) # ----------------------------------------------------------------------------- # Copyright 2015 Bloomberg Finance L.P. # # 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. # ----------------------------- END-OF-FILE -----------------------------------
"""Tests for github_webhook.webhook""" from __future__ import print_function import unittest from mock import Mock from github_webhook.webhook import Webhook class TestWebhook(unittest.TestCase): def test_constructor(self): # GIVEN app = Mock() # WHEN webhook = Webhook(app) # THEN app.add_url_rule.assert_called_once_with( '/postreceive', view_func=webhook._postreceive, methods=['POST']) # ----------------------------------------------------------------------------- # Copyright 2015 Bloomberg Finance L.P. # # 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. # ----------------------------- END-OF-FILE -----------------------------------
Fix validation of url form field value Close #3390
<?php namespace wcf\system\form\builder\field; use wcf\data\language\Language; use wcf\system\form\builder\field\validation\FormFieldValidationError; use wcf\util\Url; /** * Implementation of a form field to enter a url. * * @author Matthias Schmidt * @copyright 2001-2020 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Form\Builder\Field * @since 5.2 */ class UrlFormField extends TextFormField { /** * @inheritDoc */ protected function validateText($text, Language $language = null) { if ($this->isRequired() && ($this->getValue() === null || $this->getValue() === '')) { $this->addValidationError(new FormFieldValidationError('empty')); } else if ($this->getValue() !== null && $this->getValue() !== '') { if (!Url::is($text)) { $this->addValidationError(new FormFieldValidationError( 'invalid', 'wcf.form.field.url.error.invalid', ['language' => $language] )); } else { parent::validateText($text, $language); } } } }
<?php namespace wcf\system\form\builder\field; use wcf\data\language\Language; use wcf\system\form\builder\field\validation\FormFieldValidationError; use wcf\util\Url; /** * Implementation of a form field to enter a url. * * @author Matthias Schmidt * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Form\Builder\Field * @since 5.2 */ class UrlFormField extends TextFormField { /** * @inheritDoc */ protected function validateText($text, Language $language = null) { if ($this->isRequired() && ($this->getValue() === null || $this->getValue() === '')) { if (!Url::is($text)) { $this->addValidationError(new FormFieldValidationError( 'invalid', 'wcf.form.field.url.error.invalid', ['language' => $language] )); } else { parent::validateText($text, $language); } } } }
Add error handling to cache refreshing
<?php namespace App\Console\Commands; use App\Classes\CoinDataService; use Carbon\Carbon; use Illuminate\Console\Command; class RefreshCoinMarketCap extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'cache:refresh-cmc'; /** * The console command description. * * @var string */ protected $description = 'Refetches data from CoinMarketCap'; protected $coinDataService; /** * Create a new command instance. * * @return void */ public function __construct(CoinDataService $coinDataService) { parent::__construct(); $this->coinDataService = $coinDataService; } /** * Execute the console command. * * @return mixed */ public function handle() { if ($this->coinDataService->createProvider('CoinMarketCap')->getData(true)) { } else { $this->error(Carbon::now() . ' - There was a problem with refreshing CoinMarketCap data.'); }; } }
<?php namespace App\Console\Commands; use App\Classes\CoinDataService; use Illuminate\Console\Command; class RefreshCoinMarketCap extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'cache:refresh-cmc'; /** * The console command description. * * @var string */ protected $description = 'Refetches data from CoinMarketCap'; protected $coinDataService; /** * Create a new command instance. * * @return void */ public function __construct(CoinDataService $coinDataService) { parent::__construct(); $this->coinDataService = $coinDataService; } /** * Execute the console command. * * @return mixed */ public function handle() { $test = $this->coinDataService->createProvider('CoinMarketCap')->getData(true); } }
Add modal for ipad links
<?php function ipadPopUpScript(){ ?> jQuery("a[href$='http://bullettstoreat.wpengine.com/p/ipad-magazine-subscription/']").attr('data-reveal-id', 'ipadPopUp'); <?php } function ipadPopUpModal(){ ?> jQuery('#colophon').after('<div id="ipadPopUp" class="reveal-modal"><h2>We'+ 'are opening a new tab.</h2><p class="lead">The following link will open a'+ ' new window to the iTunes AppStore. You can subscribe to the Bullett maga'+ 'zine from there.</p><p>If you have any items in your shopping cart, they '+ 'won\'t go anywhere (as long as you don\'t close the window).</p><a href="'+ 'https://itunes.apple.com/us/app/bullett/id557294227?mt=8" class="button" '+ 'target="_blank"><\/a><a class="close-reveal-modal">&#215;<\/a><\/div>'); <?php } function PopUpModal(){ ?> <script> ipadPopUpScript(); ipadPopUpModal(); </script> <?php } add_action('wp_footer', 'PopUpModal', 33); ?>
<?php function ipadPopUpScript(){ ?> <script> jQuery("a[href$='http://bullettstoreat.wpengine.com/p/ipad-magazine-subscription/']").attr('data-reveal-id', 'ipadPopUp'); </script> <?php } function ipadPopUpModal(){ ?> jQuery('#colophon').after('<div id="ipadPopUp" class="reveal-modal"><h2>We'+ 'are opening a new tab.</h2><p class="lead">The following link will open a'+ ' new window to the iTunes AppStore. You can subscribe to the Bullett maga'+ 'zine from there.</p><p>If you have any items in your shopping cart, they '+ 'won\'t go anywhere (as long as you don\'t close the window).</p><a href="'+ 'https://itunes.apple.com/us/app/bullett/id557294227?mt=8" class="button" '+ 'target="_blank"><\/a><a class="close-reveal-modal">&#215;<\/a><\/div>'); <?php } function PopUpModal(){ ipadPopUpScript(); ipadPopUpModal(); } add_action('wp_footer', 'PopUpModal', 33); ?>
Comment out broken subscriber for now
<?php /** * This file is part of Bootstrap CMS by Graham Campbell. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. */ use GrahamCampbell\BootstrapCMS\Facades\PageRepository; /* |-------------------------------------------------------------------------- | Application Event Listeners |-------------------------------------------------------------------------- | | Here is where you can register all of the listeners for an application. | */ if (Config::get('graham-campbell/core::commands')) { $subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\CommandSubscriber'); Event::subscribe($subscriber); } // $subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\CoreSubscriber'); // Event::subscribe($subscriber); $subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\NavigationSubscriber'); Event::subscribe($subscriber); $observer = App::make('GrahamCampbell\BootstrapCMS\Observers\PageObserver'); PageRepository::observe($observer);
<?php /** * This file is part of Bootstrap CMS by Graham Campbell. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. */ use GrahamCampbell\BootstrapCMS\Facades\PageRepository; /* |-------------------------------------------------------------------------- | Application Event Listeners |-------------------------------------------------------------------------- | | Here is where you can register all of the listeners for an application. | */ if (Config::get('graham-campbell/core::commands')) { $subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\CommandSubscriber'); Event::subscribe($subscriber); } $subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\CoreSubscriber'); Event::subscribe($subscriber); $subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\NavigationSubscriber'); Event::subscribe($subscriber); $observer = App::make('GrahamCampbell\BootstrapCMS\Observers\PageObserver'); PageRepository::observe($observer);
Make Node\Expr\BinOp an abstract class Only the children should be used ...
<?php namespace PhpParser\Node\Expr; use PhpParser\Node\Expr; /** * @property Expr $left The left hand side expression * @property Expr $right The right hand side expression */ abstract class BinaryOp extends Expr { /** * Constructs a bitwise and node. * * @param Expr $left The left hand side expression * @param Expr $right The right hand side expression * @param array $attributes Additional attributes */ public function __construct(Expr $left, Expr $right, array $attributes = array()) { parent::__construct( array( 'left' => $left, 'right' => $right ), $attributes ); } }
<?php namespace PhpParser\Node\Expr; use PhpParser\Node\Expr; /** * @property Expr $left The left hand side expression * @property Expr $right The right hand side expression */ class BinaryOp extends Expr { /** * Constructs a bitwise and node. * * @param Expr $left The left hand side expression * @param Expr $right The right hand side expression * @param array $attributes Additional attributes */ public function __construct(Expr $left, Expr $right, array $attributes = array()) { parent::__construct( array( 'left' => $left, 'right' => $right ), $attributes ); } }
Move OAuth down in admin security settings For #16076 Signed-off-by: Roeland Jago Douma <982d370f7dc34a05b4abe8788f899578d515262d@famdouma.nl>
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OCA\OAuth2\Settings; use OCP\AppFramework\Http\TemplateResponse; use OCP\Settings\ISettings; class Admin implements ISettings { public function getForm(): TemplateResponse { return new TemplateResponse( 'oauth2', 'admin', [], '' ); } public function getSection(): string { return 'security'; } public function getPriority(): int { return 100; } }
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OCA\OAuth2\Settings; use OCP\AppFramework\Http\TemplateResponse; use OCP\Settings\ISettings; class Admin implements ISettings { public function getForm(): TemplateResponse { return new TemplateResponse( 'oauth2', 'admin', [], '' ); } public function getSection(): string { return 'security'; } public function getPriority(): int { return 0; } }
Set title instead of desc.
const { Command } = require('discord-akairo'); const { RichEmbed } = require('discord.js'); function exec(message, args){ args.content = isNaN(args.content) ? args.content : parseInt(args.content); const embed = new RichEmbed().setColor(args.content); let hex = isNaN(embed.color) ? '0' : embed.color.toString(16); hex = '#' + '0'.repeat(6 - hex.length) + hex; embed.setTitle(hex.toUpperCase()); return message.edit('', { embed }); } module.exports = new Command('color', exec, { aliases: ['color', 'colour'], args: [ { id: 'content', match: 'content', defaultValue: () => (1 << 24) * Math.random() | 0 } ] });
const { Command } = require('discord-akairo'); const { RichEmbed } = require('discord.js'); function exec(message, args){ args.content = isNaN(args.content) ? args.content : parseInt(args.content); const embed = new RichEmbed().setColor(args.content); let hex = isNaN(embed.color) ? '0' : embed.color.toString(16); hex = '#' + '0'.repeat(6 - hex.length) + hex; embed.setDescription(hex.toUpperCase()); return message.edit('', { embed }); } module.exports = new Command('color', exec, { aliases: ['color', 'colour'], args: [ { id: 'content', match: 'content', defaultValue: () => (1 << 24) * Math.random() | 0 } ] });
Allow files to be uploaded through the TastyPie API
import tastypie.resources import tastypie.authentication import tastypie.fields import django.contrib.auth.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] always_return_data = True authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.author = django.contrib.auth.models.User.objects.get(pk=bundle.request.user.id) return bundle def deserialize(self, request, data, format=None): if not format: format = request.META.get('CONTENT_TYPE', 'application/json') if format == 'application/x-www-form-urlencoded': return request.POST if format.startswith('multipart'): data = request.POST.copy() data.update(request.FILES) return data return super(FileResource, self).deserialize(request, data, format)
import tastypie.resources import tastypie.authentication import django.db.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.owner = django.db.models.User.objects.get(pk=bundle.request.user.id) return bundle
Revert "Use string as underlining data type" This reverts commit 286b63f64eb31716c766891614ae38a4af7f3100.
package charts import "bytes" type ChartType int const ( UnknownChart ChartType = iota SimpleBar SimpleLine ) type DataType int type DataTypes []DataType const ( UnknownType DataType = iota Text Number Time ) var charts map[string]ChartType func sequence(types DataTypes) string { var seq bytes.Buffer for _, t := range types { seq.WriteString(t.String()) } return seq.String() } func Detect(types DataTypes) ChartType { if chart, ok := charts[sequence(types)]; ok { return chart } return UnknownChart } func (ct ChartType) String() string { switch ct { case SimpleBar: return "SimpleBar" case SimpleLine: return "SimpleLine" } return "UnknownChart" } func (t DataType) String() string { switch t { case Text: return "Text" case Number: return "Number" case Time: return "Time" } return "Unknown" } func init() { charts = make(map[string]ChartType) charts[sequence(DataTypes{Text, Number})] = SimpleBar charts[sequence(DataTypes{Number, Number})] = SimpleBar charts[sequence(DataTypes{Time, Number})] = SimpleLine }
package charts import "bytes" type ChartType string const ( UnknownChart ChartType = "UnknownChart" SimpleBar ChartType = "SimpleBar" SimpleLine ChartType = "SimpleLine" ) type DataType string type DataTypes []DataType const ( UnknownType DataType = "UnknownType" Text DataType = "Text" Number DataType = "Number" Time DataType = "Time" ) var charts map[string]ChartType func sequence(types DataTypes) string { var seq bytes.Buffer for _, t := range types { seq.WriteString(t.String()) } return seq.String() } func Detect(types DataTypes) ChartType { if chart, ok := charts[sequence(types)]; ok { return chart } return UnknownChart } func (ct ChartType) String() string { return string(ct) } func (t DataType) String() string { return string(t) } func init() { charts = make(map[string]ChartType) charts[sequence(DataTypes{Text, Number})] = SimpleBar charts[sequence(DataTypes{Number, Number})] = SimpleBar charts[sequence(DataTypes{Time, Number})] = SimpleLine }
Fix tag update when there's no tag
(function() { 'use strict'; angular.module('dimApp').component('dimItemTag', { controller: ItemTagController, bindings: { item: '=' }, template: ` <select ng-options="tag as tag.label | translate for tag in $ctrl.settings.itemTags track by tag.type" ng-model="$ctrl.selected" ng-change="$ctrl.updateTag()"></select> ` }); ItemTagController.$inject = ['$scope', '$rootScope', 'dimSettingsService']; function ItemTagController($scope, $rootScope, dimSettingsService) { var vm = this; vm.settings = dimSettingsService; $scope.$watch('$ctrl.item.dimInfo.tag', function() { vm.selected = _.find(vm.settings.itemTags, function(tag) { return tag.type === vm.item.dimInfo.tag; }); }); vm.updateTag = function() { vm.item.dimInfo.tag = vm.selected.type; $rootScope.$broadcast('dim-filter-invalidate'); vm.item.dimInfo.save(); }; $scope.$on('dim-item-tag', (e, args) => { if (vm.item.dimInfo.tag === args.tag) { delete vm.item.dimInfo.tag; } else { vm.item.dimInfo.tag = args.tag; } $rootScope.$broadcast('dim-filter-invalidate'); vm.item.dimInfo.save(); }); } })();
(function() { 'use strict'; angular.module('dimApp').component('dimItemTag', { controller: ItemTagController, bindings: { item: '=' }, template: ` <select ng-options="tag as tag.label | translate for tag in $ctrl.settings.itemTags track by tag.type" ng-model="$ctrl.selected" ng-change="$ctrl.updateTag()"></select> ` }); ItemTagController.$inject = ['$scope', '$rootScope', 'dimSettingsService']; function ItemTagController($scope, $rootScope, dimSettingsService) { var vm = this; vm.settings = dimSettingsService; $scope.$watch(() => vm.item.dimInfo.tag, function() { vm.selected = _.find(vm.settings.itemTags, function(tag) { return tag.type === vm.item.dimInfo.tag; }); }); vm.updateTag = function() { vm.item.dimInfo.tag = vm.selected.type; $rootScope.$broadcast('dim-filter-invalidate'); vm.item.dimInfo.save(); }; $scope.$on('dim-item-tag', (e, args) => { if (vm.item.dimInfo.tag === args.tag) { delete vm.item.dimInfo.tag; } else { vm.item.dimInfo.tag = args.tag; } $rootScope.$broadcast('dim-filter-invalidate'); vm.item.dimInfo.save(); }); } })();