text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Rename `get_user` to `get_or_create_user` and add a new `get_user`
from django.contrib.auth.models import User from nightreads.posts.models import Tag from .models import (Subscription, SubscriptionActivation, UnsubscriptionActivation) def update_user_tags(user, tags): tags_objs = Tag.objects.filter(name__in=tags) if tags_objs: user.subscription.tags.clear() user.subscription.tags.add(*tags_objs) user.save() return True return False def get_or_create_user(email): user, created = User.objects.get_or_create(username=email) if created: Subscription.objects.create(user=user) return user def get_user(email): return User.objects.filter(username=email).first() def generate_subscribe_key(user): subscribe_key = User.objects.make_random_password(length=80) SubscriptionActivation.objects.update_or_create( user=user, defaults={'subscribe_key': subscribe_key}) return subscribe_key def generate_unsubscribe_key(user): unsubscribe_key = User.objects.make_random_password(length=80) UnsubscriptionActivation.objects.update_or_create( user=user, defaults={'unsubscribe_key': unsubscribe_key}) return unsubscribe_key def update_subscription(user, status): user.subscription.is_subscribed = status user.save()
from django.contrib.auth.models import User from nightreads.posts.models import Tag from .models import (Subscription, SubscriptionActivation, UnsubscriptionActivation) def update_user_tags(user, tags): tags_objs = Tag.objects.filter(name__in=tags) if tags_objs: user.subscription.tags.clear() user.subscription.tags.add(*tags_objs) user.save() return True return False def get_user(email): user, created = User.objects.get_or_create(username=email) if created: Subscription.objects.create(user=user) return user def generate_subscribe_key(user): subscribe_key = User.objects.make_random_password(length=80) SubscriptionActivation.objects.update_or_create( user=user, defaults={'subscribe_key': subscribe_key}) return subscribe_key def generate_unsubscribe_key(user): unsubscribe_key = User.objects.make_random_password(length=80) UnsubscriptionActivation.objects.update_or_create( user=user, defaults={'unsubscribe_key': unsubscribe_key}) return unsubscribe_key
Call setter even if object isn't writable.
"use strict"; /* @flow */ const Value = require('../Value'); let serial = 0; //TODO: We should call this a PropertyDescriptor, not a variable. class PropertyDescriptor { constructor(value) { this.value = value; this.serial = serial++; this.configurable = true; this.enumerable = true; this.writeable = true; } set(value) { if ( !this.writeable ) return; this.value = value; } *getValue(thiz) { thiz = thiz || Value.null; if ( this.getter ) { return yield * this.getter.call(thiz, []); } return this.value; } *setValue(thiz, to) { thiz = thiz || Value.null; if ( this.getter ) { return yield * this.setter.call(thiz, [to]); } if ( !this.writeable ) return this.value; this.value = to; return this.value; } } module.exports = PropertyDescriptor;
"use strict"; /* @flow */ const Value = require('../Value'); let serial = 0; //TODO: We should call this a PropertyDescriptor, not a variable. class PropertyDescriptor { constructor(value) { this.value = value; this.serial = serial++; this.configurable = true; this.enumerable = true; this.writeable = true; } set(value) { if ( !this.writeable ) return; this.value = value; } *getValue(thiz) { thiz = thiz || Value.null; if ( this.getter ) { return yield * this.getter.call(thiz, []); } return this.value; } *setValue(thiz, to) { if ( !this.writeable ) return; thiz = thiz || Value.null; if ( this.getter ) { return yield * this.setter.call(thiz, [to]); } this.value = to; return this.value; } } module.exports = PropertyDescriptor;
Remove console.log call for debugging
'use strict' const mongoose = require('mongoose') const api = require('./api') const trends = require('./twitter/trends') const config = require('./config') const mainUtils = require('./utils/main-utils') const TweetStream = require('./twitter/tweet-stream') mongoose.Promise = global.Promise // Connect to the db, then set up the intervalFunction var db = mongoose.connection db.on('error', console.error) db.once('open', () => { console.log('Successfully connected to mongodb') // Run the intervalFunction when the backend starts intervalFunction() // Then set up intervalFunction to run each server interval setInterval(intervalFunction, config.intervalLength * 1000) api.start() }) mongoose.connect('mongodb://' + config.dbAddress + '/' + config.dbName) /** * Function run once every server interval, gets trends from the * Twitter API, news from the news API and stores all relavant * information in the database. * */ var tweetStream = new TweetStream() function intervalFunction () { // At the beginning of each interval get all trends trends.getTrends() // Then update the trend info in the database .then(trends => { mainUtils.update(trends, tweetStream) tweetStream.closeStream() tweetStream.startTracking(trends.map(trendData => { return trendData.name })) }) }
'use strict' const mongoose = require('mongoose') const api = require('./api') const trends = require('./twitter/trends') const config = require('./config') const mainUtils = require('./utils/main-utils') const TweetStream = require('./twitter/tweet-stream') mongoose.Promise = global.Promise // Connect to the db, then set up the intervalFunction var db = mongoose.connection db.on('error', console.error) db.once('open', () => { console.log('Successfully connected to mongodb') // Run the intervalFunction when the backend starts intervalFunction() // Then set up intervalFunction to run each server interval setInterval(intervalFunction, config.intervalLength * 1000) api.start() }) mongoose.connect('mongodb://' + config.dbAddress + '/' + config.dbName) /** * Function run once every server interval, gets trends from the * Twitter API, news from the news API and stores all relavant * information in the database. * */ var tweetStream = new TweetStream() function intervalFunction () { console.log('interval') // At the beginning of each interval get all trends trends.getTrends() // Then update the trend info in the database .then(trends => { mainUtils.update(trends, tweetStream) tweetStream.closeStream() tweetStream.startTracking(trends.map(trendData => { return trendData.name })) }) }
Add default checked = false state to models
/** * Collection for interfacing with localStorage. */ 'use strict'; var Backbone = require('backbone'); var _ = require('lodash'); module.exports = Backbone.Collection.extend({ model: Backbone.Model, initialize: function() { this.localStorage = window.localStorage; }, fetch: function() { var history = []; var session = {}; var keys = Object.keys(this.localStorage); for (var i = 0; i < keys.length; i++) { session = {}; session.id = keys[i]; session.tree = JSON.parse(this.localStorage.getItem(this.localStorage.key(i))); history.push(session); } this.parse(history); this.trigger('sync'); }, parse: function(history) { _.each(history, _.bind(function(session) { session.checked = false; this.add(session); }, this)); }, getLatest: function() { this.fetch(); var len = this.models.length; return this.models[len-1]; } });
/** * Collection for interfacing with localStorage. */ 'use strict'; var Backbone = require('backbone'); var _ = require('lodash'); module.exports = Backbone.Collection.extend({ model: Backbone.Model, initialize: function() { this.localStorage = window.localStorage; }, fetch: function() { var history = []; var session = {}; var keys = Object.keys(this.localStorage); for (var i = 0; i < keys.length; i++) { session = {}; session.id = keys[i]; session.tree = JSON.parse(this.localStorage.getItem(this.localStorage.key(i))); history.push(session); } this.parse(history); this.trigger('sync'); }, parse: function(history) { _.each(history, _.bind(function(session) { this.add(session); }, this)); }, getLatest: function() { this.fetch(); var len = this.models.length; return this.models[len-1]; } });
Make trac related tasks available in fab
""" Collection of utilities to automate the administration of Twisted's infrastructure. Use this utility to install, update and start/stop/restart services running on twistedmatrix.com. """ """ This file is a simple entry point, nothing is final about it! Just experimenting for now. """ from fabric.api import task, sudo from fablib import package, service, load_config, requires_root from services import dns, trac __all__ = ['dns', 'trac', 'make_service_admin'] load_config('config') # TODO: Add hooks to check if updated to upstream before running any command @task @requires_root def install_exim(): package.install('exim4') service.enable('exim4') @task @requires_root def make_service_admin(username): """ Simply add the given user to the 'service-admin' group. This allows the user to execute any command as any service-specific user through sudo. """ sudo('usermod -a -G service-admin {}'.format(username))
""" Collection of utilities to automate the administration of Twisted's infrastructure. Use this utility to install, update and start/stop/restart services running on twistedmatrix.com. """ """ This file is a simple entry point, nothing is final about it! Just experimenting for now. """ from fabric.api import task, sudo from fablib import package, service, load_config, requires_root from services import dns __all__ = ['dns'] load_config('config') # TODO: Add hooks to check if updated to upstream before running any command @task @requires_root def install_exim(): package.install('exim4') service.enable('exim4') @task @requires_root def make_service_admin(username): """ Simply add the given user to the 'service-admin' group. This allows the user to execute any command as any service-specific user through sudo. """ sudo('usermod -a -G service-admin {}'.format(username))
:bug: Fix inline query handler creation
const { inline, roll, full, random, help, deprecated } = require('./query'); const { createOptions, createInlineOptions } = require('./options'); const { error } = require('./text'); /* More event type are described in official API of `node-telegram-bot-api` https://github.com/yagop/node-telegram-bot-api/blob/master/doc/usage.md */ function createHandler(bot, query) { const { regexp, reply } = query; bot.onText(regexp, (msg, match) => { try { const { id } = msg.chat; const notation = ((match && match[3]) || '').trim(); const response = reply(notation) || error; const options = createOptions(msg); bot.sendMessage(id, response, options); } catch (e) { console.error(e); } }); } function createInlineHandler(bot) { const { createInlineArticles } = inline; bot.on('inline_query', msg => { try { const { id, query } = msg; const options = createInlineOptions(); const results = createInlineArticles(query); bot.answerInlineQuery(id, results, options); } catch (e) { console.error(e); } }); } function initHandlers(bot) { createInlineHandler(bot); createHandler(bot, roll); createHandler(bot, full); createHandler(bot, random); createHandler(bot, help); createHandler(bot, deprecated); } module.exports = { initHandlers };
const { inline, roll, full, random, help, deprecated } = require('./query'); const { createOptions, createInlineOptions } = require('./options'); const { error } = require('./text'); function createHandler(bot, query) { const { regexp, reply } = query; bot.onText(regexp, (msg, match) => { try { const { id } = msg.chat; const notation = ((match && match[3]) || '').trim(); const response = reply(notation) || error; const options = createOptions(msg); bot.sendMessage(id, response, options); } catch (e) { console.error(e); } }); } function createInlineHandler(bot) { const { createInlineArticles } = inline; bot.onText('inline_query', msg => { try { const { id, query } = msg; const options = createInlineOptions(); const results = createInlineArticles(query); bot.answerInlineQuery(id, results, options); } catch (e) { console.error(e); } }); } function initHandlers(bot) { createInlineHandler(bot); createHandler(bot, roll); createHandler(bot, full); createHandler(bot, random); createHandler(bot, help); createHandler(bot, deprecated); } module.exports = { initHandlers };
Remove unused NoScoreIdx methods from index interface
<?php namespace Ehann\RediSearch; use Ehann\RediSearch\Document\BuilderInterface as DocumentBuilderInterface; use Ehann\RediSearch\Document\Document; use Ehann\RediSearch\Query\BuilderInterface as QueryBuilderInterface; use Ehann\RediSearch\Redis\RedisClient; interface IndexInterface extends DocumentBuilderInterface, QueryBuilderInterface { public function create(); public function drop(); public function info(); public function delete($id); public function makeDocument($id = null): Document; public function getRedisClient(): RedisClient; public function setRedisClient(RedisClient $redisClient): IndexInterface; public function getIndexName(): string; public function setIndexName(string $indexName): IndexInterface; public function isNoOffsetsEnabled(): bool; public function setNoOffsetsEnabled(bool $noOffsetsEnabled): IndexInterface; public function isNoFieldsEnabled(): bool; public function setNoFieldsEnabled(bool $noFieldsEnabled): IndexInterface; public function addTextField(string $name, float $weight = 1.0): IndexInterface; public function addNumericField(string $name): IndexInterface; public function addGeoField(string $name): IndexInterface; }
<?php namespace Ehann\RediSearch; use Ehann\RediSearch\Document\BuilderInterface as DocumentBuilderInterface; use Ehann\RediSearch\Document\Document; use Ehann\RediSearch\Query\BuilderInterface as QueryBuilderInterface; use Ehann\RediSearch\Redis\RedisClient; interface IndexInterface extends DocumentBuilderInterface, QueryBuilderInterface { public function create(); public function drop(); public function info(); public function delete($id); public function makeDocument($id = null): Document; public function getRedisClient(): RedisClient; public function setRedisClient(RedisClient $redisClient): IndexInterface; public function getIndexName(): string; public function setIndexName(string $indexName): IndexInterface; public function isNoOffsetsEnabled(): bool; public function setNoOffsetsEnabled(bool $noOffsetsEnabled): IndexInterface; public function isNoFieldsEnabled(): bool; public function setNoFieldsEnabled(bool $noFieldsEnabled): IndexInterface; public function isNoScoreIdxEnabled(): bool; public function setNoScoreIdxEnabled(bool $noScoreIdxEnabled): IndexInterface; public function addTextField(string $name, float $weight = 1.0): IndexInterface; public function addNumericField(string $name): IndexInterface; public function addGeoField(string $name): IndexInterface; }
Move stdout/stderr null warning out
'use strict' const path = require('path') const {spawnSync} = require('child_process') const { env: { STANDARDJS_EXECUTABLE, STANDARDJS_ARGV, SKIP_CODE_STYLE_CHECKING } } = require('process') const wdir = path.resolve(__dirname, '..') test('JavaScript Code Style: StandardJS', () => { if (SKIP_CODE_STYLE_CHECKING === 'true') return const argv = STANDARDJS_ARGV ? JSON.parse(STANDARDJS_ARGV) : [] expect(argv).toBeInstanceOf(Array) const {stdout, stderr, status} = spawnSync(STANDARDJS_EXECUTABLE || 'standard', argv, {cwd: wdir}) if (stdout === null) console.warn('standard.stdout is null') if (stderr === null) console.warn('standard.stderr is null') if (status) { throw new Error(stderr + '\n' + stdout) } })
'use strict' const path = require('path') const {spawnSync} = require('child_process') const { env: { STANDARDJS_EXECUTABLE, STANDARDJS_ARGV, SKIP_CODE_STYLE_CHECKING } } = require('process') const wdir = path.resolve(__dirname, '..') test('JavaScript Code Style: StandardJS', () => { if (SKIP_CODE_STYLE_CHECKING === 'true') return const argv = STANDARDJS_ARGV ? JSON.parse(STANDARDJS_ARGV) : [] expect(argv).toBeInstanceOf(Array) const {stdout, stderr, status} = spawnSync(STANDARDJS_EXECUTABLE || 'standard', argv, {cwd: wdir}) if (status) { if (stdout === null) console.warn('standard.stdout is null') if (stderr === null) console.warn('standard.stderr is null') throw new Error(stderr + '\n' + stdout) } })
Add ValueLink To On Change For Timepicker
let React = require("react") let cx = require("classnames") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, input} = React.DOM export default class extends React.Component { static displayName = "Frig.friggingBootstrap.TimePicker" static defaultProps = Object.assign(require("../default_props.js")) _input() { return input(Object.assign({}, this.props.inputHtml, { valueLink: { value: this.props.valueLink.value, requestChange: this._onTimeChange, }, className: cx(this.props.inputHtml.className, "form-control"), }) ) } _onTimeChange(newTime) { console.log(`New Time ${newTime}`) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: formGroupCx(this.props)}, div({}, label(this.props) ), this._input(), errorList(this.props.errors), ), ) } }
let React = require("react") let cx = require("classnames") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, input} = React.DOM export default class extends React.Component { static displayName = "Frig.friggingBootstrap.TimePicker" static defaultProps = Object.assign(require("../default_props.js")) _input() { return input(Object.assign({}, this.props.inputHtml, { valueLink: this.props.valueLink, className: cx(this.props.inputHtml.className, "form-control"), }) ) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: formGroupCx(this.props)}, div({}, label(this.props) ), this._input(), errorList(this.props.errors), ), ) } }
Use np.genfromtext to handle missing values
#!/usr/bin/env python # encoding: utf-8 """ Reader for XVISTA .prof tables. """ import numpy as np from astropy.table import Table from astropy.io import registry def xvista_table_reader(filename): dt = [('R', np.float), ('SB', np.float), ('SB_err', np.float), ('ELL', np.float), ('PA', np.float), ('EMAG', np.float), ('ELLMAG', np.float), ('ELLMAG_err', np.float), ('XC', np.float), ('YC', np.float), ('FRACONT', np.float), ('A1', np.float), ('A2', np.float), ('A4', np.float), ('CIRCMAG', np.float)] data = np.genfromtxt(filename, dtype=np.dtype(dt), skiprows=15, missing_values='*', filling_values=np.nan) return Table(data) registry.register_reader('xvistaprof', Table, xvista_table_reader)
#!/usr/bin/env python # encoding: utf-8 """ Reader for XVISTA .prof tables. """ import numpy as np from astropy.table import Table from astropy.io import registry def xvista_table_reader(filename): dt = [('R', np.float), ('SB', np.float), ('SB_err', np.float), ('ELL', np.float), ('PA', np.float), ('EMAG', np.float), ('ELLMAG', np.float), ('ELLMAG_err', np.float), ('XC', np.float), ('YC', np.float), ('FRACONT', np.float), ('A1', np.float), ('A2', np.float), ('A4', np.float), ('CIRCMAG', np.float)] data = np.loadtxt(filename, dtype=np.dtype(dt), skiprows=15) return Table(data) registry.register_reader('xvistaprof', Table, xvista_table_reader)
Set class process site map
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Opps') settings.INSTALLED_APPS += ( 'opps.article', 'opps.image', 'opps.channel', 'opps.source', 'django.contrib.redirects', 'django_thumbor', 'googl', 'redactor', 'static_sitemaps', 'tagging',) settings.MIDDLEWARE_CLASSES += ( 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',) # Opps getattr(settings, 'OPPS_SHORT', 'googl') getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort') # Sitemap if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'): settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps' # redactor getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'}) getattr(settings, 'REDACTOR_UPLOAD', 'uploads/') # thumbor getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888') getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media') getattr(settings, 'THUMBOR_SECURITY_KEY', '')
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Opps') settings.INSTALLED_APPS += ( 'opps.article', 'opps.image', 'opps.channel', 'opps.source', 'django.contrib.redirects', 'django_thumbor', 'googl', 'redactor', 'tagging',) settings.MIDDLEWARE_CLASSES += ( 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',) # Opps getattr(settings, 'OPPS_SHORT', 'googl') getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort') # redactor getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'}) getattr(settings, 'REDACTOR_UPLOAD', 'uploads/') # thumbor getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888') getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media') getattr(settings, 'THUMBOR_SECURITY_KEY', '')
Support for external plugin js script added.
<?php namespace App\Libs; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use App\Libs\ViewResolver; use Illuminate\Http\Request; abstract class Controller extends BaseController{ use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct(Request $request,ViewResolver $viewResolver){ $this->request = $request; $this->view = $viewResolver; if(app()->isInstalled()){ foreach(app()->plugins as $plugin){ foreach($plugin->getRegister('injectJs',[]) as $js){ $this->view->data['jsplugins'][] = str_contains($js,"http")? $js : $plugin->getPath().'/'.$js; } } } } public function redirect($location){ return redirect($location); } public function redirectToSelf(){ return redirect()->back(); } public function insideLink($location){ return redirect(\Config::get('horizontcms.backend_prefix')."/".$location); } }
<?php namespace App\Libs; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use App\Libs\ViewResolver; use Illuminate\Http\Request; abstract class Controller extends BaseController{ use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct(Request $request,ViewResolver $viewResolver){ $this->request = $request; $this->view = $viewResolver; if(app()->isInstalled()){ foreach(app()->plugins as $plugin){ foreach($plugin->getRegister('injectJs',[]) as $js){ $this->view->data['jsplugins'][] = $plugin->getPath().'/'.$js; } } } } public function redirect($location){ return redirect($location); } public function redirectToSelf(){ return redirect()->back(); } public function insideLink($location){ return redirect(\Config::get('horizontcms.backend_prefix')."/".$location); } }
Add origin address to build-index configuration Summary: Somehow this never got populated. We now validate that the origin address is non-empty on startup, so this was causing build-index to crash. Reviewers: #kraken, yiran, evelynl Reviewed By: #kraken, yiran, evelynl Subscribers: jenkins Differential Revision: https://code.uberinternal.com/D1823933
package tagreplication import ( "fmt" "io/ioutil" "os" "path/filepath" "code.uber.internal/infra/kraken/core" "code.uber.internal/infra/kraken/utils/randutil" "code.uber.internal/infra/kraken/utils/testutil" ) // StoreFixture creates a fixture of tagreplication.Store. func StoreFixture(rv RemoteValidator) (*Store, string, func()) { var cleanup testutil.Cleanup defer cleanup.Recover() tmpDir, err := ioutil.TempDir(".", "test-store-") if err != nil { panic(err) } cleanup.Add(func() { os.RemoveAll(tmpDir) }) source := filepath.Join(tmpDir, "test.db") store, err := NewStore(source, rv) if err != nil { panic(err) } cleanup.Add(func() { store.Close() }) return store, source, cleanup.Run } // TaskFixture creates a fixture of tagreplication.Task. func TaskFixture() *Task { tag := core.TagFixture() d := core.DigestFixture() dest := fmt.Sprintf("build-index-%s", randutil.Hex(8)) return NewTask(tag, d, core.DigestListFixture(3), dest) }
package tagreplication import ( "fmt" "io/ioutil" "os" "path/filepath" "code.uber.internal/infra/kraken/core" "code.uber.internal/infra/kraken/utils/randutil" "code.uber.internal/infra/kraken/utils/testutil" ) // StoreFixture creates a fixture of tagreplication.Store. func StoreFixture(rv RemoteValidator) (*Store, string, func()) { var cleanup testutil.Cleanup defer cleanup.Recover() tmpDir, err := ioutil.TempDir(".", "test-store-") if err != nil { panic(err) } cleanup.Add(func() { os.RemoveAll(tmpDir) }) source := filepath.Join(tmpDir, "test.db") store, err := NewStore(source, rv) if err != nil { panic(err) } cleanup.Add(func() { store.Close() }) return store, source, cleanup.Run } // TaskFixture creates a fixture of tagreplication.Task. func TaskFixture() *Task { id := randutil.Text(4) tag := fmt.Sprintf("prime/labrat-%s", id) d := core.DigestFixture() dest := fmt.Sprintf("build-index-%s", id) return NewTask(tag, d, core.DigestListFixture(3), dest) }
Remove the comments from the generated UMD files
// @ts-check import typescript from 'rollup-plugin-typescript2'; import uglify from 'rollup-plugin-uglify'; import gzip from 'rollup-plugin-gzip'; import filesize from 'rollup-plugin-filesize'; const __PROD__ = process.env.NODE_ENV === 'production'; function outputFileName() { let fileName = `react-form-with-constraints.${process.env.NODE_ENV}`; fileName += __PROD__ ? '.min.js' : '.js'; return fileName; } export default { input: './src/index.ts', output: { file: `dist/${outputFileName()}`, name: 'ReactFormWithConstraints', format: 'umd', sourcemap: true }, external: ['react', 'react-dom', 'prop-types'], globals: { react: 'React', 'react-dom': 'ReactDOM', 'prop-types': 'PropTypes' }, plugins: [ typescript({ abortOnError: false, clean: true, tsconfigOverride: {compilerOptions: {module: 'esnext', declaration: false, removeComments: true}} }), __PROD__ && uglify(), gzip({algorithm: 'zopfli'}), filesize() ] };
// @ts-check import typescript from 'rollup-plugin-typescript2'; import uglify from 'rollup-plugin-uglify'; import gzip from 'rollup-plugin-gzip'; import filesize from 'rollup-plugin-filesize'; const __PROD__ = process.env.NODE_ENV === 'production'; function outputFileName() { let fileName = `react-form-with-constraints.${process.env.NODE_ENV}`; fileName += __PROD__ ? '.min.js' : '.js'; return fileName; } export default { input: './src/index.ts', output: { file: `dist/${outputFileName()}`, name: 'ReactFormWithConstraints', format: 'umd', sourcemap: true }, external: ['react', 'react-dom', 'prop-types'], globals: { react: 'React', 'react-dom': 'ReactDOM', 'prop-types': 'PropTypes' }, plugins: [ typescript({ abortOnError: false, clean: true, tsconfigOverride: {compilerOptions: {module: 'esnext', declaration: false}} }), __PROD__ && uglify(), gzip({algorithm: 'zopfli'}), filesize() ] };
Remove debugging code from controller
<?php namespace Watson\Autologin; use Auth, Redirect; use Illuminate\Routing\Controller; use Watson\Autologin\Interfaces\AutologinInterface; class AutologinController extends Controller { /** * AutologinInterface provider instance. * * @var \Studious\Autologin\Interfaces\AutologinInterface */ protected $provider; /** * Studious Autologin instance. * * @var \Studious\Autologin\Autologin */ protected $autologin; /** * Instantiate the controller. */ public function __construct(AutologinInterface $provider, Autologin $autologin) { $this->provider = $provider; $this->autologin = $autologin; } /** * Process the autologin token and perform the redirect. */ public function autologin($token) { if ($autologin = $this->autologin->validate($token)) { // Active token found, login the user and redirect to the // intended path. Auth::loginUsingId($autologin->getUserId()); return Redirect::to($autologin->getPath()); } // Token was invalid, redirect back to the home page. return Redirect::to(base_path()); } }
<?php namespace Watson\Autologin; use Auth, Redirect; use Illuminate\Routing\Controller; use Watson\Autologin\Interfaces\AutologinInterface; class AutologinController extends Controller { /** * AutologinInterface provider instance. * * @var \Studious\Autologin\Interfaces\AutologinInterface */ protected $provider; /** * Studious Autologin instance. * * @var \Studious\Autologin\Autologin */ protected $autologin; /** * Instantiate the controller. */ public function __construct(AutologinInterface $provider, Autologin $autologin) { $this->provider = $provider; $this->autologin = $autologin; } /** * Process the autologin token and perform the redirect. */ public function autologin($token) { if ($autologin = $this->autologin->validate($token)) { dd($autologin); // Active token found, login the user and redirect to the // intended path. Auth::loginUsingId($autologin->getUserId()); return Redirect::to($autologin->getPath()); } // Token was invalid, redirect back to the home page. return Redirect::to(base_path()); } }
Allow Authorization header in CORS.
package info.agrueneberg.fhir.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; @Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type, authorization"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Expose-Headers", "location"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
package info.agrueneberg.fhir.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; @Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Expose-Headers", "location"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
Resolve database for indication unique
<?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Input; class RegisterController extends Controller { public function getRegister() { return view('register'); } public function postRegister(Request $request){ $this->validate($request, [ 'name' => 'required|max:180', 'email'=> 'required|email|unique:users.email', 'password' => 'required' ]); ## Old code. #$user = new User(); #$user->name = Input::get('name'); #$user->email = Input::get('email'); #$user->password = Input::get('password'); #$user->save(); $user = new User(); $user->name = $request->get('name'); $user->password = bcrypt($request->get('password')); $user->email = $request->get('email'); $user->save(); return redirect()->route('auth.login'); } }
<?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Input; class RegisterController extends Controller { public function getRegister() { return view('register'); } public function postRegister(Request $request){ $this->validate($request, [ 'name' => 'required|max:180', 'email'=> 'required|email|unique:users_email', 'password' => 'required' ]); ## Old code. #$user = new User(); #$user->name = Input::get('name'); #$user->email = Input::get('email'); #$user->password = Input::get('password'); #$user->save(); $user = new User(); $user->name = $request->get('name'); $user->password = bcrypt($request->get('password')); $user->email = $request->get('email'); $user->save(); } }
Enable Javascript syntax highlighting in some cmds
/** * Development commands plugin * * This houses the bot's development commands. * These commands should only be used if the operator knows what their doing. * * @license MIT license */ 'use strict'; exports.commands = { js: 'eval', eval: function (target, room, user, cmd) { if (!target) return Chat.send(room, `Usage: ${Config.cmdchar}${cmd} [target]`); try { Chat.send(room, `Javascript\n${eval(target)}`); } catch (e) { Chat.send(room, `Javascript\n${e.stack}`); } }, reload: 'hotpatch', hotpatch: function (target, room, user) { try { Chat.reload(); Chat.send(room, 'Chat has been hotpatched successfully.'); } catch (e) { Chat.send(room, `Javascript\nFailed to hotpatch chat:\n${e.stack}`); } }, };
/** * Development commands plugin * * This houses the bot's development commands. * These commands should only be used if the operator knows what their doing. * * @license MIT license */ 'use strict'; exports.commands = { js: 'eval', eval: function (target, room, user, cmd) { if (!target) return Chat.send(room, `Usage: ${Config.cmdchar}${cmd} [target]`); try { Chat.send(room, eval(target)); } catch (e) { Chat.send(room, e.stack); } }, reload: 'hotpatch', hotpatch: function (target, room, user) { try { Chat.reload(); Chat.send(room, 'Chat has been hotpatched successfully.'); } catch (e) { Chat.send(room, `Failed to hotpatch chat:\n${e.stack}`); } }, };
Fix a demo mode bug
<?php namespace Controller\Page; class PrivatePage extends \Controller\AbstractPageController { public function get() { if (PUBLIC_PAGE) { $this->response->redirect('/'); } $parameters['path'] = $this->router->path(); $parameters['template'] = $this->template->get(); return $this->response->render('_private', $parameters); } public function post() { $post = $this->request->post(); $parameters['path'] = $this->router->path(); $parameters['template'] = $this->template->get(); if (DEMO) { $this->session->set('authenticated', true); } if (PRIVATE_PAGE_PASSWORD == $post['password']) { $this->session->set('authenticated', true); return $this->response->redirect('/'); } $parameters['error'] = 'Incorrect password'; return $this->response->render('_private', $parameters); } }
<?php namespace Controller\Page; class PrivatePage extends \Controller\AbstractPageController { public function get() { if (PUBLIC_PAGE) { $this->response->redirect('/'); } $parameters['path'] = $this->router->path(); $parameters['template'] = $this->template->get(); return $this->response->render('_private', $parameters); } public function post() { $post = $this->request->post(); $parameters['path'] = $this->router->path(); $parameters['template'] = $this->template->get(); if (DEMO) { $this->session->set('authenticated', true); return $this->response->redirect('/dashboard/components'); } if (PRIVATE_PAGE_PASSWORD == $post['password']) { $this->session->set('authenticated', true); return $this->response->redirect('/'); } $parameters['error'] = 'Incorrect password'; return $this->response->render('_private', $parameters); } }
Remove duplicate association test script
""" Copyright 2020 Ronald J. Nowling Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from setuptools import setup setup(name="asaph", version=2.0, description="SNP analysis", author="Ronald J. Nowling", author_email="rnowling@gmail.com", license="Apache License, Version 2.0", zip_safe=False, packages=["asaph"], python_requires=">=3.6", install_requires = ["numpy>=0.19.1", "scipy>=0.19.1", "matplotlib", "seaborn", "sklearn", "joblib"], scripts=["bin/asaph_import", "bin/asaph_pca", "bin/asaph_query", "bin/asaph_pca_association_tests", "bin/asaph_manhattan_plot", "bin/asaph_pca_analysis", "bin/asaph_generate_data", "bin/asaph_clustering"])
""" Copyright 2020 Ronald J. Nowling Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from setuptools import setup setup(name="asaph", version=2.0, description="SNP analysis", author="Ronald J. Nowling", author_email="rnowling@gmail.com", license="Apache License, Version 2.0", zip_safe=False, packages=["asaph"], python_requires=">=3.6", install_requires = ["numpy>=0.19.1", "scipy>=0.19.1", "matplotlib", "seaborn", "sklearn", "joblib"], scripts=["bin/asaph_import", "bin/asaph_pca", "bin/asaph_association_tests", "bin/asaph_query", "bin/asaph_pca_association_tests", "bin/asaph_manhattan_plot", "bin/asaph_pca_analysis", "bin/asaph_generate_data", "bin/asaph_clustering"])
Add support to old module.exports (webpack has issue with it)
import R from 'ramda'; import And from './and'; import Or from './or'; import Conjunction from './conjunction'; /** * Check if the given object is an object-like `And` conjunction. * @param {Object} obj * @param {String} obj.type * @returns {Boolean} */ const objectIsAndConjunction = R.compose( R.equals(And.type()), R.prop('type') ); /** * Check if the given object is an object-like `Or` conjunction. * @param {Object} obj * @param {String} obj.type * @returns {Boolean} */ const objectIsOrConjunction = R.compose( R.equals(Or.type()), R.prop('type') ); const create = obj => { if (objectIsOrConjunction(obj)) { return new Or(obj.mappings); } else if (objectIsAndConjunction(obj)) { return new And(obj.mappings); } else { var message = 'Cannot create conjunction based on ' + obj; throw new Error(message); } } module.exports = { create, And, Or, Conjunction }; export default module.exports
import R from 'ramda'; import And from './and'; import Or from './or'; import Conjunction from './conjunction'; /** * Check if the given object is an object-like `And` conjunction. * @param {Object} obj * @param {String} obj.type * @returns {Boolean} */ const objectIsAndConjunction = R.compose( R.equals(And.type()), R.prop('type') ); /** * Check if the given object is an object-like `Or` conjunction. * @param {Object} obj * @param {String} obj.type * @returns {Boolean} */ const objectIsOrConjunction = R.compose( R.equals(Or.type()), R.prop('type') ); const create = obj => { if (objectIsOrConjunction(obj)) { return new Or(obj.mappings); } else if (objectIsAndConjunction(obj)) { return new And(obj.mappings); } else { var message = 'Cannot create conjunction based on ' + obj; throw new Error(message); } } export default { create, And, Or, Conjunction };
Allow doctest runner to keep going after failures It will still return an error code, but there is little need to halt the running of the three different doctest modules if an early one fails, which may in fact mask the real reason for failure in an IPy internal method. Signed-off-by: Dan McGee <a6e5737275ff1276377ee261739f3ee963671241@gmail.com>
#!/usr/bin/env python import doctest import sys if hasattr(doctest, "testfile"): total_failures, total_tests = (0, 0) print("=== Test file: README ===") failure, tests = doctest.testfile('README', optionflags=doctest.ELLIPSIS) total_failures += failure total_tests += tests print("=== Test file: test.rst ===") failure, tests = doctest.testfile('test/test.rst', optionflags=doctest.ELLIPSIS) total_failures += failure total_tests += tests print("=== Test IPy module ===") import IPy failure, tests = doctest.testmod(IPy) total_failures += failure total_tests += tests print("=== Overall Results ===") print("total tests %d, failures %d" % (total_tests, total_failures)) if total_failures: sys.exit(1) else: sys.stderr.write("WARNING: doctest has no function testfile (before Python 2.4), unable to check README\n")
#!/usr/bin/env python import doctest import sys if hasattr(doctest, "testfile"): print("=== Test file: README ===") failure, tests = doctest.testfile('README', optionflags=doctest.ELLIPSIS) if failure: sys.exit(1) print("=== Test file: test.rst ===") failure, tests = doctest.testfile('test/test.rst', optionflags=doctest.ELLIPSIS) if failure: sys.exit(1) print("=== Test IPy module ===") import IPy failure, tests = doctest.testmod(IPy) if failure: sys.exit(1) else: sys.stderr.write("WARNING: doctest has no function testfile (before Python 2.4), unable to check README\n")
Set an explicit value because Default value of 'RedirectView.permanent' will change from True to False in Django 1.9.
from django.conf.urls import patterns, url from django.views.generic import RedirectView from django_messages.views import * urlpatterns = patterns('', url(r'^$', RedirectView.as_view(permanent=True, url='inbox/'), name='messages_redirect'), url(r'^inbox/$', inbox, name='messages_inbox'), url(r'^outbox/$', outbox, name='messages_outbox'), url(r'^compose/$', compose, name='messages_compose'), url(r'^compose/(?P<recipient>[\w.@+-]+)/$', compose, name='messages_compose_to'), url(r'^reply/(?P<message_id>[\d]+)/$', reply, name='messages_reply'), url(r'^view/(?P<message_id>[\d]+)/$', view, name='messages_detail'), url(r'^delete/(?P<message_id>[\d]+)/$', delete, name='messages_delete'), url(r'^undelete/(?P<message_id>[\d]+)/$', undelete, name='messages_undelete'), url(r'^trash/$', trash, name='messages_trash'), )
from django.conf.urls import patterns, url from django.views.generic import RedirectView from django_messages.views import * urlpatterns = patterns('', url(r'^$', RedirectView.as_view(url='inbox/'), name='messages_redirect'), url(r'^inbox/$', inbox, name='messages_inbox'), url(r'^outbox/$', outbox, name='messages_outbox'), url(r'^compose/$', compose, name='messages_compose'), url(r'^compose/(?P<recipient>[\w.@+-]+)/$', compose, name='messages_compose_to'), url(r'^reply/(?P<message_id>[\d]+)/$', reply, name='messages_reply'), url(r'^view/(?P<message_id>[\d]+)/$', view, name='messages_detail'), url(r'^delete/(?P<message_id>[\d]+)/$', delete, name='messages_delete'), url(r'^undelete/(?P<message_id>[\d]+)/$', undelete, name='messages_undelete'), url(r'^trash/$', trash, name='messages_trash'), )
Remove debug code from migration
<?php use Phinx\Migration\AbstractMigration; class AddSpriteHashToAppearances extends AbstractMigration { public function up() { $this->table('appearances') ->addColumn('sprite_hash', 'string', ['length' => 32, 'null' => true]) ->update(); foreach (new DirectoryIterator(SPRITE_PATH) as $file_info){ if ($file_info->isDot()) continue; $filename = $file_info->getFilename(); $appearance_id = explode('.', $filename)[0]; $hash = md5_file($file_info->getPathname()); if ($hash !== false) { $this->query("UPDATE appearances SET sprite_hash = '$hash' WHERE id = $appearance_id"); } } } public function down() { $this->table('appearances') ->removeColumn('sprite_hash') ->update(); } }
<?php use Phinx\Migration\AbstractMigration; class AddSpriteHashToAppearances extends AbstractMigration { public function up() { $this->table('appearances') ->addColumn('sprite_hash', 'string', ['length' => 32, 'null' => true]) ->update(); foreach (new DirectoryIterator(SPRITE_PATH) as $file_info){ echo "$file_info\n"; if ($file_info->isDot()) continue; $filename = $file_info->getFilename(); $appearance_id = explode('.', $filename)[0]; $hash = md5_file($file_info->getPathname()); echo "$appearance_id:$hash\n"; if ($hash !== false) { $this->query("UPDATE appearances SET sprite_hash = '$hash' WHERE id = $appearance_id"); } } } public function down() { $this->table('appearances') ->removeColumn('sprite_hash') ->update(); } }
Add new twig extension function
<?php /** * Twig extension for barcodes * * @author Philipp A. Mohrenweiser<phiamo@googlemail.com> * @copyright 2011 Philipp Mohrenweiser * @license http://www.apache.org/licenses/LICENSE-2.0.html */ namespace Mopa\BarcodeBundle\Twig\Extension; use Mopa\BarcodeBundle\Model\BarcodeService; class BarcodeRenderExtension extends \Twig_Extension { protected $bs; /** * @param \Knp\Menu\Twig\Helper $helper */ public function __construct(BarcodeService $bs) { $this->bs = $bs; } /** * {@inheritDoc} */ public function getName() { return 'mopa_barcode_render'; } public function getFunctions() { return array( 'mopa_barcode_url' => new \Twig_Function_Method($this, 'url'), 'mopa_barcode_path' => new \Twig_Function_Method($this, 'path'), ); } public function url($type, $text) { $this->get($type, $text, false); } public function path($type, $text) { $this->get($type, $text, true); } protected function get($type, $text, $absolute) { return $this->bs->get($type, urlencode($text), $absolute); } }
<?php /** * Twig extension for barcodes * * @author Philipp A. Mohrenweiser<phiamo@googlemail.com> * @copyright 2011 Philipp Mohrenweiser * @license http://www.apache.org/licenses/LICENSE-2.0.html */ namespace Mopa\BarcodeBundle\Twig\Extension; use Mopa\BarcodeBundle\Model\BarcodeService; class BarcodeRenderExtension extends \Twig_Extension { protected $bs; /** * @param \Knp\Menu\Twig\Helper $helper */ public function __construct(BarcodeService $bs) { $this->bs = $bs; } /** * {@inheritDoc} */ public function getName() { return 'mopa_barcode_render'; } public function getFunctions() { return array( 'mopa_barcode_url' => new \Twig_Function_Method($this, 'get'), ); } public function get($type, $text){ return $this->bs->get($type, urlencode($text)); } }
Update namespaces for beta 8 Refs flarum/core#1235.
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Markdown\Listener; use Flarum\Formatter\Event\Configuring; use Illuminate\Contracts\Events\Dispatcher; class FormatMarkdown { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(Configuring::class, [$this, 'addMarkdownFormatter']); } /** * @param Configuring $event */ public function addMarkdownFormatter(Configuring $event) { $event->configurator->Litedown; } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Markdown\Listener; use Flarum\Event\ConfigureFormatter; use Illuminate\Contracts\Events\Dispatcher; class FormatMarkdown { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(ConfigureFormatter::class, [$this, 'addMarkdownFormatter']); } /** * @param ConfigureFormatter $event */ public function addMarkdownFormatter(ConfigureFormatter $event) { $event->configurator->Litedown; } }
Change was necessary to allow modifyAccount calls in storeAccounts to return. We don't really use the webOS stored credentials anyway... no idea how to read them.
var onCredentialsChangedAssistant = function (future) {}; onCredentialsChangedAssistant.prototype.run = function (outerFuture) { log("============== onCredentialsChangedAssistant"); log("Params: " + JSON.stringify(this.controller.args)); //may contain password. log("Future: " + JSON.stringify(outerFuture.result)); // if (locked === true) { // log("Locked... already running?"); // previousOperationFuture.then(this, function (f) { // log("PreviousOperation finished " + JSON.stringify(f.result) + " , starting onCredentialsChangedAssistant"); // this.run(outerFuture); // }); // return; // } //this assistant is not helpfull.. it only get's the accountId, but no new credentials??? Why??? :( finishAssistant(outerFuture, { returnValue: false, success: false }); };
var onCredentialsChangedAssistant = function (future) {}; onCredentialsChangedAssistant.prototype.run = function (outerFuture) { log("============== onCredentialsChangedAssistant"); log("Params: " + JSON.stringify(this.controller.args)); //may contain password. log("Future: " + JSON.stringify(outerFuture.result)); if (locked === true) { log("Locked... already running?"); previousOperationFuture.then(this, function (f) { log("PreviousOperation finished " + JSON.stringify(f.result) + " , starting onCredentialsChangedAssistant"); this.run(outerFuture); }); return; } //this assistant is not helpfull.. it only get's the accountId, but no new credentials??? Why??? :( finishAssistant(outerFuture, { returnValue: false, success: false }); };
Store + Shipping + Menus * Using new Store feature from Elcodi * Added Store management in Admin * Changed all definitions that was depending on such implementation * Removed under construction logic and tests * Removed menu fixtures * Defined them as dynamic content. Some of them are generated dinamically, and some of them statically. * Added neede menu builders in every Admin bundle * Changed the way menu is loaded in Admin * Removed dependency with Configuration and Configuration annotation, in order to use new implementation. * Removed configuration elements * Removed all `elcodi_config` twig extension usage * Moved custom shipping logic from elcodi/elcodi to elcodi-plugins/* * Added full repo inside Plugin folder * Using new Shipping engine * Updated some code in order to be compatible with Sf2.7 deprecations Ready for Elcodi Beta! Auu! Auu!
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014-2015 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> * @author Aldo Chiecchia <zimage@tiscali.it> * @author Elcodi Team <tech@elcodi.com> */ namespace Elcodi\Plugin\DisqusBundle; use Symfony\Component\Console\Application; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; use Symfony\Component\HttpKernel\Bundle\Bundle; use Elcodi\Component\Plugin\Interfaces\PluginInterface; use Elcodi\Plugin\DisqusBundle\DependencyInjection\ElcodiDisqusExtension; /** * Class ElcodiDisqusBundle */ class ElcodiDisqusBundle extends Bundle implements PluginInterface { /** * Returns the bundle's container extension. * * @return ExtensionInterface The container extension */ public function getContainerExtension() { return new ElcodiDisqusExtension(); } /** * Register Commands. * * Disabled as commands are registered as services. * * @param Application $application An Application instance * * @return null */ public function registerCommands(Application $application) { return null; } }
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014-2015 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> * @author Aldo Chiecchia <zimage@tiscali.it> * @author Elcodi Team <tech@elcodi.com> */ namespace Elcodi\Plugin\DisqusBundle; use Symfony\Component\Console\Application; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; use Symfony\Component\HttpKernel\Bundle\Bundle; use Elcodi\Component\Plugin\Interfaces\PluginInterface; use Elcodi\Plugin\DisqusBundle\DependencyInjection\ElcodiDisqusExtension; /** * Class ElcodiDisqusBundle */ class ElcodiDisqusBundle extends Bundle implements PluginInterface { /** * Returns the bundle's container extension. * * @return ExtensionInterface The container extension */ public function getContainerExtension() { return new ElcodiDisqusExtension(); } /** * Register Commands. * * Disabled as commands are registered as services. * * @param Application $application An Application instance */ public function registerCommands(Application $application) { return null; } }
Index: Fix pathing in the first include of dependencies.
<?php require_once realpath(__DIR__.'/../').'/vendor/autoload.php'; // Auto loads the dependencies, e.g. the whole of silex // Instantiate the app $app = new Silex\Application(); // The standard simple hello world example $app->get('/hello/{name}', function ($name) use ($app) { return 'Hello '.$app->escape($name); }); // An even simpler display of the main page, complete with html in the php, ew! $app->get('/', function() use ($app){ return '<body>The main Thinkocracy page!</body>'; }); // Let's get some api call & response working up in here $app->get('/api/{call}/{data}', function($call, $data) use ($app){ // We can actually just pass json data encoded for the url to {data} soon. $response = 'Call to a api type of '.$call.' with data '.$data; return $response; // This will be a json response shortly. }); // Aw yeah, run dat app $app->run();
<?php require_once __DIR__.'/../vendor/autoload.php'; // Auto loads the dependencies, e.g. the whole of silex // Instantiate the app $app = new Silex\Application(); // The standard simple hello world example $app->get('/hello/{name}', function ($name) use ($app) { return 'Hello '.$app->escape($name); }); // An even simpler display of the main page, complete with html in the php, ew! $app->get('/', function() use ($app){ return '<body>The main Thinkocracy page!</body>'; }); // Let's get some api call & response working up in here $app->get('/api/{call}/{data}', function($call, $data) use ($app){ // We can actually just pass json data encoded for the url to {data} soon. $response = 'Call to a api type of '.$call.' with data '.$data; return $response; // This will be a json response shortly. }); // Aw yeah, run dat app $app->run();
Test code and buy properties
import { expect } from 'chai'; import NBG from '../src/banks/NBG'; import CreditAgricole from '../src/banks/CreditAgricole'; import CBE from '../src/banks/CBE'; const { describe, it } = global; const banks = [ NBG, CreditAgricole, CBE, ]; describe('Banks', () => { banks.forEach((Bank) => { const bank = new Bank(); describe(bank.name.acronym, () => { const bankTestPromise = new Promise((resolve) => { bank.scrape((rates) => { resolve(rates); }); }); it('Should not equal null', () => bankTestPromise.then((rates) => { expect(rates).to.not.equal(null); })); it('code property in rates should be string of 3 letters', () => bankTestPromise.then((rates) => { rates.forEach((currencyRate) => { expect(currencyRate.code).to.be.a('string'); expect(currencyRate).to.have.property('code').with.lengthOf(3); }); })); it('buy property in rates should be a number', () => bankTestPromise.then((rates) => { rates.forEach((currencyRate) => { expect(currencyRate.buy).to.be.a('number'); }); })); }); }); });
import { expect } from 'chai'; import NBG from '../src/banks/NBG'; import CreditAgricole from '../src/banks/CreditAgricole'; import CBE from '../src/banks/CBE'; const { describe, it } = global; const banks = [ NBG, CreditAgricole, CBE, ]; describe('Banks', () => { banks.forEach((Bank) => { const bank = new Bank(); describe(bank.name.acronym, () => { const bankTestPromise = new Promise((resolve) => { bank.scrape((rates) => { resolve(rates); }); }); it('Should not equal null', () => bankTestPromise.then((result) => { expect(result).to.not.equal(null); })); }); }); });
Update integration test: docs, add more checks, rename
# -*- coding: utf-8 -*- ''' tests for host state ''' # Import Python libs from __future__ import absolute_import, unicode_literals # Import Salt Testing libs from tests.support.case import ModuleCase class HandleErrorTest(ModuleCase): ''' Validate that ordering works correctly ''' def test_function_do_not_return_dictionary_type(self): ''' Handling a case when function returns anything but a dictionary type ''' ret = self.run_function('state.sls', ['issue-9983-handleerror']) self.assertTrue('Data must be a dictionary type' in ret[[a for a in ret][0]]['comment']) self.assertTrue(not ret[[a for a in ret][0]]['result']) self.assertTrue(ret[[a for a in ret][0]]['changes'] == {})
# -*- coding: utf-8 -*- ''' tests for host state ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs from tests.support.case import ModuleCase class HandleErrorTest(ModuleCase): ''' Validate that ordering works correctly ''' def test_handle_error(self): ''' Test how an error can be recovered ''' # without sync_states, the custom state may not be installed # (resulting in : # State salttest.hello found in sls issue-... is unavailable ret = self.run_function('state.sls', ['issue-9983-handleerror']) self.assertTrue( 'An exception occurred in this state: Traceback' in ret[[a for a in ret][0]]['comment'])
Use client_id as url identifier.
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views import generic from django.core.urlresolvers import reverse from . import models, forms class ClientMixin(object): """ A mixin that describes Client model. """ model = models.Client pk_url_kwarg = 'client_id' form_class = forms.Client def get_success_url(self): return reverse('client-detail', args=[self.object.id]) def get_queryset(self): return super(ClientMixin, self).get_queryset() @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ClientMixin, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): kwargs = super(ClientMixin, self).get_context_data(**kwargs) kwargs['activemenu'] = 'client' return kwargs class ClientList(ClientMixin, generic.ListView): pass class ClientCreation(ClientMixin, generic.CreateView): pass class ClientUpdate(ClientMixin, generic.UpdateView): pass class ClientDetail(ClientMixin, generic.DetailView): pass
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views import generic from django.core.urlresolvers import reverse from . import models, forms class ClientMixin(object): """ A mixin that describes Client model. """ model = models.Client pk_url_kwarg = 'invoice_id' form_class = forms.Client def get_success_url(self): return reverse('client-detail', args=[self.object.id]) def get_queryset(self): return super(ClientMixin, self).get_queryset() @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ClientMixin, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): kwargs = super(ClientMixin, self).get_context_data(**kwargs) kwargs['activemenu'] = 'client' return kwargs class ClientList(ClientMixin, generic.ListView): pass class ClientCreation(ClientMixin, generic.CreateView): pass class ClientUpdate(ClientMixin, generic.UpdateView): pass class ClientDetail(ClientMixin, generic.DetailView): pass
Rename + add long_description + update keywords
from distutils.core import setup setup( name='a_john_shots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', long_description=open('README').read(), author='funilrys', author_email='contact@funilrys.com', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA-1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA', 'MD5'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
from distutils.core import setup setup( name='aJohnShots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', author='funilrys', author_email='contact@funilrys.com', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA 1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
Remove berniebuilders, callforbernie, and bernie2016states
export const slacks = { // afam4bernie: { // title: 'African Americans For Bernie', // description: 'A community of African American activists and allies' // }, // bernie2016states: { // title: 'Bernie 2016 States', // description: 'Interface with volunteers and staff in each state', // showInIndex: true // }, // berniebuilders: { // title: 'Bernie Builders', // description: 'General volunteer discussion', // showInIndex: true // }, // callforbernie: { // title: 'Call Team Slack', // description: 'Get phonebanking assistance and talk to other callers for Bernie', // showInIndex: true // }, codersforsanders: { title: 'Coders for Sanders', description: 'Volunteer development projects discussion', showInIndex: true }, textforbernie: { title: 'Text for Bernie', description: 'Text for Bernie uses Slack, a powerful group messaging program, to coordinate our efforts. Please enter your email address below to receive an email invitation to the Text for Bernie Slack team.', showInIndex: false } }
export const slacks = { // afam4bernie: { // title: 'African Americans For Bernie', // description: 'A community of African American activists and allies' // }, bernie2016states: { title: 'Bernie 2016 States', description: 'Interface with volunteers and staff in each state', showInIndex: true }, berniebuilders: { title: 'Bernie Builders', description: 'General volunteer discussion', showInIndex: true }, callforbernie: { title: 'Call Team Slack', description: 'Get phonebanking assistance and talk to other callers for Bernie', showInIndex: true }, codersforsanders: { title: 'Coders for Sanders', description: 'Volunteer development projects discussion', showInIndex: true }, textforbernie: { title: 'Text for Bernie', description: 'Text for Bernie uses Slack, a powerful group messaging program, to coordinate our efforts. Please enter your email address below to receive an email invitation to the Text for Bernie Slack team.', showInIndex: false } }
Update to new `defaults` configuration
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Hardy Jones # Copyright (c) 2013 # # License: MIT # """This module exports the Hlint plugin class.""" from SublimeLinter.lint import Linter class Hlint(Linter): """Provides an interface to hlint.""" defaults = { 'selector': 'source.haskell' } cmd = 'hlint' regex = ( r'^.+:(?P<line>\d+):' '(?P<col>\d+):\s*' '(?:(?P<error>Error)|(?P<warning>Warning)):\s*' '(?P<message>.+)$' ) multiline = True tempfile_suffix = 'hs'
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Hardy Jones # Copyright (c) 2013 # # License: MIT # """This module exports the Hlint plugin class.""" from SublimeLinter.lint import Linter class Hlint(Linter): """Provides an interface to hlint.""" syntax = ('haskell', 'haskell-sublimehaskell', 'literate haskell') cmd = 'hlint' regex = ( r'^.+:(?P<line>\d+):' '(?P<col>\d+):\s*' '(?:(?P<error>Error)|(?P<warning>Warning)):\s*' '(?P<message>.+)$' ) multiline = True tempfile_suffix = { 'haskell': 'hs', 'haskell-sublimehaskell': 'hs', 'literate haskell': 'lhs' }
Rename stream to buffer (oxy stream lib update) + move circuit breaker in the middleware chain
package server import ( "github.com/vulcand/oxy/forward" "github.com/vulcand/oxy/roundrobin" "github.com/vulcand/oxy/buffer" "github.com/vulcand/oxy/cbreaker" "net/http" "net/url" ) type ReverseProxy struct { handler http.Handler } func NewReverseProxy(backends []string) *ReverseProxy { fwd, _ := forward.New() lb, _ := roundrobin.New(fwd) for _, backend := range backends { target, _ := url.Parse(backend) lb.UpsertServer(target) } buff, _ := buffer.New(lb, buffer.Retry(`(IsNetworkError() || ResponseCode() >= 500) && Attempts() < 2`)) cb, _ := cbreaker.New(buff, `NetworkErrorRatio() > 0.5`) return &ReverseProxy{handler: cb} } func (rp *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { rp.handler.ServeHTTP(w, r) }
package server import ( "github.com/vulcand/oxy/forward" "github.com/vulcand/oxy/roundrobin" "github.com/vulcand/oxy/stream" "github.com/vulcand/oxy/cbreaker" "net/http" "net/url" ) type ReverseProxy struct { stream *stream.Streamer } func NewReverseProxy(backends []string) *ReverseProxy { fwd, _ := forward.New() cb, _ := cbreaker.New(fwd, `NetworkErrorRatio() > 0.5`) lb, _ := roundrobin.New(cb) for _, backend := range backends { target, _ := url.Parse(backend) lb.UpsertServer(target) } stream, _ := stream.New(lb, stream.Retry(`(IsNetworkError() || ResponseCode() >= 500) && Attempts() < 2`)) return &ReverseProxy{stream: stream} } func (rp *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { rp.stream.ServeHTTP(w, r) }
Throw friendly exception on unparseable JSON files PHP 7 has become a little more picky about JSON parsing, which made me stumble into a bug. Some old file was somewhat-incorrectly encoded (contained some long-space character or something), which made PHP 7's JSON parser break. The failure was silently ignored and the translation file was not loaded, which shouldn't be the case.
<?php namespace Devture\Bundle\LocalizationBundle\Translation; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\Loader\LoaderInterface; use Symfony\Component\Config\Resource\FileResource; class JsonFileLoader extends ArrayLoader implements LoaderInterface { public function load($resource, $locale, $domain = 'messages') { $contents = file_get_contents($resource); $messages = array(); if ($contents !== '') { $messages = json_decode($contents, 1); if (json_last_error() !== JSON_ERROR_NONE) { throw new \InvalidArgumentException(sprintf( 'The file "%s" cannot be JSON-decoded: %s.', $resource, json_last_error_msg() )); } } if (!is_array($messages)) { throw new \InvalidArgumentException(sprintf('The file "%s" must contain a JSON array.', $resource)); } $catalogue = parent::load($messages, $locale, $domain); $catalogue->addResource(new FileResource($resource)); return $catalogue; } }
<?php namespace Devture\Bundle\LocalizationBundle\Translation; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\Loader\LoaderInterface; use Symfony\Component\Config\Resource\FileResource; class JsonFileLoader extends ArrayLoader implements LoaderInterface { public function load($resource, $locale, $domain = 'messages') { $messages = json_decode(file_get_contents($resource), 1); // empty file if (null === $messages) { $messages = array(); } // not an array if (!is_array($messages)) { throw new \InvalidArgumentException(sprintf('The file "%s" must contain a JSON array.', $resource)); } $catalogue = parent::load($messages, $locale, $domain); $catalogue->addResource(new FileResource($resource)); return $catalogue; } }
Remove task for updating data Not sure if this is the best method to have it. Since for now is not needed, droping it from the codebase.
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish()
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_suspicions_dataset(): command = ['python', 'rosie/rosie.py', 'run', 'chamber_of_deputies', 'data', '--years=2017,2016'] subprocess.run(command, check=True) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish()
Change CheckTrigger action to be retriggerable
package com.elmakers.mine.bukkit.action.builtin; import java.util.Collection; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.action.CheckAction; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.spell.Spell; public class CheckTriggerAction extends CheckAction { private boolean sinceStartOfCast; private long startTime; private String trigger; @Override public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); trigger = parameters.getString("trigger", ""); sinceStartOfCast = parameters.getBoolean("since_start_of_cast", false); } @Override public void reset(CastContext context) { startTime = System.currentTimeMillis(); } @Override protected boolean isAllowed(CastContext context) { Long lastTrigger = context.getMage().getLastTrigger(trigger); long startTime = sinceStartOfCast ? context.getStartTime() : this.startTime; return (lastTrigger != null && lastTrigger > startTime); } @Override public void getParameterNames(Spell spell, Collection<String> parameters) { super.getParameterNames(spell, parameters); parameters.add("trigger"); } }
package com.elmakers.mine.bukkit.action.builtin; import java.util.Collection; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.action.CheckAction; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.spell.Spell; public class CheckTriggerAction extends CheckAction { private String trigger; @Override public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); trigger = parameters.getString("trigger", ""); } @Override protected boolean isAllowed(CastContext context) { Long lastTrigger = context.getMage().getLastTrigger(trigger); return (lastTrigger != null && lastTrigger > context.getStartTime()); } @Override public void getParameterNames(Spell spell, Collection<String> parameters) { super.getParameterNames(spell, parameters); parameters.add("trigger"); } }
Update bin scripts to function when installed through composer as well.
<?php /** * @file * Sample script for launching Wind as a REST server. * * This script launches a sample Wind server and stores all log request * to a file called log.log. This script requires the Monolog library. * * (c) Wouter Admiraal <wad@wadmiraal.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require './../../vendor/autoload.php'; use Monolog\Logger; use Monolog\Handler\StreamHandler; use Wind\Server\EndPoint; use Wind\Server\Router; try { $logger = new Logger('name'); $logger->pushHandler(new StreamHandler('./log.log', Logger::DEBUG)); } catch (Exception $e) { die("This example script requires Monolog. Aborting."); } $wind = new Endpoint($logger, new Router()); $wind->run();
<?php /** * @file * Sample script for launching Wind as a REST server. * * This script launches a sample Wind server and stores all log request * to a file called log.log. This script requires the Monolog library. * * (c) Wouter Admiraal <wad@wadmiraal.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require dirname(__FILE__) . '/../../vendor/autoload.php'; use Monolog\Logger; use Monolog\Handler\StreamHandler; use Wind\Server\EndPoint; use Wind\Server\Router; try { $logger = new Logger('name'); $logger->pushHandler(new StreamHandler(dirname(__FILE__) . '/log.log', Logger::DEBUG)); } catch (Exception $e) { die("This example script requires Monolog. Aborting."); } $wind = new Endpoint($logger, new Router()); $wind->run();
Prepare release notes for v1.6.0-beta.4 Signed-off-by: Derek McGowan <e1c79a582b6629e6b39e9679f4bb964d25db4aa8@mcg.dev>
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package version import "runtime" var ( // Package is filled at linking time Package = "github.com/containerd/containerd" // Version holds the complete version number. Filled in at linking time. Version = "1.6.0-beta.4+unknown" // Revision is filled with the VCS (e.g. git) revision being used to build // the program at linking time. Revision = "" // GoVersion is Go tree's version. GoVersion = runtime.Version() )
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package version import "runtime" var ( // Package is filled at linking time Package = "github.com/containerd/containerd" // Version holds the complete version number. Filled in at linking time. Version = "1.6.0-beta.3+unknown" // Revision is filled with the VCS (e.g. git) revision being used to build // the program at linking time. Revision = "" // GoVersion is Go tree's version. GoVersion = runtime.Version() )
Fix cookie keys to be 'sagebio' not 'sagbio'
package org.sagebionetworks.web.client.cookie; /** * The cookie key master. Don't tell the cookie monster! * * @author jmhill * */ public class CookieKeys { /** * Key for the selected columns shown in the datasets table. */ public static String SELECTED_DATASETS_COLUMNS = "org.sagebionetworks.datasets.selected.columns"; /** * Key for the selected filters applied on the datasets table. */ public static String APPLIED_DATASETS_FILTERS = "org.sagebionetworks.datasets.applied.filters"; /** * Login token */ public static String USER_LOGIN_TOKEN = "org.sagebionetworks.security.user.login.token"; /** * Login token */ public static String SHOW_DEMO = "org.sagebionetworks.synapse.show.demo"; /** * Last Place in the app */ public static String LAST_PLACE = "org.sagebionetworks.synapse.place.last.place"; /** * Current Place in the app */ public static String CURRENT_PLACE = "org.sagebionetworks.synapse.place.current.place"; /** * LinkedIn requestToken key */ public static String LINKEDIN = "org.sagebionetworks.synapse.linkedin"; /** * Get Satisfaction fastpass key */ public static String FASTPASS = "fastpass"; }
package org.sagebionetworks.web.client.cookie; /** * The cookie key master. Don't tell the cookie monster! * * @author jmhill * */ public class CookieKeys { /** * Key for the selected columns shown in the datasets table. */ public static String SELECTED_DATASETS_COLUMNS = "org.sagebionetworks.datasets.selected.columns"; /** * Key for the selected filters applied on the datasets table. */ public static String APPLIED_DATASETS_FILTERS = "org.sagebionetworks.datasets.applied.filters"; /** * Login token */ public static String USER_LOGIN_TOKEN = "org.sagbionetworks.security.user.login.token"; /** * Login token */ public static String SHOW_DEMO = "org.sagbionetworks.synapse.show.demo"; /** * Last Place in the app */ public static String LAST_PLACE = "org.sagbionetworks.synapse.place.last.place"; /** * Current Place in the app */ public static String CURRENT_PLACE = "org.sagbionetworks.synapse.place.current.place"; /** * LinkedIn requestToken key */ public static String LINKEDIN = "org.sagebionetworks.synapse.linkedin"; /** * Get Satisfaction fastpass key */ public static String FASTPASS = "fastpass"; }
Remove lower str and improve supported unicodes
<?php namespace USlugify; /** * USlugify * * @author Florent Denis <dflorent.pokap@gmail.com> */ class USlugify implements USlugifyInterface { /** * {@inheritdoc} */ public function slugify($text, $separator = '-') { $reservedChars = $this->getReservedChars(); $text = str_replace($reservedChars, '-', $text); $text = preg_replace('/[\p{M}\p{Z}\p{C}]+/u', '', $text); $text = trim(preg_replace('/[-\s]+/u', '-', $text), '-'); return $text; } /** * Returns list of char reserved. * http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters * * @return array */ protected function getReservedChars() { return array(' ', '!', '#', '$', '&', '\'', '"', '(', ')', '*', '+', ',', '/', ':', ';', '=', '?', '@', '[', ']'); } }
<?php namespace USlugify; /** * USlugify * * @author Florent Denis <dflorent.pokap@gmail.com> */ class USlugify implements USlugifyInterface { /** * {@inheritdoc} */ public function slugify($text) { $reservedChars = $this->getReservedChars(); $text = str_replace($reservedChars, '-', $text); $text = preg_replace('/\p{Mn}+/u', '-', $text); $text = trim(preg_replace('/[-\s]+/u', '-', $text), '-'); return mb_strtolower($text, mb_detect_encoding($text)); } /** * Returns list of char reserved. * http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters * * @return array */ protected function getReservedChars() { return array('!', '#', '$', '&', '\'', '"', '(', ')', '*', '+', ',', '/', ':', ';', '=', '?', '@', '[', ']'); } }
Fix the order of parameters to hasAccess, which broke all topic changing when +t was set
from twisted.words.protocols import irc from txircd.modbase import Mode class TopiclockMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "TOPIC": return data if "topic" not in data: return data targetChannel = data["targetchan"] if "t" in targetChannel.mode and not user.hasAccess(targetChannel.name, self.ircd.servconfig["channel_minimum_level"]["TOPIC"]): user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, targetChannel.name, ":You do not have access to change the topic on this channel") return {} return data class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): if "channel_minimum_level" not in self.ircd.servconfig: self.ircd.servconfig["channel_minimum_level"] = {} if "TOPIC" not in self.ircd.servconfig["channel_minimum_level"]: self.ircd.servconfig["channel_minimum_level"]["TOPIC"] = "o" return { "modes": { "cnt": TopiclockMode() } } def cleanup(self): self.ircd.removeMode("cnt")
from twisted.words.protocols import irc from txircd.modbase import Mode class TopiclockMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "TOPIC": return data if "topic" not in data: return data targetChannel = data["targetchan"] if "t" in targetChannel.mode and not user.hasAccess(self.ircd.servconfig["channel_minimum_level"]["TOPIC"], targetChannel.name): user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, targetChannel.name, ":You do not have access to change the topic on this channel") return {} return data class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): if "channel_minimum_level" not in self.ircd.servconfig: self.ircd.servconfig["channel_minimum_level"] = {} if "TOPIC" not in self.ircd.servconfig["channel_minimum_level"]: self.ircd.servconfig["channel_minimum_level"]["TOPIC"] = "o" return { "modes": { "cnt": TopiclockMode() } } def cleanup(self): self.ircd.removeMode("cnt")
Remove --dev from composer install. --dev is the default.
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install', $returnStatus); if ($returnStatus !== 0) { exit(1); } require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0); $phpcsViolations = $phpcsCLI->process($phpcsArguments); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } echo "Code coverage was 100%\n";
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install --dev', $returnStatus); if ($returnStatus !== 0) { exit(1); } require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0); $phpcsViolations = $phpcsCLI->process($phpcsArguments); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } echo "Code coverage was 100%\n";
Update to latest Cerebral, React. Removed deprecated warnings
var rules = require('./helpers/rules.js'); module.exports = function (options) { options = options || {}; if (options.rules) { Object.keys(options.rules).forEach(function (key) { rules[key] = options.rules[key]; }); } return function (module, controller) { module.alias('cerebral-module-forms'); module.addState({}); module.addSignals({ fieldAdded: require('./signals/fieldAdded.js'), fieldRemoved: require('./signals/fieldRemoved.js'), formAdded: require('./signals/formAdded.js'), formRemoved: require('./signals/formRemoved.js'), fieldChanged: {chain: require('./signals/fieldChanged.js'), sync: true} }); }; };
var rules = require('./helpers/rules.js'); module.exports = function (options) { options = options || {}; if (options.rules) { Object.keys(options.rules).forEach(function (key) { rules[key] = options.rules[key]; }); } return function (module, controller) { module.alias('cerebral-module-forms'); module.addState({}); module.addSignals({ fieldAdded: require('./signals/fieldAdded.js'), fieldRemoved: require('./signals/fieldRemoved.js'), formAdded: require('./signals/formAdded.js'), formRemoved: require('./signals/formRemoved.js'), fieldChanged: {chain: require('./signals/fieldChanged.js'), sync: true} }); }; };
Raise error upon dataflow cycle detection.
import {error} from 'vega-util'; /** * Assigns a rank to an operator. Ranks are assigned in increasing order * by incrementing an internal rank counter. * @param {Operator} op - The operator to assign a rank. */ export function rank(op) { op.rank = ++this._rank; } /** * Re-ranks an operator and all downstream target dependencies. This * is necessary when upstream depencies of higher rank are added to * a target operator. * @param {Operator} op - The operator to re-rank. */ export function rerank(op) { var queue = [op], cur, list, i; while (queue.length) { this.rank(cur = queue.pop()); if (list = cur._targets) { for (i=list.length; --i >= 0;) { queue.push(cur = list[i]); if (cur === op) error('Cycle detected in dataflow graph.'); } } } }
/** * Assigns a rank to an operator. Ranks are assigned in increasing order * by incrementing an internal rank counter. * @param {Operator} op - The operator to assign a rank. */ export function rank(op) { op.rank = ++this._rank; } /** * Re-ranks an operator and all downstream target dependencies. This * is necessary when upstream depencies of higher rank are added to * a target operator. * @param {Operator} op - The operator to re-rank. */ export function rerank(op) { var queue = [op], cur, list, i; while (queue.length) { this.rank(cur = queue.pop()); if (list = cur._targets) { for (i=list.length; --i >= 0;) { queue.push(cur = list[i]); if (cur === op) this.error('Cycle detected in dataflow graph.'); } } } }
Fix template name in view
from django.template import RequestContext from django.template.response import TemplateResponse from pyconcz_2016.speakers.models import Speaker, Slot def speakers_list(request, type): speakers = (Speaker.objects.all() .exclude(**{type: None}) .prefetch_related(type) .order_by('full_name')) return TemplateResponse( request, template='speakers/{}_list.html'.format(type), context={'speakers': speakers} ) def talks_timeline(request): talks = (Slot.objects.all() .select_related('talk') .prefetch_related('talk__speakers') .order_by('date')) return TemplateResponse( request, template='speakers/talks_timeline.html', context={ 'talks': talks } )
from django.template import RequestContext from django.template.response import TemplateResponse from pyconcz_2016.speakers.models import Speaker, Slot def speakers_list(request, type): speakers = (Speaker.objects.all() .exclude(**{type: None}) .prefetch_related(type) .order_by('full_name')) return TemplateResponse( request, template='speakers/speakers_list_{}.html'.format(type), context={'speakers': speakers} ) def talks_timeline(request): talks = (Slot.objects.all() .select_related('talk') .prefetch_related('talk__speakers') .order_by('date')) return TemplateResponse( request, template='speakers/talks_timeline.html', context={ 'talks': talks } )
Remove Rx.config.longStackSupport flag, which was left in unintentionally. Fixes #1.
'use strict'; const Rx = require('rx'); require('isomorphic-fetch'); module.exports = function (url, options) { return Rx.Observable.fromPromise(fetch(url, options)) .flatMapLatest((response) => { return Rx.Observable.fromPromise(response.text()) .map((body) => { return { url: response.url, status: response.status, statusText: response.statusText, headers: response.headers, text: body, size: response.size, // ??? ok: response.ok, timeout: response.timeout }; }); }); }
'use strict'; const Rx = require('rx'); require('isomorphic-fetch'); Rx.config.longStackSupport = true; module.exports = function (url, options) { return Rx.Observable.fromPromise(fetch(url, options)) .flatMapLatest((response) => { return Rx.Observable.fromPromise(response.text()) .map((body) => { return { url: response.url, status: response.status, statusText: response.statusText, headers: response.headers, text: body, size: response.size, // ??? ok: response.ok, timeout: response.timeout }; }); }); }
Update mailer timeout to 5 seconds
import logging import requests from requests.exceptions import ConnectionError, Timeout log = logging.getLogger(__name__) class MailNotifier(object): url = None api_key = None sender = None @classmethod def send_message(cls, subject, to, message): data = {'from': cls.sender, 'to': to, 'subject': subject, 'html': message} try: requests.post(cls.url, auth=('api', cls.api_key), data=data, timeout=5) except (ConnectionError, Timeout): log.error('Failed to deliver message %s', data) def includeme(config): """ Sets the mailgun properties from .ini config file :param config: The pyramid ``Configurator`` object for your app. :type config: ``pyramid.config.Configurator`` """ settings = config.get_settings() MailNotifier.url = settings['mailgun.url'] MailNotifier.api_key = settings['mailgun.key'] MailNotifier.sender = settings['mailgun.sender']
import logging import requests from requests.exceptions import ConnectionError, Timeout log = logging.getLogger(__name__) class MailNotifier(object): url = None api_key = None sender = None @classmethod def send_message(cls, subject, to, message): data = {'from': cls.sender, 'to': to, 'subject': subject, 'html': message} try: requests.post(cls.url, auth=('api', cls.api_key), data=data, timeout=3.5) except (ConnectionError, Timeout): log.error('Failed to deliver message %s', data) def includeme(config): """ Sets the mailgun properties from .ini config file :param config: The pyramid ``Configurator`` object for your app. :type config: ``pyramid.config.Configurator`` """ settings = config.get_settings() MailNotifier.url = settings['mailgun.url'] MailNotifier.api_key = settings['mailgun.key'] MailNotifier.sender = settings['mailgun.sender']
Remove slash after baseUrl and make sure entire url is not removed
const serve = require('serve/lib/server') const relativePaths = require('./relative-paths') // taken from serve cli! process.env.ASSET_DIR = '/' + Math.random().toString(36).substr(2, 10) module.exports = (cookieName) => { const baseURL = process.env.PUBLIC_URL || '' const uiPath = process.env.REACT_APP_BUILD const uiIgnored = [ '.DS_Store', '.git/', 'node_modules' ] let rootUrls = [] route.buildRelativePaths = () => { return ( relativePaths(uiPath) .then((urls) => { rootUrls = urls }) ) } return route function route (req, res) { if (cookieName && baseURL) { const cookieValue = encodeURIComponent(baseURL) const cookie = `${cookieName}=${cookieValue}; Path=/;` res.setHeader('Set-Cookie', cookie) } const uiFlags = { single: true, auth: !!process.env.SERVE_USER } const overrideUrl = rootUrls.find((x) => req.url.indexOf(x) !== -1) if (req.url.startsWith(baseURL) && req.url.length > baseUrl.length + 1) { req.url = req.url.slice(baseURL.length + 1) } if (overrideUrl) req.url = overrideUrl serve(req, res, uiFlags, uiPath, uiIgnored) } }
const serve = require('serve/lib/server') const relativePaths = require('./relative-paths') // taken from serve cli! process.env.ASSET_DIR = '/' + Math.random().toString(36).substr(2, 10) module.exports = (cookieName) => { const baseURL = process.env.PUBLIC_URL || '' const uiPath = process.env.REACT_APP_BUILD const uiIgnored = [ '.DS_Store', '.git/', 'node_modules' ] let rootUrls = [] route.buildRelativePaths = () => { return ( relativePaths(uiPath) .then((urls) => { rootUrls = urls }) ) } return route function route (req, res) { if (cookieName && baseURL) { const cookieValue = encodeURIComponent(baseURL) const cookie = `${cookieName}=${cookieValue}; Path=/;` res.setHeader('Set-Cookie', cookie) } const uiFlags = { single: true, auth: !!process.env.SERVE_USER } const overrideUrl = rootUrls.find((x) => req.url.indexOf(x) !== -1) if (req.url.startsWith(baseURL)) req.url = req.url.slice(baseURL) if (overrideUrl) req.url = overrideUrl serve(req, res, uiFlags, uiPath, uiIgnored) } }
Fix Tinymce editor not showing Bootstrap components correctly by adding container-fluid class to body.
<script src="{{ URL::to('vendor/redooor/redminportal/js/tinymce/tinymce.min.js') }}"></script> <script> !function ($) { $(function(){ tinymce.init({ skin: 'redooor', selector:'textarea', menubar:false, plugins: "link image code", convert_urls: false, relative_urls: false, toolbar: "undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link | image | code", body_class: 'container-fluid', content_css: [ @foreach (config('redminportal::tinymce') as $tinymce_css) "{{ url($tinymce_css) }}", @endforeach ] }); }) }(window.jQuery); </script>
<script src="{{ URL::to('vendor/redooor/redminportal/js/tinymce/tinymce.min.js') }}"></script> <script> !function ($) { $(function(){ tinymce.init({ skin: 'redooor', selector:'textarea', menubar:false, plugins: "link image code", convert_urls: false, relative_urls: false, toolbar: "undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link | image | code", content_css: [ @foreach (config('redminportal::tinymce') as $tinymce_css) "{{ url($tinymce_css) }}", @endforeach ] }); }) }(window.jQuery); </script>
Add message to tell if there were errors or not
<?php namespace Lighwand\Validate; use Lighwand\Validate\Loader\VideoLoader; use Lighwand\Validate\Video\VideoValidator; use Zend\ServiceManager\Config; use Zend\ServiceManager\ServiceManager; try { require_once __DIR__ . '/vendor/autoload.php'; $config = include __DIR__ . '/validate/config.php'; $serviceManager = new ServiceManager(new Config($config['services'])); $return = 0; $videoValidator = $serviceManager->get(VideoValidator::class); $videoFiles = $serviceManager->get(VideoLoader::class)->getFiles(); foreach ($videoFiles as $file) { if (!$videoValidator->isValid($file)) { $return = 1; echo join(PHP_EOL, $videoValidator->getMessages()) . PHP_EOL; } } if ($return === 0) { echo 'Everything is valid!' . PHP_EOL; } else { echo 'Invalid data found.' . PHP_EOL; } return $return; } catch (\Exception $e) { echo $e->getMessage(); return 1; }
<?php namespace Lighwand\Validate; use Lighwand\Validate\Loader\VideoLoader; use Lighwand\Validate\Video\VideoValidator; use Zend\ServiceManager\Config; use Zend\ServiceManager\ServiceManager; try { require_once __DIR__ . '/vendor/autoload.php'; $config = include __DIR__ . '/validate/config.php'; $serviceManager = new ServiceManager(new Config($config['services'])); $return = 0; $videoValidator = $serviceManager->get(VideoValidator::class); $videoFiles = $serviceManager->get(VideoLoader::class)->getFiles(); foreach ($videoFiles as $file) { if (!$videoValidator->isValid($file)) { $return = 1; echo join(PHP_EOL, $videoValidator->getMessages()) . PHP_EOL; } } return $return; } catch (\Exception $e) { echo $e->getMessage(); return 1; }
Use document instance to invert change.
import last from '../util/last' export default class SimpleChangeHistory { constructor (editorSession) { this._editorSession = editorSession this._done = [] this._undone = [] } canUndo () { return this._done.length > 0 } canRedo () { return this._undone.length > 0 } getChanges () { return this._done.slice() } addChange (change) { this._done.push(change) // undone changes are cleared whenever a new change is recorded if (this._undone.length > 0) { this._undone.length = 0 } } undo () { let change = last(this._done) if (change) { let inverted = this._editorSession.getDocument().invert(change) this._editorSession.applyChange(inverted, { replay: true }) this._done.pop() this._undone.push(change) } } redo () { let change = last(this._undone) if (change) { this._editorSession.applyChange(change, { replay: true }) this._undone.pop() this._done.push(change) } } }
import last from '../util/last' export default class SimpleChangeHistory { constructor (editorSession) { this._editorSession = editorSession this._done = [] this._undone = [] } canUndo () { return this._done.length > 0 } canRedo () { return this._undone.length > 0 } getChanges () { return this._done.slice() } addChange (change) { this._done.push(change) // undone changes are cleared whenever a new change is recorded if (this._undone.length > 0) { this._undone.length = 0 } } undo () { let change = last(this._done) if (change) { let inverted = change.invert() this._editorSession.applyChange(inverted, { replay: true }) this._done.pop() this._undone.push(change) } } redo () { let change = last(this._undone) if (change) { this._editorSession.applyChange(change, { replay: true }) this._undone.pop() this._done.push(change) } } }
Add install for junit report generator
package main var defaultTemplate = ` [vars] ignoreDirs = [".git", "Godeps", "vendor"] stopLoadingParent = [".git"] buildFlags = ["."] artifactsEnv = "CIRCLE_ARTIFACTS" testReportEnv = "CIRCLE_TEST_REPORTS" [gotestcoverage] timeout = "10s" cpu = "4" parallel = 8 race = true covermode = "atomic" [install] [install.goget] gometalinter = "github.com/alecthomas/gometalinter" golint = "github.com/golang/lint/golint" go-junit-report = "github.com/jstemmer/go-junit-report" goimports = "golang.org/x/tools/cmd/goimports" gocyclo = "github.com/alecthomas/gocyclo" aligncheck = "github.com/opennota/check/cmd/aligncheck" varcheck = "github.com/opennota/check/cmd/varcheck" dupl = "github.com/mibk/dupl" `
package main var defaultTemplate = ` [vars] ignoreDirs = [".git", "Godeps", "vendor"] stopLoadingParent = [".git"] buildFlags = ["."] artifactsEnv = "CIRCLE_ARTIFACTS" testReportEnv = "CIRCLE_TEST_REPORTS" [gotestcoverage] timeout = "10s" cpu = "4" parallel = 8 race = true covermode = "atomic" [install] [install.goget] gometalinter = "github.com/alecthomas/gometalinter" golint = "github.com/golang/lint/golint" goimports = "golang.org/x/tools/cmd/goimports" gocyclo = "github.com/alecthomas/gocyclo" aligncheck = "github.com/opennota/check/cmd/aligncheck" varcheck = "github.com/opennota/check/cmd/varcheck" dupl = "github.com/mibk/dupl" `
Fix host and path validation.
"use strict"; var fs = require("fs"), main = require("./main"), config = require("./config"); function evaluate(params) { var cmd = params.command || "", filename = params.filename || "", entrypoint = params.entrypoint || "", options = params; if (!cmd && !filename && !entrypoint) { throw new Error("command or filename or entrypoint need to be filled."); } if (cmd && filename) { throw new Error("command and filename are exclusive."); } if (params.host && params.path) { throw new Error("host and path are exclusive."); } if (filename) { cmd = fs.readFileSync(filename, "utf8"); cmd = cmd.replace(/(\r\n)/g, "\n"); } if (entrypoint) { cmd += "\n" + entrypoint + "("; if (params.data) { cmd += "'" + JSON.stringify(params.data) + "')"; } else { cmd += ")"; } } main.sendAction(cmd, config.CMD_TYPE.EVAL, "Sending command to Rserve", options); } exports.evaluate = evaluate;
"use strict"; var fs = require("fs"), main = require("./main"), config = require("./config"); function evaluate(params) { var cmd = params.command || "", filename = params.filename || "", entrypoint = params.entrypoint || "", host = params.host || "127.0.0.1", path = params.path, options = params; if (!cmd && !filename && !entrypoint) { throw new Error("command or filename or entrypoint need to be filled."); } if (cmd && filename) { throw new Error("command and filename are exclusive."); } if (host && path) { throw new Error("host and path are exclusive."); } if (filename) { cmd = fs.readFileSync(filename, "utf8"); cmd = cmd.replace(/(\r\n)/g, "\n"); } if (entrypoint) { cmd += "\n" + entrypoint + "("; if (params.data) { cmd += "'" + JSON.stringify(params.data) + "')"; } else { cmd += ")"; } } main.sendAction(cmd, config.CMD_TYPE.EVAL, "Sending command to Rserve", options); } exports.evaluate = evaluate;
Fix bug option, reader and writer parameters was not being apply if value is set.
<?php namespace Tpg\ExtjsBundle\Annotation; use Doctrine\ORM\Mapping\Annotation; /** * @Annotation * @Target("CLASS") */ final class ModelProxy implements Annotation { public $name = 'memory'; public $option = array(); public $reader = array(); public $writer = array(); public function __construct($values) { if (isset($values['value'])) { $this->name = "rest"; $this->option = array( "url"=>$values['value'], "format"=>"json", ); $this->writer = array( "type"=>"json", "writeRecordId"=>false, ); } else { if (isset($values['name'])) $this->name = $values['name']; } if (isset($values['option'])) $this->option = array_merge($this->option, $values['option']); if (isset($values['writer'])) $this->writer = array_merge($this->writer, $values['writer']); if (isset($values['reader'])) $this->reader = $values['reader']; } }
<?php namespace Tpg\ExtjsBundle\Annotation; use Doctrine\ORM\Mapping\Annotation; /** * @Annotation * @Target("CLASS") */ final class ModelProxy implements Annotation { public $name = 'memory'; public $option = array(); public $reader = array(); public $writer = array(); public function __construct($values) { if (isset($values['value'])) { $this->name = "rest"; $this->option = array( "url"=>$values['value'], "format"=>"json", ); $this->writer = array( "type"=>"json", "writeRecordId"=>false, ); } else { if (isset($values['name'])) $this->name = $values['name']; if (isset($values['option'])) $this->option = $values['option']; if (isset($values['reader'])) $this->reader = $values['reader']; if (isset($values['writer'])) $this->writer = $values['writer']; } } }
Change tested model name to VendorProduct
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models class VendorProductJoinTestCase(TestCase): def setUp(self): self.expected_fields = { 'vendor_id': models.ForeignKey, 'product_id': models.ForeignKey, 'preparation_id': models.ForeignKey, 'vendor_price': models.TextField, 'available': models.NullBooleanField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'VendorProduct') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = VendorProduct._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys()))
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models class VendorProductJoinTestCase(TestCase): def setUp(self): self.expected_fields = { 'vendor_id': models.ForeignKey, 'product_id': models.ForeignKey, 'preparation_id': models.ForeignKey, 'vendor_price': models.TextField, 'available': models.NullBooleanField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'VendorProducts') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = VendorProducts._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys()))
Add missing new line at the end of file. git-svn-id: b819289d3a0e8888cd070d2ae628b7cf730b797f@420071 13f79535-47bb-0310-9956-ffa450edef68
/* * Copyright 2000-2005 The Apache Software 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. */ package org.apache.tomcat.jni; /** Thread * * @author Mladen Turk * @version $Revision: 300969 $, $Date: 2005-07-12 16:56:11 +0200 (uto, 12 srp 2005) $ */ public class Thread { /** * Get the current thread ID handle. */ public static native long current(); }
/* * Copyright 2000-2005 The Apache Software 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. */ package org.apache.tomcat.jni; /** Thread * * @author Mladen Turk * @version $Revision: 300969 $, $Date: 2005-07-12 16:56:11 +0200 (uto, 12 srp 2005) $ */ public class Thread { /** * Get the current thread ID handle. */ public static native long current(); }
Remove closure for 5.2 and 5.3 support
<?php class RequestsTest_Transport_fsockopen extends RequestsTest_Transport_Base { protected $transport = 'Requests_Transport_fsockopen'; public function testHTTPS() { // If OpenSSL isn't loaded, this should fail if (!defined('OPENSSL_VERSION_NUMBER')) { $this->setExpectedException('Requests_Exception'); } return parent::testHTTPS(); } public function testHostHeader() { $hooks = new Requests_Hooks(); $hooks->register('fsockopen.after_headers', array($this, 'headerParseCallback')); $request = Requests::get( 'http://portquiz.positon.org:8080/', array(), $this->getOptions(array('hooks' => $hooks)) ); } public function headerParseCallback($transport) { preg_match('/Host:\s+(.+)\r\n/m', $transport, $headerMatch); $this->assertEquals('portquiz.positon.org:8080', $headerMatch[1]); } }
<?php class RequestsTest_Transport_fsockopen extends RequestsTest_Transport_Base { protected $transport = 'Requests_Transport_fsockopen'; public function testHTTPS() { // If OpenSSL isn't loaded, this should fail if (!defined('OPENSSL_VERSION_NUMBER')) { $this->setExpectedException('Requests_Exception'); } return parent::testHTTPS(); } public function testHostHeader() { $hooks = new Requests_Hooks(); $hooks->register('fsockopen.after_headers', function(&$transport) { preg_match('/Host:\s+(.+)\r\n/m', $transport, $headerMatch); $this->assertEquals('portquiz.positon.org:8080', $headerMatch[1]); }); $request = Requests::get( 'http://portquiz.positon.org:8080/', array(), $this->getOptions(array('hooks' => $hooks)) ); } }
Remove mandrill as a default configuration since it's fallen out of popularity.
<?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Stripe, Mailgun, SparkPost and others. This file provides a sane | default location for this type of information, allowing packages | to have a conventional place to find your various credentials. | */ 'mailgun' => [ 'domain' => env('MAILGUN_DOMAIN'), 'secret' => env('MAILGUN_SECRET'), ], 'ses' => [ 'key' => env('SES_KEY'), 'secret' => env('SES_SECRET'), 'region' => 'us-east-1', ], 'sparkpost' => [ 'secret' => env('SPARKPOST_SECRET'), ], 'stripe' => [ 'model' => App\User::class, 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), ], ];
<?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Stripe, Mailgun, Mandrill, and others. This file provides a sane | default location for this type of information, allowing packages | to have a conventional place to find your various credentials. | */ 'mailgun' => [ 'domain' => env('MAILGUN_DOMAIN'), 'secret' => env('MAILGUN_SECRET'), ], 'mandrill' => [ 'secret' => env('MANDRILL_SECRET'), ], 'ses' => [ 'key' => env('SES_KEY'), 'secret' => env('SES_SECRET'), 'region' => 'us-east-1', ], 'sparkpost' => [ 'secret' => env('SPARKPOST_SECRET'), ], 'stripe' => [ 'model' => App\User::class, 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), ], ];
Use max limit allowed by Spotify.
import ActionFactory from '../utils/actionFactory'; import ConstantFactory from '../utils/constantFactory'; export const USER_PLAYLIST_CONSTANTS = ConstantFactory.buildAsyncFor('USER_PLAYLISTS'); export const PLAYLIST_TRACKS_CONSTANTS = ConstantFactory.buildAsyncFor('PLAYLIST_TRACKS'); export function fetchUserPlaylists(offset = 0, limit = 50){ return ActionFactory.buildSpotifyAction(USER_PLAYLIST_CONSTANTS, { apiCall: 'getUserPlaylists', args: [{offset, limit}] }) } export function fetchPlaylistTracks(userId, playlistId, offset = 0, limit = 100){ return ActionFactory.buildSpotifyAction(PLAYLIST_TRACKS_CONSTANTS, { apiCall: 'getPlaylistTracks', args: [userId, playlistId, {offset, limit}] }, { success: (data) => { data.playlistId = playlistId; data.userId = userId; return data; } }); }
import ActionFactory from '../utils/actionFactory'; import ConstantFactory from '../utils/constantFactory'; export const USER_PLAYLIST_CONSTANTS = ConstantFactory.buildAsyncFor('USER_PLAYLISTS'); export const PLAYLIST_TRACKS_CONSTANTS = ConstantFactory.buildAsyncFor('PLAYLIST_TRACKS'); export function fetchUserPlaylists(offset = 0, limit = 20){ return ActionFactory.buildSpotifyAction(USER_PLAYLIST_CONSTANTS, { apiCall: 'getUserPlaylists', args: [{offset, limit}] }) } export function fetchPlaylistTracks(userId, playlistId, offset = 0, limit = 50){ return ActionFactory.buildSpotifyAction(PLAYLIST_TRACKS_CONSTANTS, { apiCall: 'getPlaylistTracks', args: [userId, playlistId, {offset, limit}] }, { success: (data) => { data.playlistId = playlistId; data.userId = userId; return data; } }); }
Add a method to get the previous GUI.
package io.musician101.musicianlibrary.java.minecraft.gui.chest; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; public abstract class ChestGUI<C, G extends ChestGUI<C, G, I, J, P, S>, I, J, P, S> { @Nonnull protected final List<GUIButton<C, G, I, J, P, S>> buttons; @Nonnull protected final I inventory; protected final int page; @Nonnull protected final P player; @Nonnull protected final J plugin; @Nullable protected final G prevGUI; protected ChestGUI(@Nonnull I inventory, @Nonnull P player, int page, @Nonnull List<GUIButton<C, G, I, J, P, S>> buttons, @Nullable G prevGUI, @Nonnull J plugin, boolean manualOpen) { this.inventory = inventory; this.player = player; this.page = page; this.buttons = buttons; this.prevGUI = prevGUI; this.plugin = plugin; if (!manualOpen) { open(); } } public abstract void close(); @Nullable public G getPreviousGUI() { return prevGUI; } public abstract void open(); }
package io.musician101.musicianlibrary.java.minecraft.gui.chest; import java.util.List; public abstract class ChestGUI<C, G extends ChestGUI<C, G, I, J, P, S>, I, J, P, S> { protected final List<GUIButton<C, G, I, J, P, S>> buttons; protected final I inventory; protected final int page; protected final P player; protected final J plugin; protected final G prevGUI; protected ChestGUI(I inventory, P player, int page, List<GUIButton<C, G, I, J, P, S>> buttons, G prevGUI, J plugin, boolean manualOpen) { this.inventory = inventory; this.player = player; this.page = page; this.buttons = buttons; this.prevGUI = prevGUI; this.plugin = plugin; if (!manualOpen) { open(); } } public abstract void close(); public abstract void open(); }
Add deletion of result after build
# -*- coding: utf8 -*- import json import threading import time import logging from frigg.worker import config from frigg.worker.jobs import Build logger = logging.getLogger(__name__) def fetcher(): redis = config.redis_client() while redis: task = redis.rpop('frigg:queue') if task: __start_task(task) time.sleep(2) def __start_task(json_string): task = json.loads(json_string) thread = threading.Thread(name='build-%s' % task['id'], target=__start_build, args=[task]) thread.daemon = True thread.start() logger.info('Started %s' % task) return thread def __start_build(task): build = Build(task['id'], task) build.run_tests() for result in build.results: del result del build
# -*- coding: utf8 -*- import json import threading import time import logging from frigg.worker import config from frigg.worker.jobs import Build logger = logging.getLogger(__name__) def fetcher(): redis = config.redis_client() while redis: task = redis.rpop('frigg:queue') if task: __start_task(task) time.sleep(2) def __start_task(json_string): task = json.loads(json_string) thread = threading.Thread(name='build-%s' % task['id'], target=__start_build, args=[task]) thread.daemon = True thread.start() logger.info('Started %s' % task) return thread def __start_build(task): build = Build(task['id'], task) build.run_tests() del build
Support running the callback immediately
import { timer as d3Timer } from 'd3-timer'; export default function PeriodicJS(opts) { const { duration, displaySelector, callback, runImmediately } = opts; let timer; function displayTimeLeft(time) { // find the current displayed time let element = document.querySelector(displaySelector); const currentDisplayedTime = element.innerHTML; // format incoming time const formattedTime = Math.ceil(time/1000); // don't update dom element with same string if (formattedTime.toString() !== currentDisplayedTime) { element.innerHTML = 'Update in ' + formattedTime; } } function run() { timer = d3Timer((elapsed, time) => { // tell user how much time is left displayTimeLeft(duration - elapsed); // are we done? if (elapsed > duration) { timer.stop(); // call user-provided callback, and pass along run, // so they can resume the timer, if so desired callback(run); } }); } if (runImmediately) { callback(run); } else { run(); } }
import { timer as d3Timer } from 'd3-timer'; export default function PeriodicJS(opts) { const { duration, displaySelector, callback } = opts; let timer; function displayTimeLeft(time) { // find the current displayed time let element = document.querySelector(displaySelector); const currentDisplayedTime = element.innerHTML; // format incoming time const formattedTime = Math.ceil(time/1000); // don't update dom element with same string if (formattedTime.toString() !== currentDisplayedTime) { element.innerHTML = 'update in ' + formattedTime; } } function run() { timer = d3Timer((elapsed, time) => { // tell user how much time is left displayTimeLeft(duration - elapsed); // are we done? if (elapsed > duration) { timer.stop(); // call user-provided callback, and pass along run, // so they can resume the timer, if so desired callback(run); } }); } run(); }
Stop setting up the listener on an error.
package admin import ( "net" "net/http" "strings" "github.com/rakyll/statik/fs" _ "github.com/influxdb/influxdb/statik" ) type HttpServer struct { port string listener net.Listener closed bool } // port should be a string that looks like ":8083" or whatever port to serve on. func NewHttpServer(port string) *HttpServer { return &HttpServer{port: port, closed: true} } func (s *HttpServer) ListenAndServe() { if s.port == "" { return } s.closed = false var err error s.listener, _ = net.Listen("tcp", s.port) if err != nil { return } statikFS, _ := fs.New() err = http.Serve(s.listener, http.FileServer(statikFS)) if !strings.Contains(err.Error(), "closed") { panic(err) } } func (s *HttpServer) Close() { if s.closed { return } s.closed = true s.listener.Close() }
package admin import ( "net" "net/http" "strings" "github.com/rakyll/statik/fs" _ "github.com/influxdb/influxdb/statik" ) type HttpServer struct { port string listener net.Listener closed bool } // port should be a string that looks like ":8083" or whatever port to serve on. func NewHttpServer(port string) *HttpServer { return &HttpServer{port: port, closed: true} } func (s *HttpServer) ListenAndServe() { if s.port == "" { return } s.closed = false var err error s.listener, _ = net.Listen("tcp", s.port) statikFS, _ := fs.New() err = http.Serve(s.listener, http.FileServer(statikFS)) if !strings.Contains(err.Error(), "closed") { panic(err) } } func (s *HttpServer) Close() { if s.closed { return } s.closed = true s.listener.Close() }
Improve split regex to include \r
/** * Generate a blob link. * @param {string} file - File name * @param {string} contents - Contents of the file * @param {string} title - The title of the new issue * @param {string} sha - Commit where this todo was introduced * @param {object} config - Config object * @returns {string} - GitHub blob link */ module.exports = function generateBlobLink (context, file, contents, title, sha, config) { const {repo, owner} = context.repo() const lines = contents.split(/\r\n|\r|\n/) const totalLines = lines.length const start = lines.findIndex(line => line.includes(`${config.keyword} ${title}`)) + 1 let end = start + config.blobLines // If the proposed end of range is past the last line of the file // make the end the last line of the file. if (totalLines < end) { end = totalLines } let range = `L${start}-L${end}` // Cut off blob line if the issue-to-be is on the last line if (totalLines === start || config.blobLines === 1) { range = `L${start}` } return `https://github.com/${owner}/${repo}/blob/${sha}/${file}#${range}` }
/** * Generate a blob link. * @param {string} file - File name * @param {string} contents - Contents of the file * @param {string} title - The title of the new issue * @param {string} sha - Commit where this todo was introduced * @param {object} config - Config object * @returns {string} - GitHub blob link */ module.exports = function generateBlobLink (context, file, contents, title, sha, config) { const {repo, owner} = context.repo() const lines = contents.split('\n') const totalLines = lines.length const start = lines.findIndex(line => line.includes(`${config.keyword} ${title}`)) + 1 let end = start + config.blobLines // If the proposed end of range is past the last line of the file // make the end the last line of the file. if (totalLines < end) { end = totalLines } let range = `L${start}-L${end}` // Cut off blob line if the issue-to-be is on the last line if (totalLines === start || config.blobLines === 1) { range = `L${start}` } return `https://github.com/${owner}/${repo}/blob/${sha}/${file}#${range}` }
Allow access to symphony dev front controller from the vagrant host
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !in_array(@$_SERVER['REMOTE_ADDR'], array('192.168.23.1', '127.0.0.1', 'fe80::1', '::1')) ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Check entire string for bad words
var detector = (function(){ function Filter(){ this.list = require('./lang.json').words; } Filter.prototype.isProfane = function isProfane(string){ var foundProfane = false; for(var i = 0; i < this.list.length; i++) { var words = string.split(" "); for (var j = 0; j < words.length; j++) { if (words[j].toLowerCase() == this.list[i].toLowerCase()) { return true; } } } return false; }; Filter.prototype.replaceWord = function replaceWord(string){ return string.split("").map(function(c){ return "*"; }).join(""); }; Filter.prototype.clean = function clean(string){ return string.split(" ").map(function(word){ return this.isProfane(word) ? this.replaceWord(word) : word; }.bind(this)).join(" "); }; return Filter; })(); String.prototype.clean = function clean(){ var filter = new detector(); return filter.clean(this); }; module.exports = new detector();
var detector = (function(){ function Filter(){ this.list = require('./lang.json').words; } Filter.prototype.isProfane = function isProfane(string){ for(var i = 0; i < this.list.length; i++) if(string.toLowerCase() == this.list[i].toLowerCase()) return true; return false; }; Filter.prototype.replaceWord = function replaceWord(string){ return string.split("").map(function(c){ return "*"; }).join(""); }; Filter.prototype.clean = function clean(string){ return string.split(" ").map(function(word){ return this.isProfane(word) ? this.replaceWord(word) : word; }.bind(this)).join(" "); }; return Filter; })(); String.prototype.clean = function clean(){ var filter = new detector(); return filter.clean(this); }; module.exports = new detector();
Write each byte at a time in protocol
import serial import time import binascii import struct def establishConnection(): # Define Constants SERIAL_DEVICE = "/dev/ttyACM0" # Establish Connection ser = serial.Serial(SERIAL_DEVICE, 9600) time.sleep(2) print("Connection Established") return ser # Each motor speed is a float from -1.0 to 1.0 def sendDrive(ser, left, right): if(left < -1 or left > 1 or right < -1 or right > 1): print("Incorrectly formated drive command!") return; # Write OpCode ser.write('1') # Write Left Motor Direction if (left >= 0): ser.write(bytes(0)) else: ser.write(bytes(1)) # Write Left Motor Speed ser.write(bytes(abs(left * 255))) # Write Right Motor Direction if (right >= 0): ser.write(bytes(0)) else: ser.write(bytes(1)) # Write Right Motor Speed ser.write(bytes(abs(right * 255))) # Pad message to 9 bytes ser.write(bytes(0)) ser.write(bytes(0)) ser.write(bytes(0)) ser.write(bytes(0)) print('Test') if __name__ == '__main__': ser = establishConnection() sendDrive(ser, -1.0, -1.0) time.sleep(5) sendDrive(ser, 1.0, 1.0) time.sleep(5) sendDrive(ser, 0.0, 0.0)
import serial import time import binascii import struct def establishConnection(): # Define Constants SERIAL_DEVICE = "/dev/ttyACM0" # Establish Connection ser = serial.Serial(SERIAL_DEVICE, 9600) time.sleep(2) print("Connection Established") return ser # Each motor speed is a float from -1.0 to 1.0 def sendDrive(ser, left, right): if(left < -1 or left > 1 or right < -1 or right > 1): print("Incorrectly formated drive command!") return; ser.write('1') #ser.write('0' if left >= 0 else '1') #ser.write(struct.pack("B", abs(left) * 255)) #ser.write('0' if right >= 0 else '1') #ser.write(struct.pack("B", abs(right) * 255)) ser.write('0') ser.write(bytes(255)) ser.write('0') ser.write(bytes(255)) ser.write('0') ser.write('0') ser.write('0') ser.write('0') print('test') if __name__ == '__main__': ser = establishConnection() sendDrive(ser, -1.0, -1.0) time.sleep(5) sendDrive(ser, 1.0, 1.0) time.sleep(5) sendDrive(ser, 0.0, 0.0)
Make sure npm dependencies are also requiring React 0.14-rc.
var webpack = require("webpack"); var path = require("path"); module.exports = { target: "web", cache: false, context: __dirname, devtool: false, entry: ["./src/example"], output: { path: path.join(__dirname, "static/dist"), filename: "client.js", chunkFilename: "[name].[id].js", publicPath: "dist/" }, plugins: [ new webpack.DefinePlugin({"process.env": {NODE_ENV: '"production"'}}), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin() ], module: { loaders: [ {include: /\.json$/, loaders: ["json-loader"]}, {include: /\.js$/, loaders: ["babel-loader?stage=1&optional=runtime"], exclude: /(node_modules|lib)/} ] }, resolve: { alias: { react: path.join(__dirname, "node_modules/react") }, modulesDirectories: [ "src", "node_modules", "web_modules" ], extensions: ["", ".json", ".js"] }, node: { __dirname: true, fs: 'empty' } };
var webpack = require("webpack"); var path = require("path"); module.exports = { target: "web", cache: false, context: __dirname, devtool: false, entry: ["./src/example"], output: { path: path.join(__dirname, "static/dist"), filename: "client.js", chunkFilename: "[name].[id].js", publicPath: "dist/" }, plugins: [ new webpack.DefinePlugin({"process.env": {NODE_ENV: '"production"'}}), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin() ], module: { loaders: [ {include: /\.json$/, loaders: ["json-loader"]}, {include: /\.js$/, loaders: ["babel-loader?stage=1&optional=runtime"], exclude: /(node_modules|lib)/} ] }, resolve: { modulesDirectories: [ "src", "node_modules", "web_modules" ], extensions: ["", ".json", ".js"] }, node: { __dirname: true, fs: 'empty' } };
Reduce size of console window on app startup
var Proxy = require('./proxy'); console.log('Background page initialised'); var config = { tcp: { address: '127.0.0.1', port: 9009 }, consoleType: 'basic' // 'advanced' or 'basic' }; var proxy; chrome.app.runtime.onLaunched.addListener(function() { console.log('App launched.'); startProxy(config.tcp.address, config.tcp.port); launchWindow(); }); chrome.runtime.onSuspend.addListener(function() { console.log('App is being suspended'); stopProxy(); }); function startProxy(address, port, handler) { if (proxy) { console.log('Disconnect proxy'); proxy.disconnect(); } proxy = new Proxy(address, port); } function stopProxy() { proxy.disconnect(); proxy = null; } function pathForConsoleType(type) { return config.consoleType === 'basic' ? 'ui/main.html' : 'ui/console.html'; } function launchWindow() { chrome.app.window.create(pathForConsoleType(config.consoleType), { id: 'main-window', bounds: { width: 800, height: 300, left: 100, top: 100 }, minWidth: 800, minHeight: 600 }); }
var Proxy = require('./proxy'); console.log('Background page initialised'); var config = { tcp: { address: '127.0.0.1', port: 9009 }, consoleType: 'basic' // 'advanced' or 'basic' }; var proxy; chrome.app.runtime.onLaunched.addListener(function() { console.log('App launched.'); startProxy(config.tcp.address, config.tcp.port); launchWindow(); }); chrome.runtime.onSuspend.addListener(function() { console.log('App is being suspended'); stopProxy(); }); function startProxy(address, port, handler) { if (proxy) { console.log('Disconnect proxy'); proxy.disconnect(); } proxy = new Proxy(address, port); } function stopProxy() { proxy.disconnect(); proxy = null; } function pathForConsoleType(type) { return config.consoleType === 'basic' ? 'ui/main.html' : 'ui/console.html'; } function launchWindow() { chrome.app.window.create(pathForConsoleType(config.consoleType), { id: 'main-window', bounds: { width: 800, height: 600, left: 100, top: 100 }, minWidth: 800, minHeight: 600 }); }
Support multiple concurrent test sessions
const net = require('net') const readline = require('readline') const { app, BrowserWindow } = require('electron') app.commandLine.appendSwitch('--disable-http-cache') require('electron-reload')( `${__dirname}/renderer`, { electron: `${__dirname}/node_modules/.bin/electron` } ) const Options = require('./cli/options') const options = new Options(process.argv) let server app.on('ready', () => { if (server) return server = net.createServer((socket) => { let win = new BrowserWindow({ height: 800, width: 900 }) const indexPath = `file://${__dirname}/renderer/index.html` win.loadURL(indexPath) win.on('closed', () => { win = null }) win.webContents.on('did-finish-load', () => { const socketSession = readline.createInterface({ input: socket }) socketSession.on('line', (line) => { const message = JSON.parse(line) if (options.debug) console.log(JSON.stringify(message, null, 2)) win.webContents.send(message['type'], message) }) socketSession.on('close', () => win.webContents.send('end')) }) }) server.listen(options.port || 0, () => { console.log('Cucumber GUI listening for events on port ' + server.address().port) }) })
const net = require('net') const readline = require('readline') const { app, BrowserWindow } = require('electron') app.commandLine.appendSwitch('--disable-http-cache') require('electron-reload')( `${__dirname}/renderer`, { electron: `${__dirname}/node_modules/.bin/electron` } ) const Options = require('./cli/options') const options = new Options(process.argv) let win let server app.on('ready', () => { win = new BrowserWindow({ height: 800, width: 900 }) const indexPath = `file://${__dirname}/renderer/index.html` win.loadURL(indexPath) win.on('closed', () => { win = null }) win.webContents.on('did-finish-load', () => { if (server) return server = net.createServer((socket) => { const socketSession = readline.createInterface({ input: socket }) socketSession.on('line', (line) => { const message = JSON.parse(line) if (options.debug) console.log(JSON.stringify(message, null, 2)) win.webContents.send(message['type'], message) }) socketSession.on('close', () => win.webContents.send('end')) }) server.listen(options.port || 0, () => { console.log('Cucumber GUI listening for events on port ' + server.address().port) }) }) })
Add option to Ignore Comments
'use babel' /*global atom*/ import { lint } from 'mixedindentlint' import LinterHelpers from 'atom-linter' export default { config: { ignoreComments: { type: 'boolean', default: false, title: 'Ignore Comments', description: 'Ignore comments entirely in code. Otherwise comment indentation will be scanned as well.' } }, activate() { }, deactivate() { }, scanFile( textEditor ) { const options = { comments: atom.config.get( 'linter-mixed-indent.ignoreComments' ) } const text = textEditor.getText() const linesToDecorate = lint( text, options ) return linesToDecorate.map( line => { return { type: 'Warning', text: 'Indentation different from rest of file', range: LinterHelpers.rangeFromLineNumber( textEditor, line - 1 ), filePath: textEditor.getPath() } } ) }, provideLinter() { return { name: 'MixedIndent', grammarScopes: [ '*' ], scope: 'file', lintOnFly: true, lint: this.scanFile } } }
'use babel' import { lint } from 'mixedindentlint' import LinterHelpers from 'atom-linter' export default { config: {}, activate() { }, deactivate() { }, scanFile( textEditor ) { const text = textEditor.getText() const linesToDecorate = lint( text ) return linesToDecorate.map( line => { return { type: 'Warning', text: 'Indentation different from rest of file', range: LinterHelpers.rangeFromLineNumber( textEditor, line - 1 ), filePath: textEditor.getPath() } } ) }, provideLinter() { return { name: 'MixedIndent', grammarScopes: [ '*' ], scope: 'file', lintOnFly: true, lint: this.scanFile } } }
Replace bytes by strings in zilencer/migrations.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0001_initial'), ] operations = [ migrations.CreateModel( name='Deployment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('is_active', models.BooleanField(default=True)), ('api_key', models.CharField(max_length=32, null=True)), ('base_api_url', models.CharField(max_length=128)), ('base_site_url', models.CharField(max_length=128)), ('realms', models.ManyToManyField(related_name='_deployments', to='zerver.Realm')), ], options={ }, bases=(models.Model,), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0001_initial'), ] operations = [ migrations.CreateModel( name='Deployment', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('is_active', models.BooleanField(default=True)), ('api_key', models.CharField(max_length=32, null=True)), ('base_api_url', models.CharField(max_length=128)), ('base_site_url', models.CharField(max_length=128)), ('realms', models.ManyToManyField(related_name=b'_deployments', to='zerver.Realm')), ], options={ }, bases=(models.Model,), ), ]
Fix up path to runtime library directory.
from . import tokenizer, ast, codegen import sys, os, subprocess BASE = os.path.dirname(__path__[0]) RT_DIR = os.path.join(BASE, 'rt') TRIPLES = { 'darwin': 'x86_64-apple-darwin11.0.0', 'linux2': 'x86_64-pc-linux-gnu', } def llir(fn, full=True): src = codegen.source(ast.parse(tokenizer.tokenize(open(fn)))) if not full: return src std = [] for fn in sorted(os.listdir(RT_DIR)): with open(os.path.join(RT_DIR, fn)) as f: std.append(f.read() + '\n') triple = 'target triple = "%s"\n\n' % TRIPLES[sys.platform] return triple + ''.join(std) + src def compile(fn, outfn): llfn = fn + '.ll' with open(llfn, 'w') as f: f.write(llir(fn)) subprocess.check_call(('clang', '-o', outfn, llfn)) os.unlink(llfn)
from . import tokenizer, ast, codegen import sys, os, subprocess TRIPLES = { 'darwin': 'x86_64-apple-darwin11.0.0', 'linux2': 'x86_64-pc-linux-gnu', } def llir(fn, full=True): src = codegen.source(ast.parse(tokenizer.tokenize(open(fn)))) if not full: return src std = [] for fn in sorted(os.listdir('rt')): with open(os.path.join('rt', fn)) as f: std.append(f.read() + '\n') triple = 'target triple = "%s"\n\n' % TRIPLES[sys.platform] return triple + ''.join(std) + src def compile(fn, outfn): llfn = fn + '.ll' with open(llfn, 'w') as f: f.write(llir(fn)) subprocess.check_call(('clang', '-o', outfn, llfn)) os.unlink(llfn)
Update new repository for gcfg
package config import ( "gopkg.in/gcfg.v1" "path/filepath" ) type Config struct { RabbitMq struct { Host string Username string Password string Port string Vhost string Queue string Compression bool } Prefetch struct { Count int Global bool } Exchange struct { Name string Autodelete bool Type string Durable bool } Logs struct { Error string Info string } } func LoadAndParse(location string) (*Config, error) { if !filepath.IsAbs(location) { location, err := filepath.Abs(location) if err != nil { return nil, err } location = location } cfg := Config{} if err := gcfg.ReadFileInto(&cfg, location); err != nil { return nil, err } return &cfg, nil }
package config import ( "code.google.com/p/gcfg" "path/filepath" ) type Config struct { RabbitMq struct { Host string Username string Password string Port string Vhost string Queue string Compression bool } Prefetch struct { Count int Global bool } Exchange struct { Name string Autodelete bool Type string Durable bool } Logs struct { Error string Info string } } func LoadAndParse(location string) (*Config, error) { if !filepath.IsAbs(location) { location, err := filepath.Abs(location) if err != nil { return nil, err } location = location } cfg := Config{} if err := gcfg.ReadFileInto(&cfg, location); err != nil { return nil, err } return &cfg, nil }
Fix Python 2.5 support in tests
from __future__ import with_statement from gears.asset_handler import AssetHandlerError, ExecMixin from mock import patch, Mock from unittest2 import TestCase class Exec(ExecMixin): executable = 'program' class ExecMixinTests(TestCase): @patch('gears.asset_handler.Popen') def test_returns_stdout_on_success(self, Popen): result = Mock() result.returncode = 0 result.communicate.return_value = ('output', '') Popen.return_value = result self.assertEqual(Exec().run('input'), 'output') @patch('gears.asset_handler.Popen') def test_raises_stderr_on_failure(self, Popen): result = Mock() result.returncode = 1 result.communicate.return_value = ('', 'error') Popen.return_value = result with self.assertRaises(AssetHandlerError): Exec().run('input')
from gears.asset_handler import AssetHandlerError, ExecMixin from mock import patch, Mock from unittest2 import TestCase class Exec(ExecMixin): executable = 'program' class ExecMixinTests(TestCase): @patch('gears.asset_handler.Popen') def test_returns_stdout_on_success(self, Popen): result = Mock() result.returncode = 0 result.communicate.return_value = ('output', '') Popen.return_value = result self.assertEqual(Exec().run('input'), 'output') @patch('gears.asset_handler.Popen') def test_raises_stderr_on_failure(self, Popen): result = Mock() result.returncode = 1 result.communicate.return_value = ('', 'error') Popen.return_value = result with self.assertRaises(AssetHandlerError): Exec().run('input')
Make sure the limit is an int
from flask import Flask from flask import jsonify from red_api import get_suspect_mentions, get_tweet_count, get_suspect_tweets from jsonp_flask import support_jsonp app = Flask(__name__) @app.route('/api/tweets/suspects/count', methods=['GET']) @support_jsonp def get_mentions(): return jsonify(results=get_suspect_mentions()) @app.route('/api/tweets/count', methods=['GET']) @support_jsonp def get_total_tweet_count(): return jsonify(results=get_tweet_count()) @app.route('/api/tweets/<suspect>/<limit>') @support_jsonp def get_tweets(suspect, limit): return jsonify(results=get_suspect_tweets(suspect, int(limit))) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
from flask import Flask from flask import jsonify from red_api import get_suspect_mentions, get_tweet_count, get_suspect_tweets from jsonp_flask import support_jsonp app = Flask(__name__) @app.route('/api/tweets/suspects/count', methods=['GET']) @support_jsonp def get_mentions(): return jsonify(results=get_suspect_mentions()) @app.route('/api/tweets/count', methods=['GET']) @support_jsonp def get_total_tweet_count(): return jsonify(results=get_tweet_count()) @app.route('/api/tweets/<suspect>/<limit>') @support_jsonp def get_tweets(suspect, limit): return jsonify(results=get_suspect_tweets(suspect, limit)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
Add placeholder abilities route callback.
module.exports = function(app, settings) { app.get('/status.json', function(req, res) { res.send({ status: 'true' }); }); /** * @TODO expose available fonts (and other 'abilities'). */ app.get('/abilities.json', function(req, res) { res.send({ fonts: [] }); }); /** * Inspect fields */ app.get('/:mapfile_64/fields.json', function(req, res) { }); /** * Inspect data */ app.get('/:mapfile_64/data.json', function(req, res) { }); /** * Inspect layer */ app.get('/:mapfile_64/:layer_64/layer.json', function(req, res) { }); /** * Inspect field values */ app.get('/:mapfile_64/:layer_64/:feature_64/values.json', function(req, res) { }); }
module.exports = function(app, settings) { app.get('/status.json', function(req, res) { res.send({ status: 'true' }); }); /** * Inspect fields */ app.get('/:mapfile_64/fields.json', function(req, res) { }); /** * Inspect data */ app.get('/:mapfile_64/data.json', function(req, res) { }); /** * Inspect layer */ app.get('/:mapfile_64/:layer_64/layer.json', function(req, res) { }); /** * Inspect field values */ app.get('/:mapfile_64/:layer_64/:feature_64/values.json', function(req, res) { }); }
Set redirect and alias config before starting app
import Vue from 'vue'; import VueRouter from 'vue-router'; import VueForm from 'vue-form'; import { sync } from 'vuex-router-sync'; import store from './vuex/store.js'; import * as actions from './vuex/actions.js'; import App from './app.vue'; import FeatureList from './components/featurelist.vue'; import FeatureForm from './components/featureform.vue'; Vue.use(VueRouter); Vue.use(VueForm); let router = new VueRouter({ linkActiveClass: 'active' }); /* sync route info to store */ sync(store, router); router.map({ '/list': { name: 'home' }, '/list/:page': { component: FeatureList, name: 'list-all' }, '/new': { component: FeatureForm, name: 'new-feature' } }); router.redirect({ '*': '/list/1' }); router.alias({ '/list': '/list/1' }); /* Bootstrap the application */ router.start({ template: '<div><app></app></div>', store, components: { App }, vuex: { actions }, compiled() { this.fetchFeatures(); this.fetchClients(); this.fetchProductAreas(); } }, '#app');
import Vue from 'vue'; import VueRouter from 'vue-router'; import VueForm from 'vue-form'; import { sync } from 'vuex-router-sync'; import store from './vuex/store.js'; import * as actions from './vuex/actions.js'; import App from './app.vue'; import FeatureList from './components/featurelist.vue'; import FeatureForm from './components/featureform.vue'; Vue.use(VueRouter); Vue.use(VueForm); let router = new VueRouter({ linkActiveClass: 'active' }); /* sync route info to store */ sync(store, router); router.map({ '/list': { name: 'home' }, '/list/:page': { component: FeatureList, name: 'list-all' }, '/new': { component: FeatureForm, name: 'new-feature' } }); /* Bootstrap the application */ router.start({ template: '<div><app></app></div>', store, components: { App }, vuex: { actions }, compiled() { this.fetchFeatures(); this.fetchClients(); this.fetchProductAreas(); } }, '#app'); router.redirect({ '*': '/list/1' }); router.alias({ '/list': '/list/1' });
Add support for unexpected fields and improved out of order.
/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.wire; import net.openhft.chronicle.core.Jvm; import net.openhft.chronicle.core.annotation.NotNull; import net.openhft.chronicle.core.io.IORuntimeException; /* * Created by peter on 16/03/16. */ public abstract class AbstractMarshallableCfg extends AbstractMarshallable { @Override public void readMarshallable(@NotNull WireIn wire) throws IORuntimeException { Wires.readMarshallable(this, wire, false); } @Override public void writeMarshallable(@NotNull WireOut wire) { Wires.writeMarshallable(this, wire, false); } @Override public void unexpectedField(Object event, ValueIn valueIn) { Jvm.warn().on(getClass(), "Field " + event + " ignored, was " + valueIn.object()); } }
/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.wire; import net.openhft.chronicle.core.annotation.NotNull; import net.openhft.chronicle.core.io.IORuntimeException; /* * Created by peter on 16/03/16. */ public abstract class AbstractMarshallableCfg extends AbstractMarshallable { @Override public void readMarshallable(@NotNull WireIn wire) throws IORuntimeException { Wires.readMarshallable(this, wire, false); } @Override public void writeMarshallable(@NotNull WireOut wire) { Wires.writeMarshallable(this, wire, false); } }
Add missing `await` to outer iterator `next` call. Closes #46.
module.exports = function (paginator, twiddle) { const outer = paginator[Symbol.asyncIterator]() return { [Symbol.asyncIterator]: function () { return this }, next: async function () { const inner = await outer.next() if (inner.done) { return { done: true, value: null } } return { done: false, value: inner.value.map(item => twiddle(item)) } } } }
module.exports = function (paginator, twiddle) { const outer = paginator[Symbol.asyncIterator]() return { [Symbol.asyncIterator]: function () { return this }, next: async function () { const inner = outer.next() if (inner.done) { return { done: true, value: null } } return { done: false, value: inner.value.map(item => twiddle(item)) } } } }
Fix keyword arg in deallocate cascade.
#---------------------------------------------------------------------- # Copyright (c) 2011 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Work, and to permit persons to whom the Work # is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Work. # # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS # IN THE WORK. #---------------------------------------------------------------------- import uuid from resource import Resource class FakeVM(Resource): def __init__(self, agg): super(FakeVM, self).__init__(str(uuid.uuid4()), "fakevm") self._agg = agg def deprovision(self): """Deprovision this resource at the resource provider.""" self._agg.deallocate(container=None, resources=[self])
#---------------------------------------------------------------------- # Copyright (c) 2011 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Work, and to permit persons to whom the Work # is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Work. # # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS # IN THE WORK. #---------------------------------------------------------------------- import uuid from resource import Resource class FakeVM(Resource): def __init__(self, agg): super(FakeVM, self).__init__(str(uuid.uuid4()), "fakevm") self._agg = agg def deprovision(self): """Deprovision this resource at the resource provider.""" self._agg.deallocate(containers=None, resources=[self])
Replace default transport for logging, remove file logging
const winston = require('winston'); module.exports = ({ level, transports: transports = [ { type: 'Console', options: { timestamp: true, colorize: process.env.NODE_ENV !== 'production', prettyPrint: process.env.NODE_ENV !== 'production', json: process.env.NODE_ENV === 'production', stringify: obj => JSON.stringify(obj), silent: process.env.NODE_ENV === 'test', level: 'debug', }, }, ], }) => { if (level) { for (const transport of transports) { transport.options = transport.options || {}; transport.options.level = level; } } return (category, options) => { const logger = new winston.Logger(options); for (const transport of transports) { logger.add( winston.transports[transport.type], Object.assign({}, transport.options, { label: category }) ); } return logger; }; };
const winston = require('winston'); module.exports = ({ filename, level, transports: transports = [{ type: 'Console', options: { level: 'debug' } }], }) => { if (filename) { transports.push({ type: 'File', options: { filename, level: 'debug' }, }); } if (level) { for (const transport of transports) { transport.options = transport.options || {}; transport.options.level = level; } } return (category, options) => { const logger = new winston.Logger(options); for (const transport of transports) { logger.add( winston.transports[transport.type], Object.assign({}, transport.options, { label: category }) ); } return logger; }; };
Use camel case yaml naming strategy instead of lower camel case
<?php /* * This file is part of the FixtureDumper library. * * (c) Martin Parsiegla <martin.parsiegla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sp\FixtureDumper\Generator\Alice; use Symfony\Component\Yaml\Yaml; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Sp\FixtureDumper\Converter\Alice\YamlVisitor; use Sp\FixtureDumper\Generator\AbstractAliceGenerator; /** * @author Martin Parsiegla <martin.parsiegla@gmail.com> */ class YamlFixtureGenerator extends AbstractAliceGenerator { /** * {@inheritdoc} */ public function createFilename(ClassMetadata $metadata, $multipleFiles = true) { if ($multipleFiles) { return $this->namingStrategy->fixtureName($metadata) .'.yml'; } return 'fixtures.yml'; } /** * {@inheritdoc} */ protected function prepareData(ClassMetadata $metadata, array $data) { $yaml = new Yaml(); return $yaml->dump(array($metadata->getName() => $data), 3); } /** * {@inheritdoc} */ protected function getDefaultVisitor() { return new YamlVisitor(); } }
<?php /* * This file is part of the FixtureDumper library. * * (c) Martin Parsiegla <martin.parsiegla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sp\FixtureDumper\Generator\Alice; use Symfony\Component\Yaml\Yaml; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Sp\FixtureDumper\Converter\Alice\YamlVisitor; use Sp\FixtureDumper\Generator\AbstractAliceGenerator; /** * @author Martin Parsiegla <martin.parsiegla@gmail.com> */ class YamlFixtureGenerator extends AbstractAliceGenerator { /** * {@inheritdoc} */ public function createFilename(ClassMetadata $metadata, $multipleFiles = true) { if ($multipleFiles) { return lcfirst($this->namingStrategy->fixtureName($metadata) .'.yml'); } return 'fixtures.yml'; } /** * {@inheritdoc} */ protected function prepareData(ClassMetadata $metadata, array $data) { $yaml = new Yaml(); return $yaml->dump(array($metadata->getName() => $data), 3); } /** * {@inheritdoc} */ protected function getDefaultVisitor() { return new YamlVisitor(); } }
Fix packaging (again) - 1.0b9
from setuptools import setup, find_packages setup( name = "django-waitinglist", version = "1.0b9", author = "Brian Rosner", author_email = "brosner@gmail.com", description = "a Django waiting list app for running a private beta with cohorts support", long_description = open("README.rst").read(), license = "MIT", url = "http://github.com/pinax/django-waitinglist", packages = find_packages(), package_data = {"waitinglist": ["waitinglist/templates/*"]}, install_requires = [ "django-appconf==0.5", ], classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ] )
from setuptools import setup, find_packages setup( name = "django-waitinglist", version = "1.0b8", author = "Brian Rosner", author_email = "brosner@gmail.com", description = "a Django waiting list app for running a private beta with cohorts support", long_description = open("README.rst").read(), license = "MIT", url = "http://github.com/pinax/django-waitinglist", packages = find_packages(), install_requires = [ "django-appconf==0.5", ], classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ] )
Modify test for approximate equality A change in Node 12 means that the test value we were previously using differs from the new result by `2.7755575615628914e-17`.
var chai = require('chai'); var assert = chai.assert; var TestData = require('../TestData'); // Setup var spectralKurtosis = require('../../dist/node/extractors/spectralKurtosis'); describe('spectralKurtosis', function () { it('should return correct Spectral Kurtosis value', function (done) { var en = spectralKurtosis({ ampSpectrum:TestData.VALID_AMPLITUDE_SPECTRUM, }); assert.approximately(en, 0.1511072674115075, 1e-15); done(); }); it('should throw an error when passed an empty object', function (done) { try { var en = spectralKurtosis({}); } catch (e) { done(); } }); it('should throw an error when not passed anything', function (done) { try { var en = spectralKurtosis(); } catch (e) { done(); } }); it('should throw an error when passed something invalid', function (done) { try { var en = spectralKurtosis({ signal:'not a signal' }); } catch (e) { done(); } }); });
var chai = require('chai'); var assert = chai.assert; var TestData = require('../TestData'); // Setup var spectralKurtosis = require('../../dist/node/extractors/spectralKurtosis'); describe('spectralKurtosis', function () { it('should return correct Spectral Kurtosis value', function (done) { var en = spectralKurtosis({ ampSpectrum:TestData.VALID_AMPLITUDE_SPECTRUM, }); assert.equal(en, 0.1511072674115075); done(); }); it('should throw an error when passed an empty object', function (done) { try { var en = spectralKurtosis({}); } catch (e) { done(); } }); it('should throw an error when not passed anything', function (done) { try { var en = spectralKurtosis(); } catch (e) { done(); } }); it('should throw an error when passed something invalid', function (done) { try { var en = spectralKurtosis({ signal:'not a signal' }); } catch (e) { done(); } }); });
Introduce type for parsing jsonb
package psql import ( "errors" "database/sql/driver" "encoding/json" _ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( DB *gorm.DB DBError error ) func init() { cobra.OnInitialize(ConnectDB) } func ConnectDB() { viper.SetDefault("database_scheme", "postgres") scheme := viper.GetString("database_scheme") url := viper.GetString("database_url") if len(url) == 0 { DBError = errors.New("Missing database_url") } else { if scheme != "postgres" { gorm.RegisterDialect(scheme, gorm.DialectsMap["postgres"]) } DB, DBError = gorm.Open(scheme, url) } } type JsonB map[string]interface{} func (j JsonB) Value() (driver.Value, error) { return json.Marshal(j) } func (j *JsonB) Scan(src interface{}) error { source, ok := src.([]byte) if !ok { return errors.New("Type assertion .([]byte) failed.") } var i interface{} err := json.Unmarshal(source, &i) if err != nil { return err } *j, ok = i.(map[string]interface{}) if !ok { return errors.New("Type assertion .(map[string]interface{}) failed.") } return nil }
package psql import ( "errors" _ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( DB *gorm.DB DBError error ) func init() { cobra.OnInitialize(ConnectDB) } func ConnectDB() { viper.SetDefault("database_scheme", "postgres") scheme := viper.GetString("database_scheme") url := viper.GetString("database_url") if len(url) == 0 { DBError = errors.New("Missing database_url") } else { if scheme != "postgres" { gorm.RegisterDialect(scheme, gorm.DialectsMap["postgres"]) } DB, DBError = gorm.Open(scheme, url) } }
Fix broken newsflow on launch
<? defined('C5_EXECUTE') or die("Access Denied."); $this->inc('elements/header.php', array('enableEditing' => true)); ?> <div class="ccm-ui"> <div class="newsflow" id="newsflow-main"> <? $this->inc('elements/header_newsflow.php'); ?> <table class="newsflow-layout"> <tr> <td class="newsflow-em1" style="width: 66%" rowspan="3"> <div id="ccm-dashboard-welcome-back"> <? $a = new Area('Primary'); $a->display($c); ?> </div> </td> <td><? $a = new Area('Secondary 1'); $a->display($c); ?></td> </tr> <tr> <td style="width: 34%"><? $a = new Area('Secondary 2'); $a->display($c); ?></td> </tr> <tr> <td style="width: 34%"><? $a = new Area('Secondary 5'); $a->display($c); ?></td> </tr> </table> </div> </div> <? $this->inc('elements/footer.php'); ?>
<? defined('C5_EXECUTE') or die("Access Denied."); $this->inc('elements/header.php', array('enableEditing' => true)); ?> <div class="ccm-ui"> <div class="newsflow" id="newsflow-main"> <? $this->inc('elements/header_newsflow.php'); ?> <table class="newsflow-layout"> <tr> <td class="newsflow-em1" style="width: 66%" colspan="2" rowspan="2"> <div id="ccm-dashboard-welcome-back"> <? $a = new Area('Primary'); $a->display($c); ?> </div> </td> <td><? $a = new Area('Secondary 1'); $a->display($c); ?></td> </tr> <tr> <td style="width: 34%"><? $a = new Area('Secondary 2'); $a->display($c); ?></td> </tr> <tr> <td style="width: 33%"><? $a = new Area('Secondary 3'); $a->display($c); ?></td> <td style="width: 33%"><? $a = new Area('Secondary 4'); $a->display($c); ?></td> <td style="width: 34%"><? $a = new Area('Secondary 5'); $a->display($c); ?></td> </tr> </table> </div> </div> <? $this->inc('elements/footer.php'); ?>
Fix unused title in profiles controller
(function () { 'use strict'; /* ngInject */ function ProfilesController(NavbarConfig, ProfileService) { var ctl = this; initialize(); function initialize() { ProfileService.createProfile('Donald'); ProfileService.createProfile('Mickey'); ProfileService.createProfile('Minnie'); ctl.usernames = ProfileService.getProfileNames(); var title = ctl.usernames.length ? ctl.usernames[0] : 'Profile'; NavbarConfig.set({ title: title}); } } angular.module('nih.views.profile') .controller('ProfilesController', ProfilesController); })();
(function () { 'use strict'; /* ngInject */ function ProfilesController(NavbarConfig, ProfileService) { var ctl = this; initialize(); function initialize() { ProfileService.createProfile('Donald'); ProfileService.createProfile('Mickey'); ProfileService.createProfile('Minnie'); ctl.usernames = ProfileService.getProfileNames(); var title = ctl.usernames.length ? ctl.usernames[0] : 'Profile'; NavbarConfig.set({ title: ctl.usernames[0]}); } } angular.module('nih.views.profile') .controller('ProfilesController', ProfilesController); })();
Add discrete uniform variance to namespace
'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace discreteUniform */ var discreteUniform = {}; /** * @name mean * @memberof discreteUniform * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dists/discrete-uniform/mean} */ setReadOnly( discreteUniform, 'mean', require( '@stdlib/math/base/dists/discrete-uniform/mean' ) ); /** * @name median * @memberof discreteUniform * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dists/discrete-uniform/median} */ setReadOnly( discreteUniform, 'median', require( '@stdlib/math/base/dists/discrete-uniform/median' ) ); /** * @name variance * @memberof discreteUniform * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dists/discrete-uniform/variance} */ setReadOnly( discreteUniform, 'variance', require( '@stdlib/math/base/dists/discrete-uniform/variance' ) ); // EXPORTS // module.exports = discreteUniform;
'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace discreteUniform */ var discreteUniform = {}; /** * @name mean * @memberof discreteUniform * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dists/discrete-uniform/mean} */ setReadOnly( discreteUniform, 'mean', require( '@stdlib/math/base/dists/discrete-uniform/mean' ) ); /** * @name median * @memberof discreteUniform * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dists/discrete-uniform/median} */ setReadOnly( discreteUniform, 'median', require( '@stdlib/math/base/dists/discrete-uniform/median' ) ); // EXPORTS // module.exports = discreteUniform;
Fix wide button accessibility labels
import React, { PropTypes } from 'react'; import { View, TouchableOpacity, StyleSheet, Text, } from 'react-native'; import { globalStyles } from '../../styles'; const styles = StyleSheet.create({ wideButton: { flexDirection: 'row', alignItems: 'center', marginVertical: 10, paddingHorizontal: 10, borderWidth: 1, height: 45, }, }); const WideButton = (props) => { return ( <TouchableOpacity accessible={true} accessibilityTraits={!props.disabled ? 'button' : 'text'} accessibilityLabel={props.text} onPress={props.onPress} styles={styles.container} disabled={props.disabled || false} > <View style={[styles.wideButton, props.style]}> <Text style={[globalStyles.h1, props.textStyle, { flex: 1 }]}> {props.text} </Text> {props.accessoryView} </View> </TouchableOpacity> ); }; WideButton.propTypes = { style: PropTypes.oneOfType([ View.propTypes.style, PropTypes.object, ]), textStyle: PropTypes.oneOfType([ Text.propTypes.style, PropTypes.object, ]), disabled: PropTypes.bool, accessoryView: PropTypes.object, text: PropTypes.string.isRequired, onPress: PropTypes.func, }; export default WideButton;
import React, { PropTypes } from 'react'; import { View, TouchableOpacity, StyleSheet, Text, } from 'react-native'; import { globalStyles } from '../../styles'; const styles = StyleSheet.create({ wideButton: { flexDirection: 'row', alignItems: 'center', marginVertical: 10, paddingHorizontal: 10, borderWidth: 1, height: 45, }, }); const WideButton = (props) => { return ( <TouchableOpacity onPress={props.onPress} styles={styles.container} disabled={props.disabled || false} > <View style={[styles.wideButton, props.style]}> <Text style={[globalStyles.h1, props.textStyle, { flex: 1 }]}> {props.text} </Text> {props.accessoryView} </View> </TouchableOpacity> ); }; WideButton.propTypes = { style: PropTypes.oneOfType([ View.propTypes.style, PropTypes.object, ]), textStyle: PropTypes.oneOfType([ Text.propTypes.style, PropTypes.object, ]), disabled: PropTypes.bool, accessoryView: PropTypes.object, text: PropTypes.string.isRequired, onPress: PropTypes.func, }; export default WideButton;
Remove all relative imports. We have always been at war with relative imports. git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@17009 bcc190cf-cafb-0310-a4f2-bffc1f526a37
""" JP-specific Form helpers """ from __future__ import absolute_import from django.contrib.localflavor.jp.jp_prefectures import JP_PREFECTURES from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length, min_length, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES)
""" JP-specific Form helpers """ from django.utils.translation import ugettext_lazy as _ from django.forms.fields import RegexField, Select class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, with or without a hyphen. """ default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', max_length, min_length, *args, **kwargs) def clean(self, value): """ Validates the input and returns a string that contains only numbers. Returns an empty string for empty values. """ v = super(JPPostalCodeField, self).clean(value) return v.replace('-', '') class JPPrefectureSelect(Select): """ A Select widget that uses a list of Japanese prefectures as its choices. """ def __init__(self, attrs=None): from jp_prefectures import JP_PREFECTURES super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES)
Add translate=True on academic title name
# -*- coding: utf-8 -*- ############################################################################## # # This file is part of partner_academic_title, # an Odoo module. # # Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>) # # partner_academic_title 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. # # partner_academic_title 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 partner_academic_title. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields class PartnerAcademicTitle(models.Model): _name = 'partner.academic.title' name = fields.Char(required=True, translate=True) sequence = fields.Integer(required=True, help="""defines the order to display titles""") active = fields.Boolean(default=True)
# -*- coding: utf-8 -*- ############################################################################## # # This file is part of partner_academic_title, # an Odoo module. # # Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>) # # partner_academic_title 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. # # partner_academic_title 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 partner_academic_title. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields class PartnerAcademicTitle(models.Model): _name = 'partner.academic.title' name = fields.Char(required=True) sequence = fields.Integer(required=True, help="""defines the order to display titles""") active = fields.Boolean(default=True)
Simplify done call as per PR review
import ExecutorAbstract from '../ExecutorAbstract'; import {sleep} from '../util/function'; class SleepExecutor extends ExecutorAbstract { //----------------------------------- // Constructor //----------------------------------- /** * Constructor for a new SleepExecutor, which will wait `milliseconds` before calling `this.done()` * * @param thread The parent thread that owns this executor. * @param milliseconds The number of milliseconds to sleep */ constructor(thread, milliseconds) { super(thread); this.milliseconds = milliseconds; } //----------------------------------- // Methods //----------------------------------- /** * Internal execution method called by Thread only. * * @param doneHandler The handler to call when done() is called. * @param failHandler The handler to call when fail() is called; * @private */ _execute(doneHandler, failHandler) { super._execute(doneHandler, failHandler); sleep(this.milliseconds).then(this.done); } toString() { return this.id + ': Sleep for ' + this.milliseconds + 'milliseconds'; } } export default SleepExecutor;
import ExecutorAbstract from '../ExecutorAbstract'; import {sleep} from '../util/function'; class SleepExecutor extends ExecutorAbstract { //----------------------------------- // Constructor //----------------------------------- /** * Constructor for a new SleepExecutor, which will wait `milliseconds` before calling `this.done()` * * @param thread The parent thread that owns this executor. * @param milliseconds The number of milliseconds to sleep */ constructor(thread, milliseconds) { super(thread); this.milliseconds = milliseconds; } //----------------------------------- // Methods //----------------------------------- /** * Internal execution method called by Thread only. * * @param doneHandler The handler to call when done() is called. * @param failHandler The handler to call when fail() is called; * @private */ _execute(doneHandler, failHandler) { super._execute(doneHandler, failHandler); sleep(this.milliseconds).then(() => this.done()); } toString() { return this.id + ': Sleep for ' + this.milliseconds + 'milliseconds'; } } export default SleepExecutor;
Make the _array_api submodule install correctly
#!/usr/bin/env python3 def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numpy', parent_package, top_path) config.add_subpackage('_array_api') config.add_subpackage('compat') config.add_subpackage('core') config.add_subpackage('distutils') config.add_subpackage('doc') config.add_subpackage('f2py') config.add_subpackage('fft') config.add_subpackage('lib') config.add_subpackage('linalg') config.add_subpackage('ma') config.add_subpackage('matrixlib') config.add_subpackage('polynomial') config.add_subpackage('random') config.add_subpackage('testing') config.add_subpackage('typing') config.add_data_dir('doc') config.add_data_files('py.typed') config.add_data_files('*.pyi') config.add_subpackage('tests') config.make_config_py() # installs __config__.py return config if __name__ == '__main__': print('This is the wrong setup.py file to run')
#!/usr/bin/env python3 def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numpy', parent_package, top_path) config.add_subpackage('compat') config.add_subpackage('core') config.add_subpackage('distutils') config.add_subpackage('doc') config.add_subpackage('f2py') config.add_subpackage('fft') config.add_subpackage('lib') config.add_subpackage('linalg') config.add_subpackage('ma') config.add_subpackage('matrixlib') config.add_subpackage('polynomial') config.add_subpackage('random') config.add_subpackage('testing') config.add_subpackage('typing') config.add_data_dir('doc') config.add_data_files('py.typed') config.add_data_files('*.pyi') config.add_subpackage('tests') config.make_config_py() # installs __config__.py return config if __name__ == '__main__': print('This is the wrong setup.py file to run')
Fix url rewrites in nginx
<?php /* GNU FM -- a free network service for sharing your music listening habits Copyright (C) 2009 Free Software Foundation, Inc 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/>. */ /** * Encodes an URL component in a mod_rewrite friendly way, handling plus, * ampersand, hash and slash signs. * * @param string The text to encode * @return string A mod_rewrite compatible encoding of the given text. */ function rewrite_encode($url) { if (preg_match('/Apache/', $_SERVER['SERVER_SOFTWARE'])) { $url = urlencode($url); $url = preg_replace('/%2B/', '%252B', $url); // + $url = preg_replace('/%2F/', '%252F', $url); // / $url = preg_replace('/%26/', '%2526', $url); // & $url = preg_replace('/%23/', '%2523', $url); // # } else { $url = rawurlencode($url); } return $url; }
<?php /* GNU FM -- a free network service for sharing your music listening habits Copyright (C) 2009 Free Software Foundation, Inc 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/>. */ /** * Encodes an URL component in a mod_rewrite friendly way, handling plus, * ampersand, hash and slash signs. * * @param string The text to encode * @return string A mod_rewrite compatible encoding of the given text. */ function rewrite_encode($url) { $url = urlencode($url); $url = preg_replace('/%2B/', '%252B', $url); // + $url = preg_replace('/%2F/', '%252F', $url); // / $url = preg_replace('/%26/', '%2526', $url); // & $url = preg_replace('/%23/', '%2523', $url); // # return $url; }
Add roles to user for game
Meteor.methods({ "createGame": function(gameName, lobbyName, password) { if(!GAME_DEFINITIONS.hasOwnProperty(gameName)) { throw new Meteor.Error("unrecognized-game", "A game of the specified type is not defined."); } if(Games.findOne({"lobbbyData.lobbyName": lobbyName})) { throw new Meteor.Error("lobby-name-taken", "A lobby with this name already exists."); } var game = { "gameName": gameName, "inGame": false, "lobbyData": { "private": false, "lobbyName": lobbyName, "players": [this.userId], "minPlayers": GAME_DEFINITIONS[gameName].minPlayers, "maxPlayers": GAME_DEFINITIONS[gameName].maxPlayers }, "gameData": GAME_DEFINITIONS[gameName].gameData }; if(password) { game.lobbyData.private = true; game.password = password; } Games.insert(game); Roles.addUsersToRoles(this.userId, ["player", "owner"], lobbyName); } });
Meteor.methods({ "createGame": function(gameName, lobbyName, password) { if(!GAME_DEFINITIONS.hasOwnProperty(gameName)) { throw new Meteor.Error("unrecognized-game", "A game of the specified type is not defined."); } if(Games.findOne({"lobbbyData.lobbyName": lobbyName})) { throw new Meteor.Error("lobby-name-taken", "A lobby with this name already exists."); } var game = { "gameName": gameName, "inGame": false, "lobbyData": { "private": false, "lobbyName": lobbyName, "players": [this.userId], "minPlayers": GAME_DEFINITIONS[gameName].minPlayers, "maxPlayers": GAME_DEFINITIONS[gameName].maxPlayers }, "gameData": GAME_DEFINITIONS[gameName].gameData }; if(password) { game.lobbyData.private = true; game.password = password; } Games.insert(game); } });
Add name and promotion to Card.
from django.contrib.auth.models import User from django.db import models from promotions.models import Promotion from wrestlers.models import WrestlingEntity class Review(models.Model): reviewed_by = models.ForeignKey(User) reviewed_at = models.DateTimeField() class Meta: abstract = True class Card(models.Model): date = models.DateField() promotion = models.ForeignKey(Promotion) name = models.CharField(max_length=127, null=True, blank=True) def __unicode__(self): return unicode(self.date) class Match(Review): card = models.ForeignKey(Card) participants = models.ManyToManyField(WrestlingEntity) winner = models.ForeignKey(WrestlingEntity, related_name="won_matches", null=True, blank=True) def __unicode__(self): return " vs. ".join([p.name for p in self.participants.all()])
from django.contrib.auth.models import User from django.db import models from wrestlers.models import WrestlingEntity class Review(models.Model): reviewed_by = models.ForeignKey(User) reviewed_at = models.DateTimeField() class Meta: abstract = True class Card(models.Model): date = models.DateField() def __unicode__(self): return unicode(self.date) class Match(Review): card = models.ForeignKey(Card) participants = models.ManyToManyField(WrestlingEntity) winner = models.ForeignKey(WrestlingEntity, related_name="won_matches", null=True, blank=True) def __unicode__(self): return " vs. ".join([p.name for p in self.participants.all()])