text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add autoHide prop to pass down
import React, {Component, PropTypes} from 'react' import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbox extends Component { constructor(props) { super(props) } static defaultProps = { autoHide: true, } render() { const {autoHide, children, className} = this.props return ( <Scrollbars className={classnames('fancy-scroll--container', {[className]: className})} autoHide={autoHide} autoHideTimeout={1000} autoHideDuration={250} renderTrackHorizontal={props => <div {...props} className="fancy-scroll--track-h"/>} renderTrackVertical={props => <div {...props} className="fancy-scroll--track-v"/>} renderThumbHorizontal={props => <div {...props} className="fancy-scroll--thumb-h"/>} renderThumbVertical={props => <div {...props} className="fancy-scroll--thumb-v"/>} > {children} </Scrollbars> ) } } const {bool, node, string} = PropTypes FancyScrollbox.propTypes = { children: node.isRequired, className: string, autoHide: bool, } export default FancyScrollbox
import React, {Component, PropTypes} from 'react' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbox extends Component { constructor(props) { super(props) } render() { const {children, className} = this.props return ( <Scrollbars className={`fancy-scroll--container ${className}`} autoHide={true} autoHideTimeout={1000} autoHideDuration={250} renderTrackHorizontal={props => <div {...props} className="fancy-scroll--track-h"/>} renderTrackVertical={props => <div {...props} className="fancy-scroll--track-v"/>} renderThumbHorizontal={props => <div {...props} className="fancy-scroll--thumb-h"/>} renderThumbVertical={props => <div {...props} className="fancy-scroll--thumb-v"/>} > {children} </Scrollbars> ) } } const {node, string} = PropTypes FancyScrollbox.propTypes = { children: node.isRequired, className: string.isRequired, } export default FancyScrollbox
Add some more filters & methods
<?php class Vocabulary extends Model { public function get_set() { return $this->belongs_to('Set'); } public function get_human_due_date() { // TODO return $this->due; } /** * Filters */ public static function active($orm) { return $orm->where_gte('level', 0)->order_by_asc('due'); } public static function inactive($orm) { return $orm->where_lt('level', 0)->order_by_asc('id'); } public static function level($orm, $min, $max) { return $orm->where_gte('level', $min)->where_lte('level', $max); } public static function in_set($orm, $set) { if (!$set) return $orm; return $orm->where('set_id', $set->id); } public static function due($orm) { return $orm->filter('active')->where_lte('due', date('Y-m-d H:i:s')); } public static function due_tomorrow($orm) { $datetime = new DateTime('tomorrow'); return $orm->filter('active')->where_lte('due', $datetime->format('Y-m-d H:i:s')); } public static function learned_today($orm) { return $orm->filter('active')->where('init_date', date('Y-m-d')); } }
<?php class Vocabulary extends Model { public function get_set() { return $this->belongs_to('Set'); } /** * Filters */ public static function active($orm) { return $orm->where_gte('level', 0)->order_by_asc('due'); } public static function inactive($orm) { return $orm->where_lt('level', 0)->order_by_asc('id'); } public static function level($orm, $min, $max) { return $orm->where_gte('level', $min)->where_lte('level', $max); } public static function due($orm) { return $orm->filter('active')->where_lte('due', date('Y-m-d H:i:s')); } public static function due_tomorrow($orm) { $datetime = new DateTime('tomorrow'); return $orm->filter('active')->where_lte('due', $datetime->format('Y-m-d H:i:s')); } public static function learned_today($orm) { return $orm->filter('active')->where('init_date', date('Y-m-d')); } }
Fix up the example to be proper XML. Signed-off-by: Chris Lalancette <60b62644009db6b194cc0445b64e9b27bb26433a@redhat.com>
""" Class for automated operating system installation. Oz is a set of classes to do automated operating system installation. It has built-in knowledge of the proper things to do for each of the supported operating systems, so the data that the user must provide is very minimal. This data is supplied in the form of an XML document that describes what type of operating system is to be installed and where to get the installation media. Oz handles the rest. The simplest Oz program (without error handling or any advanced features) would look something like: import oz.TDL import oz.GuestFactory tdl_xml = \"\"\" <template> <name>f13jeos</name> <os> <name>Fedora</name> <version>13</version> <arch>x86_64</arch> <install type='url'> <url>http://download.fedoraproject.org/pub/fedora/linux/releases/13/Fedora/x86_64/os/</url> </install> </os> <description>Fedora 13</description> </template> \"\"\" tdl = oz.TDL.TDL(tdl_xml) guest = oz.GuestFactory.guest_factory(tdl, None, None) guest.generate_install_media() guest.generate_diskimage() guest.install() """
""" Class for automated operating system installation. Oz is a set of classes to do automated operating system installation. It has built-in knowledge of the proper things to do for each of the supported operating systems, so the data that the user must provide is very minimal. This data is supplied in the form of an XML document that describes what type of operating system is to be installed and where to get the installation media. Oz handles the rest. The simplest Oz program (without error handling or any advanced features) would look something like: import oz.TDL import oz.GuestFactory tdl_xml = \"\"\" <template> <name>f13jeos</name> <os> <name>Fedora</name> <version>13</version> <arch>x86_64</arch> <install type='url'> <url>http://download.fedoraproject.org/pub/fedora/linux/releases/13/Fedor </install> </os> <description>Fedora 13</description> </template> \"\"\" tdl = oz.TDL.TDL(tdl_xml) guest = oz.GuestFactory.guest_factory(tdl, None, None) guest.generate_install_media() guest.generate_diskimage() guest.install() """
Allow empty so we can force new build
import sys import sh from fabric import api as fab sed = sh.sed.bake('-i bak -e') TRAVIS_YAML = '.travis.yml' REPLACE_LANGUAGE = 's/language: .*/language: {}/' def is_dirty(): return "" != sh.git.status(porcelain=True).strip() def release(language, message): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML) if is_dirty(): sh.git.add(TRAVIS_YAML) sh.git.commit(m=message, allow_empty=True) sh.git.pull(rebase=True) sh.git.push() @fab.task def release_osx(): release('objective-c', "Release OS X") @fab.task def release_linux(): release('python', "Release Linux")
import sys import sh from fabric import api as fab sed = sh.sed.bake('-i bak -e') TRAVIS_YAML = '.travis.yml' REPLACE_LANGUAGE = 's/language: .*/language: {}/' def is_dirty(): return "" != sh.git.status(porcelain=True).strip() def release(language, message): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML) if is_dirty(): sh.git.add(TRAVIS_YAML) sh.git.commit(m=message) sh.git.pull(rebase=True) sh.git.push() @fab.task def release_osx(): release('objective-c', "Release OS X") @fab.task def release_linux(): release('python', "Release Linux")
[Stitching] Enable type name conflict logging.
import { mergeSchemas, introspectSchema, makeRemoteExecutableSchema } from "graphql-tools" import { createHttpLink } from "apollo-link-http" import fetch from "node-fetch" import localSchema from "./schema" export default async function mergedSchema() { const convectionLink = createHttpLink({ fetch, uri: process.env.CONVECTION_GRAPH_URL, headers: { Authorization: `Bearer ${process.env.CONVECTION_TOKEN}`, }, }) const convectionSchema = await makeRemoteExecutableSchema({ schema: await introspectSchema(convectionLink), link: convectionLink, }) const linkTypeDefs = ` extend type Submission { artist: Artist } ` return mergeSchemas({ schemas: [localSchema, convectionSchema, linkTypeDefs], // Prefer others over the local MP schema. onTypeConflict: (_leftType, rightType) => { console.warn(`[!] Type collision ${rightType}`) // eslint-disable-line no-console return rightType }, resolvers: mergeInfo => ({ Submission: { artist: { fragment: `fragment SubmissionArtist on Submission { artist_id }`, resolve: (parent, args, context, info) => { const id = parent.artist_id return mergeInfo.delegate("query", "artist", { id }, context, info) }, }, }, }), }) }
import { mergeSchemas, introspectSchema, makeRemoteExecutableSchema } from "graphql-tools" import { createHttpLink } from "apollo-link-http" import fetch from "node-fetch" import localSchema from "./schema" export default async function mergedSchema() { const convectionLink = createHttpLink({ fetch, uri: process.env.CONVECTION_GRAPH_URL, headers: { Authorization: `Bearer ${process.env.CONVECTION_TOKEN}`, }, }) const convectionSchema = await makeRemoteExecutableSchema({ schema: await introspectSchema(convectionLink), link: convectionLink, }) const linkTypeDefs = ` extend type Submission { artist: Artist } ` return mergeSchemas({ schemas: [localSchema, convectionSchema, linkTypeDefs], // Prefer others over the local MP schema. onTypeConflict: (_leftType, rightType) => { // console.warn(`[!] Type collision ${rightType}`) return rightType }, resolvers: mergeInfo => ({ Submission: { artist: { fragment: `fragment SubmissionArtist on Submission { artist_id }`, resolve: (parent, args, context, info) => { const id = parent.artist_id return mergeInfo.delegate("query", "artist", { id }, context, info) }, }, }, }), }) }
Update unit tests to improve redis_import_error
#! /usr/bin/env python # -*- coding: utf-8 -*- from sys import modules, version_info if version_info >= (3,): from imp import reload def test_redis_import_error(): """Test that we can load FlaskMultiRedis even if redis module is not available.""" import flask_multi_redis modules['redis'] = None flask_multi_redis = reload(flask_multi_redis) FlaskMultiRedis = flask_multi_redis.FlaskMultiRedis f = FlaskMultiRedis() assert f.provider_class is None def test_constructor_app(mocker): """Test that the constructor passes the app to FlaskMultiRedis.init_app.""" import flask_multi_redis del(modules['redis']) flask_multi_redis = reload(flask_multi_redis) FlaskMultiRedis = flask_multi_redis.FlaskMultiRedis mocker.patch.object(FlaskMultiRedis, 'init_app', autospec=True) app_stub = mocker.stub(name='app_stub') FlaskMultiRedis(app_stub) FlaskMultiRedis.init_app.assert_called_once_with(mocker.ANY, app_stub)
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys sys.modules['redis'] = None def test_redis_import_error(): """Test that we can load FlaskMultiRedis even if redis module is not available.""" from flask_multi_redis import FlaskMultiRedis f = FlaskMultiRedis() assert f.provider_class is None def test_constructor_app(mocker): """Test that the constructor passes the app to FlaskMultiRedis.init_app.""" from flask_multi_redis import FlaskMultiRedis mocker.patch.object(FlaskMultiRedis, 'init_app', autospec=True) app_stub = mocker.stub(name='app_stub') FlaskMultiRedis(app_stub) FlaskMultiRedis.init_app.assert_called_once_with(mocker.ANY, app_stub)
Add delay to quit button
var player = { init: function () { this.hide(); this.initPlayer(); this.initPlayerToggle(); }, initPlayerToggle: function() { }, initPlayer: function() { var that = this; $('.row a').on('tap', function() { var control = $(this); var command = control.attr('id'); var url = '/api/exec?command=' + command; that._call(url); that.hover(control); if(that._isQuit(control)) { setTimeout(that.hide(), 1000); } }); }, hover: function(control) { control.addClass('icon_hover'); setTimeout(function() { control.removeClass('icon_hover'); }, 500); }, hide: function() { $('#controls').hide(); }, show: function() { $('#controls').show(); }, _call: function(url) { $.ajax({ method: 'GET', url: url, type: 'json' }); }, _isQuit: function(control) { return (control.attr('id') == 'quit'); }, _call: function(url) { $.ajax({ method: 'GET', url: url, type: 'json' }); } };
var player = { init: function () { this.hide(); this.initPlayer(); this.initPlayerToggle(); }, initPlayerToggle: function() { }, initPlayer: function() { var that = this; $('.row a').on('tap', function() { var control = $(this); var command = control.attr('id'); var url = '/api/exec?command=' + command; that._call(url); that.hover(control); if(that._isQuit(control)) { setTimeout(that.hide(), 500); } }); }, hover: function(control) { control.addClass('icon_hover'); setTimeout(function() { control.removeClass('icon_hover'); }, 500); }, hide: function() { $('#controls').hide(); }, show: function() { $('#controls').show(); }, _call: function(url) { $.ajax({ method: 'GET', url: url, type: 'json' }); }, _isQuit: function(control) { return (control.attr('id') == 'quit'); }, _call: function(url) { $.ajax({ method: 'GET', url: url, type: 'json' }); } };
Use os.walk() to find files to delete.
# Remove all the .pyc and .pyo files under ../Lib. def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo npyc, npyo = deltree("../Lib") print npyc, ".pyc deleted,", npyo, ".pyo deleted"
# Remove all the .pyc and .pyo files under ../Lib. def deltree(root): import os def rm(path): os.unlink(path) npyc = npyo = 0 dirs = [root] while dirs: dir = dirs.pop() for short in os.listdir(dir): full = os.path.join(dir, short) if os.path.isdir(full): dirs.append(full) elif short.endswith(".pyc"): npyc += 1 rm(full) elif short.endswith(".pyo"): npyo += 1 rm(full) return npyc, npyo npyc, npyo = deltree("../Lib") print npyc, ".pyc deleted,", npyo, ".pyo deleted"
Add callback for FaceBook function
'use strict' import FB from 'fb' import { facebookKey } from '../etc/secret.json' /** * Отправить сообщение в Фейсбук * * @param { string } message - Текст сообщения, которое будет отправлено на * страницу в Фейсбуке */ export default async function facebookIt (message, callback) { FB.setAccessToken(facebookKey) await FB.api('me/feed', 'post', { message: message }, response => { if (!response || response.error) { console.log(!response ? 'Ошибка отправки сообщения в FaceBook' : response.error) } callback(response.id) }) }
'use strict' import FB from 'fb' import { facebookKey } from '../etc/secret.json' /** * Отправить сообщение в Фейсбук * * @param { string } message - Текст сообщения, которое будет отправлено на * страницу в Фейсбуке */ export default function facebookIt (message) { FB.setAccessToken(facebookKey) FB.api('me/feed', 'post', { message: message }, response => { if (!response || response.error) { console.log(!response ? 'Ошибка отправки сообщения в FaceBook' : response.error) } console.log('ID опубликованного сообщения: ' + response.id) }) }
Refactor NPS customer gauge code.
<?php namespace Frontend\Modules\CigyWidgets\Widgets; use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Modules\CigyWidgets\Services\CustomerGauge as FrontendCigyServicesCustomerGauge; /** * This is the detail widget. */ class Nps extends FrontendBaseWidget { public function execute(): void { parent::execute(); $this->loadTemplate(); $teamNps = FrontendCigyServicesCustomerGauge::getNps($this->pageTeamFilter); $companyNps = FrontendCigyServicesCustomerGauge::getNps(); $npsData = array( 'team' => $teamNps, 'company' => $companyNps, 'target' => '9', ); $this->template->assign('widgetNps', $npsData); } }
<?php namespace Frontend\Modules\CigyWidgets\Widgets; use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Modules\CigyWidgets\Engine\Model as FrontendCigyWidgetsModel; use Frontend\Modules\CigyWidgets\Services\CustomerGauge as FrontendCigyServicesCustomerGauge; /** * This is the detail widget. */ class Nps extends FrontendBaseWidget { public function execute(): void { parent::execute(); $this->loadTemplate(); $teamNps = FrontendCigyServicesCustomerGauge::getNps($this->pageTeamFilter); $companyNps = FrontendCigyServicesCustomerGauge::getNps(); $npsData = array( 'team' => $teamNps, 'company' => $companyNps, 'target' => '9', ); $this->template->assign('widgetNps', $npsData); } }
Allow Node to Node connection.
from neb.api import TrinityResource from neb.relationship import Relationship from neb.statistic import NodeStatistic class Node(TrinityResource): def create(self, node_id, **kwargs): params = dict(id=node_id, node=kwargs) return self.post(self._node_path(), payload=params) def connect(self, to, type, **kwargs): if isinstance(to, Node): to = to.id return Relationship().create(start=self.id, to=to, type=type, **kwargs) def statistic(self, stat): return NodeStatistic().calculate(node_id=self.id, stat=stat) @staticmethod def _node_path(node_id=None): if node_id: path = 'node/%s' % node_id else: path = 'node' return path def request(self, *args, **kwargs): response = super(Node, self).request(*args, **kwargs) return Node(data=response)
from neb.api import TrinityResource from neb.relationship import Relationship from neb.statistic import NodeStatistic class Node(TrinityResource): def create(self, node_id, **kwargs): params = dict(id=node_id, node=kwargs) return self.post(self._node_path(), payload=params) def connect(self, to, type, **kwargs): return Relationship().create(start=self.id, to=to, type=type, **kwargs) def statistic(self, stat): return NodeStatistic().calculate(node_id=self.id, stat=stat) @staticmethod def _node_path(node_id=None): if node_id: path = 'node/%s' % node_id else: path = 'node' return path def request(self, *args, **kwargs): response = super(Node, self).request(*args, **kwargs) return Node(data=response)
Fix exception caused by bound function
'use babel'; /* eslint-disable no-multi-str, prefer-const, func-names */ let linkPaths; const regex = new RegExp('\ ((?:\\w:)?/?\ (?:[-\\w.]+/)*[-\\w.]+)\ :(\\d+)\ (?::(\\d+))?\ ', 'g'); const template = '<a class="-linked-path" data-path="$1" data-line="$2" data-column="$3">$&</a>'; export default linkPaths = lines => lines.replace(regex, template); linkPaths.listen = parentView => parentView.on('click', '.-linked-path', function () { const el = this; let { path, line, column } = el.dataset; line = Number(line) - 1; // column number is optional column = column ? Number(column) - 1 : 0; atom.workspace.open(path, { initialLine: line, initialColumn: column, }); });
'use babel'; /* eslint-disable no-multi-str, prefer-const*/ let linkPaths; const regex = new RegExp('\ ((?:\\w:)?/?\ (?:[-\\w.]+/)*[-\\w.]+)\ :(\\d+)\ (?::(\\d+))?\ ', 'g'); const template = '<a class="-linked-path" data-path="$1" data-line="$2" data-column="$3">$&</a>'; export default linkPaths = lines => lines.replace(regex, template); linkPaths.listen = parentView => parentView.on('click', '.-linked-path', () => { const el = this; let { path, line, column } = el.dataset; line = Number(line) - 1; // column number is optional column = column ? Number(column) - 1 : 0; atom.workspace.open(path, { initialLine: line, initialColumn: column, }); });
FIX : increase test timer for buildbot in realtime
import threading import time import Queue from mne.realtime import StimServer, StimClient from nose.tools import assert_equal def test_connection(): """Test TCP/IP connection for StimServer <-> StimClient. """ # have to start a thread to simulate the effect of two # different computers since stim_server.start() is designed to # be a blocking method trig_queue = Queue.Queue() thread = threading.Thread(target=connect_client, args=(trig_queue,)) thread.daemon = True thread.start() with StimServer('localhost', port=4218) as stim_server: stim_server.start() # Check if data is ok stim_server.add_trigger(20) # the assert_equal must be in the test_connection() method # Hence communication between threads is necessary assert_equal(trig_queue.get(), 20) def connect_client(trig_queue): """Helper method that instantiates the StimClient. """ # just wait till the main thread reaches stim_server.start() time.sleep(1.) # instantiate StimClient stim_client = StimClient('localhost', port=4218) # wait a bit more for script to reach stim_server.add_trigger() time.sleep(1.) trig_queue.put(stim_client.get_trigger())
import threading import time import Queue from mne.realtime import StimServer, StimClient from nose.tools import assert_equal def test_connection(): """Test TCP/IP connection for StimServer <-> StimClient. """ # have to start a thread to simulate the effect of two # different computers since stim_server.start() is designed to # be a blocking method trig_queue = Queue.Queue() thread = threading.Thread(target=connect_client, args=(trig_queue,)) thread.daemon = True thread.start() with StimServer('localhost', port=4218) as stim_server: stim_server.start() # Check if data is ok stim_server.add_trigger(20) # the assert_equal must be in the test_connection() method # Hence communication between threads is necessary assert_equal(trig_queue.get(), 20) def connect_client(trig_queue): """Helper method that instantiates the StimClient. """ # just wait till the main thread reaches stim_server.start() time.sleep(0.1) # instantiate StimClient stim_client = StimClient('localhost', port=4218) # wait a bit more for script to reach stim_server.add_trigger() time.sleep(0.1) trig_queue.put(stim_client.get_trigger())
Check for existince of uri
<?php namespace Talk; use Application\BaseCommentEntity; use stdClass; class TalkCommentEntity extends BaseCommentEntity { public function getUsername() { if (!isset($this->data->username)) { return null; } return $this->data->username; } public function getTalkTitle() { if (!isset($this->data->talk_title)) { return null; } return $this->data->talk_title; } public function getTalkUri() { if (!isset($this->data->talk_uri)) { return null; } return $this->data->talk_uri; } public function getCommentUri() { if (!isset($this->data->uri)) { return null; } return $this->data->uri; } public function canRateTalk($user_uri) { if (isset($this->data->user_uri) && $this->data->user_uri == $user_uri) { return false; } return true; } }
<?php namespace Talk; use Application\BaseCommentEntity; use stdClass; class TalkCommentEntity extends BaseCommentEntity { public function getUsername() { if (!isset($this->data->username)) { return null; } return $this->data->username; } public function getTalkTitle() { if (!isset($this->data->talk_title)) { return null; } return $this->data->talk_title; } public function getTalkUri() { if (!isset($this->data->talk_uri)) { return null; } return $this->data->talk_uri; } public function getCommentUri() { if (!isset($this->data->uri)) { return null; } return $this->data->uri; } public function canRateTalk($user_uri) { if ($this->data->user_uri == $user_uri) { return false; } return true; } }
Fix up various prop issues with IssueishBadge
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import Octicon from './octicon'; const typeAndStateToIcon = { Issue: { OPEN: 'issue-opened', CLOSED: 'issue-closed', }, PullRequest: { OPEN: 'git-pull-request', CLOSED: 'git-pull-request', MERGED: 'git-merge', }, }; export default function IssueishBadge({type, state, ...others}) { const icons = typeAndStateToIcon[type] || {}; const icon = icons[state] || ''; const {className, ...otherProps} = others; return ( <span className={cx('issueish-badge', 'badge', state.toLowerCase(), className)} {...otherProps}> <Octicon icon={icon} /> {state.toLowerCase()} </span> ); } IssueishBadge.propTypes = { type: PropTypes.oneOf([ 'Issue', 'PullRequest', ]).isRequired, state: PropTypes.oneOf([ 'OPEN', 'CLOSED', 'MERGED', ]).isRequired, };
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import Octicon from './octicon'; const typeAndStateToIcon = { Issue: { OPEN: 'issue-opened', CLOSED: 'issue-closed', }, PullRequest: { OPEN: 'git-pull-request', CLOSED: 'git-pull-request', MERGED: 'git-merge', }, }; export default function IssueishBadge({type, state, ...others}) { const icons = typeAndStateToIcon[type] || {}; const icon = icons[state] || ''; return ( <span className={cx('issueish-badge', 'badge', state.toLowerCase(), others.className)}> <Octicon icon={icon} /> {state.toLowerCase()} </span> ); } IssueishBadge.propTypes = { type: PropTypes.oneOf([ 'Issue', 'PullRequest', ]), state: PropTypes.oneOf([ 'OPEN', 'CLOSED', 'MERGED', ]), };
Add ui-router and build site routes
(function(){ 'use strict'; angular .module('shareMark', ['ui.router', 'templates', 'ngclipboard']) .config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: "/", template: "<home></home>" }) .state('search', { url: '/search', template: '<search></search>' }) .state('new', { url: '/new', template: '<new></new>' }) .state('show', { url: '/:id', template: '<show></show>' }) });//end config }());
(function(){ 'use strict'; angular .module('shareMark', ['ui.router', 'templates', 'ngclipboard']) .config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: "/", template: "<home></home>" }) .state('search', { url: '/search', template: '<search></search>' }) .state('new', { url: '/new', template: '<new></new>' }) .state('show', { url: '/:id', template: '<show></show>' }) }]);//end config }());
Fix infinite recursion bug in myReadCloser.Read() method. Simplify wrapper.
package objectclient import ( "bytes" "github.com/Symantec/Dominator/lib/hash" "github.com/Symantec/Dominator/proto/objectserver" "io" ) type myReadCloser struct { io.Reader } func (reader *myReadCloser) Close() error { return nil } func (objSrv *ObjectClient) getObjectReader(hashVal hash.Hash) (uint64, io.ReadCloser, error) { var request objectserver.GetObjectsRequest request.Objects = make([]hash.Hash, 1) request.Objects[0] = hashVal var reply objectserver.GetObjectsResponse err := objSrv.client.Call("ObjectServer.GetObjects", request, &reply) if err != nil { return 0, nil, err } reader := &myReadCloser{bytes.NewReader(reply.Objects[0])} return reply.ObjectSizes[0], reader, nil }
package objectclient import ( "bytes" "github.com/Symantec/Dominator/lib/hash" "github.com/Symantec/Dominator/proto/objectserver" "io" ) type myReadCloser struct { reader io.Reader } func (reader *myReadCloser) Read(b []byte) (int, error) { return reader.Read(b) } func (reader *myReadCloser) Close() error { return nil } func (objSrv *ObjectClient) getObjectReader(hashVal hash.Hash) (uint64, io.ReadCloser, error) { var request objectserver.GetObjectsRequest request.Objects = make([]hash.Hash, 1) request.Objects[0] = hashVal var reply objectserver.GetObjectsResponse err := objSrv.client.Call("ObjectServer.GetObjects", request, &reply) if err != nil { return 0, nil, err } reader := &myReadCloser{bytes.NewReader(reply.Objects[0])} return reply.ObjectSizes[0], reader, nil }
Test commit: correct username now?
package hello; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; @Entity public class Recipe { @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") private String id; private String name; private String description; protected Recipe() { } public Recipe(String name, String description) { this.name = name; this.description = description; } public String getId() { return id; } // public void setId(String id) { // this.id = id; // } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("\"id\":\"" + id + "\","); sb.append("\"name\":\"" + name + "\","); sb.append("\"description\":\"" + description + "\""); sb.append("}"); return sb.toString(); } }
package hello; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; @Entity public class Recipe { @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") private String id; private String name; private String description; protected Recipe() { } public Recipe(String name, String description) { this.name = name; this.description = description; } public String getId() { return id; } // public void setId(String id) { // this.id = id; // } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("\"id\":\"" + id + "\","); sb.append("\"name\":\"" + name + "\","); sb.append("\"description\":\"" + description + "\""); sb.append("}"); return sb.toString(); } }
Add API to mark topic as reader
# -*- coding:utf-8 -*- from flask import g, jsonify from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager from gather.topic.models import Topic, Reply bp = api_manager.create_api_blueprint( Topic, methods=["GET", "POST"], preprocessors={ 'POST': [need_auth], }, include_methods=["have_read"], exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/topic/<int:topic_id>/mark_read") def _mark_read_for_topic(topic_id): need_auth() topic = Topic.query.get_or_404(topic_id) topic.mark_read(g.token_user) return jsonify({"code": 200}) def _update_topic_updated(result=None, **kw): if not result: return reply = Reply.query.get(result["id"]) reply.topic.updated = reply.created reply.topic.clear_read() reply.topic.save() reply_bp = api_manager.create_api_blueprint( Reply, methods=["POST"], preprocessors={ 'POST': [need_auth], }, postprocessors={ 'POST': [_update_topic_updated] }, exclude_columns=EXCLUDE_COLUMNS )
# -*- coding:utf-8 -*- from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager from gather.topic.models import Topic, Reply bp = api_manager.create_api_blueprint( Topic, methods=["GET", "POST"], preprocessors={ 'POST': [need_auth], }, include_methods=["have_read"], exclude_columns=EXCLUDE_COLUMNS ) def _update_topic_updated(result=None, **kw): if not result: return reply = Reply.query.get(result["id"]) reply.topic.updated = reply.created reply.topic.clear_read() reply.topic.save() reply_bp = api_manager.create_api_blueprint( Reply, methods=["POST"], preprocessors={ 'POST': [need_auth], }, postprocessors={ 'POST': [_update_topic_updated] }, exclude_columns=EXCLUDE_COLUMNS )
Modify URLs for start and end
from flask import Flask, render_template, redirect import json app = Flask(__name__) with open("modules.json", 'r') as fp: layout = json.load(fp) @app.route('/') def main(): return redirect("start/", code=302) @app.route('/start/') def start(): return render_template("start.html", start_link = layout["start"]["target"]) @app.route('/content/<module>/') def get_content_module(module): return render_template("content.html", title = module, data = layout[module]["data"], target = layout[module]["target"]) @app.route('/end/') def end(): return render_template("end.html") if __name__ == '__main__': app.run(debug=True)
from flask import Flask, render_template, redirect import json app = Flask(__name__) with open("modules.json", 'r') as fp: layout = json.load(fp) @app.route('/') def main(): return redirect("content/start/", code=302) @app.route('/content/start/') def start(): return render_template("start.html", start_link = layout["start"]["target"]) @app.route('/content/<module>/') def get_content_module(module): return render_template("content.html", title = module, data = layout[module]["data"], target = layout[module]["target"]) @app.route('/content/end/') def end(): return render_template("end.html") if __name__ == '__main__': app.run(debug=True)
Remove return from redis object
'use strict'; var redis = require('redis'), parse = require('url').parse; var RedisClient = function(connectionURL) { var options = this.parseURL(connectionURL); this.hostname = options.hostname; this.port = options.port; this.username = options.username; this.password = options.password; }; RedisClient.prototype.parseURL = function(url) { var _url = parse(url), auth = _url.auth.split(':'); return { hostname: _url.hostname, port: _url.port, username: auth[0], password: auth[1] }; }; RedisClient.prototype.makeClient = function() { var r = redis.createClient(this.port, this.hostname); r.auth(this.password, function(error) { if (error) console.error(error); r.on('error', function(error) { console.error('redis error: ' + error); }).on('connect', function() { console.info('redis connect: ' + this.host + ':' + this.port); }); return r; }); }; RedisClient.prototype.createStoreClient = function() { var store = { redisPub: this.makeClient(), redisSub: this.makeClient(), redisClient: this.makeClient() }; return store; }; module.exports = RedisClient;
'use strict'; var redis = require('redis'), parse = require('url').parse; var RedisClient = function(connectionURL) { var options = this.parseURL(connectionURL); this.hostname = options.hostname; this.port = options.port; this.username = options.username; this.password = options.password; }; RedisClient.prototype.parseURL = function(url) { var _url = parse(url), auth = _url.auth.split(':'); return { hostname: _url.hostname, port: _url.port, username: auth[0], password: auth[1] }; }; RedisClient.prototype.makeClient = function() { var r = redis.createClient(this.port, this.hostname); return r.auth(this.password, function(error) { if (error) console.error(error); r.on('error', function(error) { console.error('redis error: ' + error); }).on('connect', function() { console.info('redis connect: ' + this.host + ':' + this.port); }); return r; }); }; RedisClient.prototype.createStoreClient = function() { var store = { redisPub: this.makeClient(), redisSub: this.makeClient(), redisClient: this.makeClient() }; return store; }; module.exports = RedisClient;
Update version and copyright year.
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from sphinx_celery import conf globals().update(conf.build_config( 'kombu', __file__, project='Kombu', version_dev='4.4', version_stable='4.3', canonical_url='https://kombu.readthedocs.io/', webdomain='kombu.readthedocs.io', github_project='celery/kombu', author='Ask Solem & contributors', author_name='Ask Solem', copyright='2009-2019', publisher='Celery Project', html_logo='images/kombusmall.jpg', html_favicon='images/favicon.ico', html_prepend_sidebars=['sidebardonations.html'], extra_extensions=['sphinx.ext.napoleon'], apicheck_ignore_modules=[ 'kombu.entity', 'kombu.messaging', 'kombu.asynchronous.aws.ext', 'kombu.asynchronous.aws.sqs.ext', 'kombu.transport.qpid_patches', 'kombu.utils', 'kombu.transport.virtual.base', ], ))
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from sphinx_celery import conf globals().update(conf.build_config( 'kombu', __file__, project='Kombu', version_dev='4.3', version_stable='4.2', canonical_url='https://kombu.readthedocs.io/', webdomain='kombu.readthedocs.io', github_project='celery/kombu', author='Ask Solem & contributors', author_name='Ask Solem', copyright='2009-2016', publisher='Celery Project', html_logo='images/kombusmall.jpg', html_favicon='images/favicon.ico', html_prepend_sidebars=['sidebardonations.html'], extra_extensions=['sphinx.ext.napoleon'], apicheck_ignore_modules=[ 'kombu.entity', 'kombu.messaging', 'kombu.asynchronous.aws.ext', 'kombu.asynchronous.aws.sqs.ext', 'kombu.transport.qpid_patches', 'kombu.utils', 'kombu.transport.virtual.base', ], ))
Fix issue where lang was not parsed properly
import os import requests from django.utils.translation import get_language from wagtailaltgenerator.translation_providers import get_current_provider from wagtailaltgenerator.providers import DescriptionResult def get_image_data(image_url): ''' Load external image and return byte data ''' image_data = requests.get(image_url) if image_data.status_code > 200 and image_data.status_code < 300: return None return image_data.content def get_local_image_data(image_file): ''' Retrive byte data from a local file ''' abs_path = os.path.abspath(image_file.path) image_data = open(abs_path, 'rb').read() return image_data def translate_description_result(result): provider = get_current_provider()() lang_and_country_code = get_language() lang_code = lang_and_country_code.split("-")[0] strings = [] if result.description: strings = [result.description] if result.tags: strings = [*strings, *result.tags] translated_strings = provider.translate( strings, target_language=lang_code ) translated_description = ( translated_strings[0] if result.description else result.description ) translated_tags = ( translated_strings[1:] if result.description else translated_strings ) return DescriptionResult( description=translated_description, tags=translated_tags, )
import os import requests from django.utils.translation import get_language from wagtailaltgenerator.translation_providers import get_current_provider from wagtailaltgenerator.providers import DescriptionResult def get_image_data(image_url): ''' Load external image and return byte data ''' image_data = requests.get(image_url) if image_data.status_code > 200 and image_data.status_code < 300: return None return image_data.content def get_local_image_data(image_file): ''' Retrive byte data from a local file ''' abs_path = os.path.abspath(image_file.path) image_data = open(abs_path, 'rb').read() return image_data def translate_description_result(result): provider = get_current_provider()() to_lang = get_language() strings = [] if result.description: strings = [result.description] if result.tags: strings = [*strings, result.tags] translated_strings = provider.translate( strings, target_language=to_lang ) translated_description = ( translated_strings[0] if result.description else result.description ) translated_tags = ( translated_strings[1:] if result.description else translated_strings ) return DescriptionResult( description=translated_description, tags=translated_tags, )
ENH: Add Beta and Binomial to automatically imported nodes
###################################################################### # Copyright (C) 2011,2012 Jaakko Luttinen # # This file is licensed under Version 3.0 of the GNU General Public # License. See LICENSE for a text of the license. ###################################################################### ###################################################################### # This file is part of BayesPy. # # BayesPy is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # BayesPy is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BayesPy. If not, see <http://www.gnu.org/licenses/>. ###################################################################### # Import some most commonly used nodes from . import * from .binomial import Binomial from .categorical import Categorical from .beta import Beta from .dirichlet import Dirichlet from .gaussian import Gaussian, GaussianARD from .wishart import Wishart from .gamma import Gamma from .gaussian_markov_chain import GaussianMarkovChain from .gaussian_markov_chain import VaryingGaussianMarkovChain from .gaussian_markov_chain import SwitchingGaussianMarkovChain from .categorical_markov_chain import CategoricalMarkovChain from .mixture import Mixture from .dot import Dot from .dot import SumMultiply
###################################################################### # Copyright (C) 2011,2012 Jaakko Luttinen # # This file is licensed under Version 3.0 of the GNU General Public # License. See LICENSE for a text of the license. ###################################################################### ###################################################################### # This file is part of BayesPy. # # BayesPy is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # BayesPy is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BayesPy. If not, see <http://www.gnu.org/licenses/>. ###################################################################### # Import some most commonly used nodes from . import * from .gaussian import Gaussian, GaussianARD from .wishart import Wishart from .gamma import Gamma from .dirichlet import Dirichlet from .categorical import Categorical from .dot import Dot, SumMultiply from .mixture import Mixture from .gaussian_markov_chain import GaussianMarkovChain from .gaussian_markov_chain import VaryingGaussianMarkovChain from .gaussian_markov_chain import SwitchingGaussianMarkovChain from .categorical_markov_chain import CategoricalMarkovChain
Implement basic list slicing operations
export function* map(fn, iterable) { for (const value of iterable) { yield fn(value); } } export function* filter(fn, iterable) { for (const value of iterable) { if (fn(value)) { yield value; } } } export function* head(iterable) { for (const value of iterable) { yield value; break; } } export function* last(iterable) { let previousValue; for (const value of iterable) { previousValue = value; } yield value; } // export function* tail(iterable) { // let iterator = iterable[Symbol.iterator](); // iterator.next(); // yield* iterator; // } export function* tail(iterable) { let first = true; for (const value of iterable) { if (first) { first = false; } else { yield value; } } } export function* init(iterable) { let previousValue; for (const value of first(iterable)) { previousValue = value; } for (const value of iterable) { yield previousValue previousValue = value; } } export function* reduce(fn, iterable) { let accumulator; for (const value of first(iterable)) { accumulator = value; } for (const value of rest(iterable)) { yield accumulator = fn(accumulator, value); } } export function* all(iterable, fn) { yield* reduce(function*(accumulator, value) { yield accumulator && fn(value); }, iterable); }
export function* map(fn, iterable) { for (const value of iterable) { yield fn(value); } } export function* filter(fn, iterable) { for (const value of iterable) { if (fn(value)) { yield value; } } } export function* first(iterable) { for (const value of iterable) { yield value; break; } } // export function* rest(iterable) { // let iterator = iterable[Symbol.iterator](); // iterator.next(); // yield* iterator; // } export function* rest(iterable) { let first = true; for (const value of iterable) { if (first) { first = false; } else { yield value; } } } export function* reduce(fn, iterable) { let accumulator; for (const value of first(iterable)) { accumulator = value; } for (const value of rest(iterable)) { yield accumulator = fn(accumulator, value); } } export function* all(iterable, fn) { yield* reduce(function*(accumulator, value) { yield accumulator && fn(value); }, iterable); }
Add logging to error output
## module loader, goes to see which submodules have 'html' directories ## and declares them at the toplevel import os,importlib,logging def find_module_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))] return subdirs def find_html_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [(o,os.path.sep.join([curdir,o,'html'])) for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'html']))] return dict(subdirs) def import_app(app): try: importlib.import_module(app) except Exception as e: logging.error("Couldn't load app: {0}, error: {1}".format(app, e)) MODULES = {} _html_dirs = find_html_dirs() [ MODULES.update({m_name:{'module': import_app('.'.join(['apps',m_name])), 'html':_html_dirs.get(m_name)}}) for m_name in find_module_dirs() ]
## module loader, goes to see which submodules have 'html' directories ## and declares them at the toplevel import os,importlib def find_module_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))] return subdirs def find_html_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [(o,os.path.sep.join([curdir,o,'html'])) for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'html']))] return dict(subdirs) def import_app(app): try: importlib.import_module(app) except Exception as e: logging.error("Couldn't load app: {0}, error: {1}".format(app, e)) MODULES = {} _html_dirs = find_html_dirs() [ MODULES.update({m_name:{'module': import_app('.'.join(['apps',m_name])), 'html':_html_dirs.get(m_name)}}) for m_name in find_module_dirs() ]
Fix a critical bug where the project member query would return wrong members Durch einen Fehler in der orWhere() Logik von Laravel konnte die project_id ignoriert werden
<?php namespace EmergencyExplorer; use Illuminate\Database\Eloquent\Model; class Project extends Model { const PROJECT_ROLE_NONE = 0; const PROJECT_ROLE_WATCHER = 1; const PROJECT_ROLE_MEMBER = 2; const PROJECT_ROLE_ADMIN = 3; protected $fillable = [ 'name', 'description', 'status', 'game_id', 'visible' ]; function game() { return $this->belongsTo(Game::class); } function users() { return $this->belongsToMany(User::class)->withPivot('role'); } function admins() { return $this->users()->wherePivot('role', self::PROJECT_ROLE_ADMIN); } function watchers() { return $this->users()->wherePivot('role', self::PROJECT_ROLE_WATCHER); } function members() { return $this->users()->whereIn('project_user.role', [self::PROJECT_ROLE_MEMBER, self::PROJECT_ROLE_ADMIN]); } function media() { return $this->belongsToMany(Media::class); } }
<?php namespace EmergencyExplorer; use Illuminate\Database\Eloquent\Model; class Project extends Model { const PROJECT_ROLE_NONE = 0; const PROJECT_ROLE_WATCHER = 1; const PROJECT_ROLE_MEMBER = 2; const PROJECT_ROLE_ADMIN = 3; protected $fillable = [ 'name', 'description', 'status', ]; function game() { return $this->belongsTo(Game::class); } function users() { return $this->belongsToMany(User::class)->withPivot('role'); } function admins() { return $this->users()->wherePivot('role', self::PROJECT_ROLE_ADMIN); } function watchers() { return $this->users()->wherePivot('role', self::PROJECT_ROLE_WATCHER); } function members() { return $this->users()->wherePivot('role', self::PROJECT_ROLE_ADMIN) ->orWherePivot('role', self::PROJECT_ROLE_MEMBER); } function media() { return $this->belongsToMany(Media::class); } }
Remove route-related stuff from test-bb/env
/* jshint strict:false */ /* global QUnit:false, Backbone:false */ // Taken from Backbone 1.1.2 test suite // Routing-specific stuff commented out (function() { var sync = Backbone.sync; var ajax = Backbone.ajax; var emulateHTTP = Backbone.emulateHTTP; var emulateJSON = Backbone.emulateJSON; // var history = window.history; // var pushState = history.pushState; // var replaceState = history.replaceState; QUnit.testStart(function() { var env = this.config.current.testEnvironment; // We never want to actually call these during tests. // history.pushState = history.replaceState = function(){}; // Capture ajax settings for comparison. Backbone.ajax = function(settings) { env.ajaxSettings = settings; }; // Capture the arguments to Backbone.sync for comparison. Backbone.sync = function(method, model, options) { env.syncArgs = { method: method, model: model, options: options }; sync.apply(this, arguments); }; }); QUnit.testDone(function() { Backbone.sync = sync; Backbone.ajax = ajax; Backbone.emulateHTTP = emulateHTTP; Backbone.emulateJSON = emulateJSON; // history.pushState = pushState; // history.replaceState = replaceState; }); })();
/* jshint strict:false */ /* global QUnit:false, Backbone:false, window:false */ // Taken from Backbone 1.1.2 test suite (function() { var sync = Backbone.sync; var ajax = Backbone.ajax; var emulateHTTP = Backbone.emulateHTTP; var emulateJSON = Backbone.emulateJSON; var history = window.history; var pushState = history.pushState; var replaceState = history.replaceState; QUnit.testStart(function() { var env = this.config.current.testEnvironment; // We never want to actually call these during tests. history.pushState = history.replaceState = function(){}; // Capture ajax settings for comparison. Backbone.ajax = function(settings) { env.ajaxSettings = settings; }; // Capture the arguments to Backbone.sync for comparison. Backbone.sync = function(method, model, options) { env.syncArgs = { method: method, model: model, options: options }; sync.apply(this, arguments); }; }); QUnit.testDone(function() { Backbone.sync = sync; Backbone.ajax = ajax; Backbone.emulateHTTP = emulateHTTP; Backbone.emulateJSON = emulateJSON; history.pushState = pushState; history.replaceState = replaceState; }); })();
Fix incorrect indexes in alembic revision
"""Add tracks Revision ID: 11890f58b1df Revises: 4d4b95748173 Create Date: 2016-08-16 16:48:27.441514 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '11890f58b1df' down_revision = '4d4b95748173' def upgrade(): op.create_table( 'tracks', sa.Column('id', sa.Integer(), nullable=False), sa.Column('title', sa.String(), nullable=False), sa.Column('event_id', sa.Integer(), nullable=False, index=True), sa.Column('position', sa.Integer(), nullable=False), sa.Column('description', sa.Text(), nullable=False), sa.ForeignKeyConstraint(['event_id'], ['events.events.id']), sa.PrimaryKeyConstraint('id'), schema='events' ) def downgrade(): op.drop_table('tracks', schema='events')
"""Add tracks Revision ID: 11890f58b1df Revises: 4d4b95748173 Create Date: 2016-08-16 16:48:27.441514 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '11890f58b1df' down_revision = '4d4b95748173' def upgrade(): op.create_table( 'tracks', sa.Column('id', sa.Integer(), nullable=False, index=True), sa.Column('title', sa.String(), nullable=False), sa.Column('event_id', sa.Integer(), nullable=False), sa.Column('position', sa.Integer(), nullable=False), sa.Column('description', sa.Text(), nullable=False), sa.ForeignKeyConstraint(['event_id'], ['events.events.id']), sa.PrimaryKeyConstraint('id'), schema='events' ) def downgrade(): op.drop_table('tracks', schema='events')
Fix AudioContext not define reference error.
/* * Copyright (c) 2013 Csernik Flaviu Andrei * * See the file LICENSE.txt for copying permission. * */ "use strict"; window.AudioContext = window.AudioContext || window.webkitAudioContext; function PropertyNotInitialized(obj, propName) { this.property = propName; this.obj = obj; } PropertyNotInitialized.prototype.toString = function () { return this.obj + " : " + this.property + " not initialized."; }; function isInteger(n) { return typeof n === "number" && Math.floor(n) == n; } function checkNat(callerName, n) { if (isInteger) { if (value <= 0) { throw new RangeError("downsampleFactor must be a positive." + "given number is not: " + value); } } else { throw new TypeError("downsampleFactor accepts an integer but" + "given type is " + typeof value); } }
/* * Copyright (c) 2013 Csernik Flaviu Andrei * * See the file LICENSE.txt for copying permission. * */ "use strict"; function PropertyNotInitialized(obj, propName) { this.property = propName; this.obj = obj; } PropertyNotInitialized.prototype.toString = function () { return this.obj + " : " + this.property + " not initialized."; }; function isInteger(n) { return typeof n === "number" && Math.floor(n) == n; } function checkNat(callerName, n) { if (isInteger) { if (value <= 0) { throw new RangeError("downsampleFactor must be a positive." + "given number is not: " + value); } } else { throw new TypeError("downsampleFactor accepts an integer but" + "given type is " + typeof value); } }
Update path of slider images.
module.exports = function(grunt) { grunt.config.merge({ imagemin: { slider: { files: [{ expand: true, cwd: 'bower_components/cacao/modules/slider/images', src: ['**/*.{png,jpg,gif}'], dest: '<%= global.dest %>/layout/images' }] } } }); grunt.registerTask('build-slider', ['imagemin:slider']); };
module.exports = function(grunt) { grunt.config.merge({ imagemin: { slider: { files: [{ expand: true, cwd: 'cacao/modules/slider/images', src: ['**/*.{png,jpg,gif}'], dest: '<%= global.dest %>/layout/images' }] } } }); grunt.registerTask('build-slider', ['imagemin:slider']); };
Print out current message offset
'use strict'; const co = require('co'); const chassis = require('../../'); const Events = chassis.events.Events; co(function* init() { const config = { provider: 'kafka', groupId: 'notify-listen', clientId: 'notify-listen', connectionString: 'localhost:9092', protos: ['io/restorecommerce/notify.proto'], protoRoot: '../../protos/', }; // Create a new microservice Server const events = new Events('kafka', config); yield events.start(); const logger = events.logger; // Subscribe to events which the business logic requires const topicName = 'io.restorecommerce.notify'; const notificationEvents = yield events.topic(topicName); const offset = yield notificationEvents.$offset(); logger.verbose(`Current offset for topic ${topicName} is ${offset}`); // Start listening to events yield notificationEvents.on('notification', function* listen(notification) { logger.info('notification', notification); }); }).catch((err) => { /* eslint no-console: ["error", { allow: ["error"] }] */ console.error('init error', err.stack); process.exit(1); });
'use strict'; const co = require('co'); const chassis = require('../../'); const Events = chassis.events.Events; co(function* init() { const config = { provider: 'kafka', groupId: 'notify-listen', clientId: 'notify-listen', connectionString: 'localhost:9092', protos: ['io/restorecommerce/notify.proto'], protoRoot: '../../protos/', }; // Create a new microservice Server const events = new Events('kafka', config); // Subscribe to events which the business logic requires const notificationEvents = yield events.topic('io.restorecommerce.notify'); yield notificationEvents.on('notification', function* listen(notification) { events.logger.info('notification', notification); }); // Start listening to events yield events.start(); }).catch((err) => { /* eslint no-console: ["error", { allow: ["error"] }] */ console.error('init error', err.stack); process.exit(1); });
Replace `@\unlink()` with a check for file existence
<?php namespace wcf\system\language\preload\command; use wcf\data\language\Language; /** * Resets the preload cache for the requested language. * * @author Alexander Ebert * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Language\Preload\Command * @since 6.0 */ final class ResetPreloadCache { private readonly Language $language; public function __construct(Language $language) { $this->language = $language; } public function __invoke(): void { // Try to remove the file if it exists. $filename = \WCF_DIR . $this->language->getPreloadCacheFilename(); if (\file_exists($filename)) { \unlink($filename); } } }
<?php namespace wcf\system\language\preload\command; use wcf\data\language\Language; /** * Resets the preload cache for the requested language. * * @author Alexander Ebert * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Language\Preload\Command * @since 6.0 */ final class ResetPreloadCache { private readonly Language $language; public function __construct(Language $language) { $this->language = $language; } public function __invoke(): void { // Try to remove the file if it exists. @\unlink(\WCF_DIR . $this->language->getPreloadCacheFilename()); } }
Delete old sqlite db before running tests.
package com.example.ollie; import com.example.ollie.model.Note; import com.example.ollie.shadows.PersistentShadowSQLiteOpenHelper; import ollie.Ollie; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.io.File; import static org.fest.assertions.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = PersistentShadowSQLiteOpenHelper.class) public class OllieTest { @BeforeClass public static void preInitialize() { new File("path").delete(); } @Before public void initialize() { Ollie.init(Robolectric.application, "OllieSample.db", 1); } @Test public void testSaveEntity() { Note note = new Note(); assertThat(note.id).isNull(); note.title = "Test note"; note.body = "Testing saving a note."; note.save(); assertThat(note.id).isNotNull(); assertThat(note.id).isGreaterThan(0l); } @Test public void testLoadEntity() { Note note = Note.find(Note.class, 1l); assertThat(note).isNotNull(); assertThat(note.id).isNotNull(); assertThat(note.id).isGreaterThan(0l); } }
package com.example.ollie; import com.example.ollie.model.Note; import com.example.ollie.shadows.PersistentShadowSQLiteOpenHelper; import ollie.Ollie; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.fest.assertions.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = PersistentShadowSQLiteOpenHelper.class) public class OllieTest { @Before public void initialize() { Ollie.init(Robolectric.application, "OllieSample.db", 1); } @Test public void testSaveEntity() { Note note = new Note(); assertThat(note.id).isNull(); note.title = "Test note"; note.body = "Testing saving a note."; note.save(); assertThat(note.id).isNotNull(); assertThat(note.id).isGreaterThan(0l); } @Test public void testLoadEntity() { Note note = Note.find(Note.class, 1l); assertThat(note).isNotNull(); assertThat(note.id).isNotNull(); assertThat(note.id).isGreaterThan(0l); } }
Add development mode error logging Remove debug console.log()
/* eslint no-process-exit:0 */ import fsp from 'fs-promise'; import _ from 'lodash'; import * as issueHandler from './issue-handler'; import {findProjectKey} from './jira-operations'; import {getJiraAPI} from './jira-connection'; export function getIssueReference(msgToParse, prjKey) { let pattern = RegExp(`${prjKey}-\\d+`, 'g'); let commentPattern = RegExp(`^#.*$`, 'gm'); msgToParse = msgToParse.replace(commentPattern, ''); let references = msgToParse.match(pattern); return _.unique(references); } export function getCommitMsg(path) { return getJiraAPI() .then(jiraAPI => { return fsp.readFile(path, {encoding:'utf8'}) .then(fileContents => getIssueReference(fileContents, findProjectKey(jiraAPI)) ) .then(issues => issueHandler.issueStrategizer(issues) ); }); } export function precommit(path) { return getCommitMsg(path) .then(() => 0) .catch(err => { if (process.env.NODE_ENV === 'development') { console.error(err.stack); } else { console.error(err.toString()); } return 1; }); }
/* eslint no-process-exit:0 */ import fsp from 'fs-promise'; import _ from 'lodash'; import * as issueHandler from './issue-handler'; import {findProjectKey} from './jira-operations'; import {getJiraAPI} from './jira-connection'; export function getIssueReference(msgToParse, prjKey) { let pattern = RegExp(`${prjKey}-\\d+`, 'g'); let commentPattern = RegExp(`^#.*$`, 'gm'); msgToParse = msgToParse.replace(commentPattern, ''); let references = msgToParse.match(pattern); return _.unique(references); } export function getCommitMsg(path) { return getJiraAPI() .then(jiraAPI => { return fsp.readFile(path, {encoding:'utf8'}) .then(fileContents => getIssueReference(fileContents, findProjectKey(jiraAPI)) ) .then(issues => issueHandler.issueStrategizer(issues) ); }); } export function precommit(path) { return getCommitMsg(path) .then(() => 0) .catch(err => { console.error(err); return 1; }); }
Update example to avoid walking entire project
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib 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. */ 'use strict'; var resolve = require( 'path' ).resolve; var lint = require( './../lib' ); var opts = { 'dir': resolve( __dirname, '..', 'test' ), 'pattern': '**/repl.txt' }; lint( opts, done ); function done( error, errs ) { if ( error ) { throw error; } if ( errs ) { console.log( JSON.stringify( errs, null, 2 ) ); } else { console.log( 'Success!' ); } }
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib 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. */ 'use strict'; var lint = require( './../lib' ); var opts = { 'pattern': '**/utils/define-property/**/repl.txt' }; lint( opts, done ); function done( error, errs ) { if ( error ) { throw error; } if ( errs ) { console.log( JSON.stringify( errs, null, 2 ) ); } else { console.log( 'Success!' ); } }
Make SecretServiceNotAvailableException a subclass of SecretStorageException
# SecretStorage module for Python # Access passwords using the SecretService DBus API # Author: Dmitry Shachnev, 2012 # License: BSD """All secretstorage functions may raise various exceptions when something goes wrong. All exceptions derive from base :exc:`SecretStorageException` class.""" class SecretStorageException(Exception): """All exceptions derive from this class.""" class SecretServiceNotAvailableException(SecretStorageException): """Raised by :class:`~secretstorage.item.Item` or :class:`~secretstorage.collection.Collection` constructors, or by other functions in the :mod:`secretstorage.collection` module, when the Secret Service API is not available.""" class LockedException(SecretStorageException): """Raised when an action cannot be performed because the collection is locked. Use :meth:`~secretstorage.collection.Collection.is_locked` to check if the collection is locked, and :meth:`~secretstorage.collection.Collection.unlock` to unlock it. """ class ItemNotFoundException(SecretStorageException): """Raised when an item does not exist or has been deleted. Example of handling: >>> try: ... item = secretstorage.Item(item_path) ... except secretstorage.ItemNotFoundException: ... print('Item not found!') ... 'Item not found!' Also, :func:`~secretstorage.collection.create_collection` may raise this exception when a prompt was dismissed during creating the collection. """
# SecretStorage module for Python # Access passwords using the SecretService DBus API # Author: Dmitry Shachnev, 2012 # License: BSD """All secretstorage functions may raise various exceptions when something goes wrong. All exceptions derive from base :exc:`SecretStorageException` class.""" class SecretStorageException(Exception): """All exceptions derive from this class.""" class SecretServiceNotAvailableException(Exception): """Raised by :class:`~secretstorage.item.Item` or :class:`~secretstorage.collection.Collection` constructors, or by other functions in the :mod:`secretstorage.collection` module, when the Secret Service API is not available.""" class LockedException(SecretStorageException): """Raised when an action cannot be performed because the collection is locked. Use :meth:`~secretstorage.collection.Collection.is_locked` to check if the collection is locked, and :meth:`~secretstorage.collection.Collection.unlock` to unlock it. """ class ItemNotFoundException(SecretStorageException): """Raised when an item does not exist or has been deleted. Example of handling: >>> try: ... item = secretstorage.Item(item_path) ... except secretstorage.ItemNotFoundException: ... print('Item not found!') ... 'Item not found!' Also, :func:`~secretstorage.collection.create_collection` may raise this exception when a prompt was dismissed during creating the collection. """
Convert arrow functions to function markup Without this, navigo will not run in IE11.
/* global __dirname, require, module*/ const path = require("path"); const yargs = require("yargs"); const env = yargs.argv.env; // use --env with webpack 2 const shouldExportToAMD = yargs.argv.amd; let libraryName = "Navigo"; let outputFile, mode; if (shouldExportToAMD) { libraryName += ".amd"; } if (env === "build") { mode = "production"; outputFile = libraryName + ".min.js"; } else { mode = "development"; outputFile = libraryName + ".js"; } const config = { mode: mode, entry: __dirname + "/src/index.ts", devtool: "source-map", target: "es5", output: { path: __dirname + "/lib", filename: outputFile.toLowerCase(), library: libraryName, libraryTarget: shouldExportToAMD ? "amd" : "umd", libraryExport: "default", umdNamedDefine: true, globalObject: "typeof self !== 'undefined' ? self : this", }, module: { rules: [ { test: /(\.jsx|\.js|\.ts|\.tsx)$/, use: { loader: "babel-loader", }, exclude: /(node_modules|bower_components)/, }, ], }, resolve: { modules: [path.resolve("./node_modules"), path.resolve("./src")], extensions: [".json", ".js", ".ts"], }, }; module.exports = config;
/* global __dirname, require, module*/ const path = require("path"); const yargs = require("yargs"); const env = yargs.argv.env; // use --env with webpack 2 const shouldExportToAMD = yargs.argv.amd; let libraryName = "Navigo"; let outputFile, mode; if (shouldExportToAMD) { libraryName += ".amd"; } if (env === "build") { mode = "production"; outputFile = libraryName + ".min.js"; } else { mode = "development"; outputFile = libraryName + ".js"; } const config = { mode: mode, entry: __dirname + "/src/index.ts", devtool: "source-map", output: { path: __dirname + "/lib", filename: outputFile.toLowerCase(), library: libraryName, libraryTarget: shouldExportToAMD ? "amd" : "umd", libraryExport: "default", umdNamedDefine: true, globalObject: "typeof self !== 'undefined' ? self : this", }, module: { rules: [ { test: /(\.jsx|\.js|\.ts|\.tsx)$/, use: { loader: "babel-loader", }, exclude: /(node_modules|bower_components)/, }, ], }, resolve: { modules: [path.resolve("./node_modules"), path.resolve("./src")], extensions: [".json", ".js", ".ts"], }, }; module.exports = config;
Fix wireless transmitter not sending container updates
package refinedstorage.tile; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.nbt.NBTTagCompound; import refinedstorage.RefinedStorageUtils; import refinedstorage.container.ContainerWirelessTransmitter; import refinedstorage.inventory.InventorySimple; import refinedstorage.item.ItemUpgrade; public class TileWirelessTransmitter extends TileMachine { public static final int RANGE_PER_UPGRADE = 8; private InventorySimple inventory = new InventorySimple("upgrades", 4, this); @Override public int getEnergyUsage() { return 8 + RefinedStorageUtils.getUpgradeEnergyUsage(inventory); } @Override public void updateMachine() { } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); RefinedStorageUtils.restoreInventory(inventory, 0, nbt); } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); RefinedStorageUtils.saveInventory(inventory, 0, nbt); } public int getRange() { return 16 + (RefinedStorageUtils.getUpgradeCount(inventory, ItemUpgrade.TYPE_RANGE) * RANGE_PER_UPGRADE); } @Override public Class<? extends Container> getContainer() { return ContainerWirelessTransmitter.class; } @Override public IInventory getDroppedInventory() { return inventory; } }
package refinedstorage.tile; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.nbt.NBTTagCompound; import refinedstorage.RefinedStorageUtils; import refinedstorage.inventory.InventorySimple; import refinedstorage.item.ItemUpgrade; public class TileWirelessTransmitter extends TileMachine { public static final int RANGE_PER_UPGRADE = 8; private InventorySimple inventory = new InventorySimple("upgrades", 4, this); @Override public int getEnergyUsage() { return 8 + RefinedStorageUtils.getUpgradeEnergyUsage(inventory); } @Override public void updateMachine() { } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); RefinedStorageUtils.restoreInventory(inventory, 0, nbt); } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); RefinedStorageUtils.saveInventory(inventory, 0, nbt); } public int getRange() { return 16 + (RefinedStorageUtils.getUpgradeCount(inventory, ItemUpgrade.TYPE_RANGE) * RANGE_PER_UPGRADE); } @Override public Class<? extends Container> getContainer() { return null; } @Override public IInventory getDroppedInventory() { return inventory; } }
Fix usage of Piwik in renderer
import {ipcRenderer} from 'electron'; import * as piwik from 'renderer/services/piwik'; import webView from 'renderer/webview'; /** * Forward a message to the webview. */ ipcRenderer.on('fwd-webview', function (event, channel, ...args) { if (webView.isLoading && (typeof webView.isLoading === 'function') && !webView.isLoading()) { webView.send(channel, ...args); } else { const onLoaded = function () { webView.send(channel, ...args); webView.removeEventListener('dom-ready', onLoaded); }; webView.addEventListener('dom-ready', onLoaded); } }); /** * Call a method of the webview. */ ipcRenderer.on('call-webview-method', function (event, method, ...args) { webView[method](...args); }); /** * Track an analytics event. */ ipcRenderer.on('track-analytics', function (event, name, args) { const tracker = piwik.getTracker(); if (tracker) { const trackerFn = tracker[name]; trackerFn(...args); } });
import {ipcRenderer} from 'electron'; import piwik from 'renderer/services/piwik'; import webView from 'renderer/webview'; /** * Forward a message to the webview. */ ipcRenderer.on('fwd-webview', function (event, channel, ...args) { if (webView.isLoading && (typeof webView.isLoading === 'function') && !webView.isLoading()) { webView.send(channel, ...args); } else { const onLoaded = function () { webView.send(channel, ...args); webView.removeEventListener('dom-ready', onLoaded); }; webView.addEventListener('dom-ready', onLoaded); } }); /** * Call a method of the webview. */ ipcRenderer.on('call-webview-method', function (event, method, ...args) { webView[method](...args); }); /** * Track an analytics event. */ ipcRenderer.on('track-analytics', function (event, name, args) { const tracker = piwik.getTracker(); if (tracker) { const trackerFn = tracker[name]; trackerFn(...args); } });
Sort the results from ls
<?php include '../util.php.inc'; $dir = $_GET['dir']; $path = bespin_get_file_name($dir); $folder_array = array(); $file_array = array(); if (is_dir($path)) { if ($dh = opendir($path)) { while (($entry = readdir($dh)) !== false) { if (substr($entry, 0, 1) == '.') { continue; } if (is_dir("$path/$entry")) { $folder_array[] = $entry; } else { $file_array[] = $entry; } } closedir($dh); } } sort($folder_array); sort($file_array); echo '<ul class="jqueryFileTree" style="display: none;">'; foreach ($folder_array as $folder) { echo "<li class=\"directory collapsed\"><a href=\"#\" rel=\"$dir/$folder/\">$folder</a></li>"; } foreach ($file_array as $file) { echo "<li class=\"file ext_css\"><a href=\"#\" rel=\"$dir/$file/\">$file</a></li>"; } echo '</ul>' ?>
<?php include '../util.php.inc'; $dir = $_GET['dir']; $path = bespin_get_file_name($dir); // Open a known directory, and proceed to read its contents if (is_dir($path)) { if ($dh = opendir($path)) { echo '<ul class="jqueryFileTree" style="display: none;">'; while (($file = readdir($dh)) !== false) { if (substr($file, 0, 1) == '.') { continue; } $class_name = is_dir("$path/$file") ? 'directory' : 'file ext_css'; $postfix = is_dir("$path/$file") ? '/' : ''; echo "<li class=\"$class_name collapsed\"><a href=\"#\" rel=\"$dir/$file$postfix\">$file</a></li>"; } closedir($dh); } } ?>
Add special case for "anywhere"
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import dataproperty import six from ._error import NetworkInterfaceNotFoundError def verify_network_interface(device): try: import netifaces except ImportError: return if device not in netifaces.interfaces(): raise NetworkInterfaceNotFoundError( "network interface not found: " + device) def sanitize_network(network): """ :return: Network string :rtype: str :raises ValueError: if the network string is invalid. """ import ipaddress if dataproperty.is_empty_string(network): return "" if network == "anywhere": return "0.0.0.0/0" try: ipaddress.IPv4Address(six.u(network)) return network + "/32" except ipaddress.AddressValueError: pass ipaddress.IPv4Network(six.u(network)) # validate network str return network
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import dataproperty import six from ._error import NetworkInterfaceNotFoundError def verify_network_interface(device): try: import netifaces except ImportError: return if device not in netifaces.interfaces(): raise NetworkInterfaceNotFoundError( "network interface not found: " + device) def sanitize_network(network): """ :return: Network string :rtype: str :raises ValueError: if the network string is invalid. """ import ipaddress if dataproperty.is_empty_string(network): return "" try: ipaddress.IPv4Address(six.u(network)) return network + "/32" except ipaddress.AddressValueError: pass ipaddress.IPv4Network(six.u(network)) # validate network str return network
Fix rainbow and staging :boom:
import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { browserHistory } from 'react-router' import { syncHistory } from 'redux-simple-router' import { combineReducers, compose, createStore, applyMiddleware } from 'redux' import { autoRehydrate } from 'redux-persist' import { analytics, requester, uploader } from './middleware' import * as reducers from './reducers' const reducer = combineReducers(reducers) const reduxRouterMiddleware = syncHistory(browserHistory) let store = null if (typeof window !== 'undefined') { const logger = createLogger({ collapsed: true, predicate: () => ENV.APP_DEBUG }) store = compose( autoRehydrate(), applyMiddleware(thunk, reduxRouterMiddleware, uploader, requester, analytics, logger), )(createStore)(reducer, window.__INITIAL_STATE__ || {}) } else { store = compose( applyMiddleware(thunk, uploader, requester, analytics), )(createStore)(reducer, {}) } export default store
import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { browserHistory } from 'react-router' import { syncHistory } from 'redux-simple-router' import { combineReducers, compose, createStore, applyMiddleware } from 'redux' import { autoRehydrate } from 'redux-persist' import { analytics, requester, uploader } from './middleware' import * as reducers from './reducers' const reducer = combineReducers(reducers) const reduxRouterMiddleware = syncHistory(browserHistory) let store = null if (typeof window !== 'undefined') { const logger = createLogger({ collapsed: true, predicate: () => ENV.APP_DEBUG }) store = compose( autoRehydrate(), applyMiddleware(thunk, reduxRouterMiddleware, uploader, requester, analytics, logger), )(createStore)(reducer, window.__INITIAL_STATE__ || {}) } else { store = compose( applyMiddleware(thunk, reduxRouterMiddleware, uploader, requester, analytics), )(createStore)(reducer, {}) } export default store
Kill more code.google.com/p/ references, and update example code to new API (It's been broken for a while)
// Simple use of the tuntap package that prints packets received by the interface. package main import ( "fmt" "os" "github.com/mistsys/tuntap" ) func main() { if len(os.Args) != 3 { fmt.Println("syntax:", os.Args[0], "tun|tap", "<device name>") return } var typ tuntap.DevKind switch os.Args[1] { case "tun": typ = tuntap.DevTun case "tap": typ = tuntap.DevTap default: fmt.Println("Unknown device type", os.Args[1]) return } tun, err := tuntap.Open(os.Args[2], typ) if err != nil { fmt.Println("Error opening tun/tap device:", err) return } fmt.Println("Listening on", tun.Name()) for { buf := make([]byte, 1536) pkt, err := tun.ReadPacket(buf) if err != nil { fmt.Println("Read error:", err) } else { if pkt.Truncated { fmt.Printf("!") } else { fmt.Printf(" ") } fmt.Printf("%x %x\n", pkt.Protocol, pkt.Body) } } }
// Simple use of the tuntap package that prints packets received by the interface. package main import ( "fmt" "os" "code.google.com/p/tuntap" ) func main() { if len(os.Args) != 3 { fmt.Println("syntax:", os.Args[0], "tun|tap", "<device name>") return } var typ tuntap.DevKind switch os.Args[1] { case "tun": typ = tuntap.DevTun case "tap": typ = tuntap.DevTap default: fmt.Println("Unknown device type", os.Args[1]) return } tun, err := tuntap.Open(os.Args[2], typ) if err != nil { fmt.Println("Error opening tun/tap device:", err) return } fmt.Println("Listening on", tun.Name()) for { pkt, err := tun.ReadPacket() if err != nil { fmt.Println("Read error:", err) } else { if pkt.Truncated { fmt.Printf("!") } else { fmt.Printf(" ") } fmt.Printf("%x %x\n", pkt.Protocol, pkt.Packet) } } }
Clean up config, only build once Need to swap to webpack though!
import fs from 'fs' import * as babel from 'babel-core' import _eval from 'eval' import babelConfig from './babelConfig' import log from './log' const configFns = readConfigFns('bastion.conf.js') export default function configPassthrough (name, config) { if (typeof configFns[name] === 'function') { log.verbose('found config function for %s', name) return configFns[name](config) } else { log.verbose('no config function four %s', name) } return config } function readConfigFns (configFile) { if (fileExists(configFile)) { log.verbose('found config file %s', configFile) const source = babel.transformFileSync(configFile, babelConfig(true)).code return _eval(source, configFile, {}, true) } else { log.verbose('no config file found at %s', configFile) return {} } } function fileExists (path) { try { fs.accessSync(path, fs.F_OK) return true } catch (e) { return false } }
import fs from 'fs' import * as babel from 'babel-core' import _eval from 'eval' import babelConfig from './babelConfig' import log from './log' const configFile = 'bastion.conf.js' export default function configPassthrough (name, config) { if (fileExists(configFile)) { log.verbose('found config file') const source = babel.transformFileSync(configFile, babelConfig(true)).code const fns = _eval(source, configFile, {}, true) if (typeof fns[name] === 'function') { log.verbose('found config function for %s', name) return fns[name](config) } else { log.verbose('no config function four %s', name) } } else { log.verbose('no config file found') } return config } function fileExists (path) { try { fs.accessSync(path, fs.F_OK) return true } catch (e) { return false } }
Add docutils to the list of requirements. Install docutils during a pip install so that rendering reStructuredText (CTRL-r) works out of the box.
import os from setuptools import setup from nvpy import nvpy # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "nvpy", version = nvpy.VERSION, author = "Charl P. Botha", author_email = "cpbotha@vxlabs.com", description = "A cross-platform simplenote-syncing note-taking app inspired by Notational Velocity.", license = "BSD", keywords = "simplenote note-taking tkinter nvalt markdown", url = "https://github.com/cpbotha/nvpy", packages=['nvpy'], long_description=read('README.rst'), install_requires = ['Markdown', 'docutils'], entry_points = { 'gui_scripts' : ['nvpy = nvpy.nvpy:main'] }, # use MANIFEST.in file # because package_data is ignored during sdist include_package_data=True, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: X11 Applications", "Environment :: MacOS X", "Environment :: Win32 (MS Windows)", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], )
import os from setuptools import setup from nvpy import nvpy # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "nvpy", version = nvpy.VERSION, author = "Charl P. Botha", author_email = "cpbotha@vxlabs.com", description = "A cross-platform simplenote-syncing note-taking app inspired by Notational Velocity.", license = "BSD", keywords = "simplenote note-taking tkinter nvalt markdown", url = "https://github.com/cpbotha/nvpy", packages=['nvpy'], long_description=read('README.rst'), install_requires = ['Markdown'], entry_points = { 'gui_scripts' : ['nvpy = nvpy.nvpy:main'] }, # use MANIFEST.in file # because package_data is ignored during sdist include_package_data=True, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: X11 Applications", "Environment :: MacOS X", "Environment :: Win32 (MS Windows)", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], )
Make tests run from correct directory.
import GenotypeNetwork as gn import os import networkx as nx # Change cwd for tests to the current path. here = os.path.dirname(os.path.realpath(__file__)) os.chdir(here) GN = gn.GenotypeNetwork() GN.read_sequences('test/Demo_052715.fasta') GN.generate_genotype_network() GN.write_genotype_network('test/Demo_052715.pkl') GN.read_genotype_network('test/Demo_052715.pkl') def test_read_sequences_works_correctly(): """ Checks that GN.read_sequences reads in correct number of sequences. """ assert len(GN.sequences) == 3 def test_generate_genotype_network(): """ Checks that the number of nodes equals the number of sequences Checks number of edges """ assert len(GN.sequences) == len(GN.G.nodes()) assert len(GN.G.edges()) == 2 # This will change based on dataset def test_write_genotype_network(): """ Checks that the pickled network is written to disk. """ assert 'Demo_052715.pkl' in os.listdir('Test') def test_read_genotype_network(): """ Checks that the genotype network is being loaded correctly by counting nodes in a test pkl file. """ G = nx.read_gpickle('Test/Demo_052715.pkl') # The length of the test file assert len(G.nodes()) == 3
import GenotypeNetwork as gn import os import networkx as nx GN = gn.GenotypeNetwork() GN.read_sequences('test/Demo_052715.fasta') GN.generate_genotype_network() GN.write_genotype_network('test/Demo_052715.pkl') GN.read_genotype_network('test/Demo_052715.pkl') def test_read_sequences_works_correctly(): """ Checks that GN.read_sequences reads in correct number of sequences. """ assert len(GN.sequences) == 3 def test_generate_genotype_network(): """ Checks that the number of nodes equals the number of sequences Checks number of edges """ assert len(GN.sequences) == len(GN.G.nodes()) assert len(GN.G.edges()) == 2 # This will change based on dataset def test_write_genotype_network(): """ Checks that the pickled network is written to disk. """ assert 'Demo_052715.pkl' in os.listdir('Test') def test_read_genotype_network(): """ Checks that the genotype network is being loaded correctly by counting nodes in a test pkl file. """ G = nx.read_gpickle('Test/Demo_052715.pkl') # The length of the test file assert len(G.nodes()) == 3
[clean-up] Remove unnecessary contentBase setting of webpack dev server.
"use strict"; const HtmlWebpackPlugin = require('html-webpack-plugin'); const HOST = process.env.HOST || "127.0.0.1"; const PORT = process.env.PORT || "8080"; module.exports = { entry: [ './src/client/web/main.jsx' ], output: { path: './build/web', filename: 'bundle.js' }, resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders:[ { test: /\.js[x]?$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' } ] }, devServer: { port: PORT, host: HOST }, plugins: [ new HtmlWebpackPlugin({ template: './src/client/web/template.html' }) ] };
"use strict"; const HtmlWebpackPlugin = require('html-webpack-plugin'); const HOST = process.env.HOST || "127.0.0.1"; const PORT = process.env.PORT || "8080"; module.exports = { entry: [ './src/client/web/main.jsx' ], output: { path: './build/web', filename: 'bundle.js' }, resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders:[ { test: /\.js[x]?$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' } ] }, devServer: { contentBase: "./build/web", port: PORT, host: HOST }, plugins: [ new HtmlWebpackPlugin({ template: './src/client/web/template.html' }) ] };
Add usage example for longestPRefixOf() method
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class TrieExample { public static void main(String[] args) { // Open the data file Scanner scf = null; try { scf = new Scanner(new File("./data/peter_piper.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } TrieST<Integer> st = new TrieST<Integer>(); // Read file's next line while (scf.hasNextLine()) { Scanner scl = new Scanner(scf.nextLine()); // Read line's next word int i = 0; while (scl.hasNext()) { String key = scl.next(); st.put(key, i); i++; } } // print results System.out.println("Symbol table:"); for (String key : st.keys()) { System.out.println("* " + key + " " + st.get(key)); } System.out.println(); System.out.println("Keys with prefix \"pi\":"); for (String key : st.keysWithPrefix("pi")) { System.out.println("* " + key); } System.out.println(); System.out.println("Longest prefix of \"peckleton\":"); System.out.println("* " + st.longestPrefixOf("peckleton")); System.out.println(); } }
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class TrieExample { public static void main(String[] args) { // Open the data file Scanner scf = null; try { scf = new Scanner(new File("./data/peter_piper.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } TrieST<Integer> st = new TrieST<Integer>(); // Read file's next line while (scf.hasNextLine()) { Scanner scl = new Scanner(scf.nextLine()); // Read line's next word int i = 0; while (scl.hasNext()) { String key = scl.next(); st.put(key, i); i++; } } // print results for (String key : st.keys()) { System.out.println(key + " " + st.get(key)); } System.out.println(); System.out.println("Keys with prefix \"pi\""); for (String key : st.keysWithPrefix("pi")) { System.out.println(key); } System.out.println(); } }
Throw a ReferenceError on animations.select(unregisterName)
'use strict' module.exports = function (animations) { let index = 0 let running = false const api = { set index (i) { console.log(animations[i].name) index = i }, next: () => { api.index = ++index % animations.length }, previous: () => { api.index = index > 0 ? index - 1 : animations.length - 1 }, select: name => { for (let i = 0; i < animations.length; i++) { if (animations[i].name.toUpperCase() === name.toUpperCase()) { api.index = i return true } } throw ReferenceError(`Cannot find animation '${name}'`) }, get running () { return running }, resume: () => { running = true }, pause: () => { running = false }, update: dt => { if (running) animations[index].update(dt) } } animations = animations.map(Animation => new Animation(api)) return api }
'use strict' module.exports = function (animations) { let index = 0 let running = false const api = { set index (i) { console.log(animations[i].name) index = i }, next: () => { api.index = ++index % animations.length }, previous: () => { api.index = index > 0 ? index - 1 : animations.length - 1 }, select: name => { for (let i = 0; i < animations.length; i++) { if (animations[i].name.toUpperCase() === name.toUpperCase()) { api.index = i break } } }, get running () { return running }, resume: () => { running = true }, pause: () => { running = false }, update: dt => { if (running) animations[index].update(dt) } } animations = animations.map(Animation => new Animation(api)) return api }
Fix query extractor UTF-8 handling
#!/usr/bin/env python """ Script to extract and then generate random queries for fuzzy searching. Usage: ./extract-random-queries.py <infile> <outfile> """ import codecs import os from random import choice, randint, random import string from subprocess import call import sys from tempfile import mkstemp __author__ = "Uwe L. Korn" __license__ = "MIT" input_file = sys.argv[1] output_file = sys.argv[2] # Randomly select 1000 lines from the input file and store them temporarily. temp_f, temp_file = mkstemp() call(['shuf', '-n', '1000', input_file, '-o', temp_file]) # Modifiy these queries so that they have a non-zero edit distance. with codecs.open(temp_file, 'r', 'utf-8') as f: with codecs.open(output_file, 'w', 'utf-8') as out: for line in f.readlines(): if random() > 0.75: pos = randint(0, len(line) - 2) line = line[0:pos] + choice(string.ascii_lowercase) + line[pos + 1:] if random() > 0.25: pos = randint(0, len(line) - 2) line = line[0:pos] + choice(string.ascii_lowercase) + line[pos + 1:] out.write(line) # Remove the temporary file again. os.unlink(temp_file)
#!/usr/bin/env python """ Script to extract and then generate random queries for fuzzy searching. Usage: ./extract-random-queries.py <infile> <outfile> """ import os from random import choice, randint, random import string from subprocess import call import sys from tempfile import mkstemp __author__ = "Uwe L. Korn" __license__ = "MIT" input_file = sys.argv[1] output_file = sys.argv[2] # Randomly select 1000 lines from the input file and store them temporarily. temp_f, temp_file = mkstemp() call(['shuf', '-n', '1000', input_file, '-o', temp_file]) # Modifiy these queries so that they have a non-zero edit distance. with open(temp_file, 'r') as f: with open(output_file, 'w') as out: for line in f.readlines(): if random() > 0.75: pos = randint(0, len(line) - 2) line = line[0:pos] + choice(string.ascii_lowercase) + line[pos + 1:] if random() > 0.25: pos = randint(0, len(line) - 2) line = line[0:pos] + choice(string.ascii_lowercase) + line[pos + 1:] out.write(line) # Remove the temporary file again. os.unlink(temp_file)
Add ModuleConcatenationPlugin to webpack compile plugins
/* eslint-disable import/no-extraneous-dependencies */ import path from 'path' import webpack from 'webpack' import packageConfig from './package.json' const banner = `${packageConfig.name} ${packageConfig.version} ${packageConfig.repository.url} Includes htmlparser2 https://github.com/fb55/htmlparser2/ https://github.com/fb55/htmlparser2/raw/master/LICENSE @license ${packageConfig.license} ${packageConfig.repository.url}/raw/master/LICENSE` const basename = path.basename(packageConfig.browser, '.js') export default { entry: { [basename]: './entry.js', [`${basename}.min`]: './entry.js', }, output: { path: path.resolve(__dirname, path.dirname(packageConfig.browser)), filename: '[name].js', libraryTarget: 'umd', umdNamedDefine: true, }, plugins: [ new webpack.BannerPlugin(banner), new webpack.optimize.ModuleConcatenationPlugin(), new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js($|\?)/i }), ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [['es2015', { modules: false }]], }, }, ], }, }
/* eslint-disable import/no-extraneous-dependencies */ import path from 'path' import webpack from 'webpack' import packageConfig from './package.json' const banner = `${packageConfig.name} ${packageConfig.version} ${packageConfig.repository.url} Includes htmlparser2 https://github.com/fb55/htmlparser2/ https://github.com/fb55/htmlparser2/raw/master/LICENSE @license ${packageConfig.license} ${packageConfig.repository.url}/raw/master/LICENSE` const basename = path.basename(packageConfig.browser, '.js') export default { entry: { [basename]: './entry.js', [`${basename}.min`]: './entry.js', }, output: { path: path.resolve(__dirname, path.dirname(packageConfig.browser)), filename: '[name].js', libraryTarget: 'umd', umdNamedDefine: true, }, plugins: [ new webpack.BannerPlugin(banner), new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js($|\?)/i }), ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [['es2015', { modules: false }]], }, }, ], }, }
Remove redundant 'repo' in WrapperPath()
#!/usr/bin/env python # # Copyright (C) 2014 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import imp import os def WrapperPath(): #return os.path.join(os.path.dirname(__file__), 'repo') return os.path.join(os.path.dirname(__file__), '') _wrapper_module = None def Wrapper(): global _wrapper_module if not _wrapper_module: _wrapper_module = imp.load_source('wrapper', WrapperPath()) return _wrapper_module
#!/usr/bin/env python # # Copyright (C) 2014 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import imp import os def WrapperPath(): return os.path.join(os.path.dirname(__file__), 'repo') _wrapper_module = None def Wrapper(): global _wrapper_module if not _wrapper_module: _wrapper_module = imp.load_source('wrapper', WrapperPath()) return _wrapper_module
Use null input handler for ErrorDialog; none needed
package csuf.cs544.hw1.dialogs; import android.R; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.os.Bundle; public class ErrorDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { String message = getArguments().getString("error"); return new AlertDialog.Builder(getActivity()) //.setIcon(R.drawable.alert_dialog_icon) .setTitle("e") .setMessage(message) .setPositiveButton("Okay", null).create(); } }
package csuf.cs544.hw1.dialogs; import android.R; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; public class ErrorDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { String message = getArguments().getString("error"); return new AlertDialog.Builder(getActivity()) //.setIcon(R.drawable.alert_dialog_icon) .setTitle("Error") .setMessage(message) .setPositiveButton("Okay", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } } ).create(); } }
Improve redirect on new comment
<?php namespace App\Http\Controllers; use App\Comment; use App\Post; use App\Sub; use Illuminate\Http\Request; class CommentController extends Controller { public function store($subName, $postSlug, Request $request) { $sub = Sub::where('name', $subName)->firstOrFail(); $post = Post::where('slug', $postSlug) ->where('sub_id', $sub->id) ->firstOrFail(); $comment = Comment::create($request->all()); $comment->post()->associate($post); $comment->user()->associate(auth()->user()); $comment->save(); return redirect()->route('sub.post.show', [$sub->name, $post->slug]); } }
<?php namespace App\Http\Controllers; use App\Comment; use App\Post; use App\Sub; use Illuminate\Http\Request; class CommentController extends Controller { public function store($subName, $postSlug, Request $request) { $sub = Sub::where('name', $subName)->firstOrFail(); $post = Post::where('slug', $postSlug) ->where('sub_id', $sub->id) ->firstOrFail(); $comment = Comment::create($request->all()); $comment->post()->associate($post); $comment->user()->associate(auth()->user()); $comment->save(); return redirect()->back(); } }
Increase margin and remove the padded space
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; var React = require('react'); class DetailPaneSection extends React.Component { render(): React.Element { var { children, hint, } = this.props; return ( <div style={styles.section}> <strong style={styles.title}>{this.props.title}</strong> {hint} {children} </div> ); } } var styles = { section: { marginBottom: 10, flexShrink: 0, }, title: { marginRight: 7, }, }; module.exports = DetailPaneSection;
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; var React = require('react'); class DetailPaneSection extends React.Component { render(): React.Element { var { children, hint, } = this.props; return ( <div style={styles.section}> <strong style={styles.title}>{this.props.title}</strong> {hint ? ' ' + hint : null} {children} </div> ); } } var styles = { section: { marginBottom: 10, flexShrink: 0, }, title: { marginRight: 5, }, }; module.exports = DetailPaneSection;
Extend test cases to resolver function returning a non string
/* eslint comma-dangle: 0 */ import createCachedSelector from '../index'; let memoizedFunction; beforeEach(() => { memoizedFunction = jest.fn(); }); describe('createCachedSelector', () => { it('Should use the same cached selector when resolver function returns the same string', () => { const cachedSelector = createCachedSelector( memoizedFunction, )( (arg1, arg2) => arg2, // Resolver ); const firstCall = cachedSelector('foo', 'bar'); const secondCallWithSameResolver = cachedSelector('foo', 'bar'); expect(memoizedFunction.mock.calls.length).toBe(1); }); it('Should create 2 different selectors when resolver function returns different strings', () => { const cachedSelector = createCachedSelector( memoizedFunction, )( (arg1, arg2) => arg2, // Resolver ); const firstCallResult = cachedSelector('foo', 'bar'); const secondCallWithDifferentResolver = cachedSelector('foo', 'moo'); expect(memoizedFunction.mock.calls.length).toBe(2); }); it('Should return "undefined" if provided resolver does not return a string', () => { const cachedSelector = createCachedSelector( memoizedFunction, )( () => {}, // Resolver ); const firstCallResult = cachedSelector('foo', 'bar'); expect(memoizedFunction.mock.calls.length).toBe(0); expect(firstCallResult).toBe(undefined); }); });
/* eslint comma-dangle: 0 */ import createCachedSelector from '../index'; let memoizedFunction; beforeEach(() => { memoizedFunction = jest.fn(); }); describe('createCachedSelector', () => { it('Should use the same cached selector when resolver function returns the same string', () => { const cachedSelector = createCachedSelector( memoizedFunction, )( (arg1, arg2) => arg2, // Resolver ); const firstCall = cachedSelector('foo', 'bar'); const secondCallWithSameResolver = cachedSelector('foo', 'bar'); expect(memoizedFunction.mock.calls.length).toBe(1); }); it('Should create 2 different selectors when resolver function returns different strings', () => { const cachedSelector = createCachedSelector( memoizedFunction, )( (arg1, arg2) => arg2, // Resolver ); const firstCallResult = cachedSelector('foo', 'bar'); const secondCallWithDifferentResolver = cachedSelector('foo', 'moo'); expect(memoizedFunction.mock.calls.length).toBe(2); }); });
Fix segmentation fault on PHP 5.6 on Travis CI Segmentation fault started occuring after adding test case related to issue #51
<?php require_once __DIR__ . '/../vendor/autoload.php'; // PHPUnit >= 6.0 compatibility if (!class_exists('PHPUnit_Framework_TestSuite') && class_exists('PHPUnit\Framework\TestSuite')) { /** @noinspection PhpIgnoredClassAliasDeclaration */ class_alias('PHPUnit\Framework\TestSuite', 'PHPUnit_Framework_TestSuite'); } if (!class_exists('PHPUnit_Framework_TestCase') && class_exists('PHPUnit\Framework\TestCase')) { /** @noinspection PhpIgnoredClassAliasDeclaration */ class_alias('PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase'); } require_once __DIR__ . '/BaseTestCase.php'; require_once __DIR__ . '/AttrDefTestCase.php'; echo "HTMLPurifier version: ", HTMLPurifier::VERSION, "\n"; echo "libxml version: ", constant('LIBXML_DOTTED_VERSION'), "\n"; echo "PHP memory limit: ", ini_get('memory_limit'), "\n"; echo "\n"; if (getenv('TRAVIS_PHP_VERSION')) { // Fixes /home/travis/.travis/functions: line 109: 4773 Segmentation fault (core dumped) gc_disable(); }
<?php require_once __DIR__ . '/../vendor/autoload.php'; // PHPUnit >= 6.0 compatibility if (!class_exists('PHPUnit_Framework_TestSuite') && class_exists('PHPUnit\Framework\TestSuite')) { /** @noinspection PhpIgnoredClassAliasDeclaration */ class_alias('PHPUnit\Framework\TestSuite', 'PHPUnit_Framework_TestSuite'); } if (!class_exists('PHPUnit_Framework_TestCase') && class_exists('PHPUnit\Framework\TestCase')) { /** @noinspection PhpIgnoredClassAliasDeclaration */ class_alias('PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase'); } require_once __DIR__ . '/BaseTestCase.php'; require_once __DIR__ . '/AttrDefTestCase.php'; echo "HTMLPurifier version: ", HTMLPurifier::VERSION, "\n"; echo "libxml version: ", constant('LIBXML_DOTTED_VERSION'), "\n"; echo "PHP memory limit: ", ini_get('memory_limit'), "\n"; echo "\n";
Remove extra line breaks in Registry.emit tests
import test from 'ava'; import Registry from '../src/registry'; test('Registry.emit calls each handler', t => { let registry = Registry([]); registry.on('enter', x => t.true(x === 'a')); registry.on('enter', y => t.true(y === 'a')); registry.on('exit', x => t.true(x === 'b')); registry.on('exit', y => t.true(y === 'b')); registry.once('enter', x => t.true(x === 'a')); registry.once('enter', y => t.true(y === 'a')); registry.once('exit', x => t.true(x === 'b')); registry.once('exit', y => t.true(y === 'b')); registry.emit('enter', 'a'); registry.emit('exit', 'b'); }); test('Registry.emit removes once handlers', t => { let registry = Registry([]); registry.once('enter', () => {}); t.true(registry.singles.enter.length === 1); registry.emit('enter', {}); t.true(!registry.singles.enter.length); }); test('Registry.emit returns the registry', t => { let registry = Registry([]); t.deepEqual(registry.emit('enter', {}), registry); });
import test from 'ava'; import Registry from '../src/registry'; test('Registry.emit calls each handler', t => { let registry = Registry([]); registry.on('enter', x => t.true(x === 'a')); registry.on('enter', y => t.true(y === 'a')); registry.on('exit', x => t.true(x === 'b')); registry.on('exit', y => t.true(y === 'b')); registry.once('enter', x => t.true(x === 'a')); registry.once('enter', y => t.true(y === 'a')); registry.once('exit', x => t.true(x === 'b')); registry.once('exit', y => t.true(y === 'b')); registry.emit('enter', 'a'); registry.emit('exit', 'b'); }); test('Registry.emit removes once handlers', t => { let registry = Registry([]); registry.once('enter', () => {}); t.true(registry.singles.enter.length === 1); registry.emit('enter', {}); t.true(!registry.singles.enter.length); }); test('Registry.emit returns the registry', t => { let registry = Registry([]); t.deepEqual(registry.emit('enter', {}), registry); });
Fix migrations - drop old domain
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "porady.siecobywatelska.pl", "name": "poradnia" } ) def update_site_backward(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "example.com", "name": "example.com" } ) class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.RunPython(update_site_forward, update_site_backward), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "poradnia.informacjapubliczna.org.pl", "name": "poradnia" } ) def update_site_backward(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "example.com", "name": "example.com" } ) class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.RunPython(update_site_forward, update_site_backward), ]
Remove single slider entry from plugin settings
package com.github.slidekb.back.settings; import java.util.ArrayList; import java.util.List; public class PluginSettings { List<String> processes; List<String> hotkeys; boolean alwaysRun; List<String> sliderList; public List<String> getSliderList() { return sliderList; } public void setSliderList(List<String> list) { this.sliderList = list; } public List<String> getProcesses() { if (processes == null) { processes = new ArrayList<>(); } return processes; } public List<String> getHotkeys() { if (hotkeys == null) { hotkeys = new ArrayList<>(); } return hotkeys; } public boolean isAlwaysRun() { return alwaysRun; } public void setAlwaysRun(boolean alwaysRun) { this.alwaysRun = alwaysRun; } }
package com.github.slidekb.back.settings; import java.util.ArrayList; import java.util.List; public class PluginSettings { String usedSlider; List<String> processes; List<String> hotkeys; boolean alwaysRun; List<String> sliderList; public List<String> getSliderList() { return sliderList; } public void setSliderList(List<String> list) { this.sliderList = list; } public String getUsedSlider() { return usedSlider; } public void setUsedSlider(String usedSlider, int position) { this.usedSlider = usedSlider; } public List<String> getProcesses() { if (processes == null) { processes = new ArrayList<>(); } return processes; } public List<String> getHotkeys() { if (hotkeys == null) { hotkeys = new ArrayList<>(); } return hotkeys; } public boolean isAlwaysRun() { return alwaysRun; } public void setAlwaysRun(boolean alwaysRun) { this.alwaysRun = alwaysRun; } }
Update meta values and remove author link.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- RSS Feed --> <link rel="alternate" type="application/rss+xml" href="/rss" /> <!-- Mobile friendliness --> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"> <meta name="apple-mobile-web-app-capable" content="yes"> <!-- Mobile IE allows us to activate ClearType technology for smoothing fonts for easy reading --> <meta http-equiv="cleartype" content="on"> <title>{{ isset($pageTitle) ? $pageTitle : Setting::get('app_name') }} | Cachet</title> <link href='//fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{{ elixir('css/all.css') }}"> @include('partials.stylesheet') @if($stylesheet = Setting::get('stylesheet')) <style type='text/css'> {{ $stylesheet }} </style> @endif <script src="{{ elixir('js/all.js') }}"></script> </head> <body class='status-page'> <div class='container'> @yield('content') </div> @include('partials.support-link') </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content="http://james-brooks.uk"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="alternate" type="application/rss+xml" href="/rss" /> <title>{{ isset($pageTitle) ? $pageTitle : Setting::get('app_name') }} | Cachet</title> <link href='//fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{{ elixir('css/all.css') }}"> @include('partials.stylesheet') @if($stylesheet = Setting::get('stylesheet')) <style type='text/css'> {{ $stylesheet }} </style> @endif <script src="{{ elixir('js/all.js') }}"></script> </head> <body class='status-page'> <div class='container'> @yield('content') </div> @include('partials.support-link') </body> </html>
test: Add missing method required for test - backported create_or_update_social_login_key from v13
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import frappe from frappe.integrations.doctype.social_login_key.social_login_key import BaseUrlNotSetError import unittest class TestSocialLoginKey(unittest.TestCase): def test_adding_frappe_social_login_provider(self): provider_name = "Frappe" social_login_key = make_social_login_key( social_login_provider=provider_name ) social_login_key.get_social_login_provider(provider_name, initialize=True) self.assertRaises(BaseUrlNotSetError, social_login_key.insert) def make_social_login_key(**kwargs): kwargs["doctype"] = "Social Login Key" if not "provider_name" in kwargs: kwargs["provider_name"] = "Test OAuth2 Provider" doc = frappe.get_doc(kwargs) return doc def create_or_update_social_login_key(): # used in other tests (connected app, oauth20) try: social_login_key = frappe.get_doc("Social Login Key", "frappe") except frappe.DoesNotExistError: social_login_key = frappe.new_doc("Social Login Key") social_login_key.get_social_login_provider("Frappe", initialize=True) social_login_key.base_url = frappe.utils.get_url() social_login_key.enable_social_login = 0 social_login_key.save() frappe.db.commit() return social_login_key
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import frappe from frappe.integrations.doctype.social_login_key.social_login_key import BaseUrlNotSetError import unittest class TestSocialLoginKey(unittest.TestCase): def test_adding_frappe_social_login_provider(self): provider_name = "Frappe" social_login_key = make_social_login_key( social_login_provider=provider_name ) social_login_key.get_social_login_provider(provider_name, initialize=True) self.assertRaises(BaseUrlNotSetError, social_login_key.insert) def make_social_login_key(**kwargs): kwargs["doctype"] = "Social Login Key" if not "provider_name" in kwargs: kwargs["provider_name"] = "Test OAuth2 Provider" doc = frappe.get_doc(kwargs) return doc
Remove unused code left from JBMP -> Flowable migration
/* * Copyright © 2015-2018 Santer Reply S.p.A. * * 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 it.reply.orchestrator; import java.util.TimeZone; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; @SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class) public class Application { public static void main(String[] args) { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); SpringApplication.run(Application.class, args); } }
/* * Copyright © 2015-2018 Santer Reply S.p.A. * * 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 it.reply.orchestrator; import bitronix.tm.jndi.BitronixInitialContextFactory; import java.util.TimeZone; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; @SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class) public class Application { public static final Class<Application> applicationClass = Application.class; static { // JBPM needs a JNDI context from which retrieve the UT and TSR System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, BitronixInitialContextFactory.class.getName()); } public static void main(String[] args) { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); SpringApplication.run(applicationClass, args); } }
Rename variable for more appropriate name
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $donationBox = (function () { $.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) { $.colorbox({ width: '100%', width: '200px', height: '155px', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); $donationBox();
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $validationBox = (function () { $.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) { $.colorbox({ width: '100%', width: '200px', height: '155px', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); $validationBox();
Set the correct Grunt working directory. Since `documentsPaths`, `filesPaths`, and `layoutsPaths` are all relative to `srcPath`, the working directory needs to be set before performing the file expansion.
/* * grunt-docs * https://github.com/shama/grunt-docs * * Copyright (c) 2013 Kyle Robinson Young * Licensed under the MIT license. */ module.exports = function(grunt) { 'use strict'; var docpad = require('docpad'); grunt.registerTask('docs', 'Compile with DocPad', function() { var done = this.async(); var config = grunt.config(this.name || 'docs'); var srcPath = config.srcPath || 'src'; // To allow paths config to use patterns Object.keys(config).forEach(function(key) { if (key.slice(-5) === 'Paths') { var options = {}; switch (key) { case 'documentsPaths': case 'filesPaths': case 'layoutsPaths': options.cwd = srcPath; break; } config[key] = grunt.file.expand(options, config[key]); } }); docpad.createInstance(config, function(err, inst) { inst.action('generate', function(err) { if (err) { return grunt.warn(err); } done(); }); }); }); };
/* * grunt-docs * https://github.com/shama/grunt-docs * * Copyright (c) 2013 Kyle Robinson Young * Licensed under the MIT license. */ module.exports = function(grunt) { 'use strict'; var docpad = require('docpad'); grunt.registerTask('docs', 'Compile with DocPad', function() { var done = this.async(); var config = grunt.config(this.name || 'docs'); // To allow paths config to use patterns Object.keys(config).forEach(function(key) { if (key.slice(-5) === 'Paths') { config[key] = grunt.file.expand(config[key]); } }); docpad.createInstance(config, function(err, inst) { inst.action('generate', function(err) { if (err) { return grunt.warn(err); } done(); }); }); }); };
Allow null reserved_by value for broken post records
<?php namespace App\Models; use ActiveRecord\DateTime; /** * @property int $id * @property int $post_id * @property int $reserved_by * @property int $response_code * @property string $failing_url * @property DateTime $created_at * @property DateTime $updated_at * @property Post $post (Via magic method) */ class BrokenPost extends NSModel { public static $belongs_to = [ ['post'] ]; public static function record(int $post_id, int $response_code, string $failing_url, ?string $reserved_by) { self::create([ 'post_id' => $post_id, 'response_code' => $response_code, 'failing_url' => $failing_url, 'reserved_by' => $reserved_by, ]); } }
<?php namespace App\Models; use ActiveRecord\DateTime; /** * @property int $id * @property int $post_id * @property int $reserved_by * @property int $response_code * @property string $failing_url * @property DateTime $created_at * @property DateTime $updated_at * @property Post $post (Via magic method) */ class BrokenPost extends NSModel { public static $belongs_to = [ ['post'] ]; public static function record(int $post_id, int $response_code, string $failing_url, string $reserved_by) { self::create([ 'post_id' => $post_id, 'response_code' => $response_code, 'failing_url' => $failing_url, 'reserved_by' => $reserved_by, ]); } }
Fix a bug where the search dropdown wouldn't toggle When clicking on the magnifying glass again, the dropdown wouldn't hide.
((function (App) { 'use strict'; App.View.HeaderView = Backbone.View.extend({ events: { 'click .js-mobile-menu': 'toggleDrawer', 'click .js-search-button': 'onClickSearchButton', }, initialize: function () { this.drawer = this.el.querySelector('.js-mobile-drawer'); this.searchContainer = this.el.querySelector('.js-search'); this.el.classList.add('initialized'); this._setListeners(); }, /** * Set the listeners not attached to any DOM element of this.el */ _setListeners: function () { document.body.addEventListener('click', function (e) { if ($(e.target).closest(this.searchContainer).length) return; this.toggleSearch(false); }.bind(this)); }, onClickSearchButton: function () { this.toggleSearch(); }, toggleDrawer: function () { var opened = this.drawer.classList.toggle('-opened'); var overflow = 'auto'; if (opened) overflow = 'hidden'; document.querySelector('body').style.overflow = overflow; }, /** * Toggle the visibility of the search container * @param {boolean} [show] Force the search to expand or contract */ toggleSearch: function(show) { this.searchContainer.classList.toggle('-expanded', show); } }); })(this.App));
((function (App) { 'use strict'; App.View.HeaderView = Backbone.View.extend({ events: { 'click .js-mobile-menu': 'toggleDrawer', 'click .js-search-button': 'toggleSearch', }, initialize: function () { this.drawer = this.el.querySelector('.js-mobile-drawer'); this.searchContainer = this.el.querySelector('.js-search'); this.el.classList.add('initialized'); this._setListeners(); }, /** * Set the listeners not attached to any DOM element of this.el */ _setListeners: function () { document.body.addEventListener('click', function (e) { if ($(e.target).closest(this.searchContainer).length) return; this.toggleSearch(false); }.bind(this)); }, toggleDrawer: function () { var opened = this.drawer.classList.toggle('-opened'); var overflow = 'auto'; if (opened) overflow = 'hidden'; document.querySelector('body').style.overflow = overflow; }, /** * Toggle the visibility of the search container * @param {boolean} [show] Force the search to expand or contract */ toggleSearch: function(show) { this.searchContainer.classList.toggle('-expanded', show); } }); })(this.App));
Support cleaning of installedChunks callbacks It requires this PR https://github.com/webpack/webpack/pull/1380 to be approved. Or using custom webpack build with that PR. Otherwise, stuck callback may cause memory leaks.
patch(); function patch() { var ensure = __webpack_require__.e; var head = document.querySelector('head'); __webpack_require__.e = function(chunkId, callback) { var loaded = false; var handler = function(error) { if (loaded) return; loaded = true; callback(error); }; ensure(chunkId, function() { handler(); }); onError(function() { if (__webpack_require__.s) { __webpack_require__.s[chunkId] = void 0; } handler(true); }); }; function onError(callback) { var script = head.lastChild; if (script.tagName !== 'SCRIPT') { // throw new Error('Script is not a script'); console.warn('Script is not a script', script); return; } script.onload = script.onerror = function() { script.onload = script.onerror = null; callback(); }; }; };
patch(); function patch() { var ensure = __webpack_require__.e; var head = document.querySelector('head'); __webpack_require__.e = function(chunkId, callback) { var loaded = false; var handler = function(error) { if (loaded) return; loaded = true; callback(error); }; ensure(chunkId, function() { handler(); }); onError(function() { handler(true); }); }; function onError(callback) { var script = head.lastChild; if (script.tagName !== 'SCRIPT') { // throw new Error('Script is not a script'); console.warn('Script is not a script', script); return; } script.onload = script.onerror = function() { script.onload = script.onerror = null; callback(); }; }; };
Rename package to fmi_weather, as 'fmi' is already taken.
#!/usr/bin/env python from distutils.core import setup setup( name='fmi_weather', version='0.50', description='FMI weather data fetcher', author='Kimmo Huoman', author_email='kipenroskaposti@gmail.com', url='https://github.com/kipe/fmi', packages=['fmi', 'fmi.symbols'], package_data={ 'fmi.symbols': [ '*.svg', 'fmi/symbols/*', ], }, install_requires=[ 'beautifulsoup4>=4.4.0', 'python-dateutil>=2.4.2', 'requests>=2.20.0', ])
#!/usr/bin/env python from distutils.core import setup setup( name='fmi', version='0.50', description='FMI weather data fetcher', author='Kimmo Huoman', author_email='kipenroskaposti@gmail.com', url='https://github.com/kipe/fmi', packages=['fmi', 'fmi.symbols'], package_data={ 'fmi.symbols': [ '*.svg', 'fmi/symbols/*', ], }, install_requires=[ 'beautifulsoup4>=4.4.0', 'python-dateutil>=2.4.2', 'requests>=2.20.0', ])
Add support for X-Real-IP Header
/** * Author: petar bojinov - @pbojinov * Date: 9/29/13 */ /** * @method getClientIp * * Get client IP address * * Will return 127.0.0.1 when testing locally * Useful when you need the user ip for geolocation or serving localized content * * @param req * @returns {string} ip */ function getClientIp(req) { var ipAddress; // Amazon EC2 / Heroku workaround to get real client IP var forwardedIpsStr = req.header('X-Forwarded-For'), clientIp = req.header('X-Real-IP') || req.header('X-Client-IP'); if (clientIp) { ipAddress = clientIp; } else if (forwardedIpsStr) { // 'x-forwarded-for' header may return multiple IP addresses in // the format: "client IP, proxy 1 IP, proxy 2 IP" so take the // the first one var forwardedIps = forwardedIpsStr.split(','); ipAddress = forwardedIps[0]; } if (!ipAddress) { // Ensure getting client IP address still works in // development environment ipAddress = req.connection.remoteAddress; } return ipAddress; } /** * Expose mode public functions */ exports.getClientIp = getClientIp;
/** * Author: petar bojinov - @pbojinov * Date: 9/29/13 */ /** * @method getClientIp * * Get client IP address * * Will return 127.0.0.1 when testing locally * Useful when you need the user ip for geolocation or serving localized content * * @param req * @returns {string} ip */ function getClientIp(req) { var ipAddress; // Amazon EC2 / Heroku workaround to get real client IP var forwardedIpsStr = req.header('X-Forwarded-For'), clientIp = req.header('X-Client-IP'); if (clientIp) { ipAddress = clientIp; } else if (forwardedIpsStr) { // 'x-forwarded-for' header may return multiple IP addresses in // the format: "client IP, proxy 1 IP, proxy 2 IP" so take the // the first one var forwardedIps = forwardedIpsStr.split(','); ipAddress = forwardedIps[0]; } if (!ipAddress) { // Ensure getting client IP address still works in // development environment ipAddress = req.connection.remoteAddress; } return ipAddress; } /** * Expose mode public functions */ exports.getClientIp = getClientIp;
Call composer from the webroot composer.json has been moved from /concrete/composer.json to /composer.json
module.exports = function(grunt, config, parameters, done) { var workFolder = parameters.releaseWorkFolder || './release/source'; function endForError(error) { process.stderr.write(error.message || error); done(false); } try { var path = require('path'), exec = require('child_process').exec, fs = require('fs'); process.stdout.write('Installng PHP dependencies with Composer... '); exec( 'composer install --prefer-dist --no-dev', { cwd: workFolder }, function(error, stdout, stderr) { if(error) { endForError(stderr || error); return; } process.stdout.write('done.\n'); done(); } ); } catch(e) { endForError(e); return; } };
module.exports = function(grunt, config, parameters, done) { var workFolder = parameters.releaseWorkFolder || './release/source'; function endForError(error) { process.stderr.write(error.message || error); done(false); } try { var path = require('path'), exec = require('child_process').exec, fs = require('fs'); process.stdout.write('Installng PHP dependencies with Composer... '); exec( 'composer install --prefer-dist --no-dev', { cwd: path.join(workFolder, 'concrete') }, function(error, stdout, stderr) { if(error) { endForError(stderr || error); return; } process.stdout.write('done.\n'); done(); } ); } catch(e) { endForError(e); return; } };
Switch back to legacy decorators For https://github.com/matrix-org/matrix-react-sdk/pull/3961
module.exports = { "sourceMaps": true, "presets": [ ["@babel/preset-env", { "targets": [ "last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions" ], }], "@babel/preset-typescript", "@babel/preset-flow", "@babel/preset-react" ], "plugins": [ ["@babel/plugin-proposal-decorators", {legacy: true}], "@babel/plugin-proposal-export-default-from", "@babel/plugin-proposal-numeric-separator", "@babel/plugin-proposal-class-properties", "@babel/plugin-proposal-object-rest-spread", "@babel/plugin-transform-flow-comments", "@babel/plugin-syntax-dynamic-import", "@babel/plugin-transform-runtime" ] };
module.exports = { "sourceMaps": true, "presets": [ ["@babel/preset-env", { "targets": [ "last 2 Chrome versions", "last 2 Firefox versions", "last 2 Safari versions" ], }], "@babel/preset-typescript", "@babel/preset-flow", "@babel/preset-react" ], "plugins": [ ["@babel/plugin-proposal-decorators", {decoratorsBeforeExport: true}], "@babel/plugin-proposal-export-default-from", "@babel/plugin-proposal-numeric-separator", "@babel/plugin-proposal-class-properties", "@babel/plugin-proposal-object-rest-spread", "@babel/plugin-transform-flow-comments", "@babel/plugin-syntax-dynamic-import", "@babel/plugin-transform-runtime" ] };
Update dsub version to 0.3.8.dev0 PiperOrigin-RevId: 293000641
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.3.8.dev0'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.3.7'
Fix bug in python client
# lockd client import httplib import json class LockdClient(object): def __init__(self, host="127.0.0.1", port=2080): self._host_port = "%s:%s" % (host, port) def is_locked(self, name): return self._lockish("GET", name, 404) def lock(self, name): return self._lockish("POST", name, 409) def unlock(self, name): return self._lockish("DELETE", name, 404) def _lockish(self, method, name, false_code): # FIXME: does name need to escaped here? path = "/lock/%s" % name # conn = httplib.HTTPConnection(self._host_port) conn.request(method, path) response = conn.getresponse() status = response.status response.read() conn.close() # if status == 200: return True elif status == false_code: return False else: msg = "Unexpected response: %s %s" % (status, response.reason) raise Exception(msg)
# lockd client import httplib import json class LockdClient(object): def __init__(self, host="127.0.0.1", port=2080): self._host_port = "%s:%s" % (host, port) def is_locked(self, name): return self._lockish("GET", name, 404) def lock(self, name): return self._lockish("POST", name, 409) def unlock(self, name): return self._lockish("DELETE", name, 404) def _lockish(self, method, name, false_code): # FIXME: does name need to escaped here? path = "/lock/%s" % name # conn = httplib.HTTPConnection(self._host_port) conn.request(method, path) response = conn.getresponse() status = response.status response.read() conn.close() # if status == 200: return True elif status == false_code: return False else: msg = "Unexpected response: %s %s; data: %s" % (status, response.reason, data) raise Exception(msg)
Make it a regular sign
package se.soy.gpg; import java.util.List; import java.util.ArrayList; public class GPG { // FIXME Remove when done static<T> void println(T arg) { System.out.println(arg); } public static void main(String[] args) { println("main"); GPG.encrypt().armor().recipient("0xrecipient").output(); /* GPG.decrypt().armor().local-user("0xlocaluser").output("/tmp/a-file"); GPG.sign().armor().(); */ } private String mode; private boolean armor = false; private List<String> recipients = new ArrayList<String>(); public void output() { println("OPTIONS:"); println(String.format("mode: %s", mode)); println(String.format("armor?: %s", (armor) ? "true" : "false")); println(String.format("recipients?: %s", recipients)); } public static GPG encrypt() { GPG gpg = new GPG(); gpg.mode = "encrypt"; return gpg; } GPG gpg = new GPG(); gpg.mode = "clearsign"; public static GPG sign() { return gpg; } public GPG armor() { this.armor = true; return this; } // TODO: Add recipients(List<String> recipients) public GPG recipient(String recipient) { this.recipients.add(recipient); return this; } }
package se.soy.gpg; import java.util.List; import java.util.ArrayList; public class GPG { // FIXME Remove when done static<T> void println(T arg) { System.out.println(arg); } public static void main(String[] args) { println("main"); GPG.encrypt().armor().recipient("0xrecipient").output(); /* GPG.decrypt().armor().local-user("0xlocaluser").output("/tmp/a-file"); GPG.sign().armor().(); */ } private String mode; private boolean armor = false; private List<String> recipients = new ArrayList<String>(); public void output() { println("OPTIONS:"); println(String.format("mode: %s", mode)); println(String.format("armor?: %s", (armor) ? "true" : "false")); println(String.format("recipients?: %s", recipients)); } public static GPG encrypt() { GPG gpg = new GPG(); gpg.mode = "encrypt"; return gpg; } public static GPG clearsign() { GPG gpg = new GPG(); gpg.mode = "clearsign"; return gpg; } public GPG armor() { this.armor = true; return this; } // TODO: Add recipients(List<String> recipients) public GPG recipient(String recipient) { this.recipients.add(recipient); return this; } }
Remove deprecated and broken pros help option
import click import proscli from proscli.utils import default_options def main(): # the program name should always be pros. don't care if it's not... try: cli.main(prog_name='pros') except KeyboardInterrupt: click.echo('Aborted!') pass @click.command('pros', cls=click.CommandCollection, context_settings=dict(help_option_names=['-h', '--help']), sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli]) @click.version_option(version='2.1.925', prog_name='pros') @default_options def cli(): pass if __name__ == '__main__': main()
import click import proscli from proscli.utils import default_options def main(): # the program name should always be pros. don't care if it's not... try: cli.main(prog_name='pros') except KeyboardInterrupt: click.echo('Aborted!') pass import prosconductor.providers.utils @proscli.flasher_cli.command('help', short_help='Show this message and exit.') @click.argument('ignore', nargs=-1, expose_value=False) @default_options @click.pass_context def help_cmd(ctx): click.echo(prosconductor.providers.utils.get_all_available_templates()) @click.command('pros', cls=click.CommandCollection, context_settings=dict(help_option_names=['-h', '--help']), sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli]) @click.version_option(version='2.1.923', prog_name='pros') @default_options def cli(): pass if __name__ == '__main__': main()
Expand check for empty strings
$(document).ready(function () { $('textarea').focus(); $('form').on('submit', function (event) { event.preventDefault(); var text = $('textarea').val(); var y = 0; if (text.replace(/^\s+|\s+$/g, '') == '') { text = 'You should probably enter some text next time.' } $('header a').addClass('dark'); $('body').css('background-color', '#090919'); $('#container').html('<div id="teleprompt_screen">' + text + '</div>') scrollText(y); function scrollText(y) { setTimeout(function () { var newY = y; var height = $('#teleprompt_screen').height(); if (newY > -1 * height - 150) { newY -= 1; $('#teleprompt_screen').css('top', newY); scrollText(newY); } }, 30); }; }); // get the height of the screen // move the text up the screen by changing the top CSS });
$(document).ready(function () { $('textarea').focus(); $('form').on('submit', function (event) { event.preventDefault(); var text = $('textarea').val(); var y = 0; if (text == '') { text = 'You should probably enter some text next time.' } $('header a').addClass('dark'); $('body').css('background-color', '#090919'); $('#container').html('<div id="teleprompt_screen">' + text + '</div>') scrollText(y); function scrollText(y) { setTimeout(function () { var newY = y; var height = $('#teleprompt_screen').height(); if (newY > -1 * height - 150) { newY -= 1; $('#teleprompt_screen').css('top', newY); scrollText(newY); } }, 30); }; }); // get the height of the screen // move the text up the screen by changing the top CSS });
Change to new search api
define('routes_api', [], function() { // List API routes here. // E.g.: // { // "route": "/foo/bar/{0}", // "another_route": "/foo/bar/{0}/asdf" // } return { 'fxa-login': '/api/v2/account/fxa-login/', 'login': '/api/v2/account/login/', 'logout': '/api/v2/account/logout/', 'search': '/api/v1/apps/search/non-public/?cache=1&vary=0', 'site-config': '/api/v2/services/config/site/?serializer=commonplace', 'permissions': '/api/v2/account/operators/', 'feed-shelves': '/api/v2/feed/shelves/', 'feed-shelves-list': '/api/v2/transonic/feed/shelves/?limit=5', 'feed-shelf': '/api/v2/feed/shelves/{0}/', 'feed-shelf-publish': '/api/v2/feed/shelves/{0}/publish/', 'feed-shelf-mine': '/api/v2/account/shelves/', }; });
define('routes_api', [], function() { // List API routes here. // E.g.: // { // "route": "/foo/bar/{0}", // "another_route": "/foo/bar/{0}/asdf" // } return { 'fxa-login': '/api/v2/account/fxa-login/', 'login': '/api/v2/account/login/', 'logout': '/api/v2/account/logout/', 'search': '/api/v1/apps/search/suggest/non-public/?cache=1&vary=0', 'site-config': '/api/v2/services/config/site/?serializer=commonplace', 'permissions': '/api/v2/account/operators/', 'feed-shelves': '/api/v2/feed/shelves/', 'feed-shelves-list': '/api/v2/transonic/feed/shelves/?limit=5', 'feed-shelf': '/api/v2/feed/shelves/{0}/', 'feed-shelf-publish': '/api/v2/feed/shelves/{0}/publish/', 'feed-shelf-mine': '/api/v2/account/shelves/', }; });
Fix false-positive of a type-check
""" This module contains the high-level functions to access the library. Care is taken to make this as pythonic as possible and hide as many of the gory implementations as possible. """ from x690.types import ObjectIdentifier # !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP # Types and thus populates the Registry. If this is not included, Non x.690 # SNMP types will not be properly detected! import puresnmp.types from puresnmp.api.pythonic import PyWrapper from puresnmp.api.raw import Client from puresnmp.credentials import V1, V2C, V3 try: import importlib.metadata as importlib_metadata except ModuleNotFoundError: import importlib_metadata # type: ignore __version__ = importlib_metadata.version("puresnmp") # type: ignore __all__ = [ "Client", "ObjectIdentifier", "PyWrapper", "V1", "V2C", "V3", "__version__", ]
""" This module contains the high-level functions to access the library. Care is taken to make this as pythonic as possible and hide as many of the gory implementations as possible. """ from x690.types import ObjectIdentifier # !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP # Types and thus populates the Registry. If this is not included, Non x.690 # SNMP types will not be properly detected! import puresnmp.types from puresnmp.api.pythonic import PyWrapper from puresnmp.api.raw import Client from puresnmp.credentials import V1, V2C, V3 try: import importlib.metadata as importlib_metadata except ModuleNotFoundError: import importlib_metadata # type: ignore __version__ = importlib_metadata.version("puresnmp") __all__ = [ "Client", "ObjectIdentifier", "PyWrapper", "V1", "V2C", "V3", "__version__", ]
Fix lint errors in the `rx-ext` code
import { merge as mergeObs } from 'rxjs/observable' import { distinctUntilChanged, map as mapObs, debounceTime } from 'rxjs/operators' import { isEqual, isFunction } from '../util/minilo' import fromOlEvent from './from-ol-event' /** * Creates Observable from OpenLayers change:* event * @param {module:ol/Observable~Observable} target * @param {string|string[]} [prop] * @param {boolean|function(a, b):boolean|undefined} [distinct] Distinct values by isEqual fn or by custom comparator * @param {number|undefined} [debounce] Debounce values by passed amount of ms. * @param {function|undefined} [selector] Custom selector * @return {Observable<{prop: string, value: *}>} */ export default function fromOlChangeEvent (target, prop, distinct, debounce, selector) { if (Array.isArray(prop)) { return mergeObs(...prop.map(p => fromOlChangeEvent(target, p))) } selector = selector || ((target, prop) => target.get(prop)) const event = `change:${prop}` const observable = fromOlEvent(target, event, () => selector(target, prop)) const operations = [] if (debounce != null) { operations.push(debounceTime(debounce)) } if (distinct) { isFunction(distinct) || (distinct = isEqual) operations.push(distinctUntilChanged(distinct)) } operations.push(mapObs(value => ({ prop, value }))) return observable.pipe(...operations) }
import { merge as mergeObs } from 'rxjs/observable' import { distinctUntilChanged, map as mapObs, debounceTime } from 'rxjs/operators' import { isEqual, isFunction } from '../util/minilo' import fromOlEvent from './from-ol-event' /** * Creates Observable from OpenLayers change:* event * @param {module:ol/Observable~Observable} target * @param {string|string[]} [prop] * @param {boolean|function(a, b):boolean|undefined} [distinct] Distinct values by isEqual fn or by custom comparator * @param {number|undefined} [debounce] Debounce values by passed amount of ms. * @param {function|undefined} [selector] Custom selector * @return {Observable<{prop: string, value: *}>} */ export default function fromOlChangeEvent (target, prop, distinct, debounce, selector) { if (Array.isArray(prop)) { return mergeObs(...prop.map(p => fromOlChangeEvent(target, p))) } selector = selector || ((target, prop) => target.get(prop)) let event = `change:${prop}` let observable = fromOlEvent(target, event, () => selector(target, prop)) let operations = [] if (debounce != null) { operations.push(debounceTime(debounce)) } if (distinct) { isFunction(distinct) || (distinct = isEqual) operations.push(distinctUntilChanged(distinct)) } operations.push(mapObs(value => ({ prop, value }))) return observable.pipe(...operations) }
Fix caching issue in standalone
var config = { // For internal server or proxying webserver. url : { configuration : 'up/configuration', update : 'up/world/{world}/{timestamp}', sendmessage : 'up/sendmessage' }, // For proxying webserver through php. // url: { // configuration: 'up.php?path=configuration', // update: 'up.php?path=world/{world}/{timestamp}', // sendmessage: 'up.php?path=sendmessage' // }, // For proxying webserver through aspx. // url: { // configuration: 'up.aspx?path=configuration', // update: 'up.aspx?path=world/{world}/{timestamp}', // sendmessage: 'up.aspx?path=sendmessage' // }, // For standalone (jsonfile) webserver. // url: { // configuration: 'standalone/dynmap_config.json', // update: 'standalone/dynmap_{world}.json?_={timestamp}', // sendmessage: 'standalone/sendmessage.php' // }, tileUrl : 'tiles/', tileWidth : 128, tileHeight : 128 };
var config = { // For internal server or proxying webserver. url : { configuration : 'up/configuration', update : 'up/world/{world}/{timestamp}', sendmessage : 'up/sendmessage' }, // For proxying webserver through php. // url: { // configuration: 'up.php?path=configuration', // update: 'up.php?path=world/{world}/{timestamp}', // sendmessage: 'up.php?path=sendmessage' // }, // For proxying webserver through aspx. // url: { // configuration: 'up.aspx?path=configuration', // update: 'up.aspx?path=world/{world}/{timestamp}', // sendmessage: 'up.aspx?path=sendmessage' // }, // For standalone (jsonfile) webserver. // url: { // configuration: 'standalone/dynmap_config.json', // update: 'standalone/dynmap_{world}.json', // sendmessage: 'standalone/sendmessage.php' // }, tileUrl : 'tiles/', tileWidth : 128, tileHeight : 128 };
Connect to mongo here so we only do it once
"use strict"; var express = require('express'), pages = require('./routes/pages.js'), signup = require('./routes/signup.js'), flash = require('connect-flash'), auth = require('./modules/auth.js'), api = require('./modules/api.js'), mongoose = require('mongoose'); mongoose.connect(process.env.MONGODB_CONNECTION_STRING); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); var app = express(); // Configuration var secret = process.env.COOKIE_SECRET || 'secret'; app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.compress()); app.use(express.methodOverride()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser(secret)); app.use(express.session({ secret: secret, cookie: { httpOnly: true } })); app.use(auth); app.use(flash()); if (app.get('env') === 'development') { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); } else { app.use(express.errorHandler()); } // Routes app.get('/', pages.index); app.get('/contact', pages.contact); app.get('/login', pages.login); app.post('/signup', signup.sendToMailchimp); app.use(express.static(__dirname + '/dist')); // Go app.listen(process.env.port || 3000); console.log("Express server started");
var express = require('express'), pages = require('./routes/pages.js'), signup = require('./routes/signup.js'), flash = require('connect-flash'), auth = require('./modules/auth.js'); var app = express(); // Configuration var secret = process.env.COOKIE_SECRET || 'secret'; app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.compress()); app.use(express.methodOverride()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser(secret)); app.use(express.session({ secret: secret, cookie: { httpOnly: true } })); app.use(auth); app.use(flash()); if (app.get('env') === 'development') { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); } else { app.use(express.errorHandler()); } // Routes app.get('/', pages.index); app.get('/contact', pages.contact); app.get('/login', pages.login); app.post('/signup', signup.sendToMailchimp); app.use(express.static(__dirname + '/dist')); // Go app.listen(process.env.port || 3000); console.log("Express server started");
Support python 2 and 3 compatability
#!/bin/python try: import urllib.request as urlrequest except ImportError: import urllib as urlrequest import json class RESTfulApi: """ Generic REST API call """ def __init__(self): """ Constructor """ pass def request(self, url): """ Web request :param: url: The url link :return JSON object """ req = urlrequest.Request(url, None, headers={ "Content-Type": "application/x-www-form-urlencoded", "Accept": "*/*", "User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.0)"}) res = urlrequest.urlopen(req) res = json.loads(res.read().decode('utf8')) return res
#!/bin/python import urllib.request import json class RESTfulApi: """ Generic REST API call """ def __init__(self): """ Constructor """ pass def request(self, url): """ Web request :param: url: The url link :return JSON object """ req = urllib.request.Request(url, None, headers={ "Content-Type": "application/x-www-form-urlencoded", "Accept": "*/*", "User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.0)"}) res = urllib.request.urlopen(req) res = json.loads(res.read().decode('utf8')) return res
Convert new path to old pattern to reuse current data in GA
// Analytics for Vaadin Components (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-658457-6', 'auto'); function locationHashChanged() { if(/vaadin/.test(window.location.hostname)) { var pageViewUrl = (window.location.pathname + window.location.hash) .replace(/vaadin-components\/latest\/(.+)\/demo/, 'components-examples/$1') .replace('#', '/'); ga('send', 'pageview', pageViewUrl) } } window.onhashchange = locationHashChanged; locationHashChanged();
// Analytics for Vaadin Components (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-658457-6', 'auto'); function locationHashChanged() { if(/vaadin/.test(window.location.hostname)) { var pageViewUrl = (window.location.pathname + window.location.hash).replace('#', '/'); ga('send', 'pageview', pageViewUrl) } } window.onhashchange = locationHashChanged; locationHashChanged();
Rewrite RouteContext as a function constructor instead of a class
function RouteContext(routes, route) { let routeIndex = routes.indexOf(route) this.parentRoutes = routes.slice(0, routeIndex) } RouteContext.prototype.trigger = function() { let parentRoutes = this.parentRoutes for (let i = parentRoutes.length - 1; i >= 0; i--) { let channel = parentRoutes[i]._contextChannel if (channel) { channel.trigger.apply(channel, arguments) } } } RouteContext.prototype.request = function(name) { let parentRoutes = this.parentRoutes for (let i = parentRoutes.length - 1; i >= 0; i--) { let channel = parentRoutes[i]._contextChannel if (channel && channel._requests[name]) { return channel.request.apply(channel, arguments) } } } export default RouteContext
export default class RouteContext { constructor(routes, route) { let routeIndex = routes.indexOf(route) this.parentRoutes = routes.slice(0, routeIndex) } trigger() { let parentRoutes = this.parentRoutes for (let i = parentRoutes.length - 1; i >= 0; i--) { let channel = parentRoutes[i]._contextChannel if (channel) { channel.trigger.apply(channel, arguments) } } } request(name) { let parentRoutes = this.parentRoutes for (let i = parentRoutes.length - 1; i >= 0; i--) { let channel = parentRoutes[i]._contextChannel if (channel && channel._requests[name]) { return channel.request.apply(channel, arguments) } } } }
Handle installs not using new settings engine
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] try: if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] except AttributeError: pass
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ]
Switch the default for --experimental_multi_threaded_digest It looks like this is fairly widely used now, and we recommend users who are still on spinning platters to upgrade their workstation. :-P Progress on #6345. PiperOrigin-RevId: 262317072
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.ssd; import com.google.devtools.common.options.Option; import com.google.devtools.common.options.OptionDocumentationCategory; import com.google.devtools.common.options.OptionEffectTag; import com.google.devtools.common.options.OptionsBase; /** * Options that tune Bazel's performance in order to increase performance on workstations with an * SSD. */ public class SsdOptions extends OptionsBase { @Option( name = "experimental_multi_threaded_digest", defaultValue = "true", documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, effectTags = {OptionEffectTag.UNKNOWN}, help = "Whether to always compute MD5 digests of files with multiple threads. Setting this to " + "false may improve performance when using a spinning platter.") public boolean experimentalMultiThreadedDigest; }
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.ssd; import com.google.devtools.common.options.Option; import com.google.devtools.common.options.OptionDocumentationCategory; import com.google.devtools.common.options.OptionEffectTag; import com.google.devtools.common.options.OptionsBase; /** * Options that tune Bazel's performance in order to increase performance on workstations with an * SSD. */ public class SsdOptions extends OptionsBase { @Option( name = "experimental_multi_threaded_digest", defaultValue = "false", documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, effectTags = {OptionEffectTag.UNKNOWN}, help = "Whether to always compute MD5 digests of files with multiple threads. Might improve " + "performance when using an SSD." ) public boolean experimentalMultiThreadedDigest; }
Update the equality test for database files
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright (c) 2015--, micronota development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from tempfile import mktemp from unittest import TestCase, main from os.path import dirname from sqlite3 import connect from micronota.bfillings.util import _get_data_dir from micronota.db.tigrfam import prepare_metadata class TigrfamTests(TestCase): def setUp(self): self.obs_db_fp = mktemp() self.exp_db_fp = _get_data_dir()('tigrfam.db') self.d = dirname(self.exp_db_fp) def test_prepare_metadata(self): prepare_metadata(self.d, self.obs_db_fp) with connect(self.obs_db_fp) as o, connect(self.exp_db_fp) as e: co = o.cursor() co.execute('SELECT * from tigrfam') ce = e.cursor() ce.execute('SELECT * from tigrfam') self.assertCountEqual(co.fetchall(), ce.fetchall()) if __name__ == '__main__': main()
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright (c) 2015--, micronota development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from tempfile import mktemp from unittest import TestCase, main from os.path import dirname from micronota.bfillings.util import _get_data_dir from micronota.db.tigrfam import prepare_metadata class TigrfamTests(TestCase): def setUp(self): self.obs_db_fp = mktemp() self.exp_db_fp = _get_data_dir()('tigrfam.db') self.d = dirname(self.exp_db_fp) def test_prepare_metadata(self): prepare_metadata(self.d, self.obs_db_fp) with open(self.obs_db_fp, 'rb') as o, open(self.exp_db_fp, 'rb') as e: self.assertEqual(o.read(), e.read()) if __name__ == '__main__': main()
Use HTTPS rather than SSH to clone Particle firmware repository.
var path = require("path"); var outputDirectory = path.resolve("./output"); var libsDirectory = path.resolve("./libs"); var tempDirectory = path.resolve("./build_temp"); module.exports = { particle: { platform: "photon", // See https://github.com/spark/firmware/blob/develop/docs/build.md#platform-nameids targetName: "weather-thingy-particle", // See https://github.com/spark/firmware/blob/develop/docs/build.md#compiling-an-application-outside-the-firmware-source firmwareDirectory: path.resolve(libsDirectory + "/particle/firmware"), firmwareRepository: "https://github.com/spark/firmware.git", firmwareVersion: "v0.4.7" }, build: { sources: { application: path.resolve("./src"), tests: path.resolve("./tests") }, output: { baseDirectory: outputDirectory, firmware: outputDirectory + "/firmware", tests: outputDirectory + "/tests" }, temp: { baseDirectory: tempDirectory, testBuildFiles: tempDirectory + "/tests/build" } }, lint: { cpp: { cppcheckOptions: "--enable=all --inline-suppr" // --check-config is quite handy for making sure that everything is configured correctly but is very noisy } } };
var path = require("path"); var outputDirectory = path.resolve("./output"); var libsDirectory = path.resolve("./libs"); var tempDirectory = path.resolve("./build_temp"); module.exports = { particle: { platform: "photon", // See https://github.com/spark/firmware/blob/develop/docs/build.md#platform-nameids targetName: "weather-thingy-particle", // See https://github.com/spark/firmware/blob/develop/docs/build.md#compiling-an-application-outside-the-firmware-source firmwareDirectory: path.resolve(libsDirectory + "/particle/firmware"), firmwareRepository: "git@github.com:spark/firmware.git", firmwareVersion: "v0.4.7" }, build: { sources: { application: path.resolve("./src"), tests: path.resolve("./tests") }, output: { baseDirectory: outputDirectory, firmware: outputDirectory + "/firmware", tests: outputDirectory + "/tests" }, temp: { baseDirectory: tempDirectory, testBuildFiles: tempDirectory + "/tests/build" } }, lint: { cpp: { cppcheckOptions: "--enable=all --inline-suppr" // --check-config is quite handy for making sure that everything is configured correctly but is very noisy } } };
Return failure on pop() from an empty queue
# Topic server import time import flask app = flask.Flask(__name__) data = [] sessions = {} # session ID -> current index # FIXME No cleanup! @app.route("/simple/newsession") def new_session(): session_id = "session" + hex(int(time.time() * 1000))[2:] sessions[session_id] = 0 return session_id @app.route("/simple/push/<session_id>/<value>") def push(session_id, value): assert session_id in sessions # Or crash, aka return error data.append(value) return str(len(data) - 1) @app.route("/simple/pop/<session_id>") def pop(session_id): assert session_id in sessions # Or crash, aka return error res = data[sessions[session_id]] # Or crash, aka return error sessions[session_id] += 1 return res if __name__ == "__main__": app.run(host="127.0.0.1", port=8080)
# Topic server import time import flask app = flask.Flask(__name__) data = [] sessions = {} # session ID -> current index # FIXME No cleanup! @app.route("/simple/newsession") def new_session(): session_id = "session" + hex(int(time.time() * 1000))[2:] sessions[session_id] = 0 return session_id @app.route("/simple/push/<session_id>/<value>") def push(session_id, value): assert session_id in sessions data.append(value) return str(len(data) - 1) @app.route("/simple/pop/<session_id>") def pop(session_id): assert session_id in sessions if sessions[session_id] >= len(data): return "" res = data[sessions[session_id]] sessions[session_id] += 1 return res if __name__ == "__main__": app.run(host="127.0.0.1", port=8080)
Fix issue with Redirect not rendering history page
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Redirect, Route, withRouter } from 'react-router'; class PrivateRoute extends Component { render() { const { component, isAuthenticated, ...rest } = this.props; return ( <Route { ...rest } render={ props => ( isAuthenticated ? ( React.createElement(component, props) ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location }, }} /> ) )} /> ) } } export default withRouter(connect( function mapStateToProps({ root }) { const { isAuthenticated } = root; return { isAuthenticated }; }, {} )(PrivateRoute));
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Redirect, Route } from 'react-router'; class PrivateRoute extends Component { render() { const { component, isAuthenticated, ...rest } = this.props; return ( <Route { ...rest } render={ props => ( isAuthenticated ? ( React.createElement(component, props) ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location }, }} /> ) )} /> ) } } export default connect( function mapStateToProps({ root }) { const { isAuthenticated } = root; return { isAuthenticated }; }, {} )(PrivateRoute);
Use variadic args in main method
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.html5; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import java.util.Arrays; @SpringBootApplication public class SpringBootAngularHTML5Application { public static void main(final String ...args) { final ApplicationContext ctx = SpringApplication.run(SpringBootAngularHTML5Application.class, args); final String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); Arrays.stream(beanNames).forEach(System.out::println); } }
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.html5; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import java.util.Arrays; @SpringBootApplication public class SpringBootAngularHTML5Application { public static void main(final String[] args) { final ApplicationContext ctx = SpringApplication.run(SpringBootAngularHTML5Application.class, args); final String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); Arrays.stream(beanNames).forEach(System.out::println); } }
Make it clear that the E-Mail address is optional.
from wtforms import Form, SubmitField, BooleanField, TextField, SelectField, \ PasswordField, IntegerField, FieldList, FormField, validators class LoginForm(Form): username = TextField('Username', [validators.Required()]) password = PasswordField('Password', [validators.Required()]) remember = BooleanField('Remember me') def login_form(rform): return LoginForm(rform) class RegisterForm(Form): username = TextField('Username', [validators.Required()]) password = PasswordField('Password', [validators.Required(), validators.Length(min=5, message='Password too short.'), validators.EqualTo('password_retype', message='Passwords must match.')]) password_retype = PasswordField('Password (verification)', [validators.Required()]) email = TextField('E-Mail (optional)', [validators.Optional(), validators.Email()]) def register_form(rform): return RegisterForm(rform)
from wtforms import Form, SubmitField, BooleanField, TextField, SelectField, \ PasswordField, IntegerField, FieldList, FormField, validators class LoginForm(Form): username = TextField('Username', [validators.Required()]) password = PasswordField('Password', [validators.Required()]) remember = BooleanField('Remember me') def login_form(rform): return LoginForm(rform) class RegisterForm(Form): username = TextField('Username', [validators.Required()]) password = PasswordField('Password', [validators.Required(), validators.Length(min=5, message='Password too short.'), validators.EqualTo('password_retype', message='Passwords must match.')]) password_retype = PasswordField('Password (verification)', [validators.Required()]) email = TextField('E-Mail', [validators.Optional(), validators.Email()]) def register_form(rform): return RegisterForm(rform)
Modify pypi description to use README.md
from setuptools import setup from os import path # read the contents of your README file this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="simple_slack_bot", packages=["simple_slack_bot"], # this must be the same as the name above version="1.3.3", description="Simple Slack Bot makes writing your next Slack bot incredibly easy", long_description=long_description, long_description_content_type="text/markdown", author="Greg Hilston", author_email="Gregory.Hilston@gmail.com", url="https://github.com/GregHilston/Simple-Slack-Bot", # use the URL to the github repo download_url="https://github.com/GregHilston/Simple-Slack-Bot/tarball/v1.1.0", keywords=["slack", "bot", "chat", "simple"], # arbitrary keywords classifiers=[], install_requires=[ "slacker==0.9.42", "slacksocket>=0.7,!=0.8,<=0.9", "pyyaml", "websocket-client==0.48", # required to define as our dependency has a dependency which broke backwards compatibility ], )
from setuptools import setup setup( name="simple_slack_bot", packages=["simple_slack_bot"], # this must be the same as the name above version="1.3.2", description="Simple Slack Bot makes writing your next Slack bot incredibly easy", long_description="Simple Slack Bot makes writing your next Slack bot incredibly easy. By factoring out common functionality all Slack Bots require, you can focus on writing your business logic by simply registering for Slack Events defined by the Slack API", author="Greg Hilston", author_email="Gregory.Hilston@gmail.com", url="https://github.com/GregHilston/Simple-Slack-Bot", # use the URL to the github repo download_url="https://github.com/GregHilston/Simple-Slack-Bot/tarball/v1.1.0", keywords=["slack", "bot", "chat", "simple"], # arbitrary keywords classifiers=[], install_requires=[ "slacker==0.9.42", "slacksocket>=0.7,!=0.8,<=0.9", "pyyaml", "websocket-client==0.48", # required to define as our dependency has a dependency which broke backwards compatibility ], )
Fix required parameter for Modal popup
'use strict' import React from 'react' import { View, TouchableHighlight, Image, Text, Modal } from 'react-native'; var css = require('../../styles/css'); // Modal with text information content and a large button (usually for dismissing the modal) export default class InfoModal extends React.Component { _onPress = () => { if (this.props.onPress) { this.props.onPress(); //callback when modal is pressed } } render() { return( <Modal animationType={'none'} transparent={true} visible={this.props.modalVisible} onRequestClose={() => {this.props.onRequestClose}}> <View style={css.modal_container}> <Text style={css.modal_text_intro}>{this.props.title}</Text> <Text style={css.modal_text}> {this.props.children} </Text> <TouchableHighlight underlayColor={'rgba(200,200,200,.5)'} onPress={this._onPress}> <View style={css.modal_button}> <Text style={css.modal_button_text}>{this.props.buttonText}</Text> </View> </TouchableHighlight> </View> </Modal> ); } }
'use strict' import React from 'react' import { View, TouchableHighlight, Image, Text, Modal } from 'react-native'; var css = require('../../styles/css'); // Modal with text information content and a large button (usually for dismissing the modal) export default class InfoModal extends React.Component { _onPress = () => { if (this.props.onPress) { this.props.onPress(); //callback when modal is pressed } } render() { return( <Modal animationType={'none'} transparent={true} visible={this.props.modalVisible}> <View style={css.modal_container}> <Text style={css.modal_text_intro}>{this.props.title}</Text> <Text style={css.modal_text}> {this.props.children} </Text> <TouchableHighlight underlayColor={'rgba(200,200,200,.5)'} onPress={this._onPress}> <View style={css.modal_button}> <Text style={css.modal_button_text}>{this.props.buttonText}</Text> </View> </TouchableHighlight> </View> </Modal> ); } }
Fix the audience for the extension hook
import path from 'path'; import jwt from 'jsonwebtoken'; import config from '../config'; import logger from '../logger'; module.exports = (hookPath) => (req, res, next) => { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { const token = req.headers.authorization.split(' ')[1]; logger.debug('Extension Hook validation token:', token); const isValid = jwt.verify(token, config('EXTENSION_SECRET'), { audience: `${config('WT_URL')}${hookPath}`, issuer: `https://${config('AUTH0_DOMAIN')}` }); if (!isValid) { logger.error('Invalid hook token:', token); return res.sendStatus(401); } return next(); } logger.error('Hook token is missing.'); return res.sendStatus(401); };
import path from 'path'; import jwt from 'jsonwebtoken'; import config from '../config'; import logger from '../logger'; module.exports = (hookPath) => (req, res, next) => { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { const token = req.headers.authorization.split(' ')[1]; logger.debug('Extension Hook validation token:', token); const isValid = jwt.verify(token, config('EXTENSION_SECRET'), { audience: path.join(config('WT_URL'), hookPath), issuer: `https://${config('AUTH0_DOMAIN')}` }); if (!isValid) { logger.error('Invalid hook token:', token); return res.sendStatus(401); } return next(); } logger.error('Hook token is missing.'); return res.sendStatus(401); };
Add Config.get() to skip KeyErrors Adds common `dict.get()` pattern to our own Config class, to enable use of fallbacks or `None`, as appropriate.
#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] def get(self, attrname, fallback=None): try: return self.config[attrname] except KeyError: return fallback # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
#! /usr/bin/env python import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
Remove the data attribute when commiting too.
$(function() { $("td").dblclick(function() { var td = $(this), originalContent = td.text(); td.addClass("cellEditing"); td.data("originalContent", originalContent); var el = document.createElement("input"), $el = $(el); $el.attr({type: "text", value: originalContent}); td.empty(); td.append(el); $el.focus(); $el.keypress(function(e) { if (e.which == 13) { var text = $(this), newContent = text.val(), td = text.parent(); td.text(newContent); td.removeData("originalContent"); td.removeClass("cellEditing"); } }); $el.blur(function() { var td = $(this).parent(); td.text(td.data("originalContent")); td.removeData("originalContent"); td.removeClass("cellEditing"); }); }); });
$(function() { $("td").dblclick(function() { var td = $(this), originalContent = td.text(); td.addClass("cellEditing"); td.data("originalContent", originalContent); var el = document.createElement("input"), $el = $(el); $el.attr({type: "text", value: originalContent}); td.empty(); td.append(el); $el.focus(); $el.keypress(function(e) { if (e.which == 13) { var text = $(this), newContent = text.val(), td = text.parent(); td.text(newContent); td.removeClass("cellEditing"); } }); $el.blur(function() { var td = $(this).parent(); td.text(td.data("originalContent")); td.removeData("originalContent"); td.removeClass("cellEditing"); }); }); });
Add runnable method to convert a callable into a runnable.
/* * Copyright 2007 Russell Harmon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.eatnumber1.util.concurrent; import java.util.concurrent.Callable; import org.jetbrains.annotations.NotNull; /** * @author Russell Harmon * @since Jul 13, 2007 */ public class ThreadUtils { private ThreadUtils() {} @NotNull public static <T> Callable<T> caughtCallable( @NotNull Callable<T> callable ) { return new ExceptionReportingCallable<T>(callable); } @NotNull public static <T> Runnable runnable( @NotNull Callable<T> callable ) { return new ThreadAdapter<T>(callable); } }
/* * Copyright 2007 Russell Harmon * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.eatnumber1.util.concurrent; import java.util.concurrent.Callable; import org.jetbrains.annotations.NotNull; /** * @author Russell Harmon * @since Jul 13, 2007 */ public class ThreadUtils { private ThreadUtils() {} @NotNull public static <T> Callable<T> caughtCallable( @NotNull Callable<T> callable ) { return new ExceptionReportingCallable<T>(callable); } }