text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add line wrap to RTE code editor
(function () { "use strict"; function CodeEditorController($scope, localizationService) { var vm = this; vm.submit = submit; vm.close = close; vm.aceOption = {}; vm.aceOption = { mode: "razor", theme: "chrome", showPrintMargin: false, autoFocus: true, advanced: { fontSize: "14px", enableSnippets: false, //The Razor mode snippets are awful (Need a way to override these) enableBasicAutocompletion: true, enableLiveAutocompletion: false, wrap: true }, onLoad: function(aceEditor) { vm.aceEditor = aceEditor; } } vm.template = {}; vm.template.content = $scope.model.content; ////////// function onInit() { // set default title if(!$scope.model.title) { // TODO: localize $scope.model.title = "Edit source code"; } } function submit(model) { // refresh the model model.content = vm.aceEditor.getValue(); if($scope.model.submit) { $scope.model.submit(model); } } function close() { if($scope.model.close) { $scope.model.close(); } } onInit(); } angular.module("umbraco").controller("Umbraco.PropertyEditors.RTECodeEditorController", CodeEditorController); })();
(function () { "use strict"; function CodeEditorController($scope, localizationService) { var vm = this; vm.submit = submit; vm.close = close; vm.aceOption = {}; vm.aceOption = { mode: "razor", theme: "chrome", showPrintMargin: false, autoFocus: true, advanced: { fontSize: "14px", enableSnippets: false, //The Razor mode snippets are awful (Need a way to override these) enableBasicAutocompletion: true, enableLiveAutocompletion: false }, onLoad: function(aceEditor) { vm.aceEditor = aceEditor; } } vm.template = {}; vm.template.content = $scope.model.content; ////////// function onInit() { // set default title if(!$scope.model.title) { // TODO: localize $scope.model.title = "Edit source code"; } } function submit(model) { // refresh the model model.content = vm.aceEditor.getValue(); if($scope.model.submit) { $scope.model.submit(model); } } function close() { if($scope.model.close) { $scope.model.close(); } } onInit(); } angular.module("umbraco").controller("Umbraco.PropertyEditors.RTECodeEditorController", CodeEditorController); })();
Move function out of the scope
"use strict"; function isFilesArg (arg) { return Array.isArray(arg) || typeof arg === "string"; } /** * Handle arguments for backwards compatibility * @param {Object} args * @returns {{config: {}, cb: *}} */ module.exports = function (args) { var config = {}; var cb; switch (args.length) { case 1 : if (isFilesArg(args[0])) { config.files = args[0]; } else if (typeof args[0] === "function") { cb = args[0]; } else { config = args[0]; } break; case 2 : // if second is a function, first MUST be config if (typeof args[1] === "function") { config = args[0] || {}; cb = args[1]; } else { config = args[1] || {}; if (!config.files) { config.files = args[0]; } } break; case 3 : config = args[1] || {}; if (!config.files) { config.files = args[0]; } cb = args[2]; } return { config: config, cb: cb }; };
"use strict"; /** * Handle arguments for backwards compatibility * @param {Object} args * @returns {{config: {}, cb: *}} */ module.exports = function (args) { var config = {}; var cb; switch (args.length) { case 1 : if (isFilesArg(args[0])) { config.files = args[0]; } else if (typeof args[0] === "function") { cb = args[0]; } else { config = args[0]; } break; case 2 : // if second is a function, first MUST be config if (typeof args[1] === "function") { config = args[0] || {}; cb = args[1]; } else { config = args[1] || {}; if (!config.files) { config.files = args[0]; } } break; case 3 : config = args[1] || {}; if (!config.files) { config.files = args[0]; } cb = args[2]; } function isFilesArg (arg) { return Array.isArray(arg) || typeof arg === "string"; } return { config: config, cb: cb }; };
Fix compilation error from previous checkin.
package com.atlassian.pageobjects.elements.test.pageobjects.page; import com.atlassian.pageobjects.Page; import com.atlassian.pageobjects.elements.Element; import com.atlassian.pageobjects.elements.ElementBy; import com.atlassian.pageobjects.elements.ElementFinder; import javax.inject.Inject; import static com.atlassian.pageobjects.elements.query.Poller.waitUntilTrue; /** * Represents the dynamicpage.html page */ public class DynamicPage implements Page { @ElementBy(id = "nameTextBox") Element nameTextBox; @ElementBy(id = "helloWorldButton") Element helloWorldButton; @ElementBy(id = "messageSpan") Element messageSpan; @ElementBy(id = "createFieldSetButton") Element createFieldSetButton; @Inject ElementFinder elementFinder; public String getUrl() { return "/html/dynamicpage.html"; } public DynamicPage createFieldSet() { createFieldSetButton.click(); waitUntilTrue(nameTextBox.timed().isVisible()); return this; } public DynamicPage helloWorld(String name) { nameTextBox.clear().type(name); helloWorldButton.click(); waitUntilTrue(messageSpan.timed().isVisible()); return this; } public String getMessage() { return messageSpan.getText(); } public ElementFinder getElementFinder() { return elementFinder; } }
package com.atlassian.pageobjects.elements.test.pageobjects.page; import com.atlassian.pageobjects.Page; import com.atlassian.pageobjects.elements.Element; import com.atlassian.pageobjects.elements.ElementBy; import com.atlassian.pageobjects.elements.ElementFinder; import javax.inject.Inject; import static com.atlassian.pageobjects.elements.query.TimedAssertions.assertTrueByDefaultTimeout; /** * Represents the dynamicpage.html page */ public class DynamicPage implements Page { @ElementBy(id = "nameTextBox") Element nameTextBox; @ElementBy(id = "helloWorldButton") Element helloWorldButton; @ElementBy(id = "messageSpan") Element messageSpan; @ElementBy(id = "createFieldSetButton") Element createFieldSetButton; @Inject ElementFinder elementFinder; public String getUrl() { return "/html/dynamicpage.html"; } public DynamicPage createFieldSet() { createFieldSetButton.click(); assertTrueByDefaultTimeout(nameTextBox.timed().isVisible()); return this; } public DynamicPage helloWorld(String name) { nameTextBox.clear().type(name); helloWorldButton.click(); assertTrueByDefaultTimeout(messageSpan.timed().isVisible()); return this; } public String getMessage() { return messageSpan.getText(); } public ElementFinder getElementFinder() { return elementFinder; } }
Use global CartConst, ignore local require.
'use strict'; /* global $, CartConst */ module.exports = function($scope, $location, $routeSegment, footerService) { console.log('CartMainCtrl'); $scope.segment = $routeSegment; $scope.location = $location; $scope.rootPath = $location.path().split('/')[1]; $scope.indexPaths = ['', 'new', 'update', 'year', 'month', 'day']; $scope.pageGoTo = function(page) { $location.url('/' + page); }; $scope.navToggle = function() { // body $('body').toggleClass('nav-expanded'); // trigger var navTriggerIcon = $('.nav-trigger span'); navTriggerIcon.bind(CartConst.ANIMATE_END_EVENT, function() { navTriggerIcon.removeClass('animated flip'); }); navTriggerIcon.addClass('animated flip'); }; $scope.loginToggle = function() { var alreadyLogin = false; if (alreadyLogin) { // already login // logout } else { // redirect to login page $location.url('/login'); } }; // route change event, when location changed $scope.$on('$routeChangeStart', function() { // reset the rootPath in url $scope.rootPath = $location.path().split('/')[1]; // detect footer pos footerService.fixFooter(); // footer fadeIn effect var footer = $('.page-footer'); footer.bind(CartConst.ANIMATE_END_EVENT, function() { footer.removeClass('animated fadeIn'); }); footer.addClass('animated fadeIn'); }); };
'use strict'; /* global $ */ var CartConst = require('../const/const.js'); module.exports = function($scope, $location, $routeSegment, footerService) { console.log('CartMainCtrl'); $scope.segment = $routeSegment; $scope.location = $location; $scope.rootPath = $location.path().split('/')[1]; $scope.indexPaths = ['', 'new', 'update', 'year', 'month', 'day']; $scope.pageGoTo = function(page) { $location.url('/' + page); }; $scope.navToggle = function() { // body $('body').toggleClass('nav-expanded'); // trigger var navTriggerIcon = $('.nav-trigger span'); navTriggerIcon.bind(CartConst.ANIMATE_END_EVENT, function() { navTriggerIcon.removeClass('animated flip'); }); navTriggerIcon.addClass('animated flip'); }; $scope.loginToggle = function() { var alreadyLogin = false; if (alreadyLogin) { // already login // logout } else { // redirect to login page $location.url('/login'); } }; // route change event, when location changed $scope.$on('$routeChangeStart', function() { // reset the rootPath in url $scope.rootPath = $location.path().split('/')[1]; // detect footer pos footerService.fixFooter(); // footer fadeIn effect var footer = $('.page-footer'); footer.bind(CartConst.ANIMATE_END_EVENT, function() { footer.removeClass('animated fadeIn'); }); footer.addClass('animated fadeIn'); }); };
Put AutoFocus focus holder in a portal. This prevent it from affecting layouts.
import {compose} from 'compose' import PropTypes from 'prop-types' import React from 'react' import withForwardedRef from 'ref' import Portal from 'widget/portal' class AutoFocus extends React.Component { focusHolderRef = React.createRef() state = {completed: false} render() { const {completed} = this.state return completed ? null : <Portal type='global'> <div ref={this.focusHolderRef} tabIndex={-1}/> </Portal> } shouldComponentUpdate(nextProps, nextState, nextContext) { const {enabled} = nextProps return !!enabled } componentDidMount() { const {enabled} = this.props if (enabled) { const focusHolderElement = this.focusHolderRef.current focusHolderElement && focusHolderElement.focus() this.update() } } componentDidUpdate() { this.update() } update() { const {forwardedRef, enabled} = this.props const focusHolderElement = this.focusHolderRef.current const element = forwardedRef.current if (!enabled || !element || !focusHolderElement) { return } if (document.activeElement !== focusHolderElement) { this.setState({completed: true}) return } element.focus() if (document.activeElement === element) { this.setState({completed: true}) } } } export default compose( AutoFocus, withForwardedRef() ) AutoFocus.propTypes = { enabled: PropTypes.any, forwardedRef: PropTypes.object }
import {compose} from 'compose' import PropTypes from 'prop-types' import React from 'react' import withForwardedRef from 'ref' class AutoFocus extends React.Component { focusHolderRef = React.createRef() state = {completed: false} render() { const {completed} = this.state return completed ? null : <div ref={this.focusHolderRef} tabIndex={-1}/> } shouldComponentUpdate(nextProps, nextState, nextContext) { const {enabled} = nextProps return !!enabled } componentDidMount() { const {enabled} = this.props if (enabled) { const focusHolderElement = this.focusHolderRef.current focusHolderElement && focusHolderElement.focus() this.update() } } componentDidUpdate() { this.update() } update() { const {forwardedRef, enabled} = this.props const focusHolderElement = this.focusHolderRef.current const element = forwardedRef.current if (!enabled || !element || !focusHolderElement) { return } if (document.activeElement !== focusHolderElement) { this.setState({completed: true}) return } element.focus() if (document.activeElement === element) { this.setState({completed: true}) } } } export default compose( AutoFocus, withForwardedRef() ) AutoFocus.propTypes = { enabled: PropTypes.any, forwardedRef: PropTypes.object }
Improve batch form return data structure.
from django import forms import csv from io import StringIO class BatchMoonScanForm(forms.Form): data = forms.CharField( widget=forms.Textarea(attrs={'class':'form-control monospace'}), ) def clean(self): cleaned_data = super(BatchMoonScanForm, self).clean() raw = StringIO(cleaned_data['data']) reader = csv.reader(raw, delimiter='\t') next(reader) res = {} current_moon = 0 percentage_sum = 0 current_scan = {} for x in reader: print(x) if len(x) == 1: if len(x[0]) == 0: raise forms.ValidationError('Invalid input format.') if current_moon != 0 and percentage_sum != 100: raise forms.ValidationError('Sum of percentages must be 100.') if len(current_scan) > 0 and current_moon != 0: res[current_moon] = current_scan current_moon = 0 percentage_sum = 0 current_scan = {} else: if len(x[0]) != 0: raise forms.ValidationError('Invalid input format.') moon_id = int(x[6]) ore_id = int(x[3]) percentage = int(round(100 * float(x[2]))) percentage_sum += percentage if current_moon == 0: current_moon = moon_id elif moon_id != current_moon: raise forms.ValidationError('Unexpected moon ID.') if ore_id in current_scan: raise forms.ValidationError('Unexpected moon ID.') current_scan[ore_id] = percentage print(res) cleaned_data['data'] = res
from django import forms import csv from io import StringIO class BatchMoonScanForm(forms.Form): data = forms.CharField( widget=forms.Textarea(attrs={'class':'form-control monospace'}), ) def clean(self): cleaned_data = super(BatchMoonScanForm, self).clean() raw = StringIO(cleaned_data['data']) reader = csv.reader(raw, delimiter='\t') next(reader) res = [] for x in reader: print(x) if len(x) == 1: assert(len(x[0]) > 0) current_moon = 0 current_scan = {} res.append(current_scan) else: assert(len(x[0]) == 0) moon_id = int(x[6]) ore_id = int(x[3]) percentage = int(round(100 * float(x[2]))) if current_moon == 0: current_moon = moon_id else: assert(moon_id == current_moon) assert(ore_id not in current_scan) current_scan[ore_id] = percentage print(res) cleaned_data['data'] = res
feat: Add error handler to file templater
"use strict"; var fs = require('fs'); var path = require('path'); var extend = require('extend'); var template = require('lodash/template'); var errorHandler = require('./errorHandler'); var _fileNumber = 1; var _config = { onEachFile: function() {}, onCompleted: function() {} }; module.exports = function() { return { run: run, setConfig: setConfig } function setConfig(config) { _config = extend(_config, config); } function run(callback) { _config.files.forEach(function(element, index, array) { templateFile(element); }); } function templateFile(filePaths) { var compiled; var output; fs.readFile(filePaths.src, 'utf8', function(err, fileContents) { if (err) errorHandler(err); compiled = template(fileContents); output = compiled(_config.data); fs.writeFile(filePaths.dest, output, 'utf8', function(err) { if (err) errorHandler(err); _config.onEachFile(filePaths.dest); if(_fileNumber === _config.files.length) { _config.onCompleted(); } _fileNumber++; }); }); } }
"use strict"; var fs = require('fs'); var path = require('path'); var extend = require('extend'); var template = require('lodash/template'); var _fileNumber = 1; var _config = { onEachFile: function() {}, onCompleted: function() {} }; module.exports = function() { return { run: run, setConfig: setConfig } function setConfig(config) { _config = extend(_config, config); } function run(callback) { _config.files.forEach(function(element, index, array) { templateFile(element); }); } function templateFile(filePaths) { var compiled; var output; fs.readFile(filePaths.src, 'utf8', function(err, fileContents) { if (err) return console.error(err) compiled = template(fileContents); output = compiled(_config.data); fs.writeFile(filePaths.dest, output, 'utf8', function(err) { if (err) return console.error(err) _config.onEachFile(filePaths.dest); if(_fileNumber === _config.files.length) { _config.onCompleted(); } _fileNumber++; }); }); } }
Fix "My Data" page JS views
//The loading screen view define(['backbone', 'underscore', 'spin'], function(Backbone, _, Spinner) { 'use strict'; var LoadScreenView = Backbone.View.extend({ className: 'spinner-container', defaultOptions: { lines: 11, // The number of lines to draw length: 24, // The length of each line width: 10, // The line thickness radius: 60, // The radius of the inner circle corners: 1, // Corner roundness (0..1) rotate: 0, // The rotation offset direction: 1, // 1: clockwise, -1: counterclockwise color: 'black', // #rgb or #rrggbb speed: 0.8, // Rounds per second trail: 67, // Afterglow percentage shadow: false, // Whether to render a shadow hwaccel: true, // Whether to use hardware acceleration className: 'spinner', // The CSS class to assign to the spinner zIndex: 2e9 // The z-index (defaults to 2000000000) }, initialize: function(opts) { this.spinner = new Spinner(_.extend(this.defaultOptions, opts)); this.render(); }, render: function() { this.spinner.spin(this.el); } }); return LoadScreenView; });
//The loading screen view define(['backbone', 'underscore', 'spin'], function(Backbone, _, Spinner) { 'use strict'; var LoadScreenView = Backbone.View.extend({ className: 'spinner-container', defaultOptions: { lines: 11, // The number of lines to draw length: 24, // The length of each line width: 10, // The line thickness radius: 60, // The radius of the inner circle corners: 1, // Corner roundness (0..1) rotate: 0, // The rotation offset direction: 1, // 1: clockwise, -1: counterclockwise color: 'black', // #rgb or #rrggbb speed: 0.8, // Rounds per second trail: 67, // Afterglow percentage shadow: false, // Whether to render a shadow hwaccel: true, // Whether to use hardware acceleration className: 'spinner', // The CSS class to assign to the spinner zIndex: 2e9 // The z-index (defaults to 2000000000) }, initialize: function(opts) { this.spinner = new Spinner(_.extend(this.defaultOptions, opts)); this.render(); }, render: function() { this.spinner.spin(this.el); //this.$el.css('height', '300px'); //modal breaks in dataseed import } }); return LoadScreenView; });
Make sentenceList scrollable at all times
"use strict"; angular.module('arethusa.core').directive('sentenceList', [ '$compile', 'navigator', function($compile, navigator) { return { restrict: 'A', scope: true, link: function(scope, element, attrs) { scope.n = navigator; function createList() { // We want this to load only once, and only if // a user requests it! if (! navigator.hasList) { var template = '\ <div class="canvas-border"/>\ <div id="canvas" class="row panel full-height scrollable" full-height>\ <ul class="sentence-list">\ <li \ class="sentence-list"\ sentence="s"\ ng-repeat="s in n.sentences">\ </li>\ </ul>\ </div>\ '; navigator.list().append($compile(template)(scope)); navigator.hasList = true; } } scope.$on('viewModeSwitched', createList); element.bind('click', function() { createList(); scope.$apply(function() { navigator.switchView(); }); }); } }; } ]);
"use strict"; angular.module('arethusa.core').directive('sentenceList', [ '$compile', 'navigator', function($compile, navigator) { return { restrict: 'A', scope: true, link: function(scope, element, attrs) { scope.n = navigator; function createList() { // We want this to load only once, and only if // a user requests it! if (! navigator.hasList) { var template = '\ <div class="canvas-border"/>\ <div id="canvas" class="row panel full-height" full-height>\ <ul class="sentence-list">\ <li \ class="sentence-list"\ sentence="s"\ ng-repeat="s in n.sentences">\ </li>\ </ul>\ </div>\ '; navigator.list().append($compile(template)(scope)); navigator.hasList = true; } } scope.$on('viewModeSwitched', createList); element.bind('click', function() { createList(); scope.$apply(function() { navigator.switchView(); }); }); } }; } ]);
Fix onChange propType in Switch component
import React from 'react'; import { Strings } from '../../constants'; export default React.createClass({ propTypes: { field : React.PropTypes.string, onClick : React.PropTypes.func, valueOn : React.PropTypes.string, valueOff : React.PropTypes.string, checked : React.PropTypes.bool, onChange: React.PropTypes.func, }, getDefaultProps () { return { valueOn : "Ativo", valueOff : "Desativado", checked : false, } }, getInitialState () { return { valueOn: this.props.valueOn, valueOff: this.props.valueOff, value: this.props.checked, } }, getText () { return this.refs[this.props.field].state.placeholder; }, getValue () { const value = this.refs[this.props.field].state.checked; return value; }, onChange (event) { this.setState({ value: event.target.checked }); if (this.props.onChange) { this.props.onChange(event.target.checked); } }, render () { return ( <div className="switch"> <label> {this.props.valueOff} <input ref={this.props.field} checked={this.state.value} name={this.props.field} type="checkbox" onChange={this.onChange}/> <span className="lever"></span> {this.props.valueOn} </label> </div> ); } });
import React from 'react'; import { Strings } from '../../constants'; export default React.createClass({ propTypes: { field : React.PropTypes.string, onClick : React.PropTypes.func, valueOn : React.PropTypes.string, valueOff : React.PropTypes.string, checked : React.PropTypes.bool, }, getDefaultProps () { return { valueOn : "Ativo", valueOff : "Desativado", checked : false, onChange: function (event) { void event; }, } }, getInitialState () { return { valueOn: this.props.valueOn, valueOff: this.props.valueOff, value: this.props.checked, } }, getText () { return this.refs[this.props.field].state.placeholder; }, getValue () { const value = this.refs[this.props.field].state.checked; return value; }, onChange (event) { this.setState({ value: event.target.checked }); this.props.onChange(event); }, render () { return ( <div className="switch"> <label> {this.props.valueOff} <input ref={this.props.field} checked={this.state.value} name={this.props.field} type="checkbox" onChange={this.onChange}/> <span className="lever"></span> {this.props.valueOn} </label> </div> ); } });
Extend import statement to support Python 3
import os as _os import dash as _dash import sys as _sys from .version import __version__ _current_path = _os.path.dirname(_os.path.abspath(__file__)) _components = _dash.development.component_loader.load_components( _os.path.join(_current_path, 'metadata.json'), 'dash_core_components' ) _this_module = _sys.modules[__name__] _js_dist = [ { "relative_package_path": "bundle.js", "external_url": ( "https://unpkg.com/dash-core-components@{}" "/dash_core_components/bundle.js" ).format(__version__) } ] _css_dist = [ { "relative_package_path": [ "[email protected]", "[email protected]" ], "external_url": [ "https://unpkg.com/[email protected]/dist/react-select.min.css", "https://unpkg.com/[email protected]/assets/index.css" ] } ] for component in _components: setattr(_this_module, component.__name__, component) setattr(component, '_js_dist', _js_dist) setattr(component, '_css_dist', _css_dist)
import os as _os import dash as _dash import sys as _sys from version import __version__ _current_path = _os.path.dirname(_os.path.abspath(__file__)) _components = _dash.development.component_loader.load_components( _os.path.join(_current_path, 'metadata.json'), 'dash_core_components' ) _this_module = _sys.modules[__name__] _js_dist = [ { "relative_package_path": "bundle.js", "external_url": ( "https://unpkg.com/dash-core-components@{}" "/dash_core_components/bundle.js" ).format(__version__) } ] _css_dist = [ { "relative_package_path": [ "[email protected]", "[email protected]" ], "external_url": [ "https://unpkg.com/[email protected]/dist/react-select.min.css", "https://unpkg.com/[email protected]/assets/index.css" ] } ] for component in _components: setattr(_this_module, component.__name__, component) setattr(component, '_js_dist', _js_dist) setattr(component, '_css_dist', _css_dist)
Fix divide by zero when no reg estimate
<?php namespace CodeDay\Clear\Controllers\Manage; use \CodeDay\Clear\Models; class DashboardController extends \Controller { public function getIndex() { return \View::make('dashboard'); } public function getChangeBatch() { if (\Input::get('id')) { Models\Batch::find(\Input::get('id'))->manage(); return \Redirect::to('/'); } else { return \View::make('change_batch'); } } public function getUpdates() { if (Models\User::me()->is_admin) { $events = Models\Batch::Managed()->events; } else { $events = Models\User::me()->current_managed_events; } $event_update = []; foreach ($events as $event) { $event_update[$event->id] = [ 'registrations' => $event->registrations->count(), 'today' => count($event->registrations_today), 'this_week' => count($event->registrations_this_week), 'percent' => $event->registration_estimate ? round(($event->registrations->count()/$event->registration_estimate)*100) : 0, 'predicted' => '?', 'notify' => $event->notify->count(), 'allow_registrations' => $event->allow_registrations ]; } return json_encode($event_update); } }
<?php namespace CodeDay\Clear\Controllers\Manage; use \CodeDay\Clear\Models; class DashboardController extends \Controller { public function getIndex() { return \View::make('dashboard'); } public function getChangeBatch() { if (\Input::get('id')) { Models\Batch::find(\Input::get('id'))->manage(); return \Redirect::to('/'); } else { return \View::make('change_batch'); } } public function getUpdates() { if (Models\User::me()->is_admin) { $events = Models\Batch::Managed()->events; } else { $events = Models\User::me()->current_managed_events; } $event_update = []; foreach ($events as $event) { $event_update[$event->id] = [ 'registrations' => $event->registrations->count(), 'today' => count($event->registrations_today), 'this_week' => count($event->registrations_this_week), 'percent' => round(($event->registrations->count()/$event->registration_estimate)*100), 'predicted' => '?', 'notify' => $event->notify->count(), 'allow_registrations' => $event->allow_registrations ]; } return json_encode($event_update); } }
Use hass.config.api instead of hass.http
""" This module exposes Home Assistant via Zeroconf. Zeroconf is also known as Bonjour, Avahi or Multicast DNS (mDNS). For more details about Zeroconf, please refer to the documentation at https://home-assistant.io/components/zeroconf/ """ import logging import socket from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) REQUIREMENTS = ["zeroconf==0.17.5"] DEPENDENCIES = ["api"] _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) params = {"version": __version__, "base_url": hass.config.api.base_url, "needs_auth": (hass.config.api.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.config.api.host), hass.config.api.port, 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True
""" This module exposes Home Assistant via Zeroconf. Zeroconf is also known as Bonjour, Avahi or Multicast DNS (mDNS). For more details about Zeroconf, please refer to the documentation at https://home-assistant.io/components/zeroconf/ """ import logging import socket from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) REQUIREMENTS = ["zeroconf==0.17.5"] _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." DEPENDENCIES = ["http"] def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) params = {"version": __version__, "base_url": hass.http.base_url, "needs_auth": (hass.http.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.http.routable_address), hass.http.server_address[1], 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True
Fix error in unit test
<?php /** * phpDocumentor * * PHP Version 5.3 * * @copyright 2010-2013 Mike van Riel / Naenius (http://www.naenius.com) * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://phpdoc.org */ namespace phpDocumentor\Descriptor; use \Mockery as m; /** * Tests the functionality for the FunctionDescriptor class. */ class FunctionDescriptorTest extends \PHPUnit_Framework_TestCase { /** @var FunctionDescriptor $fixture */ protected $fixture; /** * Creates a new (emoty) fixture object. */ protected function setUp() { $this->fixture = new FunctionDescriptor(); } /** * Tests whether all collection objects are properly initialized. * * @covers phpDocumentor\Descriptor\FunctionDescriptor::__construct */ public function testInitialize() { $this->assertAttributeInstanceOf('phpDocumentor\Descriptor\Collection', 'arguments', $this->fixture); } /** * @covers phpDocumentor\Descriptor\FunctionDescriptor::setArguments * @covers phpDocumentor\Descriptor\FunctionDescriptor::getArguments */ public function testSettingAndGettingArguments() { $this->assertInstanceOf('phpDocumentor\Descriptor\Collection', $this->fixture->getArguments()); $mockInstance = m::mock('phpDocumentor\Descriptor\Collection'); $mock = &$mockInstance; $this->fixture->setArguments($mock); $this->assertSame($mockInstance, $this->fixture->getArguments()); } }
<?php /** * phpDocumentor * * PHP Version 5.3 * * @copyright 2010-2013 Mike van Riel / Naenius (http://www.naenius.com) * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://phpdoc.org */ namespace phpDocumentor\Descriptor; use \Mockery as m; /** * Tests the functionality for the FunctionDescriptor class. */ class FunctionDescriptorTest extends \PHPUnit_Framework_TestCase { /** @var FunctionDescriptor $fixture */ protected $fixture; /** * Creates a new (emoty) fixture object. */ protected function setUp() { $this->fixture = new FunctionDescriptor(); } /** * Tests whether all collection objects are properly initialized. * * @covers phpDocumentor\Descriptor\FunctionDescriptor::__construct */ public function testInitialize() { $this->assertAttributeInstanceOf('phpDocumentor\Descriptor\Collection', 'arguments', $this->fixture); } /** * @covers phpDocumentor\Descriptor\FunctionDescriptor::setArguments * @covers phpDocumentor\Descriptor\FunctionDescriptor::getArguments */ public function testSettingAndGettingArguments() { $this->assertInstanceOf('phpDocumentor\Descriptor\Collection', $this->fixture->getArguments()); $mock = &m::mock('phpDocumentor\Descriptor\Collection'); $this->fixture->setArguments($mock); $this->assertSame($mock, $this->fixture->getArguments()); } }
Add LIMIT 1 to speed up query
from typing import List from mediawords.db.handler import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed l = create_logger(__name__) class McPostgresRegexMatch(Exception): """postgres_regex_match() exception.""" pass def postgres_regex_match(db: DatabaseHandler, strings: List[str], regex: str) -> bool: """Run the regex through the PostgreSQL engine against a given list of strings. Return True if any string matches the given regex. This is necessary because very occasionally the wrong combination of text and complex boolean regex will cause Perl (Python too?) to hang.""" strings = decode_object_from_bytes_if_needed(strings) regex = decode_object_from_bytes_if_needed(regex) if not isinstance(strings, list): raise McPostgresRegexMatch("Strings must be a list, but is: %s" % str(strings)) if len(strings) == 0: return False if not isinstance(strings[0], str): raise McPostgresRegexMatch("Strings must be a list of strings, but is: %s" % str(strings)) full_regex = '(?isx)%s' % regex match = db.query(""" SELECT 1 FROM UNNEST(%(strings)s) AS string WHERE string ~ %(regex)s LIMIT 1 """, { 'strings': strings, # list gets converted to PostgreSQL's ARRAY[] 'regex': full_regex, }).hash() if match is not None: return True else: return False
from typing import List from mediawords.db.handler import DatabaseHandler from mediawords.util.log import create_logger from mediawords.util.perl import decode_object_from_bytes_if_needed l = create_logger(__name__) class McPostgresRegexMatch(Exception): """postgres_regex_match() exception.""" pass def postgres_regex_match(db: DatabaseHandler, strings: List[str], regex: str) -> bool: """Run the regex through the PostgreSQL engine against a given list of strings. Return True if any string matches the given regex. This is necessary because very occasionally the wrong combination of text and complex boolean regex will cause Perl (Python too?) to hang.""" strings = decode_object_from_bytes_if_needed(strings) regex = decode_object_from_bytes_if_needed(regex) if not isinstance(strings, list): raise McPostgresRegexMatch("Strings must be a list, but is: %s" % str(strings)) if len(strings) == 0: return False if not isinstance(strings[0], str): raise McPostgresRegexMatch("Strings must be a list of strings, but is: %s" % str(strings)) full_regex = '(?isx)%s' % regex match = db.query(""" SELECT 1 FROM UNNEST(%(strings)s) AS string WHERE string ~ %(regex)s """, { 'strings': strings, # list gets converted to PostgreSQL's ARRAY[] 'regex': full_regex, }).hash() if match is not None: return True else: return False
Use 1-indexed counting for game IDs
""" This module is for generating fake game data for use with the API. An example of some game data:: { "id": 1, "logURL": "http://derp.nope/", "updates": [ { "status": "complete", "time": "today" } ], "players": [ { "name": "Team Awesome", "score": 1 }, { "name": "Team Less Awesome", "score": 0 }, ] } """ import datetime import random def game_data(players, count): now = datetime.datetime.now() for id in xrange(1, count+1): yield { "id": id, "logURL": "about:blank", "updates": [ { "status": "complete", "time": str(now + datetime.timedelta(minutes=id)) } ], "players": dict(zip(random.sample(players, 2), (0, 1))), }
""" This module is for generating fake game data for use with the API. An example of some game data:: { "id": 1, "logURL": "http://derp.nope/", "updates": [ { "status": "complete", "time": "today" } ], "players": [ { "name": "Team Awesome", "score": 1 }, { "name": "Team Less Awesome", "score": 0 }, ] } """ import datetime import random def game_data(players, count): now = datetime.datetime.now() for id in xrange(count): yield { "id": id, "logURL": "about:blank", "updates": [ { "status": "complete", "time": str(now + datetime.timedelta(minutes=id)) } ], "players": dict(zip(random.sample(players, 2), (0, 1))), }
Set TimeStamp field to jTime type. Run go fmt
package bittrex type Order struct { OrderUuid string `json:"OrderUuid"` Exchange string `json:"Exchange"` TimeStamp jTime `json:"TimeStamp"` OrderType string `json:"OrderType"` Limit float64 `json:"Limit"` Quantity float64 `json:"Quantity"` QuantityRemaining float64 `json:"QuantityRemaining"` Commission float64 `json:"Commission"` Price float64 `json:"Price"` PricePerUnit float64 `json:"PricePerUnit"` } // For getorder type Order2 struct { AccountId string OrderUuid string `json:"OrderUuid"` Exchange string `json:"Exchange"` Type string Quantity float64 `json:"Quantity"` QuantityRemaining float64 `json:"QuantityRemaining"` Limit float64 `json:"Limit"` Reserved float64 ReserveRemaining float64 CommissionReserved float64 CommissionReserveRemaining float64 CommissionPaid float64 Price float64 `json:"Price"` PricePerUnit float64 `json:"PricePerUnit"` Opened string Closed string IsOpen bool Sentinel string CancelInitiated bool ImmediateOrCancel bool IsConditional bool Condition string ConditionTarget string }
package bittrex type Order struct { OrderUuid string `json:"OrderUuid"` Exchange string `json:"Exchange"` TimeStamp string `json:"TimeStamp"` OrderType string `json:"OrderType"` Limit float64 `json:"Limit"` Quantity float64 `json:"Quantity"` QuantityRemaining float64 `json:"QuantityRemaining"` Commission float64 `json:"Commission"` Price float64 `json:"Price"` PricePerUnit float64 `json:"PricePerUnit"` } // For getorder type Order2 struct { AccountId string OrderUuid string `json:"OrderUuid"` Exchange string `json:"Exchange"` Type string Quantity float64 `json:"Quantity"` QuantityRemaining float64 `json:"QuantityRemaining"` Limit float64 `json:"Limit"` Reserved float64 ReserveRemaining float64 CommissionReserved float64 CommissionReserveRemaining float64 CommissionPaid float64 Price float64 `json:"Price"` PricePerUnit float64 `json:"PricePerUnit"` Opened string Closed string IsOpen bool Sentinel string CancelInitiated bool ImmediateOrCancel bool IsConditional bool Condition string ConditionTarget string }
Synchronize DateFormat usages due to it being thread unsafe (Sonar S2885)
package ru.taximaxim.pgsqlblocks.utils; import org.apache.log4j.Logger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public final class DateUtils { private static final Logger LOG = Logger.getLogger(DateUtils.class); private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX"); private final SimpleDateFormat dateFormatWithoutTimeZone = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public synchronized Date dateFromString(String dateString) { if (dateString == null || dateString.isEmpty()) { return null; } Date result = null; try { result = dateFormat.parse(dateString); } catch (ParseException exception) { LOG.error(exception.getMessage(), exception); } return result; } public synchronized String dateToString(Date date) { if (date == null) { return ""; } return dateFormatWithoutTimeZone.format(date); } public synchronized String dateToStringWithTz(Date date) { if (date == null) { return ""; } return dateFormat.format(date); } public static int compareDates(Date d1, Date d2) { if (d1 == null) { return d2 == null ? 0 : -1; } else { return d2 == null ? 1 : d1.compareTo(d2); } } }
package ru.taximaxim.pgsqlblocks.utils; import org.apache.log4j.Logger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public final class DateUtils { private static final Logger LOG = Logger.getLogger(DateUtils.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX"); private static final SimpleDateFormat dateFormatWithoutTimeZone = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static Date dateFromString(String dateString) { if (dateString == null || dateString.isEmpty()) { return null; } Date result = null; try { result = dateFormat.parse(dateString); } catch (ParseException exception) { LOG.error(exception.getMessage(), exception); } return result; } public static String dateToString(Date date) { if (date == null) { return ""; } return dateFormatWithoutTimeZone.format(date); } public static String dateToStringWithTz(Date date) { if (date == null) { return ""; } return dateFormat.format(date); } public static int compareDates(Date d1, Date d2) { if (d1 == null) { return d2 == null ? 0 : -1; } else { return d2 == null ? 1 : d1.compareTo(d2); } } }
Improve the project form a bit
from django.contrib.auth.models import User from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit import models class BaseModelForm(forms.ModelForm): helper = FormHelper() helper.form_class = 'form-horizontal' helper.add_input(Submit('submit', 'Submit')) class BaseForm(forms.Form): helper = FormHelper() helper.form_class = 'form-horizontal' helper.add_input(Submit('submit', 'Submit')) class ReleaseForm(BaseModelForm): class Meta: model = models.ReleaseStream class ProjectForm(BaseModelForm): github_url = forms.CharField(label="Git checkout URL") allowed_users = forms.ModelMultipleChoiceField( queryset=User.objects.all().order_by('username'), required=False, widget=forms.widgets.CheckboxSelectMultiple ) class Meta: model = models.Project exclude = ('idhash', 'created_by_user',) def clean(self): cleaned_data = super(ProjectForm, self).clean() uri = cleaned_data['github_url'].strip() if not (uri[-4:] == '.git'): raise forms.ValidationError("Not a valid Git URI") cleaned_data['github_url'] = uri return cleaned_data class UserForm(BaseModelForm): password = forms.CharField(widget=forms.PasswordInput(), initial='') class Meta: model = User exclude = ( 'email', 'username', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'groups', 'user_permissions' )
from django.contrib.auth.models import User from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit import models class BaseModelForm(forms.ModelForm): helper = FormHelper() helper.form_class = 'form-horizontal' helper.add_input(Submit('submit', 'Submit')) class BaseForm(forms.Form): helper = FormHelper() helper.form_class = 'form-horizontal' helper.add_input(Submit('submit', 'Submit')) class ReleaseForm(BaseModelForm): class Meta: model = models.ReleaseStream class ProjectForm(BaseModelForm): github_url = forms.CharField(label="Git checkout URL") class Meta: model = models.Project exclude = ('idhash', 'created_by_user',) def clean(self): cleaned_data = super(ProjectForm, self).clean() uri = cleaned_data['github_url'].strip() if not (uri[-4:] == '.git'): raise forms.ValidationError("Not a valid Git URI") cleaned_data['github_url'] = uri return cleaned_data class UserForm(BaseModelForm): password = forms.CharField(widget=forms.PasswordInput(), initial='') class Meta: model = User exclude = ( 'email', 'username', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'groups', 'user_permissions' )
Add the jQuery object to vui and reference that inside controls. Gives us a central point for maintaining a well-defined jQuery object
/*jslint browser: true*/ ( function( vui, $ ) { $ = vui.$; $.widget( 'vui.vui_list', { _create: function() { var $node = $( this.element ); var updateListSelection = function() { $node.find( 'li.vui-checkbox > label > input, li.vui-radio > label > input' ).each( function ( index, inputNode ) { var $input = $( inputNode ); $input.closest( 'li.vui-checkbox, li.vui-radio' ).toggleClass( 'vui-selected', $input.prop( 'checked' ) ); } ); }; updateListSelection(); $node.change( function( args ) { var $target = $( args.target ); if ( $target.attr( 'type' ) === 'checkbox' ) { $target.closest( 'li.vui-checkbox' ).toggleClass( 'vui-selected', $target.prop( 'checked' ) ); } else if ( $target.attr( 'type' ) === 'radio' ) { updateListSelection(); } } ); } } ); vui.addClassInitializer( 'vui-list', function( node ) { $( node ).vui_list(); } ); } )( window.vui );
/*jslint browser: true*/ ( function( $, vui ) { $.widget( 'vui.vui_list', { _create: function() { var $node = $( this.element ); var updateListSelection = function() { $node.find( 'li.vui-checkbox > label > input, li.vui-radio > label > input' ).each( function ( index, inputNode ) { var $input = $( inputNode ); $input.closest( 'li.vui-checkbox, li.vui-radio' ).toggleClass( 'vui-selected', $input.prop( 'checked' ) ); } ); }; updateListSelection(); $node.change( function( args ) { var $target = $( args.target ); if ( $target.attr( 'type' ) === 'checkbox' ) { $target.closest( 'li.vui-checkbox' ).toggleClass( 'vui-selected', $target.prop( 'checked' ) ); } else if ( $target.attr( 'type' ) === 'radio' ) { updateListSelection(); } } ); } } ); vui.addClassInitializer( 'vui-list', function( node ) { $( node ).vui_list(); } ); } )( window.jQuery, window.vui );
Use strings instead of numerals for "0" in rules
#!/usr/bin/env Python # -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import) import glob import re import io import unicodecsv def build_rule(fields): try: a, b, X, Y = fields b = "0" if not b else b a = "0" if not a else a return '{} -> {} / {} _ {}'.format(a, b, X, Y) except ValueError: print('Malformed rule: {}'.format(','.join(fields))) def main(): for csv in glob.glob('*.csv'): txt = re.match('[A-Za-z-]+', csv).group(0) + '.txt' with open(csv, 'rb') as f, io.open(txt, 'w', encoding='utf-8') as g: reader = unicodecsv.reader(f, encoding='utf-8') next(reader) for fields in reader: if re.match('\s*%', fields[0]): print(','.join([x for x in fields if x]), file=g) else: rule = build_rule(fields) rule = re.sub('[ ]+', ' ', rule) rule = re.sub('[ ]$', '', rule) print(rule, file=g) if __name__ == '__main__': main()
#!/usr/bin/env Python # -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import) import glob import re import io import unicodecsv def build_rule(fields): try: a, b, X, Y = fields b = 0 if not b else b a = 0 if not a else a return '{} -> {} / {} _ {}'.format(a, b, X, Y) except ValueError: print('Malformed rule: {}'.format(','.join(fields))) def main(): for csv in glob.glob('*.csv'): txt = re.match('[A-Za-z-]+', csv).group(0) + '.txt' with open(csv, 'rb') as f, io.open(txt, 'w', encoding='utf-8') as g: reader = unicodecsv.reader(f, encoding='utf-8') next(reader) for fields in reader: if re.match('\s*%', fields[0]): print(','.join([x for x in fields if x]), file=g) else: rule = build_rule(fields) rule = re.sub('[ ]+', ' ', rule) rule = re.sub('[ ]$', '', rule) print(rule, file=g) if __name__ == '__main__': main()
[NCL-702] Check for null product version when triggering a configuration
package org.jboss.pnc.rest.trigger; import com.google.common.base.Preconditions; import org.jboss.pnc.core.builder.BuildCoordinator; import org.jboss.pnc.core.exception.CoreException; import org.jboss.pnc.datastore.repositories.BuildConfigurationRepository; import org.jboss.pnc.model.BuildRecordSet; import org.jboss.pnc.model.BuildConfiguration; import org.jboss.pnc.spi.builddriver.exception.BuildDriverException; import org.jboss.pnc.spi.repositorymanager.RepositoryManagerException; import javax.ejb.Stateless; import javax.inject.Inject; @Stateless public class BuildTriggerer { private BuildCoordinator buildCoordinator; private BuildConfigurationRepository buildConfigurationRepository; //to make CDI happy public BuildTriggerer() { } @Inject public BuildTriggerer(final BuildCoordinator buildCoordinator, final BuildConfigurationRepository buildConfigurationRepository) { this.buildCoordinator = buildCoordinator; this.buildConfigurationRepository = buildConfigurationRepository; } public int triggerBuilds( final Integer configurationId ) throws InterruptedException, CoreException, BuildDriverException, RepositoryManagerException { final BuildConfiguration configuration = buildConfigurationRepository.findOne(configurationId); Preconditions.checkArgument(configuration != null, "Can't find configuration with given id=" + configurationId); final BuildRecordSet buildRecordSet = new BuildRecordSet(); if (configuration.getProductVersion() != null) { buildRecordSet.setProductMilestone(configuration.getProductVersion().getCurrentProductMilestone()); } return buildCoordinator.build(configuration).getBuildConfiguration().getId(); } }
package org.jboss.pnc.rest.trigger; import com.google.common.base.Preconditions; import org.jboss.pnc.core.builder.BuildCoordinator; import org.jboss.pnc.core.exception.CoreException; import org.jboss.pnc.datastore.repositories.BuildConfigurationRepository; import org.jboss.pnc.model.BuildRecordSet; import org.jboss.pnc.model.BuildConfiguration; import org.jboss.pnc.spi.builddriver.exception.BuildDriverException; import org.jboss.pnc.spi.repositorymanager.RepositoryManagerException; import javax.ejb.Stateless; import javax.inject.Inject; @Stateless public class BuildTriggerer { private BuildCoordinator buildCoordinator; private BuildConfigurationRepository buildConfigurationRepository; //to make CDI happy public BuildTriggerer() { } @Inject public BuildTriggerer(final BuildCoordinator buildCoordinator, final BuildConfigurationRepository buildConfigurationRepository) { this.buildCoordinator = buildCoordinator; this.buildConfigurationRepository = buildConfigurationRepository; } public int triggerBuilds( final Integer configurationId ) throws InterruptedException, CoreException, BuildDriverException, RepositoryManagerException { final BuildConfiguration configuration = buildConfigurationRepository.findOne(configurationId); Preconditions.checkArgument(configuration != null, "Can't find configuration with given id=" + configurationId); final BuildRecordSet buildRecordSet = new BuildRecordSet(); buildRecordSet.setProductMilestone(configuration.getProductVersion().getCurrentProductMilestone()); return buildCoordinator.build(configuration).getBuildConfiguration().getId(); } }
Fix filter_ method calling parent method bug
import numpy as np import cv2 from core import KpFilter class Ransac(KpFilter): def __init__(self, data): KpFilter.__init__(self, data) def __good_pts(self, kps, mps): rr = [kps[m].pt for m in mps] return np.float32(rr).reshape(-1, 1, 2) def __compute(self, good, skp, vkp, min_matches=10): """ data is a dict contained columns: [ 'kp_train', 'kp_test', 'matches'] Methods: 0 - a regular method using all the points CV_RANSAC - RANSAC-based robust method CV_LMEDS - Least-Median robust method """ if len(good) >= min_matches: src = self.__good_pts(skp, good.qix) des = self.__good_pts(vkp, good.tix) M, mask = cv2.\ findHomography(src, des, method=cv2.RANSAC, ransacReprojThreshold=5.0) return M, mask return None, None def filter_(self, min_matches=10): """ Returned by-product: M, the homography boundary """ good, skp, fkp = KpFilter.filter_(self) M, mask = self.__compute(good, skp, fkp, min_matches=min_matches) self.data['matches']['keep'] = mask return M
import numpy as np import cv2 from core import KpFilter class Ransac(KpFilter): def __init__(self, data): KpFilter.__init__(self, data) def __good_pts(self, kps, mps): rr = [kps[m].pt for m in mps] return np.float32(rr).reshape(-1, 1, 2) def __compute(self, good, skp, vkp, min_matches=10): """ data is a dict contained columns: [ 'kp_train', 'kp_test', 'matches'] Methods: 0 - a regular method using all the points CV_RANSAC - RANSAC-based robust method CV_LMEDS - Least-Median robust method """ if len(good) >= min_matches: src = self.__good_pts(skp, good.qix) des = self.__good_pts(vkp, good.tix) M, mask = cv2.\ findHomography(src, des, method=cv2.RANSAC, ransacReprojThreshold=5.0) return M, mask return None, None def filter_(self, min_matches=10): """ Returned by-product: M, the homography boundary """ good, skp, fkp = KpFilter.filter_() M, mask = self.__compute(good, skp, fkp, min_matches=min_matches) self.data['matches']['keep'] = mask return M
Change passenger schema to have a single ticket - instead of multiple tickets
exports.up = function(knex, Promise) { return knex.schema.createTable('passengers', table => { table.increments('id') .unsigned() .primary() table.string('name') table.integer('ticket') .unsigned() table.integer('station') .unsigned() }) .createTable('stations', table => { table.increments('id') .unsigned() .primary() table.string('location') .notNull() table.integer('prevStation') .unsigned() table.integer('nextStation') .unsigned() table.specificType('passengers', 'integer[]') .unsigned() }) .createTable('trains', table => { table.increments('id') .unsigned() .primary() table.decimal('capacity') .unsigned() .notNull() table.specificType('passengers', 'integer[]') .unsigned() table.decimal('station') .unsigned() }) .createTable('tickets', table => { table.increments('id') .unsigned() .primary() table.integer('purchasedFromStation') .unsigned() .notNull() table.integer('trainFor') .unsigned() .notNull() table.integer('destinationStation') .unsigned() .notNull }) } exports.down = function(knex, Promise) { return knex.schema.dropTableIfExists('passengers') .dropTableIfExists('stations') .dropTableIfExists('trains') .dropTableIfExists('people') .dropTableIfExists('tickets') }
exports.up = function(knex, Promise) { return knex.schema.createTable('passengers', table => { table.increments('id') .unsigned() .primary() table.string('name') table.specificType('tickets', 'integer[]') .unsigned() table.integer('station') .unsigned() }) .createTable('stations', table => { table.increments('id') .unsigned() .primary() table.string('location') .notNull() table.integer('prevStation') .unsigned() table.integer('nextStation') .unsigned() table.specificType('passengers', 'integer[]') .unsigned() }) .createTable('trains', table => { table.increments('id') .unsigned() .primary() table.decimal('capacity') .unsigned() .notNull() table.specificType('passengers', 'integer[]') .unsigned() table.decimal('station') .unsigned() }) .createTable('tickets', table => { table.increments('id') .unsigned() .primary() table.integer('purchasedFromStation') .unsigned() .notNull() table.integer('trainFor') .unsigned() .notNull() table.integer('destinationStation') .unsigned() .notNull }) } exports.down = function(knex, Promise) { return knex.schema.dropTableIfExists('passengers') .dropTableIfExists('stations') .dropTableIfExists('trains') .dropTableIfExists('people') .dropTableIfExists('tickets') }
Move readmode to root scope Prevents incorrect angular scope inheritance behaviour (calling $scope.readmode() would set the "read" variable on the calling scope, not in the readMode controller scope).
'use strict'; angular.module('theLawFactory') .directive('readMode', ['$location', function($location) { return { restrict: 'A', controller: function($rootScope, $scope) { $rootScope.read = $location.search()['read'] === '1'; $rootScope.readmode = function () { $("#sidebar").addClass('readmode'); if ($scope.mod === 'amendements') { $location.replace(); $location.search('read', '1'); } $rootScope.read = true; }; $rootScope.viewmode = function () { $("#sidebar").removeClass('readmode'); if ($scope.mod === 'amendements') { $location.replace(); $location.search('read', null); } $rootScope.read = false; }; if ($rootScope.read) { $rootScope.readmode(); } } } }]);
'use strict'; angular.module('theLawFactory') .directive('readMode', ['$location', function($location) { return { restrict: 'A', controller: function($scope) { $scope.read = $location.search()['read'] === '1'; $scope.readmode = function () { $("#sidebar").addClass('readmode'); if ($scope.mod === 'amendements') { $location.replace(); $location.search('read', '1'); } $scope.read = true; }; $scope.viewmode = function () { $("#sidebar").removeClass('readmode'); if ($scope.mod === 'amendements') { $location.replace(); $location.search('read', null); } $scope.read = false; }; if ($scope.read) { $scope.readmode(); } } } }]);
Remove deferred as not needed
/** * Date: 1/9/15 * Author: Shirish Goyal */ (function () { 'use strict'; angular .module('crowdsource.interceptor', []) .factory('AuthHttpResponseInterceptor', AuthHttpResponseInterceptor); AuthHttpResponseInterceptor.$inject = ['$location', '$log', '$injector', '$q']; function AuthHttpResponseInterceptor($location, $log, $injector, $q) { return { responseError: function (rejection) { if (rejection.status === 403) { if (rejection.hasOwnProperty('data') && rejection.data.hasOwnProperty('detail') && (rejection.data.detail.indexOf("Authentication credentials were not provided") != -1) ) { var $http = $injector.get('$http'); var Authentication = $injector.get('Authentication'); if (!Authentication.isAuthenticated()) { $location.path('/login'); } } } return $q.reject(rejection); } } } })();
/** * Date: 1/9/15 * Author: Shirish Goyal */ (function () { 'use strict'; angular .module('crowdsource.interceptor', []) .factory('AuthHttpResponseInterceptor', AuthHttpResponseInterceptor); AuthHttpResponseInterceptor.$inject = ['$location', '$log', '$injector', '$q']; function AuthHttpResponseInterceptor($location, $log, $injector, $q) { return { responseError: function (rejection) { if (rejection.status === 403) { if (rejection.hasOwnProperty('data') && rejection.data.hasOwnProperty('detail') && (rejection.data.detail.indexOf("Authentication credentials were not provided") != -1) ) { var $http = $injector.get('$http'); var Authentication = $injector.get('Authentication'); if (!Authentication.isAuthenticated()) { $location.path('/login'); }else{ deferred.resolve(data); } } } return $q.reject(rejection); } } } })();
Increase time range and id filtering
var spark = require('textspark'); var generateMetricParams = function(namespace, metric, unit, instance_id, dimension, period) { var endDate = new Date(); var startDate = new Date(endDate); var durationMinutes = 120; return { EndTime: endDate, MetricName: metric, Namespace: 'AWS/' + namespace, Period: period, StartTime: new Date(startDate.setMinutes(endDate.getMinutes() - durationMinutes)), Statistics: [ 'Average' ], Dimensions: [{Name: dimension, Value: instance_id}], Unit: unit }; }; module.exports = { displayMetric: function(aws, bot, channel, namespace, metric, unit, instance_id, dimension, period){ var params = generateMetricParams(namespace, metric, unit, instance_id, dimension, period); aws.getMetricStatistics(params, function(err, data) { if (err){ console.log(err); } else{ var datapoints = data['Datapoints'] if(datapoints && datapoints.length > 0){ datapoints.sort(function(x, y){ return x.Timestamp - y.Timestamp; }) var processed_data = []; datapoints.forEach(function (val, index, array) { processed_data.push(Number(val['Average']).toFixed(2)); }); bot.postMessage(channel, metric + ": " + spark(processed_data), {as_user: true}); } else{ bot.postMessage(channel, "Id '" + instance_id + "' not found", {as_user: true}); } } }); } };
var spark = require('textspark'); var generateMetricParams = function(namespace, metric, unit, instance_id, dimension, period) { var endDate = new Date(); var startDate = new Date(endDate); var durationMinutes = 60; return { EndTime: endDate, MetricName: metric, Namespace: 'AWS/' + namespace, Period: period, StartTime: new Date(startDate.setMinutes(endDate.getMinutes() - durationMinutes)), Statistics: [ 'Average' ], Dimensions: [{Name: dimension, Value: instance_id}], Unit: unit }; }; module.exports = { displayMetric: function(aws, bot, channel, namespace, metric, unit, instance_id, dimension, period){ var params = generateMetricParams(namespace, metric, unit, instance_id, dimension, period); aws.getMetricStatistics(params, function(err, data) { if (err){ console.log(err); } else{ var datapoints = data['Datapoints'] datapoints.sort(function(x, y){ return x.Timestamp - y.Timestamp; }) var processed_data = []; datapoints.forEach(function (val, index, array) { processed_data.push(Number(val['Average']).toFixed(2)); }); bot.postMessage(channel, metric + ": " + spark(processed_data), {as_user: true}); } }); } };
Fix user creation with unique username
from django.contrib.auth.models import User from django.db import models from django.utils import simplejson as json from .signals import post_associate class IdentityManager(models.Manager): def from_loginza_data(self, loginza_data): data = json.dumps(loginza_data) identity, created = self.get_or_create( identity = loginza_data['identity'], provider = loginza_data['provider'], defaults = {'data': data} ) if not created: identity.data = data identity.save() return identity class Identity(models.Model): identity = models.CharField(max_length=255) provider = models.CharField(max_length=255) user = models.ForeignKey(User, null=True) data = models.TextField() objects = IdentityManager() class Meta: unique_together = (('identity', 'provider'),) def associate(self, user): self.user = user self.save() post_associate.send(sender=type(self), instance=self) def create_user(self, username, email, password=None): existing_users = 0 new_username = None while True: existing_users += 1 qs = User.objects.all() qs = qs.filter(username=new_username or username) if not qs.exists(): break new_username = '%s_%d' % (username, existing_users) user = User.objects.create_user(new_username or username, email, password) self.associate(user) return user
from django.contrib.auth.models import User from django.db import models from django.utils import simplejson as json from .signals import post_associate class IdentityManager(models.Manager): def from_loginza_data(self, loginza_data): data = json.dumps(loginza_data) identity, created = self.get_or_create( identity = loginza_data['identity'], provider = loginza_data['provider'], defaults = {'data': data} ) if not created: identity.data = data identity.save() return identity class Identity(models.Model): identity = models.CharField(max_length=255) provider = models.CharField(max_length=255) user = models.ForeignKey(User, null=True) data = models.TextField() objects = IdentityManager() class Meta: unique_together = (('identity', 'provider'),) def associate(self, user): self.user = user self.save() post_associate.send(sender=type(self), instance=self) def create_user(self, username, email, password=None): existing_users = 0 while True: existing_users += 1 try: User.objects.get(username=username) except User.DoesNotExist: break username = '%s_%d' % (username, existing_users) user = User.objects.create_user(username, email, password) self.associate(user) return user
Add emails to auth details
from flask import session from zeus import auth from zeus.models import Email, Identity, User from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ if session.get('uid'): user = User.query.get(session['uid']) if user is None: session.clear() else: user = None if user is None: context = { 'isAuthenticated': False, } else: identity_list = list(Identity.query.filter( Identity.user_id == user.id, )) email_list = list(Email.query.filter( Email.user_id == user.id, )) context = { 'isAuthenticated': True, 'user': user_schema.dump(user).data, 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } return context def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
from flask import session from zeus import auth from zeus.models import Identity, User from .base import Resource from ..schemas import IdentitySchema, UserSchema user_schema = UserSchema(strict=True) identities_schema = IdentitySchema(many=True, strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ if session.get('uid'): user = User.query.get(session['uid']) if user is None: session.clear() else: user = None if user is None: context = { 'isAuthenticated': False, 'user': None, 'identities': [], } else: identity_list = list(Identity.query.filter( Identity.user_id == user.id, )) context = { 'isAuthenticated': True, 'user': user_schema.dump(user).data, 'identities': identities_schema.dump(identity_list).data, } return context def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
Make factory random names a bit more random to avoid clashes
import factory from django.utils.timezone import utc, now from thefederation.models import Node, Platform, Protocol, Stat class PlatformFactory(factory.DjangoModelFactory): name = factory.Faker('pystr') class Meta: model = Platform class ProtocolFactory(factory.DjangoModelFactory): name = factory.Faker('pystr') class Meta: model = Protocol class NodeFactory(factory.DjangoModelFactory): host = factory.Sequence(lambda n: 'node%s.local' % n) name = factory.Faker('company') open_signups = factory.Faker('pybool') platform = factory.SubFactory(PlatformFactory) class Meta: model = Node class Params: active = factory.Trait( last_success = factory.Faker('past_datetime', start_date='-1d', tzinfo=utc), ) @factory.post_generation def protocols(self, create, extracted, **kwargs): if not create: return if extracted: self.protocols.add(extracted) return self.protocols.add(ProtocolFactory()) class StatFactory(factory.DjangoModelFactory): date = now().date() node = factory.SubFactory(NodeFactory) users_total = factory.Faker('pyint') users_half_year = factory.Faker('pyint') users_monthly = factory.Faker('pyint') users_weekly = factory.Faker('pyint') class Meta: model = Stat
import factory from django.utils.timezone import utc, now from thefederation.models import Node, Platform, Protocol, Stat class PlatformFactory(factory.DjangoModelFactory): name = factory.Faker('word') class Meta: model = Platform class ProtocolFactory(factory.DjangoModelFactory): name = factory.Faker('word') class Meta: model = Protocol class NodeFactory(factory.DjangoModelFactory): host = factory.Sequence(lambda n: 'node%s.local' % n) name = factory.Faker('company') open_signups = factory.Faker('pybool') platform = factory.SubFactory(PlatformFactory) class Meta: model = Node class Params: active = factory.Trait( last_success = factory.Faker('past_datetime', start_date='-1d', tzinfo=utc), ) @factory.post_generation def protocols(self, create, extracted, **kwargs): if not create: return if extracted: self.protocols.add(extracted) return self.protocols.add(ProtocolFactory()) class StatFactory(factory.DjangoModelFactory): date = now().date() node = factory.SubFactory(NodeFactory) users_total = factory.Faker('pyint') users_half_year = factory.Faker('pyint') users_monthly = factory.Faker('pyint') users_weekly = factory.Faker('pyint') class Meta: model = Stat
Fix empty table not showing up
(function(angular, $, RepeaterUtilities) { 'use strict'; var module = angular.module('table.empty-table', []); module.directive('tableEmptyMessage', function($timeout, $log) { return { link: function(scope, el, attrs) { var msg = (attrs.tableEmptyMessage !== '') ? attrs.tableEmptyMessage : 'No items.'; var tr = $('<tr class="empty-msg"><td><div>' + msg + '</div></td></tr>'); var emptyToggleFn = function(val) { if (!val || val.length === 0) { tr.show(); } else { tr.hide(); } }; $timeout(function() { var modelData = RepeaterUtilities.extractCollection(el); if( modelData === undefined ) { $log.warn("no model data found."); } var tbody = el.find("tbody"); var rowCount = tbody.find("tr").length; tbody.append(tr); if( rowCount > 0) { tr.hide(); } if( modelData ) { scope.$watchCollection(modelData, emptyToggleFn); } },0, false); } }; }); })(angular, jQuery, RepeaterUtilities);
(function(angular, $, RepeaterUtilities) { 'use strict'; var module = angular.module('table.empty-table', []); module.directive('tableEmptyMessage', function($timeout, $log) { return { link: function(scope, el, attrs) { var msg = (attrs.tableEmptyMessage !== '') ? attrs.tableEmptyMessage : 'No items.'; var tr = $('<tr class="empty-msg"><div>' + msg + '</div></tr>'); var emptyToggleFn = function(val) { if (!val || val.length === 0) { tr.show(); } else { tr.hide(); } }; $timeout(function() { var modelData = RepeaterUtilities.extractCollection(el); if( modelData === undefined ) { $log.warn("no model data found."); } var tbody = el.find("tbody"); var rowCount = tbody.find("tr").length; tr.hide(); tbody.append(tr); if( rowCount === 0 ) { tr.show(); } if( modelData ) { scope.$watchCollection(modelData, emptyToggleFn); } },0, false); } }; }); })(angular, jQuery, RepeaterUtilities);
Reorder preferred mimetypes to prefer HTML over JSON
from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._html_mimetypes + \ self._json_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._json_mimetypes + \ self._html_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
Add {table} placeholder for path.
<?php namespace Josegonzalez\Upload\File\Path\Basepath; use Cake\Utility\Hash; use LogicException; trait DefaultTrait { /** * Returns the basepath for the current field/data combination. * If a `path` is specified in settings, then that will be used as * the replacement pattern * * @return string * @throws LogicException if a replacement is not valid for the current dataset */ public function basepath() { $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}'; $path = Hash::get($this->settings, 'path', $defaultPath); if (strpos($path, '{primaryKey}') !== false) { if ($this->entity->isNew()) { throw new LogicException('{primaryKey} substitution not allowed for new entities'); } if (is_array($this->table->primaryKey())) { throw new LogicException('{primaryKey} substitution not valid for composite primary keys'); } } $replacements = [ '{primaryKey}' => $this->entity->get($this->table->primaryKey()), '{model}' => $this->table->alias(), '{table}' => $this->table->table(), '{field}' => $this->field, '{time}' => time(), '{microtime}' => microtime(), '{DS}' => DIRECTORY_SEPARATOR, ]; return str_replace( array_keys($replacements), array_values($replacements), $path ); } }
<?php namespace Josegonzalez\Upload\File\Path\Basepath; use Cake\Utility\Hash; use LogicException; trait DefaultTrait { /** * Returns the basepath for the current field/data combination. * If a `path` is specified in settings, then that will be used as * the replacement pattern * * @return string * @throws LogicException if a replacement is not valid for the current dataset */ public function basepath() { $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}'; $path = Hash::get($this->settings, 'path', $defaultPath); if (strpos($path, '{primaryKey}') !== false) { if ($this->entity->isNew()) { throw new LogicException('{primaryKey} substitution not allowed for new entities'); } if (is_array($this->table->primaryKey())) { throw new LogicException('{primaryKey} substitution not valid for composite primary keys'); } } $replacements = [ '{primaryKey}' => $this->entity->get($this->table->primaryKey()), '{model}' => $this->table->alias(), '{field}' => $this->field, '{time}' => time(), '{microtime}' => microtime(), '{DS}' => DIRECTORY_SEPARATOR, ]; return str_replace( array_keys($replacements), array_values($replacements), $path ); } }
Make Rfam help url relative
var rfam = { bindings: { upi: '<', rna: '<', rfamHits: '<', toggleGoModal: '&' }, controller: ['$http', '$interpolate', 'routes', function($http, $interpolate, routes) { var ctrl = this; ctrl.$onInit = function() { ctrl.help = "/help/rfam-annotations"; // group hits with same rfam_model_id ctrl.groupedHits = []; ctrl.rfamHits.forEach(function(hit) { var existingHit = ctrl.groupedHits.find(function(existingHit) { return existingHit.rfam_model_id === hit.rfam_model_id; }); if (existingHit) { existingHit.raw.push(hit); existingHit.ranges.push([hit.sequence_start, hit.sequence_stop, hit.sequence_completeness]); } else { ctrl.groupedHits.push({ raw: [hit], ranges: [[hit.sequence_start, hit.sequence_stop, hit.sequence_completeness]], rfam_model: hit.rfam_model, rfam_model_id: hit.rfam_model.rfam_model_id }); } }); }; }], templateUrl: '/static/js/components/sequence/rfam/rfam.html' }; angular.module("rnaSequence").component("rfam", rfam);
var rfam = { bindings: { upi: '<', rna: '<', rfamHits: '<', toggleGoModal: '&' }, controller: ['$http', '$interpolate', 'routes', function($http, $interpolate, routes) { var ctrl = this; ctrl.$onInit = function() { ctrl.help = "https://rnacentral.org/help/rfam-annotations"; // group hits with same rfam_model_id ctrl.groupedHits = []; ctrl.rfamHits.forEach(function(hit) { var existingHit = ctrl.groupedHits.find(function(existingHit) { return existingHit.rfam_model_id === hit.rfam_model_id; }); if (existingHit) { existingHit.raw.push(hit); existingHit.ranges.push([hit.sequence_start, hit.sequence_stop, hit.sequence_completeness]); } else { ctrl.groupedHits.push({ raw: [hit], ranges: [[hit.sequence_start, hit.sequence_stop, hit.sequence_completeness]], rfam_model: hit.rfam_model, rfam_model_id: hit.rfam_model.rfam_model_id }); } }); }; }], templateUrl: '/static/js/components/sequence/rfam/rfam.html' }; angular.module("rnaSequence").component("rfam", rfam);
Remove date placeholder too, we need better UX for this later
<?php namespace Intracto\SecretSantaBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Intracto\SecretSantaBundle\Form\EntryType; class PoolType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('message') ->add( 'entries', 'collection', array( 'type' => new EntryType(), 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false, ) ) ->add( 'date', 'genemu_jquerydate', array( 'widget' => 'single_text', 'label' => 'Date of your Secret Santa party', ) ) ->add( 'amount', 'text', array( 'label' => 'Amount to spend', ) ); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( array( 'data_class' => 'Intracto\SecretSantaBundle\Entity\Pool' ) ); } public function getName() { return 'intracto_secretsantabundle_pooltype'; } }
<?php namespace Intracto\SecretSantaBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Intracto\SecretSantaBundle\Form\EntryType; class PoolType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('message') ->add( 'entries', 'collection', array( 'type' => new EntryType(), 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false, ) ) ->add( 'date', 'genemu_jquerydate', array( 'widget' => 'single_text', 'attr' => array('placeholder' => date('Y') . '-12-23'), 'label' => 'Date of your Secret Santa party', ) ) ->add( 'amount', 'text', array( 'label' => 'Amount to spend', ) ); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( array( 'data_class' => 'Intracto\SecretSantaBundle\Entity\Pool' ) ); } public function getName() { return 'intracto_secretsantabundle_pooltype'; } }
Add an empty array as default to prevent breakage when no filters are passed
<?php namespace CrudJsonApi\Listener; use Cake\Event\Event; use Cake\ORM\Table; use Crud\Listener\BaseListener; use RuntimeException; class SearchListener extends BaseListener { /** * Settings * * @var array */ protected $_defaultConfig = [ 'enabled' => [ 'Crud.beforeLookup', 'Crud.beforePaginate' ], 'collection' => 'default' ]; /** * Returns a list of all events that will fire in the controller during its lifecycle. * You can override this function to add your own listener callbacks * * @return array */ public function implementedEvents() { return [ 'Crud.beforeLookup' => ['callable' => 'injectSearch'], 'Crud.beforePaginate' => ['callable' => 'injectSearch'] ]; } /** * Inject search conditions into the query object. * * @param \Cake\Event\Event $event Event * @return void */ public function injectSearch(Event $event) { if (!in_array($event->getName(), $this->getConfig('enabled'))) { return; } $repository = $this->_table(); if ($repository instanceof Table && !$repository->behaviors()->has('Search')) { throw new RuntimeException(sprintf( 'Missing Search.Search behavior on %s', get_class($repository) )); } $filterParams = ['search' => $this->_request()->getQuery('filter', [])]; $filterParams['collection'] = $this->getConfig('collection'); $event->getSubject()->query->find('search', $filterParams); } }
<?php namespace CrudJsonApi\Listener; use Cake\Event\Event; use Cake\ORM\Table; use Crud\Listener\BaseListener; use RuntimeException; class SearchListener extends BaseListener { /** * Settings * * @var array */ protected $_defaultConfig = [ 'enabled' => [ 'Crud.beforeLookup', 'Crud.beforePaginate' ], 'collection' => 'default' ]; /** * Returns a list of all events that will fire in the controller during its lifecycle. * You can override this function to add your own listener callbacks * * @return array */ public function implementedEvents() { return [ 'Crud.beforeLookup' => ['callable' => 'injectSearch'], 'Crud.beforePaginate' => ['callable' => 'injectSearch'] ]; } /** * Inject search conditions into the query object. * * @param \Cake\Event\Event $event Event * @return void */ public function injectSearch(Event $event) { if (!in_array($event->getName(), $this->getConfig('enabled'))) { return; } $repository = $this->_table(); if ($repository instanceof Table && !$repository->behaviors()->has('Search')) { throw new RuntimeException(sprintf( 'Missing Search.Search behavior on %s', get_class($repository) )); } $filterParams = ['search' => $this->_request()->getQuery('filter')]; $filterParams['collection'] = $this->getConfig('collection'); $event->getSubject()->query->find('search', $filterParams); } }
Modify sms format in sms receiving event SMS parsing logic uses wildcard to ignore institute name.
package in.testpress.testpress.events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer; public class SmsReceivingEvent extends BroadcastReceiver { public String code; private Timer timer; public SmsReceivingEvent(Timer timer) { this.timer = timer; } @Override public void onReceive(Context context, Intent intent) { // Retrieves a map of extended data from the intent. final Bundle bundle = intent.getExtras(); try { if (bundle != null) { final Object[] pdusObj = (Object[]) bundle.get("pdus"); SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]); String senderNum = currentMessage.getDisplayOriginatingAddress(); if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress String smsContent = currentMessage.getDisplayMessageBody(); //get the code from smsContent code = smsContent.replaceAll(".*(?=.*)(?<=Your authorization code is )([^\n]*)(?=.).*", "$1"); timer.cancel(); timer.onFinish(); } } // bundle is null } catch (Exception e) { timer.cancel(); timer.onFinish(); } } }
package in.testpress.testpress.events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import in.testpress.testpress.R; import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer; import in.testpress.testpress.core.Constants; public class SmsReceivingEvent extends BroadcastReceiver { public String code; private Timer timer; public SmsReceivingEvent(Timer timer) { this.timer = timer; } @Override public void onReceive(Context context, Intent intent) { // Retrieves a map of extended data from the intent. final Bundle bundle = intent.getExtras(); try { if (bundle != null) { final Object[] pdusObj = (Object[]) bundle.get("pdus"); SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]); String senderNum = currentMessage.getDisplayOriginatingAddress(); if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress String smsContent = currentMessage.getDisplayMessageBody(); //get the code from smsContent code = smsContent.replaceAll(".*(?<=Thank you for registering at +"+Constants.Http.URL_BASE +"+. Your authorization code is )([^\n]*)(?=.).*", "$1"); timer.cancel(); timer.onFinish(); } } // bundle is null } catch (Exception e) { timer.cancel(); timer.onFinish(); } } }
Validate author_id and return 404 for missing data
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from uuid import UUID from changes.api.base import APIView from changes.api.auth import get_current_user from changes.models import Author, Build class AuthorBuildIndexAPIView(APIView): def _get_author(self, author_id): if author_id == 'me': user = get_current_user() if user is None: return None return Author.query.filter_by(email=user.email).first() try: author_id = UUID(author_id) except ValueError: return None return Author.query.get(author_id) def get(self, author_id): if author_id == 'me' and not get_current_user(): return '', 401 author = self._get_author(author_id) if not author: return '', 404 queryset = Build.query.options( joinedload('project'), joinedload('author'), joinedload('source').joinedload('revision'), ).filter( Build.author_id == author.id, ).order_by(Build.date_created.desc(), Build.date_started.desc()) return self.paginate(queryset) def get_stream_channels(self, author_id): author = self._get_author(author_id) if not author: return [] return ['authors:{0}:builds'.format(author.id.hex)]
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.api.auth import get_current_user from changes.models import Author, Build class AuthorBuildIndexAPIView(APIView): def _get_author(self, author_id): if author_id == 'me': user = get_current_user() if user is None: return return Author.query.filter_by(email=user.email).first() return Author.query.get(author_id) def get(self, author_id): if author_id == 'me' and not get_current_user(): return '', 401 author = self._get_author(author_id) if not author: return self.respond([]) queryset = Build.query.options( joinedload('project'), joinedload('author'), joinedload('source').joinedload('revision'), ).filter( Build.author_id == author.id, ).order_by(Build.date_created.desc(), Build.date_started.desc()) return self.paginate(queryset) def get_stream_channels(self, author_id): author = self._get_author(author_id) if not author: return [] return ['authors:{0}:builds'.format(author.id.hex)]
Add url in debug errors
const { Readable } = require('stream') const convertSDataError = require('./convertSDataError.js') class FindStream extends Readable { constructor(request, startUrl, limit = 0) { super({objectMode: true}) this.request = request this.startUrl = startUrl this.limit = limit this.numRetrieved = 0 } _read(n) { if(!this.isReading) { this.isReading = true this.startReading() } } startReading() { this.request.get(this.startUrl) .then(({statusCode, body}) => { if(statusCode !== 200) { this.emit('error', new Error('Invalid status code ' + statusCode)) return } for(let rec of body.$resources) { this.push(rec) this.numRetrieved++ if(this.numRetrieved === this.limit) { this.push(null) return } } if(body.$next) { this.startUrl = body.$next setImmediate(() => this.startReading()) } else { this.push(null) } }, err => { this.emit('error', convertSDataError(err, this.startUrl)) // we can't read any more, since we don't have a next link! So end the stream this.push(null) }) } } module.exports = FindStream
const { Readable } = require('stream') const convertSDataError = require('./convertSDataError.js') class FindStream extends Readable { constructor(request, startUrl, limit = 0) { super({objectMode: true}) this.request = request this.startUrl = startUrl this.limit = limit this.numRetrieved = 0 } _read(n) { if(!this.isReading) { this.isReading = true this.startReading() } } startReading() { this.request.get(this.startUrl) .then(({statusCode, body}) => { if(statusCode !== 200) { this.emit('error', new Error('Invalid status code ' + statusCode)) return } for(let rec of body.$resources) { this.push(rec) this.numRetrieved++ if(this.numRetrieved === this.limit) { this.push(null) return } } if(body.$next) { this.startUrl = body.$next setImmediate(() => this.startReading()) } else { this.push(null) } }, err => { this.emit('error', convertSDataError(err)) // we can't read any more, since we don't have a next link! So end the stream this.push(null) }) } } module.exports = FindStream
msys2-installer: Fix a comparison so only 32-bit executables are rebased Signed-off-by: Sebastian Schuberth <[email protected]>
function Component() { // constructor } Component.prototype.isDefault = function() { // select the component by default return true; } function createShortcuts() { var windir = installer.environmentVariable("WINDIR"); if (windir === "") { QMessageBox["warning"]( "Error" , "Error", "Could not find windows installation directory"); return; } var cmdLocation = windir + "\\system32\\cmd.exe"; component.addOperation( "CreateShortcut", cmdLocation, "@StartMenuDir@/MSYS2 Shell.lnk", "/A /Q /K " + installer.value("TargetDir") + "\\msys2_shell.bat"); component.addOperation( "CreateShortcut", cmdLocation, "@StartMenuDir@/MinGW-w64 Win32 Shell.lnk", "/A /Q /K " + installer.value("TargetDir") + "\\mingw32_shell.bat"); component.addOperation( "CreateShortcut", cmdLocation, "@StartMenuDir@/MinGW-w64 Win64 Shell.lnk", "/A /Q /K " + installer.value("TargetDir") + "\\mingw64_shell.bat"); if ("@BITNESS@bit" === "32bit") { component.addOperation( "Execute", ["@TargetDir@\\autorebase.bat"]); } component.addOperation( "Execute", ["@TargetDir@\\usr\\bin\\bash.exe", "--login", "-c", "exit"]); } Component.prototype.createOperations = function() { component.createOperations(); createShortcuts(); }
function Component() { // constructor } Component.prototype.isDefault = function() { // select the component by default return true; } function createShortcuts() { var windir = installer.environmentVariable("WINDIR"); if (windir === "") { QMessageBox["warning"]( "Error" , "Error", "Could not find windows installation directory"); return; } var cmdLocation = windir + "\\system32\\cmd.exe"; component.addOperation( "CreateShortcut", cmdLocation, "@StartMenuDir@/MSYS2 Shell.lnk", "/A /Q /K " + installer.value("TargetDir") + "\\msys2_shell.bat"); component.addOperation( "CreateShortcut", cmdLocation, "@StartMenuDir@/MinGW-w64 Win32 Shell.lnk", "/A /Q /K " + installer.value("TargetDir") + "\\mingw32_shell.bat"); component.addOperation( "CreateShortcut", cmdLocation, "@StartMenuDir@/MinGW-w64 Win64 Shell.lnk", "/A /Q /K " + installer.value("TargetDir") + "\\mingw64_shell.bat"); if ("@BITNESS@bit" === "@BITNESS@bit") { component.addOperation( "Execute", ["@TargetDir@\\autorebase.bat"]); } component.addOperation( "Execute", ["@TargetDir@\\usr\\bin\\bash.exe", "--login", "-c", "exit"]); } Component.prototype.createOperations = function() { component.createOperations(); createShortcuts(); }
Add "requires" entry to .jshintrc entry in blueprint (overlooked in previous commit)
/* globals module */ var EOL = require('os').EOL; module.exports = { description: 'Register test helpers', afterInstall: function( options ) { // Import statement var firstFile = 'tests/helpers/start-app.js', firstText = "import slregisterTestHelpers from './sl/register-test-helpers';", firstLocationText = "import Ember from 'ember';" + EOL, // Execution of registration function secondFile = 'tests/helpers/start-app.js', secondText = " slregisterTestHelpers();", secondLocationText = "application.setupForTesting();" + EOL, // .jshintrc file thirdFile = 'tests/.jshintrc', thirdText = ' "contains",' + EOL + ' "requires",', thirdLocationText = '"predef": [' + EOL; // Import statement return this.insertIntoFile( firstFile, firstText, { after: firstLocationText } ) // Execution of registration function .then( function() { return this.insertIntoFile( secondFile, secondText, { after: secondLocationText } ); }.bind(this)) // .jshintrc file .then( function() { return this.insertIntoFile( thirdFile, thirdText, { after: thirdLocationText } ); }.bind(this)); }, normalizeEntityName: function() {} };
/* globals module */ var EOL = require('os').EOL; module.exports = { description: 'Register test helpers', afterInstall: function( options ) { // Import statement var firstFile = 'tests/helpers/start-app.js', firstText = "import slregisterTestHelpers from './sl/register-test-helpers';", firstLocationText = "import Ember from 'ember';" + EOL, // Execution of registration function secondFile = 'tests/helpers/start-app.js', secondText = " slregisterTestHelpers();", secondLocationText = "application.setupForTesting();" + EOL, // .jshintrc file thirdFile = 'tests/.jshintrc', thirdText = ' "contains",', thirdLocationText = '"predef": [' + EOL; // Import statement return this.insertIntoFile( firstFile, firstText, { after: firstLocationText } ) // Execution of registration function .then( function() { return this.insertIntoFile( secondFile, secondText, { after: secondLocationText } ); }.bind(this)) // .jshintrc file .then( function() { return this.insertIntoFile( thirdFile, thirdText, { after: thirdLocationText } ); }.bind(this)); }, normalizeEntityName: function() {} };
Remove .close if the server error'd... older versions of Node.js throw hard errors if the server is not 'listening'.
'use strict'; var NET = require('net'); var PORTS = {}; function CreateServer( port, callback ){ if( (typeof port === 'number') ){ port = parseFloat(port); if( (PORTS[port.toString()]) ){ process.nextTick(CreateServer,port,callback); return; } PORTS[port.toString()] = true; NET.createServer() .on('error',function CreateServerError(error){ delete PORTS[port.toString()]; if(error.code === 'EADDRINUSE'){ callback(null,false,port); } else{ callback(true,error,port); } }) .listen(port,function CreateServerListening(){ this.close(function CreateServerClose(){ delete PORTS[port.toString()]; callback(null,true,port); }); }); } else if(typeof callback === 'function') callback(null,false); } module.exports = CreateServer;
'use strict'; var NET = require('net'); var PORTS = {}; function CreateServer( port, callback ){ if( (typeof port === 'number') ){ port = parseFloat(port); if( (PORTS[port.toString()]) ){ process.nextTick(CreateServer,port,callback); return; } PORTS[port.toString()] = true; NET.createServer() .on('error',function CreateServerError(error){ this.close(function CreateServerErrorClose(){ delete PORTS[port.toString()]; if(error.code === 'EADDRINUSE'){ callback(null,false,port); } else{ callback(true,error,port); } }); }) .listen(port,function CreateServerListening(){ this.close(function CreateServerListeningClose(){ delete PORTS[port.toString()]; callback(null,true,port); }); }); } else if(typeof callback === 'function') callback(null,false); } module.exports = CreateServer;
Implement selecting template by quick panel
import sublime import sublime_plugin class ProjectTemplateCommand(sublime_plugin.WindowCommand): SETTINGS_FILE_NAME = 'ProjectTemplate.sublime-settings' TEMPLATES_KEY = 'templates' def run(self): # Check whether the folder is open only one in the current window. folders = self.window.folders() msg = None if len(folders) == 0: msg = "No floder opened in the current window." elif len(folders) > 1: msg = "Multiple folder opened in the current window." if msg: sublime.error_message(msg) return self.folder = folders[0] # Load settings settings = sublime.load_settings(self.SETTINGS_FILE_NAME) self.templates = settings.get(self.TEMPLATES_KEY, {}) # Check the format of templates if type(self.templates) != dict: sublime.error_message("The templates should be an object.") return for name, template in self.templates.items(): if type(template) != dict: msg = ( "Template '%s' is not a object.\n" "Each of the template should be an object." ) % (name) sublime.error_message(msg) return # Show quick panel for selecting template self.template_names = list(self.templates.keys()) self.window.show_quick_panel(self.template_names, self.on_selected) def on_selected(self, idx): if idx < 0: # No template selected return template_name = self.template_names[idx] print(template_name)
import sublime import sublime_plugin class ProjectTemplateCommand(sublime_plugin.WindowCommand): SETTINGS_FILE_NAME = 'ProjectTemplate.sublime-settings' TEMPLATES_KEY = 'templates' def run(self): # Check whether the folder is open only one in the current window. folders = self.window.folders() msg = None if len(folders) == 0: msg = "No floder opened in the current window." elif len(folders) > 1: msg = "Multiple folder opened in the current window." if msg: sublime.error_message(msg) return self.folder = folders[0] # Load settings settings = sublime.load_settings(self.SETTINGS_FILE_NAME) self.templates = settings.get(self.TEMPLATES_KEY, {}) # Check the format of templates if type(self.templates) != dict: sublime.error_message("The templates should be an object.") return for name, template in self.templates.values(): if type(template) != dict: msg = ( "Template '%s' is not a object.\n" "Each of the template should be an object." ) % (name) sublime.error_message(msg) return
CA-40618: Change path to the supplemental pack Signed-off-by: Javier Alvarez-Valle <[email protected]>
import subprocess, sys, os.path class DRAC_NO_SUPP_PACK(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) class DRAC_POWERON_FAILED(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) def run2(command): run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return out, err = [ e.splitlines() for e in run.communicate() ] return run.returncode, out, err drac_path='/opt/dell/srvadmin/sbin/racadm' def DRAC( power_on_ip, user, password): if( not os.path.exists(drac_path)): raise DRAC_NO_SUPP_PACK() cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password) retcode,out,err=run2(cmd) if(len(err)==0): return str(True) else: raise DRAC_POWERON_FAILED() def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print DRAC(ip,user,password) if __name__ == "__main__": main()
import subprocess, sys, os.path class DRAC_NO_SUPP_PACK(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) class DRAC_POWERON_FAILED(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) def run2(command): run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return out, err = [ e.splitlines() for e in run.communicate() ] return run.returncode, out, err drac_path='/usr/sbin/racadm' def DRAC( power_on_ip, user, password): if( not os.path.exists(drac_path)): raise DRAC_NO_SUPP_PACK() cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password) retcode,out,err=run2(cmd) if(len(err)==0): return str(True) else: raise DRAC_POWERON_FAILED() def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print DRAC(ip,user,password) if __name__ == "__main__": main()
Tweak some config with no real rhyme or reason
'use strict'; var plusOrMinusMax = function (value) { return (Math.random() * value * 2) - value; } var Config = { Brain: { MinHiddenLayers: 1, MaxHiddenLayers: 1, MinNodesPerHiddenLayer: 3, MaxAdditionalNodesPerHiddenLayer: 3, }, ChanceOf: { ActivationFunctionChange: .01, ConnectionWeightChange: .05, ScanRadiusChange: .03, }, Creature: { AngularMaxSpeed: Math.PI / 3, LinearMaxSpeed: 25, MaxRadius: 10, StartingScanRadius: 50, MaxStartingParts: 5, MaxRadialChange: .5, Part: { MaxRadius: 7, MaxDistanceFromCreature: 25, MaxExtendContractSpeed: 5, MaxAngularSpeed: Math.PI / 25, MinRadiusForConsumption: 1, }, }, Fluxuation: { RandomConnectionWeightChange: () => plusOrMinusMax(.3), RandomScanRadiusChange: () => plusOrMinusMax(5), }, Mutation: { GlobalMutationRate: .5, }, World: { FoodDensity: .00015, GenerationLengthInSec: 10, MaxCreatures: 50, TickIntervalInMs: 10, ReproductionPercentile: .3, } }; module.exports = Config;
'use strict'; var coinFlip = function () { return Math.random() < 0.5; } var plusOrMinus = function (value) { return coinFlip() ? value : -value; } var plusOrMinusMax = function (value) { return (Math.random() * value * 2) - value; } var Config = { Brain: { MinHiddenLayers: 1, MaxHiddenLayers: 2, MinNodesPerHiddenLayer: 3, MaxAdditionalNodesPerHiddenLayer: 0, }, ChanceOf: { ActivationFunctionChange: .01, ConnectionWeightChange: .05, ScanRadiusChange: .03, }, Creature: { AngularMaxSpeed: Math.PI / 3, LinearMaxSpeed: 10, MaxRadius: 10, StartingScanRadius: 50, MaxStartingParts: 5, MaxRadialChange: .5, Part: { MaxRadius: 7, MaxDistanceFromCreature: 25, MaxExtendContractSpeed: 5, MaxAngularSpeed: Math.PI / 25, MinRadiusForConsumption: 1, }, }, Fluxuation: { RandomConnectionWeightChange: () => plusOrMinusMax(.1), RandomScanRadiusChange: () => plusOrMinusMax(5), }, Mutation: { GlobalMutationRate: .5, }, World: { FoodDensity: .0002, GenerationLengthInSec: 10, MaxCreatures: 50, TickIntervalInMs: 10, ReproductionPercentile: .5, } }; module.exports = Config;
Set isFinished to true when timed out, end on interrupt
package org.robockets.stronghold.robot.intake; import org.robockets.stronghold.robot.Robot; import edu.wpi.first.wpilibj.command.Command; /** * A Command to spin the intake motor forward or backward */ public class ManualVerticalIntake extends Command { public Direction direction; //Object for the Direction enum int time; //Used to set timeout /** * Initalizes some variables * * @param direction Used to initalize Direction enum * @param time Takes input for time * */ public ManualVerticalIntake(Direction direction, int time) { requires(Robot.intake); this.direction = direction; this.time = time; } // Called just before this Command runs the first time protected void initialize() { setTimeout(time); } // Called repeatedly when this Command is scheduled to run protected void execute() { if (direction == Direction.UP) { Robot.intake.moveUp(); } else if(direction == Direction.DOWN){ Robot.intake.moveDown(); } else { Robot.intake.stopVertical(); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { if(isTimedOut()){ return true; } return false; } // Called once after isFinished returns true protected void end() { Robot.intake.stopVertical(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { end(); } }
package org.robockets.stronghold.robot.intake; import org.robockets.stronghold.robot.Robot; import edu.wpi.first.wpilibj.command.Command; /** * A Command to spin the intake motor forward or backward */ public class ManualVerticalIntake extends Command { public Direction direction; //Object for the Direction enum int time; //Used to set timeout /** * Initalizes some variables * * @param direction Used to initalize Direction enum * @param time Takes input for time * */ public ManualVerticalIntake(Direction direction, int time) { requires(Robot.intake); this.direction = direction; this.time = time; } // Called just before this Command runs the first time protected void initialize() { setTimeout(time); } // Called repeatedly when this Command is scheduled to run protected void execute() { if (direction == Direction.UP) { Robot.intake.moveUp(); } else if(direction == Direction.DOWN){ Robot.intake.moveDown(); } else { Robot.intake.stopVertical(); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { Robot.intake.stopVertical(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
Remove any existing DKIM signature and set the Sender: header before sending.
from __future__ import print_function from ses import email_message_from_s3_bucket, event_msg_is_to_command, msg_get_header, recipient_destination_overlap from cnc import handle_command import boto3 ses = boto3.client('ses') from config import email_bucket from listcfg import ListConfiguration def lambda_handler(event, context): with email_message_from_s3_bucket(event, email_bucket) as msg: # If it's a command, handle it as such. command_address = event_msg_is_to_command(event, msg) if command_address: print('Message addressed to command ({}).'.format(command_address)) handle_command(command_address, msg) return del msg['DKIM-Signature'] print('Message from {}.'.format(msg_get_header(msg, 'from'))) # See if the message was sent to any known lists. for addr in recipient_destination_overlap(event): print('Looking for list {}...'.format(addr)) try: cfg = ListConfiguration(addr) except: continue print('Found list {}.'.format(addr)) del msg['Sender'] msg['Sender'] = cfg.address for user, flags in cfg.config['users'].iteritems(): print('> Sending to user {}.'.format(user)) ses.send_raw_email( Source=cfg.address, Destinations=[ user, ], RawMessage={ 'Data': msg.as_string(), }, )
from __future__ import print_function from ses import email_message_from_s3_bucket, event_msg_is_to_command, recipient_destination_overlap from cnc import handle_command import boto3 ses = boto3.client('ses') from config import email_bucket from listcfg import ListConfiguration def lambda_handler(event, context): with email_message_from_s3_bucket(event, email_bucket) as msg: # If it's a command, handle it as such. command_address = event_msg_is_to_command(event, msg) if command_address: print('Message addressed to command ({}).'.format(command_address)) handle_command(command_address, msg) return # See if the message was sent to any known lists. for addr in recipient_destination_overlap(event): print('Looking for list {}...'.format(addr)) try: cfg = ListConfiguration(addr) except: continue print('Found list {}.'.format(addr)) for user, flags in cfg.config['users'].iteritems(): print('> Sending to user {}.'.format(user)) ses.send_raw_email( Source=cfg.address, Destinations=[ user, ], RawMessage={ 'Data': msg.as_string(), }, )
Use CC0 and Public Domain for license
from setuptools import setup, find_packages import os from subprocess import call from setuptools import Command from distutils.command.build_ext import build_ext as _build_ext from setuptools.command.bdist_egg import bdist_egg as _bdist_egg class build_frontend(Command): """ A command class to run `frontendbuild.sh` """ description = 'build front-end JavaScript and CSS' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): print __file__ call(['./frontendbuild.sh'], cwd=os.path.dirname(os.path.abspath(__file__))) class build_ext(_build_ext): """ A build_ext subclass that adds build_frontend """ def run(self): self.run_command('build_frontend') _build_ext.run(self) class bdist_egg(_bdist_egg): """ A bdist_egg subclass that runs build_frontend """ def run(self): self.run_command('build_frontend') _bdist_egg.run(self) setup( name="regulations", version="2.0.0", packages=find_packages(), cmdclass={ 'build_frontend': build_frontend, 'build_ext': build_ext, 'bdist_egg': bdist_egg, }, install_requires=[ 'django==1.8', 'lxml', 'requests' ], classifiers=[ 'License :: Public Domain', 'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication' ] )
from setuptools import setup, find_packages import os from subprocess import call from setuptools import Command from distutils.command.build_ext import build_ext as _build_ext from setuptools.command.bdist_egg import bdist_egg as _bdist_egg class build_frontend(Command): """ A command class to run `frontendbuild.sh` """ description = 'build front-end JavaScript and CSS' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): print __file__ call(['./frontendbuild.sh'], cwd=os.path.dirname(os.path.abspath(__file__))) class build_ext(_build_ext): """ A build_ext subclass that adds build_frontend """ def run(self): self.run_command('build_frontend') _build_ext.run(self) class bdist_egg(_bdist_egg): """ A bdist_egg subclass that runs build_frontend """ def run(self): self.run_command('build_frontend') _bdist_egg.run(self) setup( name="regulations", version="2.0.0", license="public domain", packages=find_packages(), cmdclass={ 'build_frontend': build_frontend, 'build_ext': build_ext, 'bdist_egg': bdist_egg, }, install_requires=[ 'django==1.8', 'lxml', 'requests' ] )
Update to pass Travis build
/* eslint-env browser */ ;(function() { try { const onMessage = ({ data }) => { if (!data.wappalyzer) { return } const { technologies } = data.wappalyzer || {} removeEventListener('message', onMessage) postMessage({ wappalyzer: { js: technologies.reduce((technologies, { name, chains }) => { chains.forEach((chain) => { const value = chain .split('.') .reduce( (value, method) => value && value instanceof Object && value.hasOwnProperty(method) ? value[method] : undefined, window ) if (value !== undefined) { technologies.push({ name, chain, value: typeof value === 'string' || typeof value === 'number' ? value : !!value }) } }) return technologies }, []) } }) } addEventListener('message', onMessage) } catch (e) { // Fail quietly } })()
/* eslint-env browser */ ;(function() { try { const onMessage = ({ data }) => { if (!data.wappalyzer) { return } const { technologies } = data.wappalyzer || {} removeEventListener('message', onMessage) postMessage({ wappalyzer: { js: technologies.reduce((technologies, { name, chains }) => { chains.forEach((chain) => { const value = chain .split('.') .reduce( (value, method) => value && value instanceof Object && value.hasOwnProperty(method) ? value[method] : undefined, window ) if (value !== undefined) { technologies.push({ name, chain, value: typeof value === 'string' || typeof value === 'number' ? value : !!value }) } }) return technologies }, []) } }) } addEventListener('message', onMessage) } catch (e) { // Fail quietly } })()
Fix wrong namespace in new test
<?php declare(strict_types=1); namespace Snc\RedisBundle\Tests\Client\Predis\Connection; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Predis\Command\KeyScan; use Predis\Connection\NodeConnectionInterface; use Predis\Connection\Parameters; use Psr\Log\LoggerInterface; use Snc\RedisBundle\Client\Predis\Connection\ConnectionWrapper; use Snc\RedisBundle\Logger\RedisLogger; class ConnectionWrapperTest extends TestCase { private MockObject $connection; private MockObject $logger; private RedisLogger $redisLogger; private ConnectionWrapper $wrapper; protected function setUp(): void { $this->connection = $this->createMock(NodeConnectionInterface::class); $this->connection->method('getParameters')->willReturn(new Parameters(['alias' => 'default'])); $this->connection->method('executeCommand')->willReturn(''); $this->redisLogger = new RedisLogger($this->logger = $this->createMock(LoggerInterface::class)); $this->wrapper = new ConnectionWrapper($this->connection); $this->wrapper->setLogger($this->redisLogger); } public function testSanitizingArguments(): void { $command = new KeyScan(); $command->setArguments([null, 'MATCH', 'foo:bar', 'COUNT', 1000]); $this->logger->expects($this->once())->method('debug')->with('Executing command "SCAN NULL \'MATCH\' \'foo:bar\' \'COUNT\' 1000"'); $this->wrapper->executeCommand($command); } }
<?php declare(strict_types=1); namespace Client\Predis\Connection; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Predis\Command\KeyScan; use Predis\Connection\NodeConnectionInterface; use Predis\Connection\Parameters; use Psr\Log\LoggerInterface; use Snc\RedisBundle\Client\Predis\Connection\ConnectionWrapper; use Snc\RedisBundle\Logger\RedisLogger; class ConnectionWrapperTest extends TestCase { private MockObject $connection; private MockObject $logger; private RedisLogger $redisLogger; private ConnectionWrapper $wrapper; protected function setUp(): void { $this->connection = $this->createMock(NodeConnectionInterface::class); $this->connection->method('getParameters')->willReturn(new Parameters(['alias' => 'default'])); $this->connection->method('executeCommand')->willReturn(''); $this->redisLogger = new RedisLogger($this->logger = $this->createMock(LoggerInterface::class)); $this->wrapper = new ConnectionWrapper($this->connection); $this->wrapper->setLogger($this->redisLogger); } public function testSanitizingArguments(): void { $command = new KeyScan(); $command->setArguments([null, 'MATCH', 'foo:bar', 'COUNT', 1000]); $this->logger->expects($this->once())->method('debug')->with('Executing command "SCAN NULL \'MATCH\' \'foo:bar\' \'COUNT\' 1000"'); $this->wrapper->executeCommand($command); } }
Change to create connection from using default connection
var mongoose = require('mongoose'); var _ = require('lodash'); var Const = require('../const.js'); var DatabaseManager = { messageModel:null, userModel:null, fileModel:null, init: function(options){ var self = this; // Connection to our chat database console.log("Connecting mongoDB " + options.chatDatabaseUrl); try{ mongoose.createConnection(options.chatDatabaseUrl, function(err){ if (err) { console.log("Failed to connect MongoDB!"); console.error(err); } else { // Defining a schema self.messageModel = require('../Models/MessageModel').init(); self.userModel = require('../Models/UserModel').init(); self.fileModel = require('../Models/FileModel').init(); } }); } catch(ex){ console.log("Failed to connect MongoDB!"); throw ex; } } } module["exports"] = DatabaseManager;
var mongoose = require('mongoose'); var _ = require('lodash'); var Const = require('../const.js'); var DatabaseManager = { messageModel:null, userModel:null, fileModel:null, init: function(options){ var self = this; // Connection to our chat database console.log("Connecting mongoDB " + options.chatDatabaseUrl); try{ mongoose.connect(options.chatDatabaseUrl, function(err){ if (err) { console.log("Failed to connect MongoDB!"); console.error(err); } else { // Defining a schema self.messageModel = require('../Models/MessageModel').init(); self.userModel = require('../Models/UserModel').init(); self.fileModel = require('../Models/FileModel').init(); } }); } catch(ex){ console.log("Failed to connect MongoDB!"); throw ex; } } } module["exports"] = DatabaseManager;
Mark filter headers in My Library for translation
from django.utils.translation import gettext as _ from .models import Language, Partner from .helpers import get_tag_choices import django_filters class PartnerFilter(django_filters.FilterSet): tags = django_filters.ChoiceFilter( # Translators: On the MyLibrary page (https://wikipedialibrary.wmflabs.org/users/my_library), this text is shown to indicate how many subject areas a collection covers. label=_("Tags"), choices=get_tag_choices(), method="tags_filter", ) languages = django_filters.ModelChoiceFilter( # Translators: On the MyLibrary page (https://wikipedialibrary.wmflabs.org/users/my_library), this text is shown to indicate how many languages a collection supports. label=_("Languages"), queryset=Language.objects.all(), ) def __init__(self, *args, **kwargs): # grab "language_code" from kwargs and then remove it so we can call super() language_code = None if "language_code" in kwargs: language_code = kwargs.get("language_code") kwargs.pop("language_code") super(PartnerFilter, self).__init__(*args, **kwargs) self.filters["tags"].extra.update({"choices": get_tag_choices(language_code)}) # Add CSS classes to style widgets self.filters["tags"].field.widget.attrs.update( {"class": "form-control form-control-sm"} ) self.filters["languages"].field.widget.attrs.update( {"class": "form-control form-control-sm"} ) class Meta: model = Partner fields = ["languages"] def tags_filter(self, queryset, name, value): return queryset.filter(new_tags__tags__contains=value)
import django_filters from .models import Language, Partner from .helpers import get_tag_choices class PartnerFilter(django_filters.FilterSet): tags = django_filters.ChoiceFilter( label="Tags", choices=get_tag_choices(), method="tags_filter" ) languages = django_filters.ModelChoiceFilter(queryset=Language.objects.all()) def __init__(self, *args, **kwargs): # grab "language_code" from kwargs and then remove it so we can call super() language_code = None if "language_code" in kwargs: language_code = kwargs.get("language_code") kwargs.pop("language_code") super(PartnerFilter, self).__init__(*args, **kwargs) self.filters["tags"].extra.update({"choices": get_tag_choices(language_code)}) # Add CSS classes to style widgets self.filters["tags"].field.widget.attrs.update( {"class": "form-control form-control-sm"} ) self.filters["languages"].field.widget.attrs.update( {"class": "form-control form-control-sm"} ) class Meta: model = Partner fields = ["languages"] def tags_filter(self, queryset, name, value): return queryset.filter(new_tags__tags__contains=value)
Fix module call and refactor
/*! * Wef * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ /** * wef module */ (function () { var wef = function () { return new wef.prototype.init(); }; wef.prototype = { constructor:wef, version:"0.0.1", init:function () { return this; } }; wef.fn = wef.prototype; wef.prototype.init.prototype = wef.prototype; wef.fn.extend = function (receiver, giver) { var tmp = receiver, property; //both must be objects if (typeof receiver === "object" && typeof giver === "object") { if (tmp === null) { tmp = {}; } if (receiver === null) { return tmp; } for (property in giver) { tmp[property] = giver[property]; } return tmp; } wef.f.error("InvalidArgumentException: incorrect argument type"); return null; }; wef.fn.isFunction = function (obj) { return typeof obj == "function"; }; wef.fn.isString = function (obj) { return typeof obj == "string"; }; wef.fn.error = function (message) { throw new Error(message); }; //registering global variable if (window.wef) { throw new Error("wef has already been defined"); } else { window.wef = wef(); } })();
/*! * Wef * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ /** * wef module */ (function(global) { var wef = function() { return new wef.prototype.init(); }; wef.prototype = { constructor:wef, version: "0.0.1", init: function() { return this; } }; wef.fn = wef.prototype; wef.prototype.init.prototype = wef.prototype; wef.fn.extend = function (receiver, giver) { var tmp = receiver; //both must be objects if (typeof receiver === "object" && typeof giver === "object") { if (tmp === null) { tmp = {}; } if (receiver === null) { return tmp; } for (var property in giver) { tmp[property] = giver[property]; } return tmp; } wef.f.error("InvalidArgumentException: incorrect argument type"); return null; }; wef.fn.isFunction = function (obj) { return typeof obj == "function"; }; wef.fn.isString = function (obj) { return typeof obj == "string"; }; wef.fn.error = function (message) { throw new Error(message); }; //registering global variable if (global.wef) { throw new Error("wef has already been defined"); } else { global.wef = wef(); } })(window);
Tweak the JSON we export
#!/usr/bin/env python # -*- encoding: utf-8 -*- import json import os import subprocess import sys def find_json_files(): for root, _, filenames in os.walk('.'): if any( d in root for d in ['/WIP', '/.terraform', '/target'] ): continue for f in filenames: if f.lower().endswith('.json'): yield os.path.join(root, f) if __name__ == '__main__': bad_files = [] for f in find_json_files(): f_contents = open(f).read() try: data = json.loads(f_contents) except ValueError as err: print(f'[ERROR] {f} - Invalid JSON? {err}') bad_files.append(f) continue json_str = json.dumps(data, indent=2) + '\n' if json_str == f_contents: print(f'[OK] {f}') else: open(f, 'w').write(json_str) print(f'[FIXED] {f}') if bad_files: print('') print('Errors in the following files:') for f in bad_files: print(f'- {f}') sys.exit(1) else: sys.exit(0)
#!/usr/bin/env python # -*- encoding: utf-8 -*- import json import os import subprocess import sys def find_json_files(): for root, _, filenames in os.walk('.'): if any( d in root for d in ['/WIP', '/.terraform', '/target'] ): continue for f in filenames: if f.lower().endswith('.json'): yield os.path.join(root, f) if __name__ == '__main__': bad_files = [] for f in find_json_files(): f_contents = open(f).read() try: data = json.loads(f_contents) except ValueError as err: print(f'[ERROR] {f} - Invalid JSON? {err}') bad_files.append(f) continue json_str = json.dumps(f_contents, indent=2, sort_keys=True) if json_str == f_contents: print(f'[OK] {f}') else: open(f, 'w').write(json_str) print(f'[FIXED] {f}') if bad_files: print('') print('Errors in the following files:') for f in bad_files: print(f'- {f}') sys.exit(1) else: sys.exit(0)
Fix locations of web resources from relative paths to absolute
var webpack = require("webpack"); var path = require("path"); var APP_DIR = path.resolve(__dirname, "src/main/web"); var BUILD_DIR = path.resolve(__dirname, "build/web/bundle"); var config = { entry: { app: [ APP_DIR + "/index.js" ] }, output: { path: BUILD_DIR, filename: "bundle.js", publicPath: "/webjars/genie-ui/" }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("production") } }) ], resolve: { extensions: [ "", ".js" ] }, module: { loaders: [ { test: /\.jsx?/, include: APP_DIR, exclude: /(node_modules|bower_components)/, loader: "babel-loader" }, { test: /\.css$/, loader: "style-loader!css-loader" }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: "url-loader?limit=100000" }, { test: /\.(ttf|svg|eot|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?name=[path][name].[ext]" } ] } }; module.exports = config;
var webpack = require("webpack"); var path = require("path"); var APP_DIR = path.resolve(__dirname, "src/main/web"); var BUILD_DIR = path.resolve(__dirname, "build/web/bundle"); var config = { entry: { app: [ APP_DIR + "/index.js" ] }, output: { path: BUILD_DIR, filename: "bundle.js", publicPath: "webjars/genie-ui/" }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("production") } }) ], resolve: { extensions: [ "", ".js" ] }, module: { loaders: [ { test: /\.jsx?/, include: APP_DIR, exclude: /(node_modules|bower_components)/, loader: "babel-loader" }, { test: /\.css$/, loader: "style-loader!css-loader" }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: "url-loader?limit=100000" }, { test: /\.(ttf|svg|eot|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?name=[path][name].[ext]" } ] } }; module.exports = config;
Implement missing halt callback method and rename actions
package router.client.api2; import java.util.List; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; public final class OnChangeCallbackChain { @Nonnull private final List<RouteEntry<OnChangeCallbackAsync>> _chain; public OnChangeCallbackChain( @Nonnull final List<RouteEntry<OnChangeCallbackAsync>> chain ) { _chain = Objects.requireNonNull( chain ); } public void onChange( @Nullable final String previousLocation, @Nonnull final Runnable abortAction, @Nonnull final Runnable nextAction ) { onChange( previousLocation, abortAction, nextAction, 0 ); } private void onChange( @Nullable final String previousLocation, @Nonnull final Runnable abortAction, @Nonnull final Runnable nextAction, final int index ) { if ( index >= _chain.size() ) { nextAction.run(); } else { final RouteEntry<OnChangeCallbackAsync> entry = _chain.get( index ); entry.getCallback().onChange( previousLocation, entry.getLocation(), new OnChangeControl() { @Override public void abort() { abortAction.run(); } @Override public void halt() { nextAction.run(); } @Override public void proceed() { onChange( previousLocation, abortAction, nextAction, index + 1 ); } } ); } } }
package router.client.api2; import java.util.List; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; public final class OnChangeCallbackChain { @Nonnull private final List<RouteEntry<OnChangeCallbackAsync>> _chain; public OnChangeCallbackChain( @Nonnull final List<RouteEntry<OnChangeCallbackAsync>> chain ) { _chain = Objects.requireNonNull( chain ); } public void onChange( @Nullable final String previousLocation, @Nonnull final Runnable abortRoute, @Nonnull final Runnable continueRoute ) { onChange( previousLocation, abortRoute, continueRoute, 0 ); } private void onChange( @Nullable final String previousLocation, @Nonnull final Runnable abortRoute, @Nonnull final Runnable continueRoute, final int index ) { if ( index >= _chain.size() ) { continueRoute.run(); } else { final RouteEntry<OnChangeCallbackAsync> entry = _chain.get( index ); entry.getCallback().onChange( previousLocation, entry.getLocation(), new OnChangeControl() { @Override public void abort() { abortRoute.run(); } @Override public void proceed() { onChange( previousLocation, abortRoute, continueRoute, index + 1 ); } } ); } } }
Use django rest framework > 3.1
from setuptools import setup, find_packages __version__ = "0.0.13" setup( # package name in pypi name='django-oscar-api', # extract version from module. version=__version__, description="REST API module for django-oscar", long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ], keywords='', author='Lars van de Kerkhof, Martijn Jacobs', author_email='[email protected], [email protected]', url='https://github.com/tangentlabs/django-oscar-api', license='BSD', # include all packages in the egg, except the test package. packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']), # for avoiding conflict have one namespace for all apc related eggs. namespace_packages=[], # include non python files include_package_data=True, zip_safe=False, # specify dependencies install_requires=[ 'setuptools', 'django-oscar>=0.6', 'djangorestframework>=3.1.0' ], # mark test target to require extras. extras_require={ 'test': ['django-nose',] }, )
from setuptools import setup, find_packages __version__ = "0.0.13" setup( # package name in pypi name='django-oscar-api', # extract version from module. version=__version__, description="REST API module for django-oscar", long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ], keywords='', author='Lars van de Kerkhof, Martijn Jacobs', author_email='[email protected], [email protected]', url='https://github.com/tangentlabs/django-oscar-api', license='BSD', # include all packages in the egg, except the test package. packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']), # for avoiding conflict have one namespace for all apc related eggs. namespace_packages=[], # include non python files include_package_data=True, zip_safe=False, # specify dependencies install_requires=[ 'setuptools', 'django-oscar>=0.6', 'djangorestframework<3.0.0' ], # mark test target to require extras. extras_require={ 'test': ['django-nose',] }, )
Update contact on form submitted
window.ContactManager = { Models: {}, Collections: {}, Views: {}, start: function(data) { var contacts = new ContactManager.Collections.Contacts(data.contacts), router = new ContactManager.Router(); router.on('route:home', function() { router.navigate('contacts', { trigger: true, replace: true }); }); router.on('route:showContacts', function() { var contactsView = new ContactManager.Views.Contacts({ collection: contacts }); $('.main-container').html(contactsView.render().$el); }); router.on('route:newContact', function() { var newContactForm = new ContactManager.Views.ContactForm({ model: new ContactManager.Models.Contact() }); newContactForm.on('form:submitted', function(attrs) { attrs.id = contacts.isEmpty() ? 1 : (_.max(contacts.pluck('id')) + 1); contacts.add(attrs); router.navigate('contacts', true); }); $('.main-container').html(newContactForm.render().$el); }); router.on('route:editContact', function(id) { var contact = contacts.get(id), editContactForm; if (contact) { editContactForm = new ContactManager.Views.ContactForm({ model: contact }); editContactForm.on('form:submitted', function(attrs) { contact.set(attrs); router.navigate('contacts', true); }); $('.main-container').html(editContactForm.render().$el); } else { router.navigate('contacts', true); } }); Backbone.history.start(); } };
window.ContactManager = { Models: {}, Collections: {}, Views: {}, start: function(data) { var contacts = new ContactManager.Collections.Contacts(data.contacts), router = new ContactManager.Router(); router.on('route:home', function() { router.navigate('contacts', { trigger: true, replace: true }); }); router.on('route:showContacts', function() { var contactsView = new ContactManager.Views.Contacts({ collection: contacts }); $('.main-container').html(contactsView.render().$el); }); router.on('route:newContact', function() { var newContactForm = new ContactManager.Views.ContactForm({ model: new ContactManager.Models.Contact() }); newContactForm.on('form:submitted', function(attrs) { attrs.id = contacts.isEmpty() ? 1 : (_.max(contacts.pluck('id')) + 1); contacts.add(attrs); router.navigate('contacts', true); }); $('.main-container').html(newContactForm.render().$el); }); router.on('route:editContact', function(id) { var contact = contacts.get(id), editContactForm; if (contact) { editContactForm = new ContactManager.Views.ContactForm({ model: contact }); $('.main-container').html(editContactForm.render().$el); } else { router.navigate('contacts', true); } }); Backbone.history.start(); } };
Add product_number and serial_number identifiers
""" So this is where all the SQL commands live """ CREATE_SQL = """ CREATE TABLE component_type ( id INT PRIMARY KEY AUTO_INCREMENT, type VARCHAR(255) UNIQUE ); CREATE TABLE components ( id INT PRIMARY KEY AUTO_INCREMENT, serial_number VARCHAR(255), sku TEXT, type INT, status INT, FOREIGN KEY (type) REFERENCES component_type(id) ); CREATE TABLE projects ( id INT PRIMARY KEY AUTO_INCREMENT, product_number INT, motherboard INT, power_supply INT, cpu INT, hard_drive INT, proj_case INT, memory INT, FOREIGN KEY (motherboard) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (cpu) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (power_supply) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (hard_drive) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (proj_case) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (memory) REFERENCES components(id) ON DELETE CASCADE ); """ ADD_COMPONENT_TYPE = """INSERT IGNORE INTO component_type (type) VALUES ('{text}') """ GET_COMPONENT_TYPE="""SELECT * FROM component_type WHERE type='{text}'""" DELETE_COMPONENT_TYPE = """DELETE FROM component_type WHERE type='{text}' """ SELECT_ALL_COMPONENTS = """ SELECT * FROM components INNER JOIN component_type ON components.type = component_type.id; """ DROP_SQL = """ DROP TABLE projects; DROP TABLE components; DROP TABLE component_type; """
""" So this is where all the SQL commands live """ CREATE_SQL = """ CREATE TABLE component_type ( id INT PRIMARY KEY AUTO_INCREMENT, type VARCHAR(255) UNIQUE ); CREATE TABLE components ( id INT PRIMARY KEY AUTO_INCREMENT, sku TEXT, type INT, status INT, FOREIGN KEY (type) REFERENCES component_type(id) ); CREATE TABLE projects ( id INT PRIMARY KEY AUTO_INCREMENT, motherboard INT, power_supply INT, cpu INT, hard_drive INT, proj_case INT, memory INT, FOREIGN KEY (motherboard) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (cpu) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (power_supply) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (hard_drive) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (proj_case) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (memory) REFERENCES components(id) ON DELETE CASCADE ); """ ADD_COMPONENT_TYPE = """INSERT IGNORE INTO component_type (type) VALUES ('{text}') """ GET_COMPONENT_TYPE="""SELECT * FROM component_type WHERE type='{text}'""" DELETE_COMPONENT_TYPE = """DELETE FROM component_type WHERE type='{text}' """ SELECT_ALL_COMPONENTS = """ SELECT * FROM components INNER JOIN component_type ON components.type = component_type.id; """ DROP_SQL = """ DROP TABLE projects; DROP TABLE components; DROP TABLE component_type; """
Add header type for geojson
var Layer = require('../models/Layer'); var getJSON = function(type, req, res) { var ops = { id: parseFloat(req.param("id")), pid: parseFloat(req.param("pid")), z: parseFloat(req.param("z")) }, box = req.param("bbox"); if (box) box = box.replace(/\s/g,'').split(','); if (!ops.id || isNaN(ops.id)) res.send(500, "Need Layer ID (id)"); if (!ops.pid || isNaN(ops.pid)) res.send(500, "Need Period ID (pid)"); if (box && box.length < 4) res.send(500, "Box needs 2 points (x1, y1, x2, y2)"); ops.p1 = box ? [box[0], box[1]] : null; ops.p2 = box ? [box[2], box[3]] : null; if (type == 'geojson') type = 'getGeoJSON'; if (type == 'topojson') type = 'getTopoJSON'; Layer[type](ops, function(err, geojson) { if (err) res.send(500, err); res.type('application/json'); res.send(JSON.stringify(geojson)); }); }; exports.geojson = function(req, res) { return getJSON("geojson", req, res); }; exports.topojson = function(req, res) { return getJSON("topojson", req, res); };
var Layer = require('../models/Layer'); var getJSON = function(type, req, res) { var ops = { id: parseFloat(req.param("id")), pid: parseFloat(req.param("pid")), z: parseFloat(req.param("z")) }, box = req.param("bbox"); if (box) box = box.replace(/\s/g,'').split(','); if (!ops.id || isNaN(ops.id)) res.send(500, "Need Layer ID (id)"); if (!ops.pid || isNaN(ops.pid)) res.send(500, "Need Period ID (pid)"); if (box && box.length < 4) res.send(500, "Box needs 2 points (x1, y1, x2, y2)"); ops.p1 = box ? [box[0], box[1]] : null; ops.p2 = box ? [box[2], box[3]] : null; if (type == 'geojson') type = 'getGeoJSON'; if (type == 'topojson') type = 'getTopoJSON'; Layer[type](ops, function(err, geojson) { if (err) res.send(500, err); res.send(JSON.stringify(geojson)); }); }; exports.geojson = function(req, res) { return getJSON("geojson", req, res); }; exports.topojson = function(req, res) { return getJSON("topojson", req, res); };
Fix : forgot to make the actual method call when reversing an IP.
import urllib import json class Geoloc(object): """ Geoloc class definition. Given an IP adress, this object will try to reverse identify the IP using a geolocalisation API. On the return, it will spit back a list with : * IP adress, * Longitude, * Latitude, * Country, * Country flag """ def __init__(self, config): """ Inits the object by registering the configuration object """ self.config = config def get(self, ip): """ Metamethod that returns the full geoloc information for a given IP adress """ geoloc = self.getLocationAPI(ip) geoloc["ip"] = ip return geoloc def getLocationAPI(self, ip): """ Makes the actual call to the external API for IP geolookup """ try: response = urllib.urlopen(config.api_endpoint % ip) info = response.read() except Exception as e: # TODO : Add some kind of logging here if config.api_parser == "json": # Just in case you use an XML API or whatever result = self.parseJSON(info) # TODO : Get country flag from a local CSS/SVG # (see : https://github.com/lipis/flag-icon-css) def parseJSON(self, info): """ Gets a JSON message and parse it to keep only the relevant parts for us """ parsed = json.loads(info) return {'lat': parsed['latitude'], 'lon': parsed['longitude'], 'country': parsed['country'], 'code': parsed['country_code3']}
import urllib import json class Geoloc(object): """ Geoloc class definition. Given an IP adress, this object will try to reverse identify the IP using a geolocalisation API. On the return, it will spit back a list with : * IP adress, * Longitude, * Latitude, * Country, * Country flag """ def __init__(self, config): """ Inits the object by registering the configuration object """ self.config = config def get(self, ip): """ Metamethod that returns the full geoloc information for a given IP adress """ geoloc["ip"] = ip return geoloc def getLocationAPI(self, ip): """ Makes the actual call to the external API for IP geolookup """ try: response = urllib.urlopen(config.api_endpoint % ip) info = response.read() except Exception as e: # TODO : Add some kind of logging here if config.api_parser == "json": # Just in case you use an XML API or whatever result = self.parseJSON(info) # TODO : Get country flag from a local CSS/SVG # (see : https://github.com/lipis/flag-icon-css) def parseJSON(self, info): """ Gets a JSON message and parse it to keep only the relevant parts for us """ parsed = json.loads(info) return {'lat': parsed['latitude'], 'lon': parsed['longitude'], 'country': parsed['country'], 'code': parsed['country_code3']}
Fix json parsing for Python 3
import json from ffmpy import FF class FFprobe(FF): """ Wrapper for `ffprobe <https://www.ffmpeg.org/ffprobe.html>`_. Utilizes ffmpeg `pipe protocol <https://www.ffmpeg.org/ffmpeg-protocols.html#pipe>`_. Input data (as a byte string) is passed to ffprobe on standard input. Result is presented in JSON format. """ def __init__(self, executable='ffprobe', global_options='', inputs=None): """Create an instance of FFprobe. :param str executable: absolute path to ffprobe executable :param list, str global_options: global options passed to ffmpeg executable :param dict inputs: a dictionary specifying one or more inputs as keys with their corresponding options as values """ super(FFprobe, self).__init__( executable=executable, global_options=global_options, inputs=inputs ) def run(self, input_data=None): """Run ffprobe command and return its output. If the command line contains `-print_format json` also parses the JSON output and deserializes it into a dictionary. :param str input_data: media (audio, video, transport stream) data as a byte string (e.g. the result of reading a file in binary mode) :return: dictionary describing the input media :rtype: dict """ output = super(FFprobe, self).run(input_data) if '-print_format json' in self.cmd_str: output = json.loads(output.decode()) # TODO: Convert all "numeric" strings to int/float return output
import json from ffmpy import FF class FFprobe(FF): """ Wrapper for `ffprobe <https://www.ffmpeg.org/ffprobe.html>`_. Utilizes ffmpeg `pipe protocol <https://www.ffmpeg.org/ffmpeg-protocols.html#pipe>`_. Input data (as a byte string) is passed to ffprobe on standard input. Result is presented in JSON format. """ def __init__(self, executable='ffprobe', global_options='', inputs=None): """Create an instance of FFprobe. :param str executable: absolute path to ffprobe executable :param list, str global_options: global options passed to ffmpeg executable :param dict inputs: a dictionary specifying one or more inputs as keys with their corresponding options as values """ super(FFprobe, self).__init__( executable=executable, global_options=global_options, inputs=inputs ) def run(self, input_data=None): """Run ffprobe command and return its output. If the command line contains `-print_format json` also parses the JSON output and deserializes it into a dictionary. :param str input_data: media (audio, video, transport stream) data as a byte string (e.g. the result of reading a file in binary mode) :return: dictionary describing the input media :rtype: dict """ output = super(FFprobe, self).run(input_data) if '-print_format json' in self.cmd_str: output = json.loads(output) # TODO: Convert all "numeric" strings to int/float return output
Add missing MySQL 8.0 keywords
<?php namespace Doctrine\DBAL\Platforms\Keywords; use function array_merge; /** * MySQL 8.0 reserved keywords list. */ class MySQL80Keywords extends MySQL57Keywords { /** * {@inheritdoc} */ public function getName() { return 'MySQL80'; } /** * {@inheritdoc} * * @link https://dev.mysql.com/doc/refman/8.0/en/keywords.html */ protected function getKeywords() { $keywords = parent::getKeywords(); $keywords = array_merge($keywords, [ 'ADMIN', 'ARRAY', 'CUBE', 'CUME_DIST', 'DENSE_RANK', 'EMPTY', 'EXCEPT', 'FIRST_VALUE', 'FUNCTION', 'GROUPING', 'GROUPS', 'JSON_TABLE', 'LAG', 'LAST_VALUE', 'LATERAL', 'LEAD', 'MEMBER', 'NTH_VALUE', 'NTILE', 'OF', 'OVER', 'PERCENT_RANK', 'PERSIST', 'PERSIST_ONLY', 'RANK', 'RECURSIVE', 'ROW', 'ROWS', 'ROW_NUMBER', 'SYSTEM', 'WINDOW', ]); return $keywords; } }
<?php namespace Doctrine\DBAL\Platforms\Keywords; use function array_merge; /** * MySQL 8.0 reserved keywords list. */ class MySQL80Keywords extends MySQL57Keywords { /** * {@inheritdoc} */ public function getName() { return 'MySQL80'; } /** * {@inheritdoc} * * @link https://dev.mysql.com/doc/refman/8.0/en/keywords.html */ protected function getKeywords() { $keywords = parent::getKeywords(); $keywords = array_merge($keywords, [ 'ADMIN', 'CUBE', 'CUME_DIST', 'DENSE_RANK', 'EMPTY', 'EXCEPT', 'FIRST_VALUE', 'FUNCTION', 'GROUPING', 'GROUPS', 'JSON_TABLE', 'LAG', 'LAST_VALUE', 'LEAD', 'NTH_VALUE', 'NTILE', 'OF', 'OVER', 'PERCENT_RANK', 'PERSIST', 'PERSIST_ONLY', 'RANK', 'RECURSIVE', 'ROW', 'ROWS', 'ROW_NUMBER', 'SYSTEM', 'WINDOW', ]); return $keywords; } }
Change the way we get a clean, blank line before rendering letter bank
from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | O | | | | | / | | --------- """) def render_bank(letters=[], **kw): sz = 6 # Size of table if not any(letters): let = [' '] else: let = sorted(list(letters)) table = SingleTable([let[i:i + sz] for i in range(0, len(let), sz)], 'Incorrect Guesses') table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns = {idx: val for idx, val in enumerate(['center'] * sz)} print("\n{}".format(table.table)) def render_game_state(word="", found=[], **kw): for letter in word: if letter in found: print(letter, end='') else: print(' _ ', end='')
from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | O | | | | | / | | --------- """) def render_bank(letters=[], **kw): sz = 6 # Size of table if not any(letters): let = [' '] else: let = sorted(list(letters)) table = SingleTable([let[i:i + sz] for i in range(0, len(let), sz)], 'Incorrect Guesses') table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns = {idx: val for idx, val in enumerate(['center'] * sz)} print() print(table.table) def render_game_state(word="", found=[], **kw): for letter in word: if letter in found: print(letter, end='') else: print(' _ ', end='')
Add override settings for CI without local settings.
from django.test import override_settings from mock import patch from sms.tests.test_sms import GarfieldTwilioTestCase from sms.tests.test_sms import GarfieldTwilioTestClient @override_settings(TWILIO_PHONE_NUMBER="+15558675309") class GarfieldTestSimSmsCaseNewJohn(GarfieldTwilioTestCase): @patch('sms.tasks.save_sms_message.apply_async') def test_sim_receive_sms(self, mock_save_sms_message): response = self.client.sms("Test.", path="/sims/sms/receive/") self.assert_twiml(response) self.assertTrue(mock_save_sms_message.called) @patch('sms.tasks.save_sms_message.apply_async') def test_sim_send_sms(self, mock_save_sms_message): response = self.client.sms("Test.", path="/sims/sms/send/") self.assert_twiml(response) self.assertTrue(mock_save_sms_message.called) @override_settings(TWILIO_PHONE_NUMBER="+15558675309") class GarfieldTestSimVoiceCase(GarfieldTwilioTestCase): def test_sims_receive_call(self): response = self.client.call("Test.", path="/sims/voice/receive/") self.assert_twiml(response) def test_sims_send_call(self): response = self.client.call("Test.", path="/sims/voice/send/") self.assert_twiml(response)
from mock import patch from sms.tests.test_sms import GarfieldTwilioTestCase from sms.tests.test_sms import GarfieldTwilioTestClient class GarfieldTestSimSmsCaseNewJohn(GarfieldTwilioTestCase): @patch('sms.tasks.save_sms_message.apply_async') def test_sim_receive_sms(self, mock_save_sms_message): response = self.client.sms("Test.", path="/sims/sms/receive/") self.assert_twiml(response) self.assertTrue(mock_save_sms_message.called) @patch('sms.tasks.save_sms_message.apply_async') def test_sim_send_sms(self, mock_save_sms_message): response = self.client.sms("Test.", path="/sims/sms/send/") self.assert_twiml(response) self.assertTrue(mock_save_sms_message.called) class GarfieldTestSimVoiceCase(GarfieldTwilioTestCase): def test_sims_receive_call(self): response = self.client.call("Test.", path="/sims/voice/receive/") self.assert_twiml(response) def test_sims_send_call(self): response = self.client.call("Test.", path="/sims/voice/send/") self.assert_twiml(response)
Allow the user to set the working directory.
'use strict'; const { exec } = require('child_process'); const branchName = (option) => { const config = Object.assign({}, option); return new Promise((resolve, reject) => { exec('git symbolic-ref --short HEAD', { cwd : config.cwd }, (err, stdout, stderr) => { if (err) { err.stderr = stderr; reject(err); return; } resolve(stdout.trimRight()); }); }); }; // Get the current branch name, unless one is not available, in which case // return the provided branch as a fallback. branchName.assume = (assumedName, option) => { return branchName(option).catch((err) => { const problem = err.stderr.substring('fatal; '.length); const noBranchErrors = [ 'Not a git repository', 'ref HEAD is not a symbolic ref' ]; const matchProblem = (scenario) => { return problem.startsWith(scenario); }; if (noBranchErrors.some(matchProblem)) { return assumedName; } throw err; }); }; // Master is a nice fallback assumption because it is // the default branch name in git. branchName.assumeMaster = (option) => { return branchName.assume('master', option); }; module.exports = branchName;
'use strict'; const { exec } = require('child_process'); const get = () => { return new Promise((resolve, reject) => { exec('git symbolic-ref --short HEAD', (err, stdout, stderr) => { if (err) { err.stderr = stderr; reject(err); return; } resolve(stdout.trimRight()); }); }); }; // Get the current branch name, unless one is not available, in which case // return the provided branch as a fallback. const assume = (assumedName) => { return get().catch((err) => { const problem = err.stderr.substring('fatal; '.length); const noBranchErrors = [ 'Not a git repository', 'ref HEAD is not a symbolic ref' ]; const matchProblem = (scenario) => { return problem.startsWith(scenario); }; if (noBranchErrors.some(matchProblem)) { return assumedName; } throw err; }); }; // Master is a nice fallback assumption because it is // the default branch name in git. const assumeMaster = () => { return assume('master'); }; module.exports = { get, assume, assumeMaster };
Fix bug in config test
import unittest import yaml import keepaneyeon.config from keepaneyeon.http import HttpDownloader class TestConfig(unittest.TestCase): def test_register(self): # custom type we want to load from YAML class A(): def __init__(self, **opts): self.opts = opts # YAML loader we will customize class CustomLoader(yaml.Loader): pass # register our new type keepaneyeon.config.register(CustomLoader, 'a', A) # parse some YAML config_string = """ - !a k1: v1 k2: v2 """ parsed = yaml.load(config_string, Loader=CustomLoader) self.assertEqual(len(parsed), 1) self.assertIsInstance(parsed[0], A) self.assertEqual(parsed[0].opts['k1'], 'v1') self.assertEqual(parsed[0].opts['k2'], 'v2') def test_load(self): # test loading one of our registered types config_string = """ - !downloader/http k1: v1 k2: v2 """ parsed = keepaneyeon.config.load(config_string) self.assertEqual(len(parsed), 1) self.assertIsInstance(parsed[0], HttpDownloader) self.assertEqual(parsed[0].base['k1'], 'v1') self.assertEqual(parsed[0].base['k2'], 'v2')
import unittest import yaml import keepaneyeon.config from keepaneyeon.http import HttpDownloader class TestConfig(unittest.TestCase): def test_register(self): # custom type we want to load from YAML class A(): def __init__(self, **opts): self.opts = opts # YAML loader we will customize class CustomLoader(yaml.Loader): pass # register our new type keepaneyeon.config.register(CustomLoader, 'a', A) # parse some YAML config_sting = """ - !a k1: v1 k2: v2 """ parsed = yaml.load(config_string, Loader=CustomLoader) self.assertEqual(len(parsed), 1) self.assertIsInstance(parsed[0], A) self.assertEqual(parsed[0].opts['k1'], 'v1') self.assertEqual(parsed[0].opts['k2'], 'v2') def test_load(self): # test loading one of our registered types config_string = """ - !downloader/http k1: v1 k2: v2 """ parsed = keepaneyeon.config.load(config_string) self.assertEqual(len(parsed), 1) self.assertIsInstance(parsed[0], HttpDownloader) self.assertEqual(parsed[0].base['k1'], 'v1') self.assertEqual(parsed[0].base['k2'], 'v2')
Print the URL that erred out, along with the other info
import asyncio import aiohttp import logging log = logging.getLogger(__name__) @asyncio.coroutine def http_get_auth_request(auth_string, url, content_type="application/json", auth_method="Token", payload={}): headers = { 'Content-type': content_type, 'Authorization': "%s %s" % (auth_method, auth_string), } response = yield from aiohttp.get(url, headers=headers, params=payload) if not response.status == 200: text = yield from response.text() log.error("URL: %s" % url) log.error("Response status code was %s" % str(response.status)) log.error(response.headers) log.error(text) response.close() return "" return (yield from response.text()) @asyncio.coroutine def http_get_request(url, content_type="application/json"): headers = { 'Content-type': content_type, } response = yield from aiohttp.get(url, headers=headers) if not response.status == 200: text = yield from response.text() log.error("URL: %s" % url) log.error("Response status code was %s" % str(response.status)) log.error(response.headers) log.error(text) response.close() return "" return (yield from response.text())
import asyncio import aiohttp import logging log = logging.getLogger(__name__) @asyncio.coroutine def http_get_auth_request(auth_string, url, content_type="application/json", auth_method="Token", payload={}): headers = { 'Content-type': content_type, 'Authorization': "%s %s" % (auth_method, auth_string), } response = yield from aiohttp.get(url, headers=headers, params=payload) if not response.status == 200: text = yield from response.text() log.error("Response status code was %s" % str(response.status)) log.error(response.headers) log.error(text) response.close() return "" return (yield from response.text()) @asyncio.coroutine def http_get_request(url, content_type="application/json"): headers = { 'Content-type': content_type, } response = yield from aiohttp.get(url, headers=headers) if not response.status == 200: text = yield from response.text() log.error("Response status code was %s" % str(response.status)) log.error(response.headers) log.error(text) response.close() return "" return (yield from response.text())
Add button that toggles `<Pic>` to make it easier to develop for unmount
'use strict'; import React, { Component } from 'react'; import Pic from '../lib/index.js'; export default class Playground extends Component { constructor(props) { super(props); this.state = { show: true }; this.clickHandler = this.clickHandler.bind(this); } clickHandler() { this.setState({show:!this.state.show}); } render() { return ( <html> <head> <meta charSet='UTF-8' /> <title>react-pic</title> </head> <body> <div id="root" style={{height:1500}}> <button onClick={this.clickHandler}> Toggle </button> { this.state.show && <Pic alt='winky face' images={[ { width: 40, url: 'http://placehold.it/40?text=😉' }, { width: 200, url: 'http://placehold.it/200?text=😉' }, { width: 400, url: 'http://placehold.it/400?text=😉' }, { width: 600, url: 'http://placehold.it/600?text=😉' }, { width: 800, url: 'http://placehold.it/800?text=😉' } ]} /> } </div> <script src='//localhost:8080/build/react-pic.js' /> </body> </html> ); } }
'use strict'; import React, { Component } from 'react'; import Pic from '../lib/index.js'; export default class Playground extends Component { render() { return ( <html> <head> <meta charSet='UTF-8' /> <title>react-pic</title> </head> <body> <div id="root"> <Pic alt='winky face' images={[ { width: 40, url: 'http://placehold.it/40?text=😉' }, { width: 200, url: 'http://placehold.it/200?text=😉' }, { width: 400, url: 'http://placehold.it/400?text=😉' }, { width: 600, url: 'http://placehold.it/600?text=😉' }, { width: 800, url: 'http://placehold.it/800?text=😉' } ]} /> </div> <script src='//localhost:8080/build/react-pic.js' /> </body> </html> ); } }
Add a double requestAnimationFrame to count paint performance
import {PureComponent} from 'react'; import parseDiff from 'parse-diff'; import File from './File'; import './App.css'; /* eslint-disable no-console */ export default class App extends PureComponent { state = { diff: null, viewType: 'split' }; async componentDidMount() { const response = await fetch('assets/large.diff'); const text = await response.text(); console.time('parse'); const diff = parseDiff(text); console.timeEnd('parse'); this.setState({diff}); } componentWillUpdate() { console.time('render'); } componentDidUpdate() { console.timeEnd('render'); console.time('paint'); requestAnimationFrame(() => requestAnimationFrame(() => console.timeEnd('paint'))); } switchViewType() { const {viewType} = this.state; this.setState({viewType: viewType === 'unified' ? 'split' : 'unified'}); } render() { const {diff, viewType} = this.state; if (!diff) { return <div />; } return ( <div className="app"> <header> <button className="switch" onClick={::this.switchViewType}> 切换至{viewType === 'unified' ? '双列' : '单列'}视图 </button> </header> <div> {diff.map((file, i) => <File key={i} {...file} viewType={viewType} />)} </div> </div> ); } }
import {PureComponent} from 'react'; import parseDiff from 'parse-diff'; import File from './File'; import './App.css'; /* eslint-disable no-console */ export default class App extends PureComponent { state = { diff: null, viewType: 'split' }; async componentDidMount() { const response = await fetch('assets/small.diff'); const text = await response.text(); console.time('parse'); const diff = parseDiff(text); console.timeEnd('parse'); this.setState({diff}); } componentWillUpdate() { console.time('render'); } componentDidUpdate() { console.timeEnd('render'); } switchViewType() { const {viewType} = this.state; this.setState({viewType: viewType === 'unified' ? 'split' : 'unified'}); } render() { const {diff, viewType} = this.state; if (!diff) { return <div />; } return ( <div className="app"> <header> <button className="switch" onClick={::this.switchViewType}> 切换至{viewType === 'unified' ? '双列' : '单列'}视图 </button> </header> <div> {diff.map((file, i) => <File key={i} {...file} viewType={viewType} />)} </div> </div> ); } }
Fix duplicate cookie issue and header parsing
import time import requests import bs4 import cgi from databot.recursive import call class DownloadErrror(Exception): pass def dump_response(response): return { 'headers': dict(response.headers), 'cookies': response.cookies.get_dict(), 'status_code': response.status_code, 'encoding': response.encoding, 'content': response.content, } def download(url, delay=None, update=None, **kwargs): update = update or {} def func(row): if delay is not None: time.sleep(delay) kw = call(kwargs, row) _url = url(row) response = requests.get(_url, **kw) if response.status_code == 200: value = dump_response(response) for k, fn in update.items(): value[k] = fn(row) yield _url, value else: raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % ( _url, response.status_code, response.content, )) return func def get_content(data): content_type_header = data.get('headers', {}).get('Content-Type', '') content_type, params = cgi.parse_header(content_type_header) if content_type == 'text/html': soup = bs4.BeautifulSoup(data['content'], 'lxml') return data['content'].decode(soup.original_encoding) else: return data['content']
import time import requests import bs4 from databot.recursive import call class DownloadErrror(Exception): pass def dump_response(response): return { 'headers': dict(response.headers), 'cookies': dict(response.cookies), 'status_code': response.status_code, 'encoding': response.encoding, 'content': response.content, } def download(url, delay=None, update=None, **kwargs): update = update or {} def func(row): if delay is not None: time.sleep(delay) kw = call(kwargs, row) _url = url(row) response = requests.get(_url, **kw) if response.status_code == 200: value = dump_response(response) for k, fn in update.items(): value[k] = fn(row) yield _url, value else: raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % ( _url, response.status_code, response.content, )) return func def get_content(data): content_type = data.get('headers', {}).get('Content-Type') if content_type == 'text/html': soup = bs4.BeautifulSoup(data['content'], 'lxml') return data['content'].decode(soup.original_encoding) else: return data['content']
Add Value Link Prop To Textarea Component Add value link prop to textarea component in order to use with ReactLink Addon.
let React = require("react") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, textarea} = React.DOM let cx = require("classnames") export default class extends React.Component { static displayName = "Frig.friggingBootstrap.Text" static defaultProps = Object.assign(require("../default_props.js")) constructor(props) { super(props) this.state = { errors: undefined, edited: false, } } _inputHtml() { return Object.assign({}, this.props.inputHtml, { className: `${this.props.className || ""} form-control`.trim(), valueLink: this.props.valueLink, }) } _cx() { return cx({ "form-group": true, "has-error": this.state.errors != null, "has-success": this.state.edited && this.state.errors == null, }) } _errorList() { if (this.state.errors == null) return "" return errorList(this.state.errors) } _label() { if (this.props.label == null) return "" return label(this.props.labelHtml, this.props.label) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: this._cx()}, this._label(), div({className: "controls"}, textarea(this._inputHtml()), ), this._errorList(), ), ) } }
let React = require("react") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, textarea} = React.DOM let cx = require("classnames") export default class extends React.Component { static displayName = "Frig.friggingBootstrap.Text" static defaultProps = Object.assign(require("../default_props.js")) constructor(props) { super(props) this.state = { errors: undefined, edited: false, } } _inputHtml() { return Object.assign({}, this.props.inputHtml, { className: `${this.props.className || ""} form-control`.trim(), }) } _cx() { return cx({ "form-group": true, "has-error": this.state.errors != null, "has-success": this.state.edited && this.state.errors == null, }) } _errorList() { if (this.state.errors == null) return "" return errorList(this.state.errors) } _label() { if (this.props.label == null) return "" return label(this.props.labelHtml, this.props.label) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: this._cx()}, this._label(), div({className: "controls"}, textarea(this._inputHtml()), ), this._errorList(), ), ) } }
Add a getter to scheduled task's time field
const { PhoneNumberUtil } = require('google-libphonenumber'); const scheduledTasksSchemaFunc = require('./schemas/scheduled-tasks-schema'); const phoneUtil = PhoneNumberUtil.getInstance(); const validatePhoneNumber = (number) => { const parsedNumber = phoneUtil.parseAndKeepRawInput(number, 'KE'); return phoneUtil.isValidNumber(parsedNumber); }; module.exports = (sequelize, DataTypes) => { const overrides = { engineersPhoneNumber: { type: DataTypes.STRING, validate: { isValidPhoneNumber(value) { if (!validatePhoneNumber(value)) { throw new Error(`${value} is an invalid phone number.`); } } } }, contactPersonsPhoneNumber: { type: DataTypes.STRING, allowNull: false, validate: { isValidPhoneNumber(value) { if (!validatePhoneNumber(value)) { throw new Error(`${value} is an invalid phone number.`); } } } }, time: { type: DataTypes.TIME, allowNull: false, get() { return `${this.getDataValue('time')}hrs`; } } }; const scheduledTasksSchema = Object.assign( {}, scheduledTasksSchemaFunc(DataTypes), overrides ); const ScheduledTask = sequelize.define( 'ScheduledTask', scheduledTasksSchema, { tableName: 'scheduled_tasks', classMethods: { associate: (models) => { ScheduledTask.belongsTo(models.User, { foreignKey: 'userId', onDelete: 'CASCADE' }); } } } ); return ScheduledTask; };
const { PhoneNumberUtil } = require('google-libphonenumber'); const scheduledTasksSchemaFunc = require('./schemas/scheduled-tasks-schema'); const phoneUtil = PhoneNumberUtil.getInstance(); const validatePhoneNumber = (number) => { const parsedNumber = phoneUtil.parseAndKeepRawInput(number, 'KE'); return phoneUtil.isValidNumber(parsedNumber); }; module.exports = (sequelize, DataTypes) => { const overrides = { engineersPhoneNumber: { type: DataTypes.STRING, validate: { isValidPhoneNumber(value) { if (!validatePhoneNumber(value)) { throw new Error(`${value} is an invalid phone number.`); } } } }, contactPersonsPhoneNumber: { type: DataTypes.STRING, allowNull: false, validate: { isValidPhoneNumber(value) { if (!validatePhoneNumber(value)) { throw new Error(`${value} is an invalid phone number.`); } } } } }; const scheduledTasksSchema = Object.assign( {}, scheduledTasksSchemaFunc(DataTypes), overrides ); const ScheduledTask = sequelize.define( 'ScheduledTask', scheduledTasksSchema, { tableName: 'scheduled_tasks', classMethods: { associate: (models) => { ScheduledTask.belongsTo(models.User, { foreignKey: 'userId', onDelete: 'CASCADE' }); } } } ); return ScheduledTask; };
Update trove to remove Python 3.2, add Python 3.5
from distutils.core import setup import skyfield # safe, because __init__.py contains no import statements setup( name='skyfield', version=skyfield.__version__, description=skyfield.__doc__.split('\n', 1)[0], long_description=open('README.rst').read(), license='MIT', author='Brandon Rhodes', author_email='[email protected]', url='http://github.com/brandon-rhodes/python-skyfield/', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Astronomy', ], packages=[ 'skyfield', 'skyfield.data', 'skyfield.tests', ], package_data = { 'skyfield': ['documentation/*.rst'], 'skyfield.data': ['*.npy', '*.txt'], }, install_requires=[ 'jplephem>=2.3', 'numpy', 'sgp4>=1.4', ])
from distutils.core import setup import skyfield # safe, because __init__.py contains no import statements setup( name='skyfield', version=skyfield.__version__, description=skyfield.__doc__.split('\n', 1)[0], long_description=open('README.rst').read(), license='MIT', author='Brandon Rhodes', author_email='[email protected]', url='http://github.com/brandon-rhodes/python-skyfield/', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Scientific/Engineering :: Astronomy', ], packages=[ 'skyfield', 'skyfield.data', 'skyfield.tests', ], package_data = { 'skyfield': ['documentation/*.rst'], 'skyfield.data': ['*.npy', '*.txt'], }, install_requires=[ 'jplephem>=2.3', 'numpy', 'sgp4>=1.4', ])
Split html with newlines for easier debugging
define([ 'common/views/govuk', 'stache!common/templates/dashboard' ], function (GovUkView, contentTemplate) { var DashboardView = GovUkView.extend({ contentTemplate: contentTemplate, initialize: function () { GovUkView.prototype.initialize.apply(this, arguments); this.dashboardType = this.model.get('dashboard-type'); }, getContent: function () { var context = this.getContext(); return this.contentTemplate(context); }, getContext: function () { var context = this.model.toJSON(); context.modules = _.map(this.moduleInstances, function (module) { return module.html; }).join('\n'); context.header = this.getPageHeader(); context.dashboardType = this.dashboardType; context.tagline = this.getTagline(); context.hasFooter = false; return context; }, getTagline: function () { return this.model.get('tagline'); }, getPageHeader: function () { return this.model.get('title'); }, getPageTitleItems: function () { var items = []; var strapline = this.model.get('strapline'); if (strapline) { items.push(strapline); } items.push(this.getPageHeader()); return items; }, getBreadcrumbCrumbs: function () { var crumbs = [ {'path': '/performance', 'title': 'Performance'} ]; return crumbs; } }); return DashboardView; });
define([ 'common/views/govuk', 'stache!common/templates/dashboard' ], function (GovUkView, contentTemplate) { var DashboardView = GovUkView.extend({ contentTemplate: contentTemplate, initialize: function () { GovUkView.prototype.initialize.apply(this, arguments); this.dashboardType = this.model.get('dashboard-type'); }, getContent: function () { var context = this.getContext(); return this.contentTemplate(context); }, getContext: function () { var context = this.model.toJSON(); context.modules = _.map(this.moduleInstances, function (module) { return module.html; }).join(''); context.header = this.getPageHeader(); context.dashboardType = this.dashboardType; context.tagline = this.getTagline(); context.hasFooter = false; return context; }, getTagline: function () { return this.model.get('tagline'); }, getPageHeader: function () { return this.model.get('title'); }, getPageTitleItems: function () { var items = []; var strapline = this.model.get('strapline'); if (strapline) { items.push(strapline); } items.push(this.getPageHeader()); return items; }, getBreadcrumbCrumbs: function () { var crumbs = [ {'path': '/performance', 'title': 'Performance'} ]; return crumbs; } }); return DashboardView; });
Add React to include JSX in schema
/* eslint-disable no-unused-vars */ import React from 'react'; /* eslint-enable no-unused-vars */ let SERVICE_SCHEMA = { type: 'object', properties: { General: { description: 'Configure your container', type: 'object', properties: { id: { default: '/service', title: 'ID', description: 'The id for the service', type: 'string' }, cpus: { title: 'CPUs', description: 'The amount of CPUs which are used for the service', type:'number' }, mem: { title: 'Mem (MiB)', type: 'number' }, disk: { title: 'Disk (MiB)', type: 'number' }, instances: { title: 'Instances', type: 'number' }, cmd: { title: 'Command', default: 'sleep 1000;', description: 'The command which is executed by the service', type: 'string', multiLine: true } }, required: [ 'id' ] }, 'Container Settings': { description: 'Configure your Docker Container', type: 'object', properties: { image: { default: '', description: 'name of your docker image', type: 'string' } }, required: [] } }, required: [ 'General' ] }; module.exports = SERVICE_SCHEMA;
let SERVICE_SCHEMA = { type: 'object', properties: { General: { description: 'Configure your container', type: 'object', properties: { id: { default: '/service', title: 'ID', description: 'The id for the service', type: 'string' }, cpus: { title: 'CPUs', description: 'The amount of CPUs which are used for the service', type:'number' }, mem: { title: 'Mem (MiB)', type: 'number' }, disk: { title: 'Disk (MiB)', type: 'number' }, instances: { title: 'Instances', type: 'number' }, cmd: { title: 'Command', default: 'sleep 1000;', description: 'The command which is executed by the service', type: 'string', multiLine: true } }, required: [ 'id' ] }, 'Container Settings': { description: 'Configure your Docker Container', type: 'object', properties: { image: { default: '', description: 'name of your docker image', type: 'string' } }, required: [] } }, required: [ 'General' ] }; module.exports = SERVICE_SCHEMA;
Fix trade signs on Bitfinex * Trades from all other exchanges are presented with positive amounts (with the trade type indicating direction). On Bitfinex, sells were arriving negative and buys positive.
package info.bitrich.xchangestream.bitfinex.dto; import com.fasterxml.jackson.annotation.JsonFormat; import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade; import java.math.BigDecimal; /** * Created by Lukas Zaoralek on 7.11.17. */ @JsonFormat(shape = JsonFormat.Shape.ARRAY) public class BitfinexWebSocketTrade { public long tradeId; public long timestamp; public BigDecimal amount; public BigDecimal price; public BitfinexWebSocketTrade() { } public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) { this.tradeId = tradeId; this.timestamp = timestamp; this.amount = amount; this.price = price; } public long getTradeId() { return tradeId; } public long getTimestamp() { return timestamp; } public BigDecimal getAmount() { return amount; } public BigDecimal getPrice() { return price; } public BitfinexTrade toBitfinexTrade() { String type; if (amount.compareTo(BigDecimal.ZERO) < 0) { type = "sell"; } else { type = "buy"; } return new BitfinexTrade(price, amount.abs(), timestamp / 1000, "bitfinex", tradeId, type); } }
package info.bitrich.xchangestream.bitfinex.dto; import com.fasterxml.jackson.annotation.JsonFormat; import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade; import java.math.BigDecimal; /** * Created by Lukas Zaoralek on 7.11.17. */ @JsonFormat(shape = JsonFormat.Shape.ARRAY) public class BitfinexWebSocketTrade { public long tradeId; public long timestamp; public BigDecimal amount; public BigDecimal price; public BitfinexWebSocketTrade() { } public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) { this.tradeId = tradeId; this.timestamp = timestamp; this.amount = amount; this.price = price; } public long getTradeId() { return tradeId; } public long getTimestamp() { return timestamp; } public BigDecimal getAmount() { return amount; } public BigDecimal getPrice() { return price; } public BitfinexTrade toBitfinexTrade() { String type; if (amount.compareTo(BigDecimal.ZERO) < 0) { type = "sell"; } else { type = "buy"; } return new BitfinexTrade(price, amount, timestamp / 1000, "bitfinex", tradeId, type); } }
fix(identify): Make setUp method compatible with PHPUnit TestCase
<?php namespace Unicodeveloper\Identify\Test; use Mockery as m; use PHPUnit\Framework\TestCase; use Unicodeveloper\Identify\{ Identify, IdentifyServiceProvider }; class IdentifyServiceProviderTest extends TestCase { /** * @var MockInterface */ protected $mockApp; /** * @var IdentifyServiceProvider */ protected $provider; protected function setUp(): void { parent::setUp(); $this->mockApp = m::mock('\Illuminate\Contracts\Foundation\Application'); $this->provider = new IdentifyServiceProvider($this->mockApp); } /** * Test that it registers the correct service name with Identity */ public function testRegister() { $this->mockApp->shouldReceive('bind') ->once() ->andReturnUsing(function($name, $closure) { $this->assertEquals('laravel-identify', $name); $this->assertInstanceOf(Identify::class, $closure()); }); $this->provider->register(); } /** * Test that it provides the correct service name */ public function testProvides() { $expected = ['laravel-identify']; $actual = $this->provider->provides(); $this->assertEquals($expected, $actual); } }
<?php namespace Unicodeveloper\Identify\Test; use Mockery as m; use PHPUnit\Framework\TestCase; use Unicodeveloper\Identify\{ Identify, IdentifyServiceProvider }; class IdentifyServiceProviderTest extends TestCase { /** * @var MockInterface */ protected $mockApp; /** * @var IdentifyServiceProvider */ protected $provider; protected function setUp() { parent::setUp(); $this->mockApp = m::mock('\Illuminate\Contracts\Foundation\Application'); $this->provider = new IdentifyServiceProvider($this->mockApp); } /** * Test that it registers the correct service name with Identity */ public function testRegister() { $this->mockApp->shouldReceive('bind') ->once() ->andReturnUsing(function($name, $closure) { $this->assertEquals('laravel-identify', $name); $this->assertInstanceOf(Identify::class, $closure()); }); $this->provider->register(); } /** * Test that it provides the correct service name */ public function testProvides() { $expected = ['laravel-identify']; $actual = $this->provider->provides(); $this->assertEquals($expected, $actual); } }
Use JSON.stringify to stringify Array
class OutletsReceivable { static transform(modified, ...names) { modified.outlets = names; modified._argsTransformFns.push(this.filterOutlets.bind(null, modified)); } static filterOutlets(modified, opts, ...args) { let names = modified.outlets; let outlets = opts.outlets || {}; let newOpts = {}; for (let prop in opts) { if (opts.hasOwnProperty(prop)) { newOpts[prop] = opts[prop]; } } newOpts.outlets = {}; for (let name of names) { if (outlets.hasOwnProperty(name)) { newOpts.outlets[name] = outlets[name]; } else { throw new Error([ 'Route expected outlets ', JSON.stringify(names), ' but received ', JSON.stringify(Object.keys(outlets).sort()), '.' ].join('')); } } return [newOpts, ...args]; } } export default OutletsReceivable;
class OutletsReceivable { static transform(modified, ...names) { modified.outlets = names; modified._argsTransformFns.push(this.filterOutlets.bind(null, modified)); } static filterOutlets(modified, opts, ...args) { let names = modified.outlets; let outlets = opts.outlets || {}; let newOpts = {}; for (let prop in opts) { if (opts.hasOwnProperty(prop)) { newOpts[prop] = opts[prop]; } } newOpts.outlets = {}; for (let name of names) { if (outlets.hasOwnProperty(name)) { newOpts.outlets[name] = outlets[name]; } else { let quote = function(s) { return ['"',s,'"'].join(''); }; throw new Error([ 'Route expected outlets [', names.map(quote), '] but received [', Object.keys(outlets).sort().map(quote), '].' ].join('')); } } return [newOpts, ...args]; } } export default OutletsReceivable;
Add json files to subfolder
import re from setuptools import setup from io import open __version__, = re.findall('__version__ = "(.*)"', open('mappyfile/__init__.py').read()) def readme(): with open('README.rst', "r", encoding="utf-8") as f: return f.read() setup(name='mappyfile', version=__version__, description='A pure Python MapFile parser for working with MapServer', long_description=readme(), classifiers=[ # See https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Intended Audience :: Developers', 'Topic :: Text Processing :: Linguistic', 'Topic :: Software Development :: Build Tools' ], package_data={ '': ['*.g'], 'schemas': ['schemas/*.json'] }, url='http://github.com/geographika/mappyfile', author='Seth Girvin', author_email='[email protected]', license='MIT', packages=['mappyfile'], install_requires=['lark-parser', 'jsonschema'], zip_safe=False)
import re from setuptools import setup from io import open __version__, = re.findall('__version__ = "(.*)"', open('mappyfile/__init__.py').read()) def readme(): with open('README.rst', "r", encoding="utf-8") as f: return f.read() setup(name='mappyfile', version=__version__, description='A pure Python MapFile parser for working with MapServer', long_description=readme(), classifiers=[ # See https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Intended Audience :: Developers', 'Topic :: Text Processing :: Linguistic', 'Topic :: Software Development :: Build Tools' ], package_data={ '': ['*.g'], '': ['schemas/*.json'] }, url='http://github.com/geographika/mappyfile', author='Seth Girvin', author_email='[email protected]', license='MIT', packages=['mappyfile'], install_requires=['lark-parser', 'jsonschema'], zip_safe=False)
Call "checkAccessible()" before rendering any page templates To prevent that we render for example "title.tpl" which might access $viewer, for whose existance we chek in checkAccessible
<?php class CM_RenderAdapter_Page extends CM_RenderAdapter_Component { protected function _prepareViewResponse(CM_Frontend_ViewResponse $viewResponse) { $viewResponse->set('pageTitle', $this->fetchTitle()); } /** * @return string|null */ public function fetchDescription() { return $this->_fetchMetaTemplate('meta-description'); } /** * @return string|null */ public function fetchKeywords() { return $this->_fetchMetaTemplate('meta-keywords'); } /** * @return string|null */ public function fetchTitle() { return $this->_fetchMetaTemplate('title'); } /** * @param string $templateName * @return string|null */ protected function _fetchMetaTemplate($templateName) { $templatePath = $this->_getMetaTemplatePath($templateName); if (null === $templatePath) { return null; } $this->_getPage()->checkAccessible($this->getRender()->getEnvironment()); $html = $this->getRender()->fetchTemplate($templatePath, $this->_getViewResponse()->getData()); return trim($html); } /** * @param string $templateName * @return string|null */ protected function _getMetaTemplatePath($templateName) { $templatePath = $this->getRender()->getTemplatePath($this->_getView(), $templateName); if (null === $templatePath) { $templatePath = $this->getRender()->getLayoutPath('Page/Abstract/' . $templateName . '.tpl', null, null, null, false); } return $templatePath; } /** * @return CM_Page_Abstract */ private function _getPage() { return $this->_getView(); } }
<?php class CM_RenderAdapter_Page extends CM_RenderAdapter_Component { protected function _prepareViewResponse(CM_Frontend_ViewResponse $viewResponse) { $viewResponse->set('pageTitle', $this->fetchTitle()); } /** * @return string|null */ public function fetchDescription() { return $this->_fetchMetaTemplate('meta-description'); } /** * @return string|null */ public function fetchKeywords() { return $this->_fetchMetaTemplate('meta-keywords'); } /** * @return string|null */ public function fetchTitle() { return $this->_fetchMetaTemplate('title'); } /** * @param string $templateName * @return string|null */ protected function _fetchMetaTemplate($templateName) { $templatePath = $this->_getMetaTemplatePath($templateName); if (null === $templatePath) { return null; } return trim($this->getRender()->fetchTemplate($templatePath, $this->_getViewResponse()->getData())); } /** * @param string $templateName * @return string|null */ protected function _getMetaTemplatePath($templateName) { $templatePath = $this->getRender()->getTemplatePath($this->_getView(), $templateName); if (null === $templatePath) { $templatePath = $this->getRender()->getLayoutPath('Page/Abstract/' . $templateName . '.tpl', null, null, null, false); } return $templatePath; } }
Add example for url prefix in config
module.exports = { server: { host: 'localhost', port: 3000 }, router: { // e.g. api/v2/ urlPrefix: '' }, database: { host: 'localhost', user: 'root', password: 'root', database: 'dominion' }, media: { urlPath: '/media', saveDir: '../../media', supportsTypes: [ 'image/jpeg', 'image/png', 'image/gif' ] }, smsGate: { active: 1, providers: [ { name: 'smsProvider1', senderName: 'Dominion', token: '' }, { name: 'smsProvider2', senderName: 'Dominion', token: '' } ] }, session: { regularTtl: 3600 * 1000, persistentTtl: 3 * 31 * 24 * 3600 * 1000 }, mailGate: { active: 0, providers: [ { name: 'SMTP', user: '[email protected]', password: '' }, { name: 'localost', user: '', password: '' } ] } };
module.exports = { server: { host: 'localhost', port: 3000 }, router: { urlPrefix: '' }, database: { host: 'localhost', user: 'root', password: 'root', database: 'dominion' }, media: { urlPath: '/media', saveDir: '../../media', supportsTypes: [ 'image/jpeg', 'image/png', 'image/gif' ] }, smsGate: { active: 1, providers: [ { name: 'smsProvider1', senderName: 'Dominion', token: '' }, { name: 'smsProvider2', senderName: 'Dominion', token: '' } ] }, session: { regularTtl: 3600 * 1000, persistentTtl: 3 * 31 * 24 * 3600 * 1000 }, mailGate: { active: 0, providers: [ { name: 'SMTP', user: '[email protected]', password: '' }, { name: 'localost', user: '', password: '' } ] } };
Disable node/no-deprecated-api for Buffer constructor The use is deprecated since Node 6 but we still support Node 4 so we can't replace it yet.
'use strict'; const got = require('got'); class Request { constructor (options) { options = options || {}; this.baseUrl = 'https://api.glesys.com'; this.userAgent = 'https://github.com/jwilsson/glesys-api'; this.apiKey = options.apiKey; this.apiUser = options.apiUser; } get (url, data) { const options = { method: 'GET', query: data, }; url = this.baseUrl + url; return this.request(url, options); } post (url, data) { const options = { body: data, method: 'POST', }; url = this.baseUrl + url; return this.request(url, options); } request (url, options) { // eslint-disable-next-line node/no-deprecated-api const authString = new Buffer(`${ this.apiUser }:${ this.apiKey }`).toString('base64'); const defaults = { headers: { Authorization: `Basic ${ authString }`, }, json: true, }; options = Object.assign(defaults, options); return got(url, options); } } module.exports = Request;
'use strict'; const got = require('got'); class Request { constructor (options) { options = options || {}; this.baseUrl = 'https://api.glesys.com'; this.userAgent = 'https://github.com/jwilsson/glesys-api'; this.apiKey = options.apiKey; this.apiUser = options.apiUser; } get (url, data) { const options = { method: 'GET', query: data, }; url = this.baseUrl + url; return this.request(url, options); } post (url, data) { const options = { body: data, method: 'POST', }; url = this.baseUrl + url; return this.request(url, options); } request (url, options) { const authString = new Buffer(`${ this.apiUser }:${ this.apiKey }`).toString('base64'); const defaults = { headers: { Authorization: `Basic ${ authString }`, }, json: true, }; options = Object.assign(defaults, options); return got(url, options); } } module.exports = Request;
Update the list of regexps for BLOCKING resource loading on page.
/* eslint no-console: 0 */ 'use strict'; const phantom = require('phantom'); function* blockResourceLoading(page) { yield page.property('onResourceRequested', function(requestData, request) { var BLOCKED_RESOURCES = [ /\.gif/gi, /\.png/gi, /\.css/gi ]; var is_blacklisted_resource = BLOCKED_RESOURCES.some(function(r) { return r.test(requestData['url']); }); if (is_blacklisted_resource) { request.abort(); } }); } function* fetchPageContent(url, instance, block_assets=true) { let is_local_instance = false; if (!instance) { instance = yield * initPhantomInstance(); is_local_instance = true; } const page = yield instance.createPage(); if (block_assets) { yield * blockResourceLoading(page); } yield page.open(url); let html = yield page.property('content'); yield page.close(); if (is_local_instance) { instance.exit(); } return html; } function* initPhantomInstance() { return yield phantom.create(); } module.exports = { blockResourceLoading: blockResourceLoading, fetchPageContent: fetchPageContent, initPhantomInstance: initPhantomInstance };
/* eslint no-console: 0 */ 'use strict'; const phantom = require('phantom'); function* blockResourceLoading(page) { yield page.property('onResourceRequested', function(requestData, request) { var BLOCKED_RESOURCES = [ /\.gif/gi, /\.png/gi, /\.css/gi, /^((?!(feuseradmin\.js|tinymce|jquery-)).)*\.js.*/gi ]; var is_blacklisted_resource = BLOCKED_RESOURCES.some(function(r) { return r.test(requestData['url']); }); if (is_blacklisted_resource) { request.abort(); } }); } function* fetchPageContent(url, instance, block_assets=true) { let is_local_instance = false; if (!instance) { instance = yield * initPhantomInstance(); is_local_instance = true; } const page = yield instance.createPage(); if (block_assets) { yield * blockResourceLoading(page); } yield page.open(url); let html = yield page.property('content'); yield page.close(); if (is_local_instance) { instance.exit(); } return html; } function* initPhantomInstance() { return yield phantom.create(); } module.exports = { blockResourceLoading: blockResourceLoading, fetchPageContent: fetchPageContent, initPhantomInstance: initPhantomInstance };
Change Java client to expose exceptions.
import java.awt.Color; import com.allsparkcube.CubeClient; public class HelloWorld { public static void main(String[] args) { try { // final String HOST = "localhost"; final String HOST = "cube.ac"; final int PORT = 12345; CubeClient client = new CubeClient(HOST, PORT); // Set all LEDs to blue client.setAllLeds(Color.white); // Set the first LED (#0) to red client.setLed(0, Color.red); // Set the second LED (#1) to a custom color (teal-ish) Color teal = new Color(100, 255, 95); client.setLed(1, teal); // Starting at LED #48, set 16 LEDs to yellow client.setLedRange(48, 16, Color.yellow); // Set the last LED (#4095) to green client.setLed(4095, Color.green); // Actually send the data to the cube client.send(); System.out.println("Success..."); } catch (TException e) { e.printStackTrace(); } } }
import java.awt.Color; import com.allsparkcube.CubeClient; public class HelloWorld { public static void main(String[] args) { try { // final String HOST = "localhost"; final String HOST = "cube.ac"; final int PORT = 12345; CubeClient client = new CubeClient(HOST, PORT); // Set all LEDs to blue client.setAllLeds(Color.white); // Set the first LED (#0) to red client.setLed(0, Color.red); // Set the second LED (#1) to a custom color (teal-ish) Color teal = new Color(100, 255, 95); client.setLed(1, teal); // Starting at LED #48, set 16 LEDs to yellow client.setLedRange(48, 16, Color.yellow); // Set the last LED (#4095) to green client.setLed(4095, Color.green); // Actually send the data to the cube client.send(); System.out.println("Success..."); } catch (TException e) { e.printStackTrace(); } }
Fix IO Properties decode error
<?php namespace Uro\TeltonikaFmParser\Codec; use Uro\TeltonikaFmParser\Model\IoValue; use Uro\TeltonikaFmParser\Model\IoElement; use Uro\TeltonikaFmParser\Model\IoProperty; class Codec8Extended extends BaseCodec { public function decodeIoElement(): IoElement { return (new IoElement( $this->reader->readUInt16(), // Event ID $this->reader->readUInt16() // Number of elements ))->addProperties($this->decodeIoProperties()); } private function decodeIoProperties(): array { $properties = []; for($bytes = 1; $bytes <= 8; $bytes *= 2) { $numberOfProperties = $this->reader->readUInt16(); for($i = 0; $i < $numberOfProperties; $i++) { $properties[] = new IoProperty( $this->reader->readUInt16(), new IoValue($this->reader->readBytes($bytes)) ); } } return array_merge($properties, $this->decodeVariableLengthProperties()); } private function decodeVariableLengthProperties() { $properties = []; $numberOfProperties = $this->reader->readUInt16(); for($i = 0; $i < $numberOfProperties; $i++) { $properties[] = new IoProperty( $this->reader->readUInt16(), new IoValue($this->reader->readBytes($this->reader->readUInt16())) ); } return $properties; } }
<?php namespace Uro\TeltonikaFmParser\Codec; use Uro\TeltonikaFmParser\Model\IoValue; use Uro\TeltonikaFmParser\Model\IoElement; use Uro\TeltonikaFmParser\Model\IoProperty; class Codec8Extended extends BaseCodec { public function decodeIoElement(): IoElement { return (new IoElement( $this->reader->readUInt16(), // Event ID $this->reader->readUInt16() // Number of elements ))->addProperties($this->decodeIoProperties()); } private function decodeIoProperties(): array { $properties = []; for($bytes = 1; $bytes <= 8; $bytes *= 2) { $numberOfProperties = $this->reader->readUInt16(); foreach(range(1,$numberOfProperties) as $i) { $properties[] = new IoProperty( $this->reader->readUInt16(), new IoValue($this->reader->readBytes($bytes)) ); } } return array_merge($properties, $this->decodeVariableLengthProperties()); } private function decodeVariableLengthProperties() { $properties = []; $numberOfProperties = $this->reader->readUInt16(); foreach(range(1, $numberOfProperties) as $i) { $properties[] = new IoProperty( $this->reader->readUInt16(), new IoValue($this->reader->readBytes($this->reader->readUInt16())) ); } return $properties; } }
Fix star image from advanced search in javascript
define('app/views/image_list_item', [ 'text!app/templates/image_list_item.html','ember'], /** * * Image List Item View * * @returns Class */ function(image_list_item_html) { return Ember.View.extend({ tagName:'li', starImage: function() { var payload = { 'action': 'star' }; var backend_id = this.image.backend.id var image_id = this.image.id; var that = this; $.ajax({ url: '/backends/' + backend_id + '/images/' + image_id, type: "POST", data: JSON.stringify(payload), contentType: "application/json", headers: { "cache-control": "no-cache" }, dataType: "json", success: function (){ var backend = Mist.backendsController.getBackendById(backend_id); if (backend.images.content.indexOf(that.image) == -1) { if (image.star == false) { backend.images.content.unshiftObject(that.image); } } } }); }, didInsertElement: function(){ $('#images-list').listview('refresh'); try{ $('#images-list .ember-checkbox').checkboxradio(); } catch(e){} }, launchImage: function(){ var AddView = Mist.MachineAddView.create(); AddView.selectProvider(this.image.backend); AddView.selectImage(this.image); $('#images .dialog-add').panel('open'); }, template: Ember.Handlebars.compile(image_list_item_html), }); } );
define('app/views/image_list_item', [ 'text!app/templates/image_list_item.html','ember'], /** * * Image List Item View * * @returns Class */ function(image_list_item_html) { return Ember.View.extend({ tagName:'li', starImage: function() { var payload = { 'action': 'star' }; var backend_id = this.image.backend.id var image_id = this.image.id; $.ajax({ url: '/backends/' + backend_id + '/images/' + image_id, type: "POST", data: JSON.stringify(payload), contentType: "application/json", headers: { "cache-control": "no-cache" }, dataType: "json" }); }, didInsertElement: function(){ $('#images-list').listview('refresh'); try{ $('#images-list .ember-checkbox').checkboxradio(); } catch(e){} }, launchImage: function(){ var AddView = Mist.MachineAddView.create(); AddView.selectProvider(this.image.backend); AddView.selectImage(this.image); $('#images .dialog-add').panel('open'); }, template: Ember.Handlebars.compile(image_list_item_html), }); } );
Fix ServiceWorker https protocol check
(function() { function install(options, callback, errback) { callback || (callback = function() {}); errback || (errback = function() {}); <% if (ServiceWorker) { %> if ( 'serviceWorker' in navigator && (window.fetch || 'imageRendering' in document.documentElement.style) && (window.location.protocol === 'https:' || window.location.hostname === 'localhost') ) { navigator.serviceWorker .register(<%- JSON.stringify(ServiceWorker.output) %>) .then(function() { callback({ service: 'ServiceWorker' }); }).catch(function(err) { errback({ service: 'ServiceWorker' }); }); return; } <% } %> <% if (AppCache) { %> if (window.applicationCache) { var directory = <%- JSON.stringify(AppCache.directory) %>; var name = <%- JSON.stringify(AppCache.name) %>; var doLoad = function() { var page = directory + name + '.html'; var iframe = document.createElement('iframe'); iframe.src = page; iframe.style.display = 'none'; document.body.appendChild(iframe); }; if (document.readyState === 'complete') { setTimeout(doLoad); } else { window.addEventListener('load', doLoad); } return; } <% } %> setTimeout(function() { callback({ service: '' }); }); } return { install: install }; }())
(function() { function install(options, callback, errback) { callback || (callback = function() {}); errback || (errback = function() {}); <% if (ServiceWorker) { %> if ( 'serviceWorker' in navigator && (window.fetch || 'imageRendering' in document.documentElement.style) && (window.location.protocol === 'https' || window.location.hostname === 'localhost') ) { navigator.serviceWorker .register(<%- JSON.stringify(ServiceWorker.output) %>) .then(function() { callback({ service: 'ServiceWorker' }); }).catch(function(err) { errback({ service: 'ServiceWorker' }); }); return; } <% } %> <% if (AppCache) { %> if (window.applicationCache) { var directory = <%- JSON.stringify(AppCache.directory) %>; var name = <%- JSON.stringify(AppCache.name) %>; var doLoad = function() { var page = directory + name + '.html'; var iframe = document.createElement('iframe'); iframe.src = page; iframe.style.display = 'none'; document.body.appendChild(iframe); }; if (document.readyState === 'complete') { setTimeout(doLoad); } else { window.addEventListener('load', doLoad); } return; } <% } %> setTimeout(function() { callback({ service: '' }); }); } return { install: install }; }())
Fix docstring, return the settlement
from .base import Base class Capture(Base): @classmethod def get_resource_class(cls, client): from ..resources.captures import Captures return Captures(client) @property def id(self): return self._get_property('id') @property def mode(self): return self._get_property('mode') @property def amount(self): return self._get_property('amount') @property def settlement_amount(self): return self._get_property('settlementAmount') @property def payment_id(self): return self._get_property('paymentId') @property def shipment_id(self): return self._get_property('shipmentId') @property def settlement_id(self): return self._get_property('settlementId') @property def created_at(self): return self._get_property('createdAt') @property def payment(self): """Return the payment for this capture.""" return self.client.payments.get(self.payment_id) @property def shipment(self): """Return the shipment for this capture.""" from .shipment import Shipment url = self._get_link('shipment') if url: resp = self.client.orders.perform_api_call(self.client.orders.REST_READ, url) return Shipment(resp) @property def settlement(self): """Return the settlement for this capture.""" return self.client.settlements.get(self.settlement_id)
from .base import Base class Capture(Base): @classmethod def get_resource_class(cls, client): from ..resources.captures import Captures return Captures(client) @property def id(self): return self._get_property('id') @property def mode(self): return self._get_property('mode') @property def amount(self): return self._get_property('amount') @property def settlement_amount(self): return self._get_property('settlementAmount') @property def payment_id(self): return self._get_property('paymentId') @property def shipment_id(self): return self._get_property('shipmentId') @property def settlement_id(self): return self._get_property('settlementId') @property def created_at(self): return self._get_property('createdAt') @property def payment(self): """Return the payment for this capture.""" return self.client.payments.get(self.payment_id) @property def shipment(self): """Return the shipment for this capture.""" from .shipment import Shipment url = self._get_link('shipment') if url: resp = self.client.orders.perform_api_call(self.client.orders.REST_READ, url) return Shipment(resp) @property def settlement(self): """Return the payment for this capture.""" return self.client.settlements.get(self.settlement_id)
Use correct m2m join table name in LatestCommentsFeed --HG-- extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409089
from django.conf import settings from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site from django.contrib import comments class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"%s comments" % self._site.name def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"Latest comments on %s" % self._site.name def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
from django.conf import settings from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site from django.contrib import comments class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"%s comments" % self._site.name def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"Latest comments on %s" % self._site.name def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
Revert "Freeze mozlog version because of proposed API changes." This reverts commit 932b9d0b8e432ec1a7ff175c8716c8948b0beddd.
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup PACKAGE_VERSION = '0.1' deps = ['fxos-appgen>=0.2.10', 'marionette_client>=0.7.1.1', 'marionette_extension >= 0.4', 'mozdevice >= 0.33', 'mozlog >= 1.8', 'moznetwork >= 0.24', 'mozprocess >= 0.18', 'wptserve >= 1.0.1', 'wptrunner >= 0.3.8'] setup(name='fxos-certsuite', version=PACKAGE_VERSION, description='Certification suite for FirefoxOS', classifiers=[], keywords='mozilla', author='Mozilla Automation and Testing Team', author_email='[email protected]', url='https://github.com/mozilla-b2g/fxos-certsuite', license='MPL', packages=['certsuite'], include_package_data=True, zip_safe=False, install_requires=deps, entry_points=""" # -*- Entry points: -*- [console_scripts] runcertsuite = certsuite:harness_main cert = certsuite:certcli """)
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup PACKAGE_VERSION = '0.1' deps = ['fxos-appgen>=0.2.10', 'marionette_client>=0.7.1.1', 'marionette_extension >= 0.4', 'mozdevice >= 0.33', 'mozlog == 1.8', 'moznetwork >= 0.24', 'mozprocess >= 0.18', 'wptserve >= 1.0.1', 'wptrunner >= 0.3.8'] setup(name='fxos-certsuite', version=PACKAGE_VERSION, description='Certification suite for FirefoxOS', classifiers=[], keywords='mozilla', author='Mozilla Automation and Testing Team', author_email='[email protected]', url='https://github.com/mozilla-b2g/fxos-certsuite', license='MPL', packages=['certsuite'], include_package_data=True, zip_safe=False, install_requires=deps, entry_points=""" # -*- Entry points: -*- [console_scripts] runcertsuite = certsuite:harness_main cert = certsuite:certcli """)
Use test container when available
<?php /* * This file is part of the `liip/LiipImagineBundle` project. * * (c) https://github.com/liip/LiipImagineBundle/graphs/contributors * * For the full copyright and license information, please view the LICENSE.md * file that was distributed with this source code. */ namespace Liip\ImagineBundle\Tests\Functional; use Liip\ImagineBundle\Tests\Functional\app\AppKernel; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\BrowserKit\Client; abstract class AbstractWebTestCase extends WebTestCase { /** * @return string */ public static function getKernelClass() { require_once __DIR__.'/app/AppKernel.php'; return AppKernel::class; } /** * @return object */ protected function getService(string $name) { if (property_exists($this, 'container')) { return static::$container->get($name); } return static::$kernel->getContainer()->get($name); } /** * @return mixed */ protected function getParameter(string $name) { if (property_exists($this, 'container')) { return static::$container->getParameter($name); } return static::$kernel->getContainer()->getParameter($name); } /** * @param object $object * * @return mixed */ protected function getPrivateProperty($object, string $name) { $r = new \ReflectionObject($object); $p = $r->getProperty($name); $p->setAccessible(true); return $p->getValue($object); } }
<?php /* * This file is part of the `liip/LiipImagineBundle` project. * * (c) https://github.com/liip/LiipImagineBundle/graphs/contributors * * For the full copyright and license information, please view the LICENSE.md * file that was distributed with this source code. */ namespace Liip\ImagineBundle\Tests\Functional; use Liip\ImagineBundle\Tests\Functional\app\AppKernel; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\BrowserKit\Client; abstract class AbstractWebTestCase extends WebTestCase { /** * @return string */ public static function getKernelClass() { require_once __DIR__.'/app/AppKernel.php'; return AppKernel::class; } /** * @return object */ protected function getService(string $name) { return static::$kernel->getContainer()->get($name); } /** * @return mixed */ protected function getParameter(string $name) { return static::$kernel->getContainer()->getParameter($name); } /** * @param object $object * * @return mixed */ protected function getPrivateProperty($object, string $name) { $r = new \ReflectionObject($object); $p = $r->getProperty($name); $p->setAccessible(true); return $p->getValue($object); } }
Fix URL argument to wasmFolder to be string, not array Fixes https://github.com/magjac/d3-graphviz/issues/154 For some reason this incorrectness was working in @hpcc-js/wasm version 0.3.11 and before, but with the changes in https://github.com/hpcc-systems/hpcc-js-wasm/commit/1e4f67e26a94f9de6f6b1a7b9ceed85bceed3007 it no longer does.
/* This file is excluded from coverage because the intrumented code * translates "self" which gives a reference error. */ /* istanbul ignore next */ export function workerCode() { self.document = {}; // Workaround for "ReferenceError: document is not defined" in hpccWasm var hpccWasm; self.onmessage = function(event) { if (event.data.vizURL) { importScripts(event.data.vizURL); hpccWasm = self["@hpcc-js/wasm"]; hpccWasm.wasmFolder(event.data.vizURL.match(/.*\//)[0]); // This is an alternative workaround where wasmFolder() is not needed // document = {currentScript: {src: event.data.vizURL}}; } hpccWasm.graphviz.layout(event.data.dot, "svg", event.data.engine, event.data.options).then((svg) => { if (svg) { self.postMessage({ type: "done", svg: svg, }); } else if (event.data.vizURL) { self.postMessage({ type: "init", }); } else { self.postMessage({ type: "skip", }); } }).catch(error => { self.postMessage({ type: "error", error: error.message, }); }); } }
/* This file is excluded from coverage because the intrumented code * translates "self" which gives a reference error. */ /* istanbul ignore next */ export function workerCode() { self.document = {}; // Workaround for "ReferenceError: document is not defined" in hpccWasm var hpccWasm; self.onmessage = function(event) { if (event.data.vizURL) { importScripts(event.data.vizURL); hpccWasm = self["@hpcc-js/wasm"]; hpccWasm.wasmFolder(event.data.vizURL.match(/.*\//)); // This is an alternative workaround where wasmFolder() is not needed // document = {currentScript: {src: event.data.vizURL}}; } hpccWasm.graphviz.layout(event.data.dot, "svg", event.data.engine, event.data.options).then((svg) => { if (svg) { self.postMessage({ type: "done", svg: svg, }); } else if (event.data.vizURL) { self.postMessage({ type: "init", }); } else { self.postMessage({ type: "skip", }); } }).catch(error => { self.postMessage({ type: "error", error: error.message, }); }); } }
Truncate imports table on seed
<?php use App\Models\Setting; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Model::unguard(); $this->call(CompanySeeder::class); $this->call(CategorySeeder::class); $this->call(UserSeeder::class); $this->call(DepreciationSeeder::class); $this->call(DepartmentSeeder::class); $this->call(ManufacturerSeeder::class); $this->call(LocationSeeder::class); $this->call(SupplierSeeder::class); $this->call(AssetModelSeeder::class); $this->call(DepreciationSeeder::class); $this->call(StatuslabelSeeder::class); $this->call(AccessorySeeder::class); $this->call(AssetSeeder::class); $this->call(LicenseSeeder::class); $this->call(ComponentSeeder::class); $this->call(ConsumableSeeder::class); $this->call(ActionlogSeeder::class); $this->call(CustomFieldSeeder::class); // Only create default settings if they do not exist in the db. if(!Setting::first()) { factory(Setting::class)->create(); } Artisan::call('snipeit:sync-asset-locations', ['--output' => 'all']); $output = Artisan::output(); \Log::info($output); Model::reguard(); DB::table('imports')->truncate(); } }
<?php use App\Models\Setting; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Model::unguard(); $this->call(CompanySeeder::class); $this->call(CategorySeeder::class); $this->call(UserSeeder::class); $this->call(DepreciationSeeder::class); $this->call(DepartmentSeeder::class); $this->call(ManufacturerSeeder::class); $this->call(LocationSeeder::class); $this->call(SupplierSeeder::class); $this->call(AssetModelSeeder::class); $this->call(DepreciationSeeder::class); $this->call(StatuslabelSeeder::class); $this->call(AccessorySeeder::class); $this->call(AssetSeeder::class); $this->call(LicenseSeeder::class); $this->call(ComponentSeeder::class); $this->call(ConsumableSeeder::class); $this->call(ActionlogSeeder::class); $this->call(CustomFieldSeeder::class); // Only create default settings if they do not exist in the db. if(!Setting::first()) { factory(Setting::class)->create(); } Artisan::call('snipeit:sync-asset-locations', ['--output' => 'all']); $output = Artisan::output(); \Log::info($output); Model::reguard(); } }
Set signal high to give IA priority
(function (env) { "use strict"; env.ddg_spice_wikinews = function(api_result){ if (api_result.error) { return Spice.failed('wikinews'); } DDG.require('moment.js', function(){ Spice.add({ id: "wikinews", name: "Wikinews", signal: "high", data: api_result.query.categorymembers, meta: { total: api_result.query.categorymembers.length, sourceName: 'Wikinews', sourceUrl: "https://en.wikinews.org/wiki/Main_Page", itemType: "Latest Wikinews articles" }, normalize: function(item) { var timestamp = new Date(item.timestamp).getTime(); return { title: item.title, url: "https:///en.wikinews.org/?curid=" + item.pageid, post_domain: "wikinews.org", date_from: moment(timestamp).fromNow() }; }, templates: { group: 'text', options: { footer: Spice.wikinews.footer }, detail: false, item_detail: false, variants: { tileTitle: "4line", }, elClass: { tileTitle: 'tx--17' } } }); }); }; }(this));
(function (env) { "use strict"; env.ddg_spice_wikinews = function(api_result){ if (api_result.error) { return Spice.failed('wikinews'); } DDG.require('moment.js', function(){ Spice.add({ id: "wikinews", name: "Wikinews", data: api_result.query.categorymembers, meta: { total: api_result.query.categorymembers.length, sourceName: 'Wikinews', sourceUrl: "https://en.wikinews.org/wiki/Main_Page", itemType: "Latest Wikinews articles" }, normalize: function(item) { var timestamp = new Date(item.timestamp).getTime(); return { title: item.title, url: "https:///en.wikinews.org/?curid=" + item.pageid, post_domain: "wikinews.org", date_from: moment(timestamp).fromNow() }; }, templates: { group: 'text', options: { footer: Spice.wikinews.footer }, detail: false, item_detail: false, variants: { tileTitle: "4line", }, elClass: { tileTitle: 'tx--17' } } }); }); }; }(this));
Add debugtools as a dependency.
#!/usr/bin/env python3 # encoding: utf-8 try: from setuptools import setup except ImportError: from distutils.core import setup import re with open('glooey/__init__.py') as file: version_pattern = re.compile("__version__ = '(.*)'") version = version_pattern.search(file.read()).group(1) with open('README.rst') as file: readme = file.read() setup( name='glooey', version=version, author='Kale Kundert', author_email='[email protected]', description='An object-oriented GUI library for pyglet.', long_description=readme, url='https://github.com/kxgames/glooey', packages=[ 'glooey', ], include_package_data=True, install_requires=[ 'pyglet', 'more_itertools', 'vecrec', 'autoprop', 'debugtools', ], license='MIT', zip_safe=False, keywords=[ 'glooey', 'pyglet', 'gui', 'library', ], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3.5', 'Topic :: Games/Entertainment', 'Topic :: Software Development :: User Interfaces', 'Topic :: Software Development :: Libraries', ], )
#!/usr/bin/env python3 # encoding: utf-8 try: from setuptools import setup except ImportError: from distutils.core import setup import re with open('glooey/__init__.py') as file: version_pattern = re.compile("__version__ = '(.*)'") version = version_pattern.search(file.read()).group(1) with open('README.rst') as file: readme = file.read() setup( name='glooey', version=version, author='Kale Kundert', author_email='[email protected]', description='An object-oriented GUI library for pyglet.', long_description=readme, url='https://github.com/kxgames/glooey', packages=[ 'glooey', ], include_package_data=True, install_requires=[ 'pyglet', 'more_itertools', 'vecrec', 'autoprop', ], license='MIT', zip_safe=False, keywords=[ 'glooey', 'pyglet', 'gui', 'library', ], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3.5', 'Topic :: Games/Entertainment', 'Topic :: Software Development :: User Interfaces', 'Topic :: Software Development :: Libraries', ], )
Remove steps data from query in list of queries
import React, { Component } from 'react'; import {graphql, gql} from 'react-apollo'; import RecipeCard from './card'; class RecipesIndex extends Component { renderRecipes(){ return ( this.props.data.allRecipes.map(recipe => ( <div className="col-xs-12 col-sm-6 col-md-4 col-lg-3 equalHeightCol" style={{paddingTop: '5px', paddingBottom: '5px'}} key={recipe.id}> <RecipeCard recipe={recipe}/> </div> )) ); } render(){ if (this.props.data.loading){ return (<h1 className="text-info">Loading...</h1>); } if (this.props.data.error){ return (<h1 className="text-danger">Error</h1>) } return ( <div> <h1>Recipes</h1> <div className="row equalHeightColsRow"> {this.renderRecipes()} </div> </div> ); } } const getAllRecipesQuery = gql` query { allRecipes{ id, title, imageUrl, summary } } `; export default graphql(getAllRecipesQuery)(RecipesIndex);
import React, { Component } from 'react'; import {graphql, gql} from 'react-apollo'; import RecipeCard from './card'; class RecipesIndex extends Component { renderRecipes(){ return ( this.props.data.allRecipes.map(recipe => ( <div className="col-xs-12 col-sm-6 col-md-4 col-lg-3 equalHeightCol" style={{paddingTop: '5px', paddingBottom: '5px'}} key={recipe.id}> <RecipeCard recipe={recipe}/> </div> )) ); } render(){ if (this.props.data.loading){ return (<h1 className="text-info">Loading...</h1>); } if (this.props.data.error){ return (<h1 className="text-danger">Error</h1>) } return ( <div> <h1>Recipes</h1> <div className="row equalHeightColsRow"> {this.renderRecipes()} </div> </div> ); } } const getAllRecipesQuery = gql` query { allRecipes{ id, title, imageUrl, summary steps { description } } } `; export default graphql(getAllRecipesQuery)(RecipesIndex);
Add columns to src packages.
#!/usr/bin/env python from setuptools import setup import sys install_requires = [ 'six==1.6.1', 'python-dateutil>=2.2', 'pytimeparse>=1.1.5' ] if sys.version_info == (2, 6): install_requires.append('ordereddict>=1.1') setup( name='agate', version='0.6.0', description='', long_description=open('README').read(), author='Christopher Groskopf', author_email='[email protected]', url='http://agate.readthedocs.org/', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages=[ 'agate', 'agate.columns' ], install_requires=install_requires )
#!/usr/bin/env python from setuptools import setup import sys install_requires = [ 'six==1.6.1', 'python-dateutil>=2.2', 'pytimeparse>=1.1.5' ] if sys.version_info == (2, 6): install_requires.append('ordereddict>=1.1') setup( name='agate', version='0.6.0', description='', long_description=open('README').read(), author='Christopher Groskopf', author_email='[email protected]', url='http://agate.readthedocs.org/', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages=[ 'agate', ], install_requires=install_requires )
Add filter to show button only if selected role tutor
from datetime import datetime from django import template from wye.base.constants import WorkshopStatus register = template.Library() def show_draft_button(workshop, user): if (workshop.status in [WorkshopStatus.REQUESTED, WorkshopStatus.ACCEPTED, WorkshopStatus.DECLINED] and user in workshop.requester.user.all()): return True return False register.filter(show_draft_button) def show_requested_button(workshop, user): if (workshop.status == WorkshopStatus.HOLD and user in workshop.requester.user.all()): return True return False register.filter(show_requested_button) def show_accepted_button(workshop, user): if (workshop.status == WorkshopStatus.REQUESTED and 'tutor' in user.profile.get_user_type): return True return False register.filter(show_accepted_button) def show_feedback_button(workshop, user): if (workshop.status == WorkshopStatus.COMPLETED and (user in workshop.requester.user.all() or user in workshop.presenter.all()) and datetime.now().date() > workshop.expected_date): return True return False register.filter(show_feedback_button) def show_decline_button(workshop, user): if (workshop.status == WorkshopStatus.ACCEPTED and user in workshop.presenter.all()): return True return False register.filter(show_decline_button)
from django import template from datetime import datetime from wye.base.constants import WorkshopStatus register = template.Library() def show_draft_button(workshop, user): if (workshop.status in [WorkshopStatus.REQUESTED, WorkshopStatus.ACCEPTED, WorkshopStatus.DECLINED] and user in workshop.requester.user.all()): return True return False register.filter(show_draft_button) def show_requested_button(workshop, user): if (workshop.status == WorkshopStatus.HOLD and user in workshop.requester.user.all()): return True return False register.filter(show_requested_button) def show_accepted_button(workshop, user): if workshop.status == WorkshopStatus.REQUESTED: return True return False register.filter(show_accepted_button) def show_feedback_button(workshop, user): if (workshop.status == WorkshopStatus.COMPLETED and (user in workshop.requester.user.all() or user in workshop.presenter.all()) and datetime.now().date() > workshop.expected_date): return True return False register.filter(show_feedback_button) def show_decline_button(workshop, user): if (workshop.status == WorkshopStatus.ACCEPTED and user in workshop.presenter.all()): return True return False register.filter(show_decline_button)
Fix wrong testcase this types correctly resolved to /issue/issue/* but should be /issue/*
<?php /** * test_classes_issue.php * * @category * @author Johannes Brinksmeier <[email protected]> * @version $Id: $ */ namespace issue { interface Class_With_Underscores { } class SomeClass implements Class_With_Underscores { } class ClassWithDependencyToClassWithUnderscores { /** * @inject * @var \issue\Class_With_Underscores */ protected $dependency; /** * @param \issue\Class_With_Underscores $dependency * @return ClassWithDependencyToClassWithUnderscores */ public function setDependency($dependency) { $this->dependency = $dependency; return $this; } /** * @return \issue\Class_With_Underscores */ public function getDependency() { return $this->dependency; } } } namespace issue9\name { /** * @implementedBy default issue9\name\D * @implementedBy abc issue9\name\C * @implementedBy abd issue9\name\D */ interface B { } class C implements B { } class D implements B { } class A { /** * @inject * @named abc * @var B */ protected $myB; } }
<?php /** * test_classes_issue.php * * @category * @author Johannes Brinksmeier <[email protected]> * @version $Id: $ */ namespace issue { interface Class_With_Underscores { } class SomeClass implements Class_With_Underscores { } class ClassWithDependencyToClassWithUnderscores { /** * @inject * @var issue\Class_With_Underscores */ protected $dependency; /** * @param issue\Class_With_Underscores $dependency * @return ClassWithDependencyToClassWithUnderscores */ public function setDependency($dependency) { $this->dependency = $dependency; return $this; } /** * @return issue\Class_With_Underscores */ public function getDependency() { return $this->dependency; } } } namespace issue9\name { /** * @implementedBy default issue9\name\D * @implementedBy abc issue9\name\C * @implementedBy abd issue9\name\D */ interface B { } class C implements B { } class D implements B { } class A { /** * @inject * @named abc * @var B */ protected $myB; } }