text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Use BytecodeScanningDetector as base class
package edu.umd.cs.findbugs.detect; import org.apache.bcel.classfile.CodeException; import edu.umd.cs.findbugs.internalAnnotations.DottedClassName; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; public class DontCatchNullPointerException extends BytecodeScanningDetector { private final BugReporter reporter; public DontCatchNullPointerException(BugReporter reporter) { this.reporter = reporter; } @DottedClassName private static final String NULLPOINTER_EXCEPTION_FQCN = "java.lang.NullPointerException"; @Override public void visit(CodeException exc) { int type = exc.getCatchType(); if (type == 0) return; String name = getConstantPool() .constantToString(getConstantPool() .getConstant(type)); if (name.equals(NULLPOINTER_EXCEPTION_FQCN)) { BugInstance bug = new BugInstance(this, "DCN_NULLPOINTER_EXCEPTION", NORMAL_PRIORITY); bug.addClassAndMethod(this); bug.addSourceLine(getClassContext(), this, exc.getHandlerPC()); reporter.reportBug(bug); } } }
package edu.umd.cs.findbugs.detect; import org.apache.bcel.classfile.CodeException; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; public class DontCatchNullPointerException extends PreorderVisitor implements Detector { private final BugReporter reporter; ClassContext classContext; public DontCatchNullPointerException(BugReporter reporter) { this.reporter = reporter; } private static final String NullPtrExceptionID = "java.lang.NullPointerException"; @Override public void visit(CodeException exc) { int type = exc.getCatchType(); if (type == 0) return; String name = getConstantPool() .constantToString(getConstantPool() .getConstant(type)); if (name.equals(NullPtrExceptionID)) { BugInstance bug = new BugInstance(this, "DCN_NULLPOINTER_EXCEPTION", NORMAL_PRIORITY); bug.addClassAndMethod(this); bug.addSourceLine(this.classContext, this, exc.getHandlerPC()); reporter.reportBug(bug); } } @Override public void visitClassContext(ClassContext classContext) { this.classContext = classContext; this.classContext.getJavaClass().accept(this); } @Override public void report() { } }
Fix missing default values with autocomplete
import { inject, bindable, bindingMode } from 'aurelia-framework'; import { Config } from 'aurelia-api'; @inject(Element, Config) export class UiAutocomplete { @bindable({defaultBindingMode: bindingMode.twoWay}) value; @bindable from; @bindable placeholder; @bindable searchParams = {}; @bindable displayValue = 'name'; @bindable storeValue = 'id'; @bindable defaultText = ''; @bindable multiple = false; constructor(element, config) { this.element = element; this.endpoint = config.getEndpoint('api'); this.doQuery = (settings, callback) => { let path = `${this.from}/`; let params = this.searchParams; params.search = settings.urlData.query; this.endpoint.find(path, params).then(data => { callback(data); }); } this.updateFromDropdown = (value, text, choice) => { this.value = value; } } defaultTextChanged(value) { if (this.dropdown) { this.dropdown.dropdown('set text', this.defaultText); } } attached() { setTimeout(() => { this.dropdown = $('.search.selection.dropdown', this.element).dropdown({ apiSettings: { responseAsync: this.doQuery, }, fields: { remoteValues: 'results', name: this.displayValue, value: this.storeValue, }, onChange: this.updateFromDropdown, localSearch: false, }); this.dropdown.dropdown('set text', this.defaultText); }, 1); } }
import { inject, bindable, bindingMode } from 'aurelia-framework'; import { Config } from 'aurelia-api'; @inject(Element, Config) export class UiAutocomplete { @bindable({defaultBindingMode: bindingMode.twoWay}) value; @bindable from; @bindable placeholder; @bindable searchParams = {}; @bindable displayValue = 'name'; @bindable storeValue = 'id'; @bindable defaultText = ''; @bindable multiple = false; constructor(element, config) { this.element = element; this.endpoint = config.getEndpoint('api'); this.doQuery = (settings, callback) => { let path = `${this.from}/`; let params = this.searchParams; params.search = settings.urlData.query; this.endpoint.find(path, params).then(data => { callback(data); }); } this.updateFromDropdown = (value, text, choice) => { this.value = value; } } attached() { setTimeout(() => { this.dropdown = $('.search.selection.dropdown', this.element).dropdown({ apiSettings: { responseAsync: this.doQuery, }, fields: { remoteValues: 'results', name: this.displayValue, value: this.storeValue, }, onChange: this.updateFromDropdown, localSearch: false, }); this.dropdown.dropdown('set text', this.defaultText); }, 1); } }
Implement rdatatype-aware and NoAnswer-aware DNS handling This will work for CNAME entries because CNAMEs hit by A or AAAA lookups behave like `dig` does - they will trigger a second resultset for the CNAME entry in order to return the IP address. This also is amended to handle a "NoAnswer" response - i.e. if there are no IPv4 or IPv6 addresses for a given CNAME or records lookup. The list will therefore have all the CNAME-resolved IP addresses as independent strings.
import dns import dns.resolver import dns.rdatatype from typing import Union, List class DNSResolver(dns.resolver.Resolver): def __init__(self, filename='/etc/resolv.conf', configure=False, nameservers: Union[str, List[str]] = None): # Run the dns.resolver.Resolver superclass init call to configure # the object. Then, depending on the value in configure argument, # do something with the nameservers argument, which is unique to this # class object instead. super(DNSResolver, self).__init__(filename, configure) if not configure: if isinstance(nameservers, str): self.nameservers = [nameservers] elif isinstance(nameservers, list): self.nameservers = nameservers else: self.nameservers = ['8.8.8.8, 8.8.4.4'] def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list: addrs = [] try: for answer in resolver.query(domain, 'A').response.answer: for item in answer: if item.rdtype == dns.rdatatype.A: addrs.append(item.address) except dns.resolver.NoAnswer: pass try: for answer in resolver.query(domain, 'AAAA').response.answer: for item in answer: if item.rdtype == dns.rdatatype.AAAA: addrs.append(item.address) except dns.resolver.NoAnswer: pass return addrs
import dns import dns.resolver import dns.rdatatype from typing import Union, List class DNSResolver(dns.resolver.Resolver): def __init__(self, filename='/etc/resolv.conf', configure=False, nameservers: Union[str, List[str]] = None): # Run the dns.resolver.Resolver superclass init call to configure # the object. Then, depending on the value in configure argument, # do something with the nameservers argument, which is unique to this # class object instead. super(DNSResolver, self).__init__(filename, configure) if not configure: if isinstance(nameservers, str): self.nameservers = [nameservers] elif isinstance(nameservers, list): self.nameservers = nameservers else: self.nameservers = ['8.8.8.8, 8.8.4.4'] def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list: addrs = [] for answer in resolver.query(domain, 'A').response.answer: for item in answer: addrs.append(item.address) for answer in resolver.query(domain, 'AAAA').response.answer: for item in answer: addrs.append(item.address) return addrs
Move serializer into the class so it can be subclassed.
import cPickle as pickle import logging import time class Serializer(object): """A pluggable Serializer class""" name = "default" def __init__(self, name='default'): """Constructor""" self.ser = logging.getLogger('testserializer') self.data = {} self.name = name def process_request(self, request): request_dict = { 'name': self.name, 'time': time.time(), 'path': request.path, 'get': request.GET, 'post': request.POST, 'arg_dict': request.REQUEST, 'method': request.method, } return request_dict def save_request(self, request): """Saves the Request to the serialization stream""" request_dict = self.process_request(request) self.ser.info(pickle.dumps(request_dict)) self.ser.info('---REQUEST_BREAK---') def process_response(self, path, response): response_dict = { 'name': self.name, 'time': time.time(), 'path': path, 'context': response.context, 'content': response.content, 'status_code': response.status_code, 'cookies': response.cookies, 'headers': response._headers, } return response_dict def save_response(self, path, response): """Saves the Response-like objects information that might be tested""" response_dict = self.process_response(path, response) try: self.ser.info(pickle.dumps(response_dict)) self.ser.info('---RESPONSE_BREAK---') except (TypeError, pickle.PicklingError): #Can't pickle wsgi.error objects pass
import cPickle as pickle import logging import time ser = logging.getLogger('testserializer') class Serializer(object): """A pluggable Serializer class""" name = "default" def __init__(self, name='default'): """Constructor""" self.data = {} self.name = name def save_request(self, request): """Saves the Request to the serialization stream""" request_dict = { 'name': self.name, 'time': time.time(), 'path': request.path, 'get': request.GET, 'post': request.POST, 'arg_dict': request.REQUEST, } ser.info(pickle.dumps(request_dict)) ser.info('---REQUEST_BREAK---') def save_response(self, path, response): """Saves the Response-like objects information that might be tested""" response_dict = { 'name': self.name, 'time': time.time(), 'path': path, 'context': response.context, 'content': response.content, 'status_code': response.status_code, 'cookies': response.cookies, 'headers': response._headers, } try: ser.info(pickle.dumps(response_dict)) ser.info('---RESPONSE_BREAK---') except (TypeError, pickle.PicklingError): #Can't pickle wsgi.error objects pass
Remove unnecessary commented out lines
(function() { describe('awesome-app.search module', function() { var $controller, $scope, SearchService, $rootScope, controller; beforeEach(function() { module('awesome-app.search'); inject(function(_$controller_, _SearchService_, _$rootScope_) { $controller = _$controller_; SearchService = _SearchService_; $rootScope = _$rootScope_; }); $scope = $rootScope.$new(); $scope.$on = function() {}; controller = $controller('SearchCtrl', {$scope: $scope}); }); describe('search controller tests', function(){ it('should call getTypeaheadData', function() { spyOn(SearchService, 'getTypeaheadData') .and.returnValue({then: function() {}}); $scope.getTypeaheadData(); expect(SearchService.getTypeaheadData).toHaveBeenCalled(); }); it('should emit event with teamMembers', function() { spyOn($scope, '$emit'); $scope.teamMembers = []; $scope.refreshTeamList(); expect($scope.$emit).toHaveBeenCalledWith('saveTeamMembers', $scope.teamMembers); }); it('should remove teamMember', function() { $scope.teamMembers = [ { name: 'Ross Gellar' }, { name: 'Chandler Bing' } ]; $scope.removeTeamMember(0); expect($scope.teamMembers).toEqual([{name: 'Chandler Bing'}]); }); }); }); })();
(function() { describe('awesome-app.search module', function() { var $controller, $scope, SearchService, $rootScope, controller, element; beforeEach(function() { module('awesome-app.search'); inject(function(_$controller_, _SearchService_, _$rootScope_, _$compile_, _$templateCache_) { $controller = _$controller_; SearchService = _SearchService_; $rootScope = _$rootScope_; }); $scope = $rootScope.$new(); $scope.$on = function() {}; controller = $controller('SearchCtrl', {$scope: $scope}); }); describe('search controller tests', function(){ it('should call getTypeaheadData', function() { spyOn(SearchService, 'getTypeaheadData') .and.returnValue({then: function() {}}); $scope.getTypeaheadData(); expect(SearchService.getTypeaheadData).toHaveBeenCalled(); }); it('should emit event with teamMembers', function() { spyOn($scope, '$emit'); $scope.teamMembers = []; $scope.refreshTeamList(); expect($scope.$emit).toHaveBeenCalledWith('saveTeamMembers', $scope.teamMembers); }); it('should remove teamMember', function() { $scope.teamMembers = [ { name: 'Ross Gellar' }, { name: 'Chandler Bing' } ]; $scope.removeTeamMember(0); expect($scope.teamMembers).toEqual([{name: 'Chandler Bing'}]); }); }); }); })();
Add logging to see who we can't get the info for
var moment = require('moment'); var userCache = {}; var cacheTimeInMilliseconds = 1000 * 60 * 15; /** * Every time a user posts a message, we update their slack profile so we can stay up to date on their profile * @param {Object} bot * @param {Object} message * @param {Object} controller */ module.exports = function updateSlackProfile(bot, message, controller) { // Cache the user updates for 15 minutes so we don't do too much stuff if (userCache[message.user]) { var userCacheExpiration = moment(userCache[message.user]); if (userCacheExpiration.diff(moment(), 'minutes') < 15) { return; } } controller.storage.users.get(message.user, function(err, user) { if (err) { return console.trace(err); } bot.api.users.info({user: message.user}, function(err, res) { if (err) { console.error('could not get info for user %s', message.user); return console.trace(err); } if (!user) { user = { id: message.user, }; } user.slackUser = res.user; controller.storage.users.save(user, function() { userCache[user.id] = new Date(); }); }); }); };
var moment = require('moment'); var userCache = {}; var cacheTimeInMilliseconds = 1000 * 60 * 15; /** * Every time a user posts a message, we update their slack profile so we can stay up to date on their profile * @param {Object} bot * @param {Object} message * @param {Object} controller */ module.exports = function updateSlackProfile(bot, message, controller) { // Cache the user updates for 15 minutes so we don't do too much stuff if (userCache[message.user]) { var userCacheExpiration = moment(userCache[message.user]); if (userCacheExpiration.diff(moment(), 'minutes') < 15) { return; } } controller.storage.users.get(message.user, function(err, user) { if (err) { return console.trace(err); } bot.api.users.info({user: message.user}, function(err, res) { if (err) { return console.trace(err); } if (!user) { user = { id: message.user, }; } user.slackUser = res.user; controller.storage.users.save(user, function() { userCache[user.id] = new Date(); }); }); }); };
Fix HtlmIFrameSrcDoc test, 27 failing [ci skip]
/*global describe, it*/ var expect = require('../unexpected-with-plugins'), AssetGraph = require('../../lib/AssetGraph'); describe('relations/HtmlIFrameSrcDoc', function () { it('should handle a test case with an existing <iframe srcdoc=...> element', function () { return new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlIFrameSrcDoc/'}) .loadAssets('index.html') .populate({ startAssets: { isInitial: true }, followRelations: {to: {url: /^file:/}} }) .then(function (assetGraph) { expect(assetGraph, 'to contain assets', 'Html', 3); expect(assetGraph, 'to contain asset', {type: 'Html', isInline: true}); expect(assetGraph, 'to contain relation', 'HtmlIFrame'); expect(assetGraph, 'to contain relation', 'HtmlIFrameSrcDoc'); expect(assetGraph, 'to contain relations', 'HtmlAnchor', 2); var asset = assetGraph.findRelations({type: 'HtmlIFrameSrcDoc'})[0].to, document = asset.parseTree; document.firstChild.appendChild(document.createTextNode('Hello from the outside!')); asset.markDirty(); expect(assetGraph.findAssets({url: /\/index\.html$/})[0].text, 'to match', /Hello from the outside!/); }); }); });
/*global describe, it*/ var expect = require('../unexpected-with-plugins'), AssetGraph = require('../../lib/AssetGraph'); describe('relations/HtmlIFrameSrcDoc', function () { it('should handle a test case with an existing <iframe srcdoc=...> element', function () { return new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlIFrameSrcDoc/'}) .loadAssets('index.html') .populate({ followRelations: {to: {url: /^file:/}} }) .then(function (assetGraph) { expect(assetGraph, 'to contain assets', 'Html', 3); expect(assetGraph, 'to contain asset', {type: 'Html', isInline: true}); expect(assetGraph, 'to contain relation', 'HtmlIFrame'); expect(assetGraph, 'to contain relation', 'HtmlIFrameSrcDoc'); expect(assetGraph, 'to contain relations', 'HtmlAnchor', 2); var asset = assetGraph.findRelations({type: 'HtmlIFrameSrcDoc'})[0].to, document = asset.parseTree; document.firstChild.appendChild(document.createTextNode('Hello from the outside!')); asset.markDirty(); expect(assetGraph.findAssets({url: /\/index\.html$/})[0].text, 'to match', /Hello from the outside!/); }); }); });
Add client and channel models
''' Created on Nov 9, 2014 @author: fechnert ''' import yaml import logging import features class Configuration(dict): ''' Read and provide the yaml config ''' def __init__(self, path): ''' Initialize the file ''' with open(path, 'r') as f: self.update(yaml.load(f)) class Supervisor(object): ''' Guide the different features to do their work ''' def __init__(self): ''' Initialize the Config ''' self.config = Configuration('config.yml') def execute(self): for feature in self._import_features().values(): try: feature.run() except NotImplementedError: logging.warn('Can\'t run Feature \'{}\''.format(feature.__class__.__name__)) def _get_enabled_features(self): ''' Get all features which are enabled in config ''' features = [] for feature in self.config['features']: if self.config['features'][feature]['enable']: features.append(feature) return features def _import_features(self): ''' Import only the needed features ''' feature_objects = {} for feature in self._get_enabled_features(): feature_objects.update({ feature: getattr(features, feature)(self.config['features'][feature]) }) return feature_objects class Client(object): ''' Represents the client ''' def __init__(self, **kwargs): ''' Fill the object dynamically with client attributes got from telnet ''' for key, value in kwargs.items(): setattr(self, key, value) class Channel(object): ''' Represents the Channel ''' def __init__(self, **kwargs): ''' Fill the object dynamically with channel attributes got from telnet ''' for key, value in kwargs.items(): setattr(self, key, value)
''' Created on Nov 9, 2014 @author: fechnert ''' import yaml import logging import features class Configuration(dict): ''' Read and provide the yaml config ''' def __init__(self, path): ''' Initialize the file ''' with open(path, 'r') as f: self.update(yaml.load(f)) class Supervisor(object): ''' Guide the different features to do their work ''' def __init__(self): ''' Initialize the Config ''' self.config = Configuration('config.yml') def execute(self): for feature in self._import_features().values(): try: feature.run() except NotImplementedError: logging.warn('Can\'t run Feature \'{}\''.format(feature.__class__.__name__)) def _get_enabled_features(self): ''' Get all features which are enabled in config ''' features = [] for feature in self.config['features']: if self.config['features'][feature]['enable']: features.append(feature) return features def _import_features(self): ''' Import only the needed features ''' feature_objects = {} for feature in self._get_enabled_features(): feature_objects.update({ feature: getattr(features, feature)(self.config['features'][feature]) }) return feature_objects
Extend MOP for RayTracer depth sorting.
package codechicken.lib.raytracer; import net.minecraft.entity.Entity; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; public class ExtendedMOP extends MovingObjectPosition implements Comparable<ExtendedMOP> { public Object data; public double dist; public ExtendedMOP(Entity entity, Object data) { super(entity); setData(data); } public ExtendedMOP(int x, int y, int z, int side, Vec3 hit, Object data) { super(x, y, z, side, hit); setData(data); } public ExtendedMOP(MovingObjectPosition mop, Object data, double dist) { super(0, 0, 0, 0, mop.hitVec); typeOfHit = mop.typeOfHit; blockX = mop.blockX; blockY = mop.blockY; blockZ = mop.blockZ; sideHit = mop.sideHit; subHit = mop.subHit; setData(data); this.dist = dist; } public void setData(Object data) { if(data instanceof Integer) subHit = ((Integer) data).intValue(); this.data = data; } @SuppressWarnings("unchecked") public static <T> T getData(MovingObjectPosition mop) { if(mop instanceof ExtendedMOP) return (T)((ExtendedMOP)mop).data; return (T)Integer.valueOf(mop.subHit); } @Override public int compareTo(ExtendedMOP o) { return dist == o.dist ? 0 : dist < o.dist ? -1 : 1; } }
package codechicken.lib.raytracer; import net.minecraft.entity.Entity; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; public class ExtendedMOP extends MovingObjectPosition { public Object data; public ExtendedMOP(Entity entity, Object data) { super(entity); setData(data); } public ExtendedMOP(int x, int y, int z, int side, Vec3 hit, Object data) { super(x, y, z, side, hit); setData(data); } public ExtendedMOP(MovingObjectPosition mop, Object data) { super(0, 0, 0, 0, mop.hitVec); typeOfHit = mop.typeOfHit; blockX = mop.blockX; blockY = mop.blockY; blockZ = mop.blockZ; sideHit = mop.sideHit; subHit = mop.subHit; setData(data); } public void setData(Object data) { if(data instanceof Integer) subHit = ((Integer) data).intValue(); this.data = data; } @SuppressWarnings("unchecked") public static <T> T getData(MovingObjectPosition mop) { if(mop instanceof ExtendedMOP) return (T)((ExtendedMOP)mop).data; return (T)Integer.valueOf(mop.subHit); } }
Move some class references to imports.
package gx.realtime; import gx.realtime.RealtimeLoader.OnDocumentLoadedCallback; import gx.realtime.RealtimeLoader.InitializeModelCallback; import gx.realtime.RealtimeLoader.HandleErrorsCallback; /** * Options (key/value) for the RealtimeLoader. */ public class RealtimeOptions { private String clientId; private String docId; private OnDocumentLoadedCallback onFileLoaded; private InitializeModelCallback initializeModel; private HandleErrorsCallback handleErrors; // Methods public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getDocId() { return docId; } public void setDocId(String docId) { this.docId = docId; } public OnDocumentLoadedCallback getOnFileLoaded() { return onFileLoaded; } public void setOnFileLoaded(OnDocumentLoadedCallback onFileLoaded) { this.onFileLoaded = onFileLoaded; } public InitializeModelCallback getInitializeModel() { return initializeModel; } public void setInitializeModel(InitializeModelCallback initializeModel) { this.initializeModel = initializeModel; } public HandleErrorsCallback getHandleErrors() { return handleErrors; } public void setHandleErrors(HandleErrorsCallback handleErrors) { this.handleErrors = handleErrors; } }
package gx.realtime; import gx.realtime.RealtimeLoader.InitializeModelCallback; import gx.realtime.RealtimeLoader.HandleErrorsCallback; /** * Options (key/value) for the RealtimeLoader. */ public class RealtimeOptions { // Attributes private String clientId; private String docId; private RealtimeLoader.OnDocumentLoadedCallback onFileLoaded; private InitializeModelCallback initializeModel; private HandleErrorsCallback handleErrors; // Methods public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getDocId() { return docId; } public void setDocId(String docId) { this.docId = docId; } public RealtimeLoader.OnDocumentLoadedCallback getOnFileLoaded() { return onFileLoaded; } public void setOnFileLoaded(RealtimeLoader.OnDocumentLoadedCallback onFileLoaded) { this.onFileLoaded = onFileLoaded; } public InitializeModelCallback getInitializeModel() { return initializeModel; } public void setInitializeModel(InitializeModelCallback initializeModel) { this.initializeModel = initializeModel; } public HandleErrorsCallback getHandleErrors() { return handleErrors; } public void setHandleErrors(HandleErrorsCallback handleErrors) { this.handleErrors = handleErrors; } }
Enable death listener to disable data-emitter
AFRAME.registerComponent('death-listener', { schema: { characterId: {default: undefined} }, init: function () { const el = this.el; const data = this.data; window.addEventListener('characterDestroyed', function (e) { if(data.characterId === e.detail.characterId) { if(el.components.spawner) { el.components.spawner.pause(); setTimeout(() => { el.components.spawner.play(); }, 5000) } if(el.components['data-emitter']) { el.components['data-emitter'].pause(); setTimeout(() => { el.components['data-emitter'].play(); }, 5000) } } // const characterId = e.detail.characterId; // console.log('character killed:', characterId); // const blackPlane = document.createElement('a-plane'); // blackPlane.setAttribute('position', '0 0 -0.2'); // blackPlane.setAttribute('material', 'shader', 'flat'); // el.appendChild(blackPlane); // const opacityAnimation = document.createElement('a-animation'); // opacityAnimation.setAttribute('attribute', 'material.opacity'); // opacityAnimation.setAttribute('from', 0); // opacityAnimation.setAttribute('to', 1); // opacityAnimation.setAttribute('dur', 1500); // opacityAnimation.setAttribute('easing', 'ease-out'); // blackPlane.appendChild(opacityAnimation); // el.appendChild(blackPlane); // setTimeout(() => { // el.removeChild(blackPlane) // }, 3000); }); } });
AFRAME.registerComponent('death-listener', { schema: { characterId: {default: undefined} }, init: function () { const el = this.el; const data = this.data; window.addEventListener('characterDestroyed', function (e) { if(data.characterId === e.detail.characterId) { if(el.components.spawner) { el.components.spawner.pause(); setTimeout(() => { el.components.spawner.play(); }, 5000) } } // const characterId = e.detail.characterId; // console.log('character killed:', characterId); // const blackPlane = document.createElement('a-plane'); // blackPlane.setAttribute('position', '0 0 -0.2'); // blackPlane.setAttribute('material', 'shader', 'flat'); // el.appendChild(blackPlane); // const opacityAnimation = document.createElement('a-animation'); // opacityAnimation.setAttribute('attribute', 'material.opacity'); // opacityAnimation.setAttribute('from', 0); // opacityAnimation.setAttribute('to', 1); // opacityAnimation.setAttribute('dur', 1500); // opacityAnimation.setAttribute('easing', 'ease-out'); // blackPlane.appendChild(opacityAnimation); // el.appendChild(blackPlane); // setTimeout(() => { // el.removeChild(blackPlane) // }, 3000); }); } });
Add proxy settings to NetworkConfig
package netconf type NetworkConfig struct { PreCmds []string `yaml:"pre_cmds,omitempty"` Dns DnsConfig `yaml:"dns,omitempty"` Interfaces map[string]InterfaceConfig `yaml:"interfaces,omitempty"` PostCmds []string `yaml:"post_cmds,omitempty"` HttpProxy string `yaml:"http_proxy,omitempty"` HttpsProxy string `yaml:"https_proxy,omitempty"` NoProxy string `yaml:"no_proxy,omitempty"` } type InterfaceConfig struct { Match string `yaml:"match,omitempty"` DHCP bool `yaml:"dhcp,omitempty"` DHCPArgs string `yaml:"dhcp_args,omitempty"` Address string `yaml:"address,omitempty"` Addresses []string `yaml:"addresses,omitempty"` IPV4LL bool `yaml:"ipv4ll,omitempty"` Gateway string `yaml:"gateway,omitempty"` GatewayIpv6 string `yaml:"gateway_ipv6,omitempty"` MTU int `yaml:"mtu,omitempty"` Bridge string `yaml:"bridge,omitempty"` Bond string `yaml:"bond,omitempty"` BondOpts map[string]string `yaml:"bond_opts,omitempty"` PostUp []string `yaml:"post_up,omitempty"` PreUp []string `yaml:"pre_up,omitempty"` Vlans string `yaml:"vlans,omitempty"` } type DnsConfig struct { Nameservers []string `yaml:"nameservers,flow,omitempty"` Search []string `yaml:"search,flow,omitempty"` }
package netconf type NetworkConfig struct { PreCmds []string `yaml:"pre_cmds,omitempty"` Dns DnsConfig `yaml:"dns,omitempty"` Interfaces map[string]InterfaceConfig `yaml:"interfaces,omitempty"` PostCmds []string `yaml:"post_cmds,omitempty"` } type InterfaceConfig struct { Match string `yaml:"match,omitempty"` DHCP bool `yaml:"dhcp,omitempty"` DHCPArgs string `yaml:"dhcp_args,omitempty"` Address string `yaml:"address,omitempty"` Addresses []string `yaml:"addresses,omitempty"` IPV4LL bool `yaml:"ipv4ll,omitempty"` Gateway string `yaml:"gateway,omitempty"` GatewayIpv6 string `yaml:"gateway_ipv6,omitempty"` MTU int `yaml:"mtu,omitempty"` Bridge string `yaml:"bridge,omitempty"` Bond string `yaml:"bond,omitempty"` BondOpts map[string]string `yaml:"bond_opts,omitempty"` PostUp []string `yaml:"post_up,omitempty"` PreUp []string `yaml:"pre_up,omitempty"` Vlans string `yaml:"vlans,omitempty"` } type DnsConfig struct { Nameservers []string `yaml:"nameservers,flow,omitempty"` Search []string `yaml:"search,flow,omitempty"` }
Add the asyncio wait_for back in
import asyncio import json from discode_server import db from discode_server import fragments connected = set() notified = set() async def feed(request, ws): global connected connected.add(ws) print("Open WebSockets: ", len(connected)) try: while True: if not ws.open: return async with request.app.config.DB.acquire() as conn: await conn.execute(f"LISTEN channel") try: msg = await asyncio.wait_for( conn.connection.notifies.get(), 1) except asyncio.TimeoutError: continue if not ws.open: return fingerprint = ws.remote_address, msg.payload if fingerprint in notified: continue notified.add(fingerprint) paste_id, lineno, comment_id = msg.payload.split(',') paste = await db.get_paste(conn, int(paste_id)) html = fragments.comment_row(lineno, paste.comments[int(lineno)]) data = json.dumps({ "html": html, "lineno": lineno, "paste_id": paste.id, "comment_id": comment_id, }) await ws.send(data) finally: connected.remove(ws) print("Open WebSockets: ", len(connected))
import json from discode_server import db from discode_server import fragments connected = set() notified = set() async def feed(request, ws): global connected connected.add(ws) print("Open WebSockets: ", len(connected)) try: while True: if not ws.open: return async with request.app.config.DB.acquire() as conn: await conn.execute(f"LISTEN channel") msg = await conn.connection.notifies.get() if not ws.open: return fingerprint = ws.remote_address, msg.payload if fingerprint in notified: continue notified.add(fingerprint) paste_id, lineno, comment_id = msg.payload.split(',') paste = await db.get_paste(conn, int(paste_id)) html = fragments.comment_row(lineno, paste.comments[int(lineno)]) data = json.dumps({ "html": html, "lineno": lineno, "paste_id": paste.id, "comment_id": comment_id, }) await ws.send(data) finally: connected.remove(ws) print("Open WebSockets: ", len(connected))
Update container to use mock array rather than wrappers
<?php namespace Michaeljennings\Carpenter\Nexus; use ArrayAccess; use ArrayIterator; use IteratorAggregate; class Container implements ArrayAccess, IteratorAggregate { /** * The items in the container. * * @var array */ protected $items = []; public function __construct(array $items, array $config) { foreach ($items as &$item) { $item = new MockArray($item); } $this->items = $items; } /** * Get an iterator for the items. * * @return \ArrayIterator */ public function getIterator() { return new ArrayIterator($this->items); } /** * Determine if an item exists at an offset. * * @param mixed $key * @return bool */ public function offsetExists($key) { return array_key_exists($key, $this->items); } /** * Get an item at a given offset. * * @param mixed $key * @return mixed */ public function offsetGet($key) { return $this->items[$key]; } /** * Set the item at a given offset. * * @param mixed $key * @param mixed $value * @return void */ public function offsetSet($key, $value) { $this->items[$key] = $value; } /** * Unset the item at a given offset. * * @param string $key * @return void */ public function offsetUnset($key) { unset($this->items[$key]); } }
<?php namespace Michaeljennings\Carpenter\Nexus; use ArrayAccess; use ArrayIterator; use IteratorAggregate; class Container implements ArrayAccess, IteratorAggregate { /** * @var array */ protected $items = []; public function __construct(array $items, array $config, $wrapper) { foreach ($items as &$item) { $item = (new \ReflectionClass($wrapper))->newInstanceArgs([$item]); } $this->items = $items; } /** * Get an iterator for the items. * * @return \ArrayIterator */ public function getIterator() { return new ArrayIterator($this->items); } /** * Determine if an item exists at an offset. * * @param mixed $key * @return bool */ public function offsetExists($key) { return array_key_exists($key, $this->items); } /** * Get an item at a given offset. * * @param mixed $key * @return mixed */ public function offsetGet($key) { return $this->items[$key]; } /** * Set the item at a given offset. * * @param mixed $key * @param mixed $value * @return void */ public function offsetSet($key, $value) { $this->items[$key] = $value; } /** * Unset the item at a given offset. * * @param string $key * @return void */ public function offsetUnset($key) { unset($this->items[$key]); } }
Clear parameters before editing/adding. Before it was been unpossible to call two functions in sequence.
import json import api class WWWDomain(api.API): def __init__(self, auth_handler): self.url = auth_handler.url self.sessid = auth_handler.sessid self.func = 'wwwdomain.edit' self.out = 'json' self._clear_params() def _clear_params(self): try: self.params.clear() except NameError: pass self.params = { 'auth' : self.sessid, 'out' : 'json', 'func' : self.func, } def list(self, domain=None): """List all www domains. If domains is used, list details about this one.""" self._clear_params() if domain: self.params['elid'] = domain else: self.params['func'] = 'wwwdomain' data = self.process_api(self.url, self.params) out = json.load(data) try: return out['elem'] except KeyError: return out def add(self, domain='', owner='', admin='', ip='', **kwargs): """Add a new wwwdomain to configuration. If a DNS server is configurated, API adds domain there too.""" self._clear_params() self.params['sok'] = 'yes' self.params['domain'] = domain self.params['owner'] = owner self.params['admin'] = admin self.params['ip'] = ip for key in kwargs: self.params[key] = kwargs[key] data = self.process_api(self.url, self.params) out = json.load(data) return out
import json import api class WWWDomain(api.API): def __init__(self, auth_handler): self.url = auth_handler.url self.sessid = auth_handler.sessid self.func = 'wwwdomain.edit' self.out = 'json' self.params = { 'auth' : self.sessid, 'out' : self.out, 'func' : self.func, } def list(self, domain=None): """List all www domains. If domains is used, list details about this one.""" if domain: self.params['elid'] = domain else: self.params['func'] = 'wwwdomain' data = self.process_api(self.url, self.params) out = json.load(data) try: return out['elem'] except KeyError: return out def add(self, domain='', owner='', admin='', ip='', **kwargs): """Add a new wwwdomain to configuration. If a DNS server is configurated, API adds domain there too.""" self.params['sok'] = 'yes' self.params['domain'] = domain self.params['owner'] = owner self.params['admin'] = admin self.params['ip'] = ip for key in kwargs: self.params[key] = kwargs[key] data = self.process_api(self.url, self.params) out = json.load(data) return out
[Build] Test for CSS file in webpack.prod
const { resolve } = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const config = require('config'); const PORT = config.get('server.port'); module.exports = { entry: '../src/index.jsx', output: { filename: 'bundle.js', path: resolve(__dirname, '../dist'), publicPath: '/', }, context: resolve(__dirname, '../src'), resolve: { extensions: ['.', '.js', '.jsx'] }, module: { rules: [ { test: /\.jsx?$/, use: [ 'babel-loader', ], exclude: /node_modules/, }, { test: /\.json?$/, loader: 'json-loader' }, { test: /\.(s?)css$/, loaders: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader!sass-loader' }) }, ], }, plugins: [ new ExtractTextPlugin('style.css'), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.OccurrenceOrderPlugin(), new HtmlWebpackPlugin({ template: resolve(__dirname, '../src/index.tpl.html'), inject: 'body', filename: 'index.html', }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), ], };
const { resolve } = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const config = require('config'); const PORT = config.get('server.port'); module.exports = { entry: '../src/index.jsx', output: { filename: 'bundle.js', path: resolve(__dirname, '../dist'), publicPath: '/', }, context: resolve(__dirname, '../src'), resolve: { extensions: ['.', '.js', '.jsx'] }, module: { rules: [ { test: /\.jsx?$/, use: [ 'babel-loader', ], exclude: /node_modules/, }, { test: /\.json?$/, loader: 'json-loader' }, { test: /\.scss$/, loaders: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader!sass-loader' }) }, ], }, plugins: [ new ExtractTextPlugin('style.css'), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.OccurrenceOrderPlugin(), new HtmlWebpackPlugin({ template: resolve(__dirname, '../src/index.tpl.html'), inject: 'body', filename: 'index.html', }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), ], };
Add sort order to query results * Hard coded the sort order for now.
'use strict'; var _ = require('lodash'), Promise = require('bluebird'); module.exports = ['data', function (data) { var filters = function (query) { var where = data.utils.rangeFilter('Year', query.start, query.end); return _.assign(where, data.utils.inFilter('Make', query.makes)); }; return { '/:operation?': { get: function (req) { return new Promise(function (resolve, reject) { var op = data.utils.operation(req.params), pagination = data.utils.pagination(req.query); switch (op) { case 'count': data.Recall.count(filters(req.query)).exec(function (err, count) { if (err) { reject(err); return; } resolve([200, undefined, { count: count }]); }); break; default: var query = data.Recall.find(filters(req.query)).sort({ Year: 1, Make: 1, Model: 1 }); if (pagination) { query.skip(pagination.from).limit(pagination.limit); } query.exec(function (err, recalls) { if (err) { reject(err); return; } resolve([200, undefined, recalls]); }); break; } }); } } }; }];
'use strict'; var _ = require('lodash'), Promise = require('bluebird'); module.exports = ['data', function (data) { var filters = function (query) { var where = data.utils.rangeFilter('Year', query.start, query.end); return _.assign(where, data.utils.inFilter('Make', query.makes)); }; return { '/:operation?': { get: function (req) { return new Promise(function (resolve, reject) { var op = data.utils.operation(req.params), pagination = data.utils.pagination(req.query); switch (op) { case 'count': data.Recall.count(filters(req.query)).exec(function (err, count) { if (err) { reject(err); return; } resolve([200, undefined, { count: count }]); }); break; default: var query = data.Recall.find(filters(req.query)); if (pagination) { query.skip(pagination.from).limit(pagination.limit); } query.exec(function (err, recalls) { if (err) { reject(err); return; } resolve([200, undefined, recalls]); }); break; } }); } } }; }];
Use dateutil to calculate age of container.
#!/usr/bin/env python from __future__ import print_function from argparse import ArgumentParser from datetime import ( datetime, timedelta, ) import json import os import subprocess import sys from dateutil import ( parser as date_parser, tz, ) def list_old_juju_containers(hours): env = dict(os.environ) containers = json.loads(subprocess.check_output([ 'lxc', 'list', '--format', 'json'], env=env)) now = datetime.now(tz.gettz('UTC')) for container in containers: name = container['name'] if not name.startswith('juju-'): continue created_at = date_parser.parse(container['created_at']) age = now - created_at if age <= timedelta(hours=hours): continue yield name, age def main(): parser = ArgumentParser('Delete old juju containers') parser.add_argument('--dry-run', action='store_true', help='Do not actually delete.') parser.add_argument('--hours', type=int, default=1, help='Number of hours a juju container may exist.') args = parser.parse_args() for container, age in list_old_juju_containers(args.hours): print('deleting {} ({} old)'.format(container, age)) if args.dry_run: continue subprocess.check_call(('lxc', 'delete', '--verbose', '--force', container)) if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python from __future__ import print_function from argparse import ArgumentParser from datetime import ( datetime, timedelta, ) import json import os import subprocess import sys def list_old_juju_containers(hours): env = dict(os.environ) containers = json.loads(subprocess.check_output([ 'lxc', 'list', '--format', 'json'], env=env)) now = datetime.now() for container in containers: name = container['name'] if not name.startswith('juju-'): continue # This produces local time. lxc does not respect TZ=UTC. created_at = datetime.strptime( container['created_at'][:-6], '%Y-%m-%dT%H:%M:%S') age = now - created_at if age <= timedelta(hours=hours): continue yield name, age def main(): parser = ArgumentParser('Delete old juju containers') parser.add_argument('--dry-run', action='store_true', help='Do not actually delete.') parser.add_argument('--hours', type=int, default=1, help='Number of hours a juju container may exist.') args = parser.parse_args() for container, age in list_old_juju_containers(args.hours): print('deleting {} ({} old)'.format(container, age)) if args.dry_run: continue subprocess.check_call(('lxc', 'delete', '--verbose', '--force', container)) if __name__ == '__main__': sys.exit(main())
Fix status handling in getRestaurants The changes in #15 were meant to fix a bug where we were looking at an incorrect field for the status code of the fetch response. However, these changes were not thoroughly tested and actually didn't completely work as coded, because when the response is a success it does not have a "statusCode" property on the body. This patch checks the actual HTTP response status instead of the response body message.
;(function () { /* global fetch: false */ 'use strict'; function getRestaurants(coords) { var fetchUrl = '/restaurants?latitude=' + coords.latitude + '&longitude=' + coords.longitude; return fetch(fetchUrl) .then(function(response) { // handle any errors if (!response.ok) { return response.json().then(function (errorBody) { throw new Error(errorBody.description || 'An error occurred while fetching restaurants'); }); } // no errors, parse response json return response.json(); }); } var $status = document.getElementById('status'); if (!navigator.geolocation) { $status.innerHTML = 'geolocation is not supported on this platform'; return; } $status.innerHTML = 'retrieving your location...'; navigator.geolocation.getCurrentPosition(function (position) { $status.innerHTML = 'your location is: lat(' + position.coords.latitude + '), lon(' + position.coords.longitude + ')'; console.log('Geolocation position', position); getRestaurants(position.coords) .then(function (restaurants) { $status.innerHTML = restaurants.map(function (r) { return r.name + '<br />'; }).join(''); }).catch(function (err) { $status.innerHTML = 'Error retrieving restaurants<br />' + err; }); }, function (error) { $status.innerHTML = 'location could not be retrieved.'; console.error('Geolocation error', error); }); })();
;(function () { /* global fetch: false */ 'use strict'; function getRestaurants(coords) { var fetchUrl = '/restaurants?latitude=' + coords.latitude + '&longitude=' + coords.longitude; return fetch(fetchUrl) .then(function(response) { return response.json(); }).then(function(response) { if (response.statusCode >= 200 && response.statusCode < 300) { return response; } throw new Error(response.description); }); } var $status = document.getElementById('status'); if (!navigator.geolocation) { $status.innerHTML = 'geolocation is not supported on this platform'; return; } $status.innerHTML = 'retrieving your location...'; navigator.geolocation.getCurrentPosition(function (position) { $status.innerHTML = 'your location is: lat(' + position.coords.latitude + '), lon(' + position.coords.longitude + ')'; console.log('Geolocation position', position); getRestaurants(position.coords) .then(function (restaurants) { $status.innerHTML = restaurants.map(function (r) { return r.name + '<br />'; }).join(''); }).catch(function (err) { $status.innerHTML = 'Error retrieving restaurants<br />' + err; }); }, function (error) { $status.innerHTML = 'location could not be retrieved.'; console.error('Geolocation error', error); }); })();
Comment out modules with broken tests.
#!/usr/bin/python import unittest import doctest import sys from optparse import OptionParser from firmant.utils import get_module # Import this now to avoid it throwing errors. import pytz if __name__ == '__main__': suite = unittest.TestSuite() modules = ['firmant.du', 'firmant.extensions', 'firmant.feeds', 'firmant.i18n', #'firmant.parser', 'firmant.parsers', 'firmant.parsers.posts', 'firmant.tags', 'firmant.utils', #'firmant.writers', #'firmant.writers.j2' ] for module in modules: mod = get_module(module) args = {} for attr in ['module_relative', 'package', 'setUp', 'tearDown', 'globs', 'optionflags', 'parser', 'encoding']: if hasattr(mod, '_' + attr): args[attr] = getattr(mod, '_' + attr) suite.addTest(doctest.DocTestSuite(mod, **args)) results = unittest.TextTestRunner(verbosity=2).run(suite) if not results.wasSuccessful(): sys.exit(1)
#!/usr/bin/python import unittest import doctest import sys from optparse import OptionParser from firmant.utils import get_module # Import this now to avoid it throwing errors. import pytz if __name__ == '__main__': suite = unittest.TestSuite() modules = ['firmant.du', 'firmant.extensions', 'firmant.feeds', 'firmant.i18n', 'firmant.parser', 'firmant.parsers', 'firmant.parsers.posts', 'firmant.tags', 'firmant.utils', 'firmant.writers', 'firmant.writers.j2' ] for module in modules: mod = get_module(module) args = {} for attr in ['module_relative', 'package', 'setUp', 'tearDown', 'globs', 'optionflags', 'parser', 'encoding']: if hasattr(mod, '_' + attr): args[attr] = getattr(mod, '_' + attr) suite.addTest(doctest.DocTestSuite(mod, **args)) results = unittest.TextTestRunner(verbosity=2).run(suite) if not results.wasSuccessful(): sys.exit(1)
Remove unnecessary assert from view for Notice home.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from operator import itemgetter import logging from django.http import Http404 from django.template.response import TemplateResponse from django.views.generic.base import View from regulations.generator.api_reader import ApiReader from regulations.views.preamble import ( notice_data, CommentState) logger = logging.getLogger(__name__) class NoticeHomeView(View): """ Basic view that provides a list of regulations and notices to the context. """ template_name = None # We should probably have a default notice template. def get(self, request, *args, **kwargs): notices = ApiReader().notices().get("results", []) context = {} notices_meta = [] for notice in notices: try: if notice.get("document_number"): _, meta, _ = notice_data(notice["document_number"]) notices_meta.append(meta) except Http404: pass notices_meta = sorted(notices_meta, key=itemgetter("publication_date"), reverse=True) context["notices"] = notices_meta # Django templates won't show contents of CommentState as an Enum, so: context["comment_state"] = {state.name: state.value for state in CommentState} template = self.template_name return TemplateResponse(request=request, template=template, context=context)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from operator import itemgetter import logging from django.http import Http404 from django.template.response import TemplateResponse from django.views.generic.base import View from regulations.generator.api_reader import ApiReader from regulations.views.preamble import ( notice_data, CommentState) logger = logging.getLogger(__name__) class NoticeHomeView(View): """ Basic view that provides a list of regulations and notices to the context. """ template_name = None # We should probably have a default notice template. def get(self, request, *args, **kwargs): notices = ApiReader().notices().get("results", []) context = {} notices_meta = [] for notice in notices: try: if notice.get("document_number"): _, meta, _ = notice_data(notice["document_number"]) notices_meta.append(meta) except Http404: pass notices_meta = sorted(notices_meta, key=itemgetter("publication_date"), reverse=True) context["notices"] = notices_meta # Django templates won't show contents of CommentState as an Enum, so: context["comment_state"] = {state.name: state.value for state in CommentState} assert self.template_name template = self.template_name return TemplateResponse(request=request, template=template, context=context)
Allow user to change connection flags
<?php namespace Ddeboer\Imap; use Ddeboer\Imap\Exception\AuthenticationFailedException; class Server { protected $hostname; protected $port; protected $connection; protected $mailboxes; /** * Constructor * * @param string $hostname * @param int $port * @param string $flags */ public function __construct($hostname, $port = 993, $flags = '/imap/ssl/validate-cert') { $this->server = "{{$hostname}:{$port}{$flags}}"; } /** * Authenticate connection * * @param string $username Username * @param string $password Password * * @return \Ddeboer\Imap\Connection * @throws AuthenticationFailedException */ public function authenticate($username, $password) { $resource = @\imap_open($this->server, $username, $password, null, 1); if (false === $resource) { throw new AuthenticationFailedException($username); } $check = imap_check($resource); $mailbox = $check->Mailbox; $this->connection = substr($mailbox, 0, strpos($mailbox, '}')+1); // These are necessary to get rid of PHP throwing IMAP errors imap_errors(); imap_alerts(); return new Connection($resource, $this->connection); } }
<?php namespace Ddeboer\Imap; use Ddeboer\Imap\Exception\AuthenticationFailedException; class Server { protected $hostname; protected $port; protected $connection; protected $mailboxes; public function __construct($hostname, $port = '993') { if ($port == 993) { $cert = 'ssl'; } else { $cert = 'novalidate-cert'; } $this->server = '{' . $hostname . ':' . $port . '/imap/' . $cert . '}'; } /** * Authenticate connection * * @param string $username Username * @param string $password Password * * @return \Ddeboer\Imap\Connection * @throws AuthenticationFailedException */ public function authenticate($username, $password) { $resource = @\imap_open($this->server, $username, $password, null, 1); if (false === $resource) { throw new AuthenticationFailedException($username); } $check = imap_check($resource); $mailbox = $check->Mailbox; $this->connection = substr($mailbox, 0, strpos($mailbox, '}')+1); // These are necessary to get rid of PHP throwing IMAP errors imap_errors(); imap_alerts(); return new Connection($resource, $this->connection); } }
Refresh page after user creation
function viewUsers(view) { getUsers( success = function (data) { //console.log(data); populateUsersTable(data); }, error = function (jqxhr) { handleApiError(jqxhr); } ); function populateUsersTable(data) { var usersHtml = templates.userList(data); var isEditor = false; $('.section').html(usersHtml); $('.collections-select-table tbody tr').click(function () { $('.collections-select-table tbody tr').removeClass('selected'); $(this).addClass('selected'); var userId = $(this).attr('data-id'); viewUserDetails(userId); }); $('.radioBtnDiv').change(function () { if($('input:checked').val() === 'publisher') { isEditor = true; } else { isEditor = false; } }); $('.form-create-user').submit(function (e) { e.preventDefault(); var username = $('#create-user-username').val(); var email = $('#create-user-email').val(); var password = $('#create-user-password').val(); if (username.length < 1) { sweetAlert("Please enter the users name."); return; } if (email.length < 1) { sweetAlert("Please enter the users name."); return; } if (password.length < 1) { sweetAlert("Please enter the users password."); return; } postUser(username, email, password, isEditor); viewUsers(); }); } }
function viewUsers(view) { getUsers( success = function (data) { //console.log(data); populateUsersTable(data); }, error = function (jqxhr) { handleApiError(jqxhr); } ); function populateUsersTable(data) { var usersHtml = templates.userList(data); var isEditor = false; $('.section').html(usersHtml); $('.collections-select-table tbody tr').click(function () { $('.collections-select-table tbody tr').removeClass('selected'); $(this).addClass('selected'); var userId = $(this).attr('data-id'); viewUserDetails(userId); }); $('.radioBtnDiv').change(function () { if($('input:checked').val() === 'publisher') { isEditor = true; alert(isEditor); } else { isEditor = false; alert(isEditor); } }); $('.form-create-user').submit(function (e) { e.preventDefault(); var username = $('#create-user-username').val(); var email = $('#create-user-email').val(); var password = $('#create-user-password').val(); if (username.length < 1) { sweetAlert("Please enter the users name."); return; } if (email.length < 1) { sweetAlert("Please enter the users name."); return; } if (password.length < 1) { sweetAlert("Please enter the users password."); return; } postUser(username, email, password, isEditor); }); } }
Update webpack externals to fix issue with React
import { resolve } from 'path'; import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'; const config = { entry: { core: resolve('src', 'core', 'index.js'), react: resolve('src', 'react'), }, output: { filename: '[name].js', path: resolve('dist'), library: 'Typewriter', libraryTarget: 'umd', libraryExport: 'default', umdNamedDefine: true, }, externals: { react: 'react', 'react-dom': 'react-dom', }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { useBuiltIns: 'entry', corejs: 3, targets: { browsers: [ 'last 2 versions', 'ie >= 11', ], }, }, ], '@babel/preset-react', ], plugins: [ '@babel/plugin-proposal-class-properties', 'babel-plugin-transform-react-remove-prop-types', ] } } }, ] }, plugins: [ new BundleAnalyzerPlugin() ] }; export default config;
import { resolve } from 'path'; import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'; const config = { entry: { core: resolve('src', 'core', 'index.js'), react: resolve('src', 'react'), }, output: { filename: '[name].js', path: resolve('dist'), library: 'Typewriter', libraryTarget: 'umd', libraryExport: 'default', umdNamedDefine: true, }, externals: { react: 'React', }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { useBuiltIns: 'entry', corejs: 3, targets: { browsers: [ 'last 2 versions', 'ie >= 11', ], }, }, ], '@babel/preset-react', ], plugins: [ '@babel/plugin-proposal-class-properties', 'babel-plugin-transform-react-remove-prop-types', ] } } }, ] }, plugins: [ new BundleAnalyzerPlugin() ] }; export default config;
Use a tuple instead of a list for protocol membership test
# -*- coding: utf-8 -*- import KISSmetrics from KISSmetrics import request from urllib3 import PoolManager class Client: def __init__(self, key, trk_host=KISSmetrics.TRACKING_HOSTNAME, trk_proto=KISSmetrics.TRACKING_PROTOCOL): self.key = key if trk_proto not in ('http', 'https'): raise ValueError('trk_proto must be one of (http, https)') self.http = PoolManager() self.trk_host = trk_host self.trk_proto = trk_proto def request(self, query, method="GET"): url = '%s://%s/%s' % (self.trk_proto, self.trk_host, query) return self.http.request(method, url) def record(self, person, event, properties=None, timestamp=None, uri=KISSmetrics.RECORD_URI): this_request = request.record(self.key, person, event, timestamp=timestamp, properties=properties, uri=uri) return self.request(this_request) def set(self, person, properties=None, timestamp=None, uri=KISSmetrics.SET_URI): this_request = request.set(self.key, person, timestamp=timestamp, properties=properties, uri=uri) return self.request(this_request) def alias(self, person, identity, uri=KISSmetrics.ALIAS_URI): this_request = request.alias(self.key, person, identity, uri=uri) return self.request(this_request)
# -*- coding: utf-8 -*- import KISSmetrics from KISSmetrics import request from urllib3 import PoolManager class Client: def __init__(self, key, trk_host=KISSmetrics.TRACKING_HOSTNAME, trk_proto=KISSmetrics.TRACKING_PROTOCOL): self.key = key if trk_proto not in ['http', 'https']: raise ValueError('trk_proto must be one of (http, https)') self.http = PoolManager() self.trk_host = trk_host self.trk_proto = trk_proto def request(self, query, method="GET"): url = '%s://%s/%s' % (self.trk_proto, self.trk_host, query) return self.http.request(method, url) def record(self, person, event, properties=None, timestamp=None, uri=KISSmetrics.RECORD_URI): this_request = request.record(self.key, person, event, timestamp=timestamp, properties=properties, uri=uri) return self.request(this_request) def set(self, person, properties=None, timestamp=None, uri=KISSmetrics.SET_URI): this_request = request.set(self.key, person, timestamp=timestamp, properties=properties, uri=uri) return self.request(this_request) def alias(self, person, identity, uri=KISSmetrics.ALIAS_URI): this_request = request.alias(self.key, person, identity, uri=uri) return self.request(this_request)
Add summary price own components --skip-ci
import React from 'react' import Helper from '../../helpers' import SingleComponentItemView from './SingleComponentItemView' import './ItemView.css' const ItemView = props => { const {typeID, name, quantity, components, component_me, facility_me, prices} = props let price = 0 let cmps = Helper.manufactureQty(components, component_me, facility_me, quantity) let _components = cmps.map(val => { price += val.qty * prices[val.item_id] return <SingleComponentItemView key={val.item_id} typeID={val.item_id} name={val.item_name} quantity={val.qty} prices={prices} /> }) return ( <li> <div className='item-view-cont'> <div className='img-box'> <img alt={name} src={`https://image.eveonline.com/Type/${typeID}_32.png`}/> </div> <div className='item-descr'> <div className='item-row-first'> <div className='item-name'> {name} </div> <div className='item-amount'> {'x'}&nbsp;{Helper.qty(quantity)} </div> <div className='item-price txt-lime'> {Helper.price(price)} </div> </div> </div> </div> <ul className="ulOwnComponents">{_components}</ul> </li> ) } export default ItemView
import React from 'react' import Helper from '../../helpers' import SingleComponentItemView from './SingleComponentItemView' import './ItemView.css' const ItemView = props => { const {typeID, name, quantity, components, component_me, facility_me, prices} = props const sum = Helper.price(props.price * quantity) const price = Helper.price(props.price) let cmps = Helper.manufactureQty(components, component_me, facility_me, quantity) let _components = cmps.map(val => { return <SingleComponentItemView key={val.item_id} typeID={val.item_id} name={val.item_name} quantity={val.qty} prices={prices} /> }) return ( <li> <div className='item-view-cont'> <div className='img-box'> <img alt={name} src={`https://image.eveonline.com/Type/${typeID}_32.png`}/> </div> <div className='item-descr'> <div className='item-row-first'> <div className='item-name'> {name} </div> <div className='item-amount'> {'x'}&nbsp;{Helper.qty(quantity)} </div> <div className='item-price txt-lime'> {price} </div> </div> </div> </div> <ul className="ulOwnComponents">{_components}</ul> </li> ) } export default ItemView
Add long description (from README.md)
#!/usr/bin/env python import os from setuptools import setup def get_long_description(): filename = os.path.join(os.path.dirname(__file__), 'README.md') with open(filename) as f: return f.read() setup(name='pyannotate', version='1.0.5', description="PyAnnotate: Auto-generate PEP-484 annotations", long_description=get_long_description(), author='Dropbox', author_email='[email protected]', url='https://github.com/dropbox/pyannotate', license='Apache 2.0', platforms=['POSIX'], packages=['pyannotate_runtime', 'pyannotate_tools', 'pyannotate_tools.annotations', 'pyannotate_tools.fixes'], entry_points={'console_scripts': ['pyannotate=pyannotate_tools.annotations.__main__:main']}, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development', ], install_requires = ['six', 'mypy_extensions', 'typing >= 3.5.3; python_version < "3.5"' ], )
#!/usr/bin/env python from setuptools import setup setup(name='pyannotate', version='1.0.5', description="PyAnnotate: Auto-generate PEP-484 annotations", author='Dropbox', author_email='[email protected]', url='https://github.com/dropbox/pyannotate', license='Apache 2.0', platforms=['POSIX'], packages=['pyannotate_runtime', 'pyannotate_tools', 'pyannotate_tools.annotations', 'pyannotate_tools.fixes'], entry_points={'console_scripts': ['pyannotate=pyannotate_tools.annotations.__main__:main']}, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development', ], install_requires = ['six', 'mypy_extensions', 'typing >= 3.5.3; python_version < "3.5"' ], )
Return json, not just a string id
import logging from flask import request from flask_restplus import Resource from gameserver.game import Game from gameserver.models import Player from gameserver.api.restplus import api from gameserver.api.serializers import player_get, player_post from gameserver.database import db db_session = db.session log = logging.getLogger(__name__) ns = api.namespace('players', description='Operations related to players') game = Game() @ns.route('/') class PlayerCollection(Resource): @api.response(200, 'Success') @api.marshal_list_with(player_get) def get(self): """ Returns list of players. """ players = game.get_players() return players @api.response(201, 'Player successfully created.') @api.expect(player_post) def post(self): """ Creates a new game player. """ data = request.json player = game.create_player(data['name']) db_session.commit() return dict(id=player.id), 201 @ns.route('/<string:id>') @ns.param('id', 'The player id') class Player(Resource): @api.response(404, 'Player not found') @api.response(200, 'Success') @api.marshal_with(player_get) def get(self, id): """ Returns the specified player. """ player = game.get_player(id) if not player: api.abort(404) return player
import logging from flask import request from flask_restplus import Resource from gameserver.game import Game from gameserver.models import Player from gameserver.api.restplus import api from gameserver.api.serializers import player_get, player_post from gameserver.database import db db_session = db.session log = logging.getLogger(__name__) ns = api.namespace('players', description='Operations related to players') game = Game() @ns.route('/') class PlayerCollection(Resource): @api.response(200, 'Success') @api.marshal_list_with(player_get) def get(self): """ Returns list of players. """ players = game.get_players() return players @api.response(201, 'Player successfully created.') @api.expect(player_post) def post(self): """ Creates a new game player. """ data = request.json player = game.create_player(data['name']) db_session.commit() return player.id, 201 @ns.route('/<string:id>') @ns.param('id', 'The player id') class Player(Resource): @api.response(404, 'Player not found') @api.response(200, 'Success') @api.marshal_with(player_get) def get(self, id): """ Returns the specified player. """ player = game.get_player(id) if not player: api.abort(404) return player
Validate XLIFF files in tests using the XSD
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Tests\Resources; use PHPUnit\Framework\TestCase; use Symfony\Component\Translation\Util\XliffUtils; class TranslationFilesTest extends TestCase { /** * @dataProvider provideTranslationFiles */ public function testTranslationFileIsValid($filePath) { $document = new \DOMDocument(); $document->loadXML(file_get_contents($filePath)); $errors = XliffUtils::validateSchema($document); $this->assertCount(0, $errors, sprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message')))); } public function provideTranslationFiles() { return array_map( function ($filePath) { return (array) $filePath; }, glob(\dirname(__DIR__, 2).'/Resources/translations/*.xlf') ); } public function testNorwegianAlias() { $this->assertFileEquals( \dirname(__DIR__, 2).'/Resources/translations/validators.nb.xlf', \dirname(__DIR__, 2).'/Resources/translations/validators.no.xlf', 'The NO locale should be an alias for the NB variant of the Norwegian language.' ); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Tests\Resources; use PHPUnit\Framework\TestCase; use PHPUnit\Util\Xml\Loader; class TranslationFilesTest extends TestCase { /** * @dataProvider provideTranslationFiles */ public function testTranslationFileIsValid($filePath) { $loader = class_exists(Loader::class) ? [new Loader(), 'loadFile'] : ['PHPUnit\Util\XML', 'loadfile']; $loader($filePath, false, false, true); $this->addToAssertionCount(1); } public function provideTranslationFiles() { return array_map( function ($filePath) { return (array) $filePath; }, glob(\dirname(__DIR__, 2).'/Resources/translations/*.xlf') ); } public function testNorwegianAlias() { $this->assertFileEquals( \dirname(__DIR__, 2).'/Resources/translations/validators.nb.xlf', \dirname(__DIR__, 2).'/Resources/translations/validators.no.xlf', 'The NO locale should be an alias for the NB variant of the Norwegian language.' ); } }
Make component name match file name
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import IconButton from './../molecules/IconButton'; class SocialMediaIcons extends Component { shareOnFacebook() { const url = window.location.href; window.open(`https://www.facebook.com/sharer/sharer.php?u=${url}`, '_blank'); } shareOnTwitter() { let message = this.props.social.description; if (message.length >= 144) { message = this.props.social.shortDescription; } const url = `https://twitter.com/intent/tweet?text=${message}&source=webclient`; window.open(url, '_blank'); } render() { return ( <section data-primary={this.props.primary} className="social-media-sharing"> <IconButton square onClick={this.shareOnFacebook.bind(this)}> <span className="icon-facebook2"></span> </IconButton> <IconButton square onClick={this.shareOnTwitter.bind(this)}> <span className="icon-twitter"></span> </IconButton> <IconButton square> <span className="icon-link"></span> </IconButton> <label>Share</label> </section> ); } } SocialMediaIcons.propTypes = { social: PropTypes.object, primary: PropTypes.bool }; export default SocialMediaIcons;
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import IconButton from './../molecules/IconButton'; class SocialMediaSharing extends Component { shareOnFacebook() { const url = window.location.href; window.open(`https://www.facebook.com/sharer/sharer.php?u=${url}`, '_blank'); } shareOnTwitter() { let message = this.props.social.description; if (message.length >= 144) { message = this.props.social.shortDescription; } const url = `https://twitter.com/intent/tweet?text=${message}&source=webclient`; window.open(url, '_blank'); } render() { return ( <section data-primary={this.props.primary} className="social-media-sharing"> <IconButton square onClick={this.shareOnFacebook.bind(this)}> <span className="icon-facebook2"></span> </IconButton> <IconButton square onClick={this.shareOnTwitter.bind(this)}> <span className="icon-twitter"></span> </IconButton> <IconButton square> <span className="icon-link"></span> </IconButton> <label>Share</label> </section> ); } } SocialMediaSharing.propTypes = { social: PropTypes.object, primary: PropTypes.bool }; export default SocialMediaSharing;
Configure HTTP and Sockets API
'use strict'; var _ = require('underscore'), path = require('path'), winston = module.parent.require('winston'), meta = module.parent.require('./meta'), routes = require('./app/routes'), sockets = require('./app/sockets'), emitter = module.parent.require('./emitter'), settings = null, namespace = 'ns:custom_fields'; (function (Plugin) { function changeTemplates() { var fs = require('fs-extra'), path = require('path'), nconf = module.parent.require('nconf'), editPath = path.join(nconf.get('base_dir'), 'public/templates/account/edit.tpl'); winston.log('debug', 'Template %s will be replaces with a template for custom fields'); fs.copySync(path.join(__dirname, './public/templates/account/edit.tpl'), editPath); } //NodeBB list of Hooks: https://github.com/NodeBB/NodeBB/wiki/Hooks Plugin.hooks = { filters: { menu: function (custom_header, callback) { custom_header.plugins.push({ route: '/plugins/custom-fields', icon : 'fa-plus-square', name : 'Custom Fields' }); callback(null, custom_header); } }, statics: { load: function (params, callback) { routes.setup(params, function () { sockets.setup(callback); }); //emitter.on('templates:compiled', changeTemplates); } } }; })(module.exports);
'use strict'; var _ = require('underscore'), path = require('path'), winston = module.parent.require('winston'), meta = module.parent.require('./meta'), routes = require('./app/routes'), emitter = module.parent.require('./emitter'), settings = null, namespace = 'ns:custom_fields'; (function (Plugin) { function changeTemplates() { var fs = require('fs-extra'), path = require('path'), nconf = module.parent.require('nconf'), editPath = path.join(nconf.get('base_dir'), 'public/templates/account/edit.tpl'); winston.log('debug', 'Template %s will be replaces with a template for custom fields'); fs.copySync(path.join(__dirname, './public/templates/account/edit.tpl'), editPath); } //NodeBB list of Hooks: https://github.com/NodeBB/NodeBB/wiki/Hooks Plugin.hooks = { filters: { menu: function (custom_header, callback) { custom_header.plugins.push({ route: '/plugins/custom-fields', icon : 'fa-plus-square', name : 'Custom Fields' }); callback(null, custom_header); } }, statics: { load: function (params, callback) { routes.setup(params, callback); //emitter.on('templates:compiled', changeTemplates); } } }; })(module.exports);
Add default values to get field values
/* * Copyright 2011 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.splunk; public class DistributedPeer extends Entity { public DistributedPeer(Service service, String path) { super(service, path); } public String getBuild() { return getString("build", null); } public String[] getBundleVersions() { return getStringArray("bundle_versions", null); } public String getGuid() { return getString("guid", null); } public String getLicenseSignature() { return getString("licenseSignature", null); } public String getPeerName() { return getString("peerName", null); } public String getPeerType() { return getString("peerType", null); } public String getReplicationStatus() { return getString("replicationStatus", null); } public String getStatus() { return getString("status", null); } public String getVersion() { return getString("version", null); } public boolean isDisabled() { return getBoolean("disabled", true); } public boolean isHttps() { return getBoolean("is_https", true); } }
/* * Copyright 2011 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.splunk; public class DistributedPeer extends Entity { public DistributedPeer(Service service, String path) { super(service, path); } public String getBuild() { return getString("build"); } public String[] getBundleVersions() { return getStringArray("bundle_versions", null); } public String getGuid() { return getString("guid"); } public String getLicenseSignature() { return getString("licenseSignature"); } public String getPeerName() { return getString("peerName"); } public String getPeerType() { return getString("peerType"); } public String getReplicationStatus() { return getString("replicationStatus"); } public String getStatus() { return getString("status"); } public String getVersion() { return getString("version"); } public boolean isDisabled() { return getBoolean("disabled"); } public boolean isHttps() { return getBoolean("is_https"); } }
Remove old comment, and unessary if logic
import React from "react"; import ReactDOM from "react-dom"; import $ from "jquery"; import Backbone from "backbone"; export default React.createClass({ displayName: "Tag", propTypes: { tag: React.PropTypes.instanceOf(Backbone.Model).isRequired, renderLinks: React.PropTypes.bool }, getDefaultProps: function() { return { renderLinks: true } }, onClick(e) { let { onTagClick } = this.props; e.stopPropagation(); e.preventDefault(); if (onTagClick) { onTagClick(this.props.tag); } }, componentDidMount: function() { // FIXME: // https://github.com/yannickcr/eslint-plugin-react/issues/678#issue-165177220 var el = ReactDOM.findDOMNode(this), $el = $(el), tag = this.props.tag; $el.tooltip({ title: tag.get("description"), placement: "left" }); }, render: function() { var tag = this.props.tag, tagName = tag.get("name"), link; return ( <li className="tag"> <span onClick={ this.onClick }> {tagName} </span> </li> ); } });
import React from "react"; import ReactDOM from "react-dom"; import $ from "jquery"; import Backbone from "backbone"; export default React.createClass({ displayName: "Tag", propTypes: { tag: React.PropTypes.instanceOf(Backbone.Model).isRequired, renderLinks: React.PropTypes.bool }, getDefaultProps: function() { return { renderLinks: true } }, onClick(e) { let { onTagClick } = this.props; e.stopPropagation(); e.preventDefault(); // Still causing a warning // "Failed Context Types: Required context `router`" if (onTagClick) { onTagClick(this.props.tag); } }, componentDidMount: function() { // FIXME: // https://github.com/yannickcr/eslint-plugin-react/issues/678#issue-165177220 var el = ReactDOM.findDOMNode(this), $el = $(el), tag = this.props.tag; $el.tooltip({ title: tag.get("description"), placement: "left" }); }, render: function() { var tag = this.props.tag, tagName = tag.get("name"), link; if (this.props.renderLinks) { link = ( <span onClick={ this.onClick }> {tagName} </span> ); } else { link = ( <span> {tagName} </span> ) } return ( <li className="tag"> {link} </li> ); } });
Add in windows drive pattern match. As title.
from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim from numba import cuda from numba.core import config class MyError(Exception): pass regex_pattern = ( r'In function [\'"]test_exc[\'"], file [\:\.\/\\\-a-zA-Z_0-9]+, line \d+' ) class TestUserExc(SerialMixin, unittest.TestCase): def test_user_exception(self): @cuda.jit("void(int32)", debug=True) def test_exc(x): if x == 1: raise MyError elif x == 2: raise MyError("foo") test_exc(0) # no raise with self.assertRaises(MyError) as cm: test_exc(1) if not config.ENABLE_CUDASIM: self.assertRegexpMatches(str(cm.exception), regex_pattern) self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]", str(cm.exception)) with self.assertRaises(MyError) as cm: test_exc(2) if not config.ENABLE_CUDASIM: self.assertRegexpMatches(str(cm.exception), regex_pattern) self.assertRegexpMatches(str(cm.exception), regex_pattern) self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]: foo", str(cm.exception)) if __name__ == '__main__': unittest.main()
from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim from numba import cuda from numba.core import config class MyError(Exception): pass regex_pattern = ( r'In function [\'"]test_exc[\'"], file [\.\/\\\-a-zA-Z_0-9]+, line \d+' ) class TestUserExc(SerialMixin, unittest.TestCase): def test_user_exception(self): @cuda.jit("void(int32)", debug=True) def test_exc(x): if x == 1: raise MyError elif x == 2: raise MyError("foo") test_exc(0) # no raise with self.assertRaises(MyError) as cm: test_exc(1) if not config.ENABLE_CUDASIM: self.assertRegexpMatches(str(cm.exception), regex_pattern) self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]", str(cm.exception)) with self.assertRaises(MyError) as cm: test_exc(2) if not config.ENABLE_CUDASIM: self.assertRegexpMatches(str(cm.exception), regex_pattern) self.assertRegexpMatches(str(cm.exception), regex_pattern) self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]: foo", str(cm.exception)) if __name__ == '__main__': unittest.main()
Support of comparison null values in object properties
package lv.ctco.cukesrest.internal.matchers; import org.hamcrest.*; import java.math.*; public class EqualToIgnoringTypeMatcher { public static Matcher<String> equalToIgnoringType(final String value) { return new BaseMatcher<String>() { @Override public void describeTo(Description description) { description.appendText("equal to ignoring type " + value); } @Override public boolean matches(Object item) { if (item == null) { return value.equalsIgnoreCase("null"); } String toString = item.toString(); if (toString.equals(value)) return true; if (item instanceof Number) { BigDecimal observedValue = item instanceof BigDecimal ? (BigDecimal) item : new BigDecimal(toString); return new BigDecimal(value).compareTo(observedValue) == 0; } return false; } }; } public static Matcher<String> notEqualToIgnoringType(final String value) { return new BaseMatcher<String>() { @Override public void describeTo(Description description) { description.appendText("not equal to ignoring type " + value); } @Override public boolean matches(Object item) { String toString = item.toString(); if (!toString.equals(value)) return true; if (item instanceof Number) { BigDecimal observedValue = item instanceof BigDecimal ? (BigDecimal) item : new BigDecimal(toString); return new BigDecimal(value).compareTo(observedValue) != 0; } return false; } }; } }
package lv.ctco.cukesrest.internal.matchers; import org.hamcrest.*; import java.math.*; public class EqualToIgnoringTypeMatcher { public static Matcher<String> equalToIgnoringType(final String value) { return new BaseMatcher<String>() { @Override public void describeTo(Description description) { description.appendText("equal to ignoring type " + value); } @Override public boolean matches(Object item) { String toString = item.toString(); if (toString.equals(value)) return true; if (item instanceof Number) { BigDecimal observedValue = item instanceof BigDecimal ? (BigDecimal) item : new BigDecimal(toString); return new BigDecimal(value).compareTo(observedValue) == 0; } return false; } }; } public static Matcher<String> notEqualToIgnoringType(final String value) { return new BaseMatcher<String>() { @Override public void describeTo(Description description) { description.appendText("not equal to ignoring type " + value); } @Override public boolean matches(Object item) { String toString = item.toString(); if (!toString.equals(value)) return true; if (item instanceof Number) { BigDecimal observedValue = item instanceof BigDecimal ? (BigDecimal) item : new BigDecimal(toString); return new BigDecimal(value).compareTo(observedValue) != 0; } return false; } }; } }
Check if there are associated acts before querying for them
from artgraph.node import NodeTypes from artgraph.plugins import Plugin class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node @staticmethod def get_target_node_type(): return NodeTypes.ARTIST def get_nodes(self): from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship relationships = [] wikicode = self.get_wikicode(self._node.get_dbtitle()) if wikicode: templates = wikicode.filter_templates() for t in templates: if t.name.matches('Infobox musical artist'): # Fill in current node info if t.has('birth_name'): name = str(t.get('birth_name').value) db = self.get_artistgraph_connection() cursor = db.cursor() cursor.execute("UPDATE artist SET name = %s WHERE artistID = %s", (name, self._node.get_id())) db.commit() db.close() if not t.has('associated_acts'): continue associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(str(w.title), NodeTypes.ARTIST))) return relationships
from artgraph.node import NodeTypes from artgraph.plugins import Plugin class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node @staticmethod def get_target_node_type(): return NodeTypes.ARTIST def get_nodes(self): from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship relationships = [] wikicode = self.get_wikicode(self._node.get_dbtitle()) if wikicode: templates = wikicode.filter_templates() for t in templates: if t.name.matches('Infobox musical artist'): # Fill in current node info if t.has('birth_name'): name = str(t.get('birth_name').value) db = self.get_artistgraph_connection() cursor = db.cursor() cursor.execute("UPDATE artist SET name = %s WHERE artistID = %s", (name, self._node.get_id())) db.commit() db.close() associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(str(w.title), NodeTypes.ARTIST))) return relationships
[JUnit] Remove cucumber.api glue annotation check
package io.cucumber.junit; import io.cucumber.core.exception.CucumberException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; final class Assertions { private Assertions() { } static void assertNoCucumberAnnotatedMethods(Class clazz) { for (Method method : clazz.getDeclaredMethods()) { for (Annotation annotation : method.getAnnotations()) { if (annotation.annotationType().getName().startsWith("io.cucumber")) { throw new CucumberException( "\n\n" + "Classes annotated with @RunWith(Cucumber.class) must not define any\n" + "Step Definition or Hook methods. Their sole purpose is to serve as\n" + "an entry point for JUnit. Step Definitions and Hooks should be defined\n" + "in their own classes. This allows them to be reused across features.\n" + "Offending class: " + clazz + "\n" ); } } } } }
package io.cucumber.junit; import io.cucumber.core.exception.CucumberException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; final class Assertions { private Assertions() { } static void assertNoCucumberAnnotatedMethods(Class clazz) { for (Method method : clazz.getDeclaredMethods()) { for (Annotation annotation : method.getAnnotations()) { if (annotation.annotationType().getName().startsWith("cucumber") //TODO: Remove once migrated || annotation.annotationType().getName().startsWith("io.cucumber")) { throw new CucumberException( "\n\n" + "Classes annotated with @RunWith(Cucumber.class) must not define any\n" + "Step Definition or Hook methods. Their sole purpose is to serve as\n" + "an entry point for JUnit. Step Definitions and Hooks should be defined\n" + "in their own classes. This allows them to be reused across features.\n" + "Offending class: " + clazz + "\n" ); } } } } }
Check and makse sure we have no dispatcher object
<?php namespace Conduit\Middleware; use Phly\Conduit\MiddlewareInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Aura\Router\Router; use Aura\Dispatcher\Dispatcher; use Aura\Di\Container; class ApplicationMiddleware implements MiddlewareInterface { private $container; public function __construct(Container $container) { $this->container = $container; } public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $router = $this->container->get('router'); $dispatcher = $this->container->get('dispatcher'); $server = $request->getServerParams(); $path = parse_url($server['REQUEST_URI'], PHP_URL_PATH); $route = $router->match($path, $server); if (! $route) { return $next($request, $response); } $params = $route->params; if (is_string($params['controller']) && ! $this->dispatcher->hasObject($params['controller']) ) { // create the controller object $params['controller'] = $this->container->newInstance($params['controller']); } $params['request'] = $request; $params['response'] = $response; $result = $dispatcher->__invoke($params); if ($result instanceof ResponseInterface) { return $result; } if (is_string($result)) { return $response->write($result); } return $response; } }
<?php namespace Conduit\Middleware; use Phly\Conduit\MiddlewareInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; use Aura\Router\Router; use Aura\Dispatcher\Dispatcher; use Aura\Di\Container; class ApplicationMiddleware implements MiddlewareInterface { private $container; public function __construct(Container $container) { $this->container = $container; } public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $router = $this->container->get('router'); $dispatcher = $this->container->get('dispatcher'); $server = $request->getServerParams(); $path = parse_url($server['REQUEST_URI'], PHP_URL_PATH); $route = $router->match($path, $server); if (! $route) { return $next($request, $response); } $params = $route->params; if (is_string($params['controller'])) { // create the controller object $params['controller'] = $this->container->newInstance($params['controller']); } $params['request'] = $request; $params['response'] = $response; $result = $dispatcher->__invoke($params); if ($result instanceof ResponseInterface) { return $result; } if (is_string($result)) { return $response->write($result); } return $response; } }
Set cov-core dependency to 1.9
import setuptools setuptools.setup(name='pytest-cov', version='1.6', description='py.test plugin for coverage reporting with ' 'support for both centralised and distributed testing, ' 'including subprocesses and multiprocessing', long_description=open('README.rst').read().strip(), author='Marc Schlaich', author_email='[email protected]', url='https://github.com/schlamar/pytest-cov', py_modules=['pytest_cov'], install_requires=['pytest>=2.5.2', 'cov-core>=1.9'], entry_points={'pytest11': ['pytest_cov = pytest_cov']}, license='MIT License', zip_safe=False, keywords='py.test pytest cover coverage distributed parallel', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Topic :: Software Development :: Testing'])
import setuptools setuptools.setup(name='pytest-cov', version='1.6', description='py.test plugin for coverage reporting with ' 'support for both centralised and distributed testing, ' 'including subprocesses and multiprocessing', long_description=open('README.rst').read().strip(), author='Marc Schlaich', author_email='[email protected]', url='https://github.com/schlamar/pytest-cov', py_modules=['pytest_cov'], install_requires=['pytest>=2.5.2', 'cov-core>=1.8'], entry_points={'pytest11': ['pytest_cov = pytest_cov']}, license='MIT License', zip_safe=False, keywords='py.test pytest cover coverage distributed parallel', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Topic :: Software Development :: Testing'])
Fix missing semi-colon bug in javascript file
import 'jquery-ui-dist/jquery-ui'; $(() => { // Is there already one prefix section on this Phase? // // draggableSections - A jQuery object, the sortable element. // // Returns Boolean function prefixSectionExists(draggableSections) { return !!draggableSections .has('[data-modifiable=true]:nth-child(1)').length && !!draggableSections.has('[data-modifiable=true]:nth-child(2)').length; } // Initialize the draggable-sections element as a jQuery sortable. // Read the docs here for more info: http://api.jqueryui.com/sortable/ $('.draggable-sections').sortable({ handle: 'i.fa-bars', axis: 'y', cursor: 'move', beforeStop() { if (prefixSectionExists($(this))) { // Prevent the sort action from completing. Moves element back to source $(this).sortable('cancel'); // Display a wobble effec to signify error $(this).effect('shake'); } }, update() { // Collect the section-id from each section element on the page. const sectionIds = $('.section[data-section-id]') .map((i, element) => $(element).data('section-id')).toArray(); // Post the section IDs to the server in their new order on the page. $.rails.ajax({ url: $(this).data('url'), method: 'post', data: { sort_order: sectionIds }, }); }, }); });
import 'jquery-ui-dist/jquery-ui'; $(() => { // Is there already one prefix section on this Phase? // // draggableSections - A jQuery object, the sortable element. // // Returns Boolean function prefixSectionExists(draggableSections) { return !!draggableSections .has('[data-modifiable=true]:nth-child(1)').length && !!draggableSections.has('[data-modifiable=true]:nth-child(2)').length } // Initialize the draggable-sections element as a jQuery sortable. // Read the docs here for more info: http://api.jqueryui.com/sortable/ $('.draggable-sections').sortable({ handle: 'i.fa-bars', axis: 'y', cursor: 'move', beforeStop() { if (prefixSectionExists($(this))) { // Prevent the sort action from completing. Moves element back to source $(this).sortable('cancel'); // Display a wobble effec to signify error $(this).effect('shake'); } }, update() { // Collect the section-id from each section element on the page. const sectionIds = $('.section[data-section-id]') .map((i, element) => $(element).data('section-id')).toArray(); // Post the section IDs to the server in their new order on the page. $.rails.ajax({ url: $(this).data('url'), method: 'post', data: { sort_order: sectionIds }, }); }, }); });
Fix typo in test name
package com.genymobile.scrcpy; import junit.framework.Assert; import org.junit.Test; import java.nio.charset.StandardCharsets; public class StringUtilsTest { @Test @SuppressWarnings("checkstyle:MagicNumber") public void testUtf8Truncate() { String s = "aÉbÔc"; byte[] utf8 = s.getBytes(StandardCharsets.UTF_8); Assert.assertEquals(7, utf8.length); int count; count = StringUtils.getUtf8TruncationIndex(utf8, 1); Assert.assertEquals(1, count); count = StringUtils.getUtf8TruncationIndex(utf8, 2); Assert.assertEquals(1, count); // É is 2 bytes-wide count = StringUtils.getUtf8TruncationIndex(utf8, 3); Assert.assertEquals(3, count); count = StringUtils.getUtf8TruncationIndex(utf8, 4); Assert.assertEquals(4, count); count = StringUtils.getUtf8TruncationIndex(utf8, 5); Assert.assertEquals(4, count); // Ô is 2 bytes-wide count = StringUtils.getUtf8TruncationIndex(utf8, 6); Assert.assertEquals(6, count); count = StringUtils.getUtf8TruncationIndex(utf8, 7); Assert.assertEquals(7, count); count = StringUtils.getUtf8TruncationIndex(utf8, 8); Assert.assertEquals(7, count); // no more chars } }
package com.genymobile.scrcpy; import junit.framework.Assert; import org.junit.Test; import java.nio.charset.StandardCharsets; public class StringUtilsTest { @Test @SuppressWarnings("checkstyle:MagicNumber") public void testUtf8Trucate() { String s = "aÉbÔc"; byte[] utf8 = s.getBytes(StandardCharsets.UTF_8); Assert.assertEquals(7, utf8.length); int count; count = StringUtils.getUtf8TruncationIndex(utf8, 1); Assert.assertEquals(1, count); count = StringUtils.getUtf8TruncationIndex(utf8, 2); Assert.assertEquals(1, count); // É is 2 bytes-wide count = StringUtils.getUtf8TruncationIndex(utf8, 3); Assert.assertEquals(3, count); count = StringUtils.getUtf8TruncationIndex(utf8, 4); Assert.assertEquals(4, count); count = StringUtils.getUtf8TruncationIndex(utf8, 5); Assert.assertEquals(4, count); // Ô is 2 bytes-wide count = StringUtils.getUtf8TruncationIndex(utf8, 6); Assert.assertEquals(6, count); count = StringUtils.getUtf8TruncationIndex(utf8, 7); Assert.assertEquals(7, count); count = StringUtils.getUtf8TruncationIndex(utf8, 8); Assert.assertEquals(7, count); // no more chars } }
Use github auth token for api.github.com
<?php namespace PharIo\Phive; class CurlConfigBuilder { /** * @var Environment */ private $environment; /** * @var PhiveVersion */ private $phiveVersion; /** * @param Environment $environment * @param PhiveVersion $phiveVersion */ public function __construct(Environment $environment, PhiveVersion $phiveVersion) { $this->environment = $environment; $this->phiveVersion = $phiveVersion; } public function build() { $curlConfig = new CurlConfig( sprintf('Phive %s on %s', $this->phiveVersion->getVersion(), $this->environment->getRuntimeString() ) ); $curlConfig->addLocalSslCertificate( new LocalSslCertificate( 'hkps.pool.sks-keyservers.net', __DIR__ . '/../../../conf/ssl/ca_certs/sks-keyservers.netCA.pem' ) ); if ($this->environment->hasProxy()) { $curlConfig->setProxy($this->environment->getProxy()); } if ($this->environment->hasGitHubAuthToken()) { $curlConfig->addAuthenticationToken( 'api.github.com', $this->environment->getGitHubAuthToken() ); } return $curlConfig; } }
<?php namespace PharIo\Phive; class CurlConfigBuilder { /** * @var Environment */ private $environment; /** * @var PhiveVersion */ private $phiveVersion; /** * @param Environment $environment * @param PhiveVersion $phiveVersion */ public function __construct(Environment $environment, PhiveVersion $phiveVersion) { $this->environment = $environment; $this->phiveVersion = $phiveVersion; } public function build() { $curlConfig = new CurlConfig( sprintf('Phive %s on %s', $this->phiveVersion->getVersion(), $this->environment->getRuntimeString() ) ); $curlConfig->addLocalSslCertificate( new LocalSslCertificate( 'hkps.pool.sks-keyservers.net', __DIR__ . '/../../../conf/ssl/ca_certs/sks-keyservers.netCA.pem' ) ); if ($this->environment->hasProxy()) { $curlConfig->setProxy($this->environment->getProxy()); } if ($this->environment->hasGitHubAuthToken()) { $curlConfig->addAuthenticationToken( 'github.com', $this->environment->getGitHubAuthToken() ); } return $curlConfig; } }
Address review concerns: allow range requirements, specify requirments file path explicitly, ...
import os import re REQUIREMENT_RE = re.compile(r'^(([^=]+)[=<>]+[^#]+)(#.*)?$') def update_pins(setup_args): # Use requirements and constraints to set version pins packages = set() install_dir = os.path.dirname(__file__) with open(os.path.join(install_dir, 'requirements.txt')) as requirements: for r in requirements: if r.lower().strip() == 'dallinger': continue if not r.startswith('-') or r.startswith('#'): packages.add(r.strip().lower()) requirements = [] with open(os.path.join(install_dir, 'constraints.txt')) as constraints: for c in constraints: matches = REQUIREMENT_RE.match(c.strip()) if not matches: continue match = matches.group(2).lower().strip() req = matches.group(1).strip() if match in packages: requirements.append(req) # pin extra requirements for extra in setup_args['extras_require']: extra_packages = setup_args['extras_require'][extra] for i, package in enumerate(extra_packages[:]): if package.lower() == match: extra_packages[i] = req if requirements: setup_args['install_requires'] = requirements # If not on Heroku, install setuptools-markdown. try: os.environ["DYNO"] except KeyError: setup_args.update({ "setup_requires": ['setuptools-markdown==0.2'], "long_description_markdown_filename": 'README.md', })
import os import re def update_pins(setup_args): # Use requirements and constraints to set version pins packages = set() with open('./requirements.txt') as requirements: for r in requirements: if r.lower().strip() == 'dallinger': continue if not r.startswith('-') or r.startswith('#'): packages.add(r.strip().lower()) requirements = [] REQUIREMENT_RE = re.compile(r'^(([^=]+)==[^#]+)(#.*)?$') with open('./constraints.txt') as constraints: for c in constraints: matches = REQUIREMENT_RE.match(c.strip()) if not matches: continue match = matches.group(2).lower().strip() req = matches.group(1).strip() if match in packages: requirements.append(req) # pin extra requirements for extra in setup_args['extras_require']: extra_packages = setup_args['extras_require'][extra] for i, package in enumerate(extra_packages[:]): if package.lower() == match: extra_packages[i] = req if requirements: setup_args['install_requires'] = requirements # If not on Heroku, install setuptools-markdown. try: os.environ["DYNO"] except KeyError: setup_args.update({ "setup_requires": ['setuptools-markdown==0.2'], "long_description_markdown_filename": 'README.md', })
Add QA skip for import ordering
from logging import getLogger from pkg_resources import get_distribution from django import apps log = getLogger(__name__) class AppConfig(apps.AppConfig): name = "axes" initialized = False @classmethod def initialize(cls): """ Initialize Axes logging and show version information. This method is re-entrant and can be called multiple times. It displays version information exactly once at application startup. """ if cls.initialized: return cls.initialized = True # Only import settings, checks, and signals one time after Django has been initialized from axes.conf import settings # noqa from axes import checks, signals # noqa # Skip startup log messages if Axes is not set to verbose if settings.AXES_VERBOSE: log.info("AXES: BEGIN LOG") log.info( "AXES: Using django-axes version %s", get_distribution("django-axes").version, ) if settings.AXES_ONLY_USER_FAILURES: log.info("AXES: blocking by username only.") elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: log.info("AXES: blocking by combination of username and IP.") elif settings.AXES_LOCK_OUT_BY_USER_OR_IP: log.info("AXES: blocking by username or IP.") else: log.info("AXES: blocking by IP only.") def ready(self): self.initialize()
from logging import getLogger from pkg_resources import get_distribution from django import apps log = getLogger(__name__) class AppConfig(apps.AppConfig): name = "axes" initialized = False @classmethod def initialize(cls): """ Initialize Axes logging and show version information. This method is re-entrant and can be called multiple times. It displays version information exactly once at application startup. """ if cls.initialized: return cls.initialized = True # Only import settings, checks, and signals one time after Django has been initialized from axes.conf import settings from axes import checks, signals # noqa # Skip startup log messages if Axes is not set to verbose if settings.AXES_VERBOSE: log.info("AXES: BEGIN LOG") log.info( "AXES: Using django-axes version %s", get_distribution("django-axes").version, ) if settings.AXES_ONLY_USER_FAILURES: log.info("AXES: blocking by username only.") elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: log.info("AXES: blocking by combination of username and IP.") elif settings.AXES_LOCK_OUT_BY_USER_OR_IP: log.info("AXES: blocking by username or IP.") else: log.info("AXES: blocking by IP only.") def ready(self): self.initialize()
Fix issue detected by scrutinizer
<?php namespace Vision\Hydrator\Strategy; use Vision\Annotation\Paragraph; use Vision\Annotation\Symbol; use Vision\Annotation\Word; use Zend\Hydrator\Strategy\StrategyInterface; class SymbolsStrategy implements StrategyInterface { /** * @var TextPropertyStrategy */ protected $textPropertyStrategy; /** * @var BoundingPolyStrategy */ protected $boundingPolyStrategy; public function __construct() { $this->textPropertyStrategy = new TextPropertyStrategy; $this->boundingPolyStrategy = new BoundingPolyStrategy; } /** * @param Symbol[] $value * @return array */ public function extract($value) { return array_map(function(Symbol $symbolEntity) { return array_filter([ 'property' => $this->textPropertyStrategy->extract($symbolEntity->getProperty()), 'boundingBox' => $this->boundingPolyStrategy->extract($symbolEntity->getBoundingBox()), 'text' => $symbolEntity->getText(), ]); }, $value); } /** * @param array $value * @return Symbol[] */ public function hydrate($value) { $symbolEntities = []; foreach ($value as $symbolEntityInfo) { $symbolEntities[] = new Symbol( $this->textPropertyStrategy->hydrate($symbolEntityInfo['property']), $this->boundingPolyStrategy->hydrate($symbolEntityInfo['boundingBox']), $symbolEntityInfo['text'] ); } return $symbolEntities; } }
<?php namespace Vision\Hydrator\Strategy; use Vision\Annotation\Paragraph; use Vision\Annotation\Symbol; use Vision\Annotation\Word; use Zend\Hydrator\Strategy\StrategyInterface; class SymbolsStrategy implements StrategyInterface { /** * @var TextPropertyStrategy */ protected $textPropertyStrategy; /** * @var BoundingPolyStrategy */ protected $boundingPolyStrategy; public function __construct() { $this->textPropertyStrategy = new TextPropertyStrategy; $this->boundingPolyStrategy = new BoundingPolyStrategy; } /** * @param Symbol[] $value * @return array */ public function extract($value) { return array_map(function(Symbol $symbolEntity) { return array_filter([ 'property' => $this->textPropertyStrategy->extract($symbolEntity->getProperty()), 'boundingBox' => $this->boundingPolyStrategy->extract($symbolEntity->getBoundingBox()), 'text' => $symbolEntity->getSymbols(), ]); }, $value); } /** * @param array $value * @return Symbol[] */ public function hydrate($value) { $symbolEntities = []; foreach ($value as $symbolEntityInfo) { $symbolEntities[] = new Symbol( $this->textPropertyStrategy->hydrate($symbolEntityInfo['property']), $this->boundingPolyStrategy->hydrate($symbolEntityInfo['boundingBox']), $symbolEntityInfo['text'] ); } return $symbolEntities; } }
Use new create() factory function
'use strict'; /* eslint-env node */ module.exports = { name: 'ember-cli-eslint', // TODO: Disable this (or set it to return false) before committing isDevelopingAddon: function() { return false; }, // instructs ember-cli-qunit and ember-cli-mocha to // disable their lintTree implementations (which use JSHint) isDefaultJSLinter: true, init() { this._super.init && this._super.init.apply(this, arguments); var VersionChecker = require('ember-cli-version-checker'); var checker = new VersionChecker(this); if (checker.for('ember-cli-qunit', 'npm').satisfies('*')) { this._testGenerator = 'qunit'; } else if (checker.for('ember-cli-mocha', 'npm').satisfies('*')) { this._testGenerator = 'mocha'; } }, included: function (app) { this._super.included.apply(this, arguments); this.options = app.options.eslint || {}; }, lintTree: function(type, tree) { var ui = this.ui; if (type === 'templates') { return undefined; } var ESLint = require('broccoli-lint-eslint'); return ESLint.create(tree, { testGenerator: this.options.testGenerator || this._testGenerator, console: { log: function(message) { ui.writeLine(message); }, error: function(message) { ui.writeLine(message, 'ERROR'); } } }); } };
'use strict'; /* eslint-env node */ module.exports = { name: 'ember-cli-eslint', // TODO: Disable this (or set it to return false) before committing isDevelopingAddon: function() { return false; }, // instructs ember-cli-qunit and ember-cli-mocha to // disable their lintTree implementations (which use JSHint) isDefaultJSLinter: true, init() { this._super.init && this._super.init.apply(this, arguments); var VersionChecker = require('ember-cli-version-checker'); var checker = new VersionChecker(this); if (checker.for('ember-cli-qunit', 'npm').satisfies('*')) { this._testGenerator = 'qunit'; } else if (checker.for('ember-cli-mocha', 'npm').satisfies('*')) { this._testGenerator = 'mocha'; } }, included: function (app) { this._super.included.apply(this, arguments); this.options = app.options.eslint || {}; }, lintTree: function(type, tree) { var ui = this.ui; if (type === 'templates') { return undefined; } var eslint = require('broccoli-lint-eslint'); return eslint(tree, { testGenerator: this.options.testGenerator || this._testGenerator, console: { log: function(message) { ui.writeLine(message); }, error: function(message) { ui.writeLine(message, 'ERROR'); } } }); } };
Fix error in delta_minutes, use timedelta.total_seconds()/60 instead of timedelta.seconds/60.
from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = delta_datetime.total_seconds() / 60 return minutes_ago
from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = delta_datetime.seconds / 60 return minutes_ago
Fix employee test to check for returned result keys
import { expect } from 'chai'; import util from './util'; describe('Employees API', () => { describe('fetch', () => { it('should get employee list', (done) => { const fsapi = util.getFullSlate(); fsapi.employees() .then((employees) => { expect(employees).to.be.an('array'); }) .then(done); }); it('should get single employee', (done) => { const fsapi = util.getFullSlate(); fsapi.employees() .then((employees) => { return employees.length ? fsapi.employees(employees[0].id) : done(); // make test inconclusive }) .then((employee) => { expect(employee).to.be.an('object'); expect(employee).to.have.any.keys([ 'id', 'description', 'first_name', 'last_name', 'services' ]); expect(employee.services).to.be.an('array'); }) .then(done); }); it('should reject invalid employee', (done) => { const fsapi = util.getFullSlate(); fsapi.employees(-1) .catch((result) => { const { failure, errorMessage } = result; expect(failure).to.be.true; expect(errorMessage).to.equal('Employee not found.'); done(); }); }); it('should reject invalid employee number', () => { const fsapi = util.getFullSlate(); expect(() => fsapi.employees('invalid_id')).to.throw('Invalid employee id'); }); }); });
import { expect } from 'chai'; import util from './util'; describe('Employees API', () => { describe('fetch', () => { it('should get employee list', (done) => { const fsapi = util.getFullSlate(); fsapi.employees() .then((employees) => { expect(employees).to.be.an('array'); }) .then(done); }); it('should get single employee', (done) => { const fsapi = util.getFullSlate(); fsapi.employees() .then((employees) => { return employees.length ? fsapi.employees(employees[0].id) : done(); // make test inconclusive }) .then((employee) => { const { id, first_name, last_name, services } = employee; expect(employee).to.be.an('object'); expect(id).to.exist; expect(first_name).to.exist; expect(last_name).to.exist; expect(services).to.exist; }) .then(done); }); it('should reject invalid employee', (done) => { const fsapi = util.getFullSlate(); fsapi.employees(-1) .catch((result) => { const { failure, errorMessage } = result; expect(failure).to.be.true; expect(errorMessage).to.equal('Employee not found.'); done(); }); }); it('should reject invalid employee number', () => { const fsapi = util.getFullSlate(); expect(() => fsapi.employees('invalid_id')).to.throw('Invalid employee id'); }); }); });
Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached`
# coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
# coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
Update List View Item View with live urls. Waiting for API to get more data.
app.views.PlanListView = Backbone.View.extend({ tagName:'ul', className:'table-view', initialize:function () { var self = this; this.model.on("reset", this.render, this); this.model.on("add", function (plan) { self.$el.append(new app.views.PlanListItemView({model:plan}).render().el); }); }, render:function () { this.$el.empty(); _.each(this.model.models, function (plan) { this.$el.append(new app.views.PlanListItemView({model:plan}).render().el); }, this); return this; } }); app.views.PlanListItemView = Backbone.View.extend({ tagName:"li", appendParamsToLi: function(){ //$("a", this.$el).attr("href", "#formulary/4692/1838/nm"); $("a", this.$el).removeClass("pull-right"); }, className: "table-view-cell", initialize:function () { this.model.on("change", this.render, this); this.model.on("destroy", this.close, this); }, render:function () { this.model.attributes["drug_id"] = 1838; this.$el.html(this.template(this.model.attributes)); this.appendParamsToLi(); return this; } });
app.views.PlanListView = Backbone.View.extend({ tagName:'ul', className:'table-view', initialize:function () { var self = this; this.model.on("reset", this.render, this); this.model.on("add", function (plan) { self.$el.append(new app.views.PlanListItemView({model:plan}).render().el); }); }, render:function () { this.$el.empty(); _.each(this.model.models, function (plan) { this.$el.append(new app.views.PlanListItemView({model:plan}).render().el); }, this); return this; } }); app.views.PlanListItemView = Backbone.View.extend({ tagName:"li", appendParamsToLi: function(){ $("a", this.$el).attr("href", "#formulary/4692/1838/nm"); $("a", this.$el).removeClass("pull-right"); }, className: "table-view-cell", initialize:function () { this.model.on("change", this.render, this); this.model.on("destroy", this.close, this); }, render:function () { this.model.attributes["drug_id"] = 1838; this.$el.html(this.template(this.model.attributes)); this.appendParamsToLi(); return this; } });
Add done flag to experiment.
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = 'Look at grain size as it relates to hardness'; this.aim = ''; this.done = false; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = 'Look at grain size as it relates to hardness'; this.aim = ''; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
Use https for artworks on BOS
// // FRAMES // // Rename plugins to extensions db.Frame.update({}, { $rename: { 'plugins': 'extensions'}}, {multi: 1}); // Replace embedded current artwork with a relationship db.Frame.find().snapshot().forEach( function (elem) { if (elem._current_artwork) { db.Frame.update( { _id: elem._id }, { $set: { currentArtworkId: elem._current_artwork.id }, $unset: { _current_artwork: 1, current_artwork: 1 } } ); } } ); // Rename plugins to required_extensions db.Artwork.update({}, { $rename: {'plugins': 'required_extensions'}, $unset: {aspect_mode: 1, format_other: 1, passwordConfirm: 1}}, {multi: 1}); // Use https for artworks on BOS db.Artwork.find({url: /http:\/\/thebookofshaders\.com.*/}).forEach(function(e,i) { e.url=e.url.replace("http://","https://"); db.Artwork.save(e); }); // Make sure existing users are marked as 'verified' db.OpenframeUser.update({}, {$set: {emailVerified: true}}, {multi: 1});
// // FRAMES // // Rename plugins to extensions db.Frame.update({}, { $rename: { 'plugins': 'extensions'}}, {multi: 1}); // Replace embedded current artwork with a relationship db.Frame.find().snapshot().forEach( function (elem) { if (elem._current_artwork) { db.Frame.update( { _id: elem._id }, { $set: { currentArtworkId: elem._current_artwork.id }, $unset: { _current_artwork: 1, current_artwork: 1 } } ); } } ); // Rename plugins to required_extensions db.Artwork.update({}, { $rename: {'plugins': 'required_extensions'}, $unset: {aspect_mode: 1, format_other: 1, passwordConfirm: 1}}, {multi: 1}); // Make sure existing users are marked as 'verified' db.OpenframeUser.update({}, {$set: {emailVerified: true}}, {multi: 1});
Set development status to stable Thanks Uri Rodberg for the suggestion.
from setuptools import setup, find_packages setup( name='sorl-thumbnail', use_scm_version=True, description='Thumbnails for Django', long_description=open('README.rst').read(), author="Mikko Hellsing", author_email='[email protected]', maintainer="Jazzband", maintainer_email="[email protected]", license="BSD", url='https://github.com/jazzband/sorl-thumbnail', packages=find_packages(exclude=['tests', 'tests.*']), platforms='any', python_requires='>=3.6', zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Multimedia :: Graphics', 'Framework :: Django', 'Framework :: Django :: 2.2', 'Framework :: Django :: 3.1', 'Framework :: Django :: 3.2', 'Framework :: Django :: 4.0', 'Framework :: Django :: 4.1', ], setup_requires=['setuptools_scm'], )
from setuptools import setup, find_packages setup( name='sorl-thumbnail', use_scm_version=True, description='Thumbnails for Django', long_description=open('README.rst').read(), author="Mikko Hellsing", author_email='[email protected]', maintainer="Jazzband", maintainer_email="[email protected]", license="BSD", url='https://github.com/jazzband/sorl-thumbnail', packages=find_packages(exclude=['tests', 'tests.*']), platforms='any', python_requires='>=3.6', zip_safe=False, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Multimedia :: Graphics', 'Framework :: Django', 'Framework :: Django :: 2.2', 'Framework :: Django :: 3.1', 'Framework :: Django :: 3.2', 'Framework :: Django :: 4.0', 'Framework :: Django :: 4.1', ], setup_requires=['setuptools_scm'], )
Trim both expected and actual content in assertion In order to prevent silly errors that may be caused by the presence or absence of a newline character at the end of fixtures and/or HTTP responses, we trim both the expected and the actuel content before passing them to the PHPUnit assertion.
<?php namespace Tests; use PHPUnit\Framework\Assert as PHPUnit; use Illuminate\Foundation\Testing\TestResponse; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; function setUp() { parent::setUp(); // Define an assertion method to test if an // HTTP response has a given conten-type. // // The macro signature is as follows: // TestResponse assertContentType(string $contentType) TestResponse::macro('assertContentType', function ($contentType) { $utf8Formats = ['text/html', 'text/xml', 'text/csv']; if (in_array($contentType, $utf8Formats)) { $contentType .= '; charset=UTF-8'; } $this->assertHeader('Content-Type', $contentType); // Return the instance to allow chaining. return $this; }); // Define an assertion method to test if the body of // an HTTP response is identical to a given string. // // The macro signature is as follows: // TestResponse assertContentEquals(string $pathToContent) TestResponse::macro('assertContentEquals', function ($pathToContent) { $expectedContent = file_get_contents($pathToContent); PHPUnit::assertEquals( trim($expectedContent), trim($this->content()), 'The content of the HTTP response is not the same as expected.' ); // Return the instance to allow chaining. return $this; }); } }
<?php namespace Tests; use PHPUnit\Framework\Assert as PHPUnit; use Illuminate\Foundation\Testing\TestResponse; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; function setUp() { parent::setUp(); // Define an assertion method to test if an // HTTP response has a given conten-type. // // The macro signature is as follows: // TestResponse assertContentType(string $contentType) TestResponse::macro('assertContentType', function ($contentType) { $utf8Formats = ['text/html', 'text/xml', 'text/csv']; if (in_array($contentType, $utf8Formats)) { $contentType .= '; charset=UTF-8'; } $this->assertHeader('Content-Type', $contentType); // Return the instance to allow chaining. return $this; }); // Define an assertion method to test if the body of // an HTTP response is identical to a given string. // // The macro signature is as follows: // TestResponse assertContentEquals(string $pathToContent) TestResponse::macro('assertContentEquals', function ($pathToContent) { $expectedContent = file_get_contents($pathToContent); PHPUnit::assertEquals( $expectedContent, $this->content(), 'The content of the HTTP response is not the same as expected.' ); // Return the instance to allow chaining. return $this; }); } }
Add content type for proper PyPI rendering
# -*- coding: utf-8 -*- import codecs import re import sys from setuptools import setup def get_version(): return re.search(r"""__version__\s+=\s+(?P<quote>['"])(?P<version>.+?)(?P=quote)""", open('aiodns/__init__.py').read()).group('version') setup(name = "aiodns", version = get_version(), author = "Saúl Ibarra Corretgé", author_email = "[email protected]", url = "http://github.com/saghul/aiodns", description = "Simple DNS resolver for asyncio", long_description = codecs.open("README.rst", encoding="utf-8").read(), long_description_content_type = "text/x-rst", install_requires = ['pycares>=3.0.0', 'typing; python_version<"3.7"'], packages = ['aiodns'], platforms = ["POSIX", "Microsoft Windows"], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Operating System :: Microsoft :: Windows", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7" ] )
# -*- coding: utf-8 -*- import codecs import re import sys from setuptools import setup def get_version(): return re.search(r"""__version__\s+=\s+(?P<quote>['"])(?P<version>.+?)(?P=quote)""", open('aiodns/__init__.py').read()).group('version') setup(name = "aiodns", version = get_version(), author = "Saúl Ibarra Corretgé", author_email = "[email protected]", url = "http://github.com/saghul/aiodns", description = "Simple DNS resolver for asyncio", long_description = codecs.open("README.rst", encoding="utf-8").read(), install_requires = ['pycares>=3.0.0', 'typing; python_version<"3.7"'], packages = ['aiodns'], platforms = ["POSIX", "Microsoft Windows"], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Operating System :: Microsoft :: Windows", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7" ] )
Change the wording of the text in the box on the /equality page.
define([], function() { return ["$timeout", "$rootScope", "api", function($timeout, $rootScope, api) { return { scope: { state: "=", questionDoc: "=", editorMode: "=", }, restrict: "A", templateUrl: "/partials/equation_editor/equation_input.html", link: function(scope, element, attrs) { scope.edit = function() { $rootScope.showEquationEditor(scope.state, scope.questionDoc, scope.editorMode).then(function(finalState) { scope.state = finalState; scope.$apply(); }); }; scope.$watch("state", function(s) { if (s && s.result) { katex.render(s.result.tex, element.find(".eqn-preview")[0]); } else if (scope.questionDoc) { element.find(".eqn-preview").html("Click to enter your answer"); } else { element.find(".eqn-preview").html("Click to enter a formula!"); } }) } }; }]; });
define([], function() { return ["$timeout", "$rootScope", "api", function($timeout, $rootScope, api) { return { scope: { state: "=", questionDoc: "=", editorMode: "=", }, restrict: "A", templateUrl: "/partials/equation_editor/equation_input.html", link: function(scope, element, attrs) { scope.edit = function() { $rootScope.showEquationEditor(scope.state, scope.questionDoc, scope.editorMode).then(function(finalState) { scope.state = finalState; scope.$apply(); }); }; scope.$watch("state", function(s) { if (s && s.result) { katex.render(s.result.tex, element.find(".eqn-preview")[0]); } else { element.find(".eqn-preview").html("Click to enter your answer"); } }) } }; }]; });
Create basic password reset form
from flask_wtf import Form from wtforms import TextField, PasswordField from wtforms.validators import DataRequired, Email, Length, EqualTo from project.models import User class LoginForm(Form): email = TextField('email', validators=[DataRequired(), Email()]) password = PasswordField('password', validators=[DataRequired()]) class RegisterForm(Form): email = TextField( 'email', validators=[DataRequired(), Email(message=None), Length(min=6, max=40)]) password = PasswordField( 'password', validators=[DataRequired(), Length(min=6, max=25)] ) confirm = PasswordField( 'Repeat password', validators=[ DataRequired(), EqualTo('password', message='Passwords must match.') ] ) def validate(self): initial_validation = super(RegisterForm, self).validate() if not initial_validation: return False user = User.query.filter_by(email=self.email.data).first() if user: self.email.errors.append("Email already registered") return False return True class ResetPasswordForm(Form): email = TextField( 'email', validators=[DataRequired(), Email(message=None), Length(min=6, max=40)]) class ChangePasswordForm(Form): password = PasswordField( 'password', validators=[DataRequired(), Length(min=6, max=25)] ) confirm = PasswordField( 'Repeat password', validators=[ DataRequired(), EqualTo('password', message='Passwords must match.') ] )
from flask_wtf import Form from wtforms import TextField, PasswordField from wtforms.validators import DataRequired, Email, Length, EqualTo from project.models import User class LoginForm(Form): email = TextField('email', validators=[DataRequired(), Email()]) password = PasswordField('password', validators=[DataRequired()]) class RegisterForm(Form): email = TextField( 'email', validators=[DataRequired(), Email(message=None), Length(min=6, max=40)]) password = PasswordField( 'password', validators=[DataRequired(), Length(min=6, max=25)] ) confirm = PasswordField( 'Repeat password', validators=[ DataRequired(), EqualTo('password', message='Passwords must match.') ] ) def validate(self): initial_validation = super(RegisterForm, self).validate() if not initial_validation: return False user = User.query.filter_by(email=self.email.data).first() if user: self.email.errors.append("Email already registered") return False return True class ChangePasswordForm(Form): password = PasswordField( 'password', validators=[DataRequired(), Length(min=6, max=25)] ) confirm = PasswordField( 'Repeat password', validators=[ DataRequired(), EqualTo('password', message='Passwords must match.') ] )
Add term-missing to coverage call
from setuptools import setup, find_packages, Command version = __import__('eemeter').get_version() long_description = "Standard methods for calculating energy efficiency savings." class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import subprocess import sys errno = subprocess.call([sys.executable, 'runtests.py', '--runslow', '--cov-report', 'term-missing', '--cov=eemeter' ]) raise SystemExit(errno) setup(name='eemeter', version=version, description='Open Energy Efficiency Meter', long_description=long_description, url='https://github.com/impactlab/eemeter/', author='Matt Gee, Phil Ngo, Eric Potash', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], cmdclass = {'test': PyTest}, keywords='open energy efficiency meter method methods calculation savings', packages=find_packages(), install_requires=['pint', 'pyyaml', 'scipy', 'numpy', 'pandas', 'requests', 'pytz'], package_data={'': ['*.json','*.gz']}, )
from setuptools import setup, find_packages, Command version = __import__('eemeter').get_version() long_description = "Standard methods for calculating energy efficiency savings." class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import subprocess import sys errno = subprocess.call([sys.executable, 'runtests.py', '--runslow', '--cov-report=', '--cov=eemeter', 'tests/']) raise SystemExit(errno) setup(name='eemeter', version=version, description='Open Energy Efficiency Meter', long_description=long_description, url='https://github.com/impactlab/eemeter/', author='Matt Gee, Phil Ngo, Eric Potash', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], cmdclass = {'test': PyTest}, keywords='open energy efficiency meter method methods calculation savings', packages=find_packages(), install_requires=['pint', 'pyyaml', 'scipy', 'numpy', 'pandas', 'requests', 'pytz'], package_data={'': ['*.json','*.gz']}, )
Create archive folder if it does not exist.
from imaplib import IMAP4, IMAP4_SSL from .base import EmailTransport, MessageParseError class ImapTransport(EmailTransport): def __init__(self, hostname, port=None, ssl=False, archive=''): self.hostname = hostname self.port = port self.archive = archive if ssl: self.transport = IMAP4_SSL if not self.port: self.port = 993 else: self.transport = IMAP4 if not self.port: self.port = 143 def connect(self, username, password): self.server = self.transport(self.hostname, self.port) typ, msg = self.server.login(username, password) self.server.select() def get_message(self): typ, inbox = self.server.search(None, 'ALL') if not inbox[0]: return if self.archive: typ, folders = self.server.list(pattern=self.archive) if folders[0] is None: # If the archive folder does not exist, create it self.server.create(self.archive) for key in inbox[0].split(): try: typ, msg_contents = self.server.fetch(key, '(RFC822)') message = self.get_email_from_bytes(msg_contents[0][1]) yield message except MessageParseError: continue if self.archive: self.server.copy(key, self.archive) self.server.store(key, "+FLAGS", "\\Deleted") self.server.expunge() return
from imaplib import IMAP4, IMAP4_SSL from .base import EmailTransport, MessageParseError class ImapTransport(EmailTransport): def __init__(self, hostname, port=None, ssl=False, archive=''): self.hostname = hostname self.port = port self.archive = archive if ssl: self.transport = IMAP4_SSL if not self.port: self.port = 993 else: self.transport = IMAP4 if not self.port: self.port = 143 def connect(self, username, password): self.server = self.transport(self.hostname, self.port) typ, msg = self.server.login(username, password) self.server.select() def get_message(self): typ, inbox = self.server.search(None, 'ALL') if not inbox[0]: return if self.archive: typ, folders = self.server.list(pattern=self.archive) if folders[0] == None: self.archive = False for key in inbox[0].split(): try: typ, msg_contents = self.server.fetch(key, '(RFC822)') message = self.get_email_from_bytes(msg_contents[0][1]) yield message except MessageParseError: continue if self.archive: self.server.copy(key, self.archive) self.server.store(key, "+FLAGS", "\\Deleted") self.server.expunge() return
Fix a CPython comparison test in CPython 3.3 which was apparently fixed only in 3.4 and later.
# mode: run # tag: generator import cython import sys def test_generator_frame_cycle(): """ >>> test_generator_frame_cycle() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) # Frame object cycle eval('g.throw(ValueError)', {'g': g}) del g return tuple(testit) def test_generator_frame_cycle_with_outer_exc(): """ >>> test_generator_frame_cycle_with_outer_exc() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) try: raise ValueError() except ValueError as exc: assert sys.exc_info()[1] is exc, sys.exc_info() # Frame object cycle eval('g.throw(ValueError)', {'g': g}) # CPython 3.3 handles this incorrectly itself :) if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]: assert sys.exc_info()[1] is exc, sys.exc_info() del g if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]: assert sys.exc_info()[1] is exc, sys.exc_info() return tuple(testit)
# mode: run # tag: generator import cython import sys def test_generator_frame_cycle(): """ >>> test_generator_frame_cycle() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) # Frame object cycle eval('g.throw(ValueError)', {'g': g}) del g if cython.compiled: # FIXME: this should not be necessary, but I can't see how to do it... import gc; gc.collect() return tuple(testit) def test_generator_frame_cycle_with_outer_exc(): """ >>> test_generator_frame_cycle_with_outer_exc() ("I'm done",) """ testit = [] def whoo(): try: yield except: yield finally: testit.append("I'm done") g = whoo() next(g) try: raise ValueError() except ValueError as exc: assert sys.exc_info()[1] is exc, sys.exc_info() # Frame object cycle eval('g.throw(ValueError)', {'g': g}) assert sys.exc_info()[1] is exc, sys.exc_info() del g assert sys.exc_info()[1] is exc, sys.exc_info() if cython.compiled: # FIXME: this should not be necessary, but I can't see how to do it... import gc; gc.collect() return tuple(testit)
Remove icon from plain email link shortcode.
<?php namespace Carawebs\Contact\Shortcodes; use Carawebs\Contact\Traits\CssClasses; /** * Hook function for Email Button shortcode */ class EmailLink extends ContactAction { use CssClasses; public function __construct() { parent::__construct(); $this->setDefaultContactStrings([ 'text' => 'Email Us', 'mobileViewText' => 'Email Us' ]); } /** * Override the handler method from parent. * * This method is called when the shortcode is registered. * @param array $atts Shortcode arguments * @param string $content Shortcode contents * @return string Shortcode output */ public function handler($atts, $content = NULL) { $args = shortcode_atts([ 'align' => 'left', 'text' => $this->defaultContactStrings['text'] ?? NULL, 'mobile_view_text' => $this->defaults['mobileViewText'] ?? NULL, 'classes' => '', 'email' => $this->defaultContactDetails['email'], ], $atts ); $args['text'] = !empty($content) ? $content : $args['text']; $args['classes'] = explode( ',', preg_replace('/\s/', '', $args['classes'])); return $this->output($args); } protected function output(array $args) { //$args['icon'] = '<i class="email-icon"></i>'; ob_start(); echo \Carawebs\Contact\Views\MakeEmailLink::text($args); return ob_get_clean(); } }
<?php namespace Carawebs\Contact\Shortcodes; use Carawebs\Contact\Traits\CssClasses; /** * Hook function for Email Button shortcode */ class EmailLink extends ContactAction { use CssClasses; public function __construct() { parent::__construct(); $this->setDefaultContactStrings([ 'text' => 'Email Us', 'mobileViewText' => 'Email Us' ]); } /** * Override the handler method from parent. * * This method is called when the shortcode is registered. * @param array $atts Shortcode arguments * @param string $content Shortcode contents * @return string Shortcode output */ public function handler($atts, $content = NULL) { $args = shortcode_atts([ 'align' => 'left', 'text' => $this->defaultContactStrings['text'] ?? NULL, 'mobile_view_text' => $this->defaults['mobileViewText'] ?? NULL, 'classes' => '', 'email' => $this->defaultContactDetails['email'], ], $atts ); $args['text'] = !empty($content) ? $content : $args['text']; $args['classes'] = explode( ',', preg_replace('/\s/', '', $args['classes'])); return $this->output($args); } protected function output(array $args) { $args['icon'] = '<i class="email-icon"></i>'; ob_start(); echo \Carawebs\Contact\Views\MakeEmailLink::text($args); return ob_get_clean(); } }
Update Request, only return response time Request: remove status_code and get_response_time() and only return the response time on do() function
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type class RequestTimeError(Exception): pass
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) self.started = time() response = getattr(requests, self.type)( url=self.url, data=data ) self.finished = time() self.status_code = response.status_code except AttributeError: raise RequestTypeError(type=self.type) def get_response_time(self): try: return self.finished - self.started except AttributeError: raise RequestTimeError class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type class RequestTimeError(Exception): pass
Fix search indexing populating thread wordcount
<?php class SV_WordCountSearch_XenForo_Search_DataHandler_Thread extends XFCP_SV_WordCountSearch_XenForo_Search_DataHandler_Thread { protected function _insertIntoIndex(XenForo_Search_Indexer $indexer, array $data, array $parentData = null) { $wordcount = 0; if (!empty($data['threadmark_count']) && empty($data['word_count']) || empty($data['threadmark_count']) && !empty($data['word_count'])) { $wordcount = $this->_getThreadModel()->rebuildThreadWordCount( $data['thread_id'] ); } $metadata = array(); $metadata[SV_WordCountSearch_Globals::WordCountField] = $wordcount; if ($indexer instanceof SV_SearchImprovements_Search_IndexerProxy) { $indexer->setProxyMetaData($metadata); } else { $indexer = new SV_SearchImprovements_Search_IndexerProxy( $indexer, $metadata ); } parent::_insertIntoIndex($indexer, $data, $parentData); } public function quickIndex(XenForo_Search_Indexer $indexer, array $contentIds) { $indexer = new SV_SearchImprovements_Search_IndexerProxy($indexer, array()); return parent::quickIndex($indexer, $contentIds); } }
<?php class SV_WordCountSearch_XenForo_Search_DataHandler_Thread extends XFCP_SV_WordCountSearch_XenForo_Search_DataHandler_Thread { protected function _insertIntoIndex(XenForo_Search_Indexer $indexer, array $data, array $parentData = null) { $wordcount = 0; if (!empty($data['threadmark_count']) && empty($thread['word_count']) || empty($data['threadmark_count']) && !empty($thread['word_count'])) { $wordcount = $this->_getThreadModel()->rebuildThreadWordCount( $data['thread_id'] ); } $metadata = array(); $metadata[SV_WordCountSearch_Globals::WordCountField] = $wordcount; if ($indexer instanceof SV_SearchImprovements_Search_IndexerProxy) { $indexer->setProxyMetaData($metadata); } else { $indexer = new SV_SearchImprovements_Search_IndexerProxy( $indexer, $metadata ); } parent::_insertIntoIndex($indexer, $data, $parentData); } public function quickIndex(XenForo_Search_Indexer $indexer, array $contentIds) { $indexer = new SV_SearchImprovements_Search_IndexerProxy($indexer, array()); return parent::quickIndex($indexer, $contentIds); } }
Use a lodash filter instead - Map doesn't work the way I expected.
/* global define */ (function() { 'use strict'; define(['lodash', 'moment'], function(_, moment) { var ToolController = function($q, $timeout, $location, $scope, ClusterService, ToolService) { if (ClusterService.clusterId === null) { $location.path('/first'); return; } $scope.clusterName = ClusterService.clusterModel.name; $scope.logui = 'spinner'; var promises = [ToolService.log()]; $q.all(promises).then(function(results) { (function(logs) { if (logs.length === 0) { $scope.logui = 'empty'; return; } var lines = _.filter(logs.lines.split('\n').reverse(), function(line) { return !(line === '' || line === undefined); }); $scope.logs = _.map(lines, function(log) { var line = log.split(' '); return { timestamp: moment(line[0] + ' ' + line[1]).fromNow(), unit: line[2], address: line[3] + ' ' + line[4], rest: line.slice(6).join(' '), }; }); $scope.logui = 'logs'; })(results[0]); $scope.up = true; }); }; return ['$q', '$timeout', '$location', '$scope', 'ClusterService', 'ToolService', ToolController]; }); })();
/* global define */ (function() { 'use strict'; define(['lodash', 'moment'], function(_, moment) { var ToolController = function($q, $timeout, $location, $scope, ClusterService, ToolService) { if (ClusterService.clusterId === null) { $location.path('/first'); return; } $scope.clusterName = ClusterService.clusterModel.name; $scope.logui = 'spinner'; var promises = [ToolService.log()]; $q.all(promises).then(function(results) { (function(logs) { if (logs.length === 0) { $scope.logui = 'empty'; return; } var lines = logs.lines.split('\n').reverse(); $scope.logs = _.map(lines, function(log) { var line = log.split(' '); if (line === '' || line === undefined) { return; } return { timestamp: moment(line[0] + ' ' + line[1]).fromNow(), unit: line[2], address: line[3] + ' ' + line[4], rest: line.slice(6).join(' '), }; }); $scope.logui = 'logs'; })(results[0]); $scope.up = true; }); }; return ['$q', '$timeout', '$location', '$scope', 'ClusterService', 'ToolService', ToolController]; }); })();
Fix channel definition in add method
# Module: node # Date: ... # Author: ... """Node ... """ from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
# Module: node # Date: ... # Author: ... """Node ... """ from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs['channel'] if 'channel' in kwargs else \ '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
Create Tasks on a tasklist
<?php namespace Rossedman\Teamwork; use Rossedman\Teamwork\Traits\RestfulTrait; class Tasklist extends AbstractObject { protected $wrapper = 'todo-list'; protected $endpoint = 'tasklists'; /** * GET /tasklists/{$id}.json * @return mixed */ public function find() { return $this->client->get("$this->endpoint/$this->id")->response(); } /** * PUT /todo_lists/{$id}.json * @return mixed */ public function update($data) { return $this->client->put("$this->endpoint/$this->id", [$this->wrapper => $data])->response(); } /** * DELETE /todo_lists/{$id}.json * @return mixed */ public function delete() { return $this->client->delete("$this->endpoint/$this->id")->response(); } /** * GET /tasklists/templates.json * @return [type] [description] */ public function templates() { return $this->client->get("$this->endpoint/templates")->response(); } /** * Time Totals * GET /projects/{id}/time/total.json * * @return mixed */ public function timeTotal() { return $this->client->get("tasklists/$this->id/time/total")->response(); } /** * Create Task * GET /tasklists/{id}/tasks.json * * @return mixed */ public function createTask($data) { return $this->client->post("tasklists/$this->id/tasks", ['todo-item' => $data])->response(); } }
<?php namespace Rossedman\Teamwork; use Rossedman\Teamwork\Traits\RestfulTrait; class Tasklist extends AbstractObject { protected $wrapper = 'todo-list'; protected $endpoint = 'tasklists'; /** * GET /tasklists/{$id}.json * @return mixed */ public function find() { return $this->client->get("$this->endpoint/$this->id")->response(); } /** * PUT /todo_lists/{$id}.json * @return mixed */ public function update($data) { return $this->client->put("$this->endpoint/$this->id", [$this->wrapper => $data])->response(); } /** * DELETE /todo_lists/{$id}.json * @return mixed */ public function delete() { return $this->client->delete("$this->endpoint/$this->id")->response(); } /** * GET /tasklists/templates.json * @return [type] [description] */ public function templates() { return $this->client->get("$this->endpoint/templates")->response(); } /** * Time Totals * GET /projects/{id}/time/total.json * * @return mixed */ public function timeTotal() { return $this->client->get("tasklists/$this->id/time/total")->response(); } }
Store cleanet phone number for use in SQL extracts
# -*- coding: utf-8 -*- from openerp import models, fields, api import string class ResPartner(models.Model): _inherit = ['res.partner'] mobile_clean = fields.Char(compute='_compute_mobile_clean', store=True) @api.multi @api.depends('mobile','phone') def _compute_mobile_clean(self): allowed_chars = '+0123456789' for p in self: # Filter allowed chars if not p.mobile: p.mobile = p.phone mobile_clean = ''.join([c for c in p.mobile if c in allowed_chars]) if p.mobile else '' # Make sure number starts with country code if len(mobile_clean) > 0 and mobile_clean[0] != '+': if len(mobile_clean) >= 2 and mobile_clean[0:2] == '00': mobile_clean = '+' + mobile_clean[2:] else: # @todo: Use country prefix from partner's country setting mobile_clean = '+45' + mobile_clean # Number can only have '+' as the first char - and length must be less than 18 chars # (two numbers will be at least 2 * 8 + 3 = 19 chars (3 for '+45') if '+' in mobile_clean[1:] or len(mobile_clean) > 18: mobile_clean = False p.mobile_clean = mobile_clean
# -*- coding: utf-8 -*- from openerp import models, fields, api import string class ResPartner(models.Model): _inherit = ['res.partner'] mobile_clean = fields.Char(compute='_compute_mobile_clean') @api.multi @api.depends('mobile') def _compute_mobile_clean(self): allowed_chars = '+0123456789' for p in self: # Filter allowed chars mobile_clean = ''.join([c for c in p.mobile if c in allowed_chars]) if p.mobile else '' # Make sure number starts with country code if len(mobile_clean) > 0 and mobile_clean[0] != '+': if len(mobile_clean) >= 2 and mobile_clean[0:2] == '00': mobile_clean = '+' + mobile_clean[2:] else: # @todo: Use country prefix from partner's country setting mobile_clean = '+45' + mobile_clean # Number can only have '+' as the first char - and length must be less than 18 chars # (two numbers will be at least 2 * 8 + 3 = 19 chars (3 for '+45') if '+' in mobile_clean[1:] or len(mobile_clean) > 18: mobile_clean = False p.mobile_clean = mobile_clean
FIx issue with oneway methods
import os import datetime import tornado.gen import statsd if os.environ.get("STATSD_URL", None): ip, port = os.environ.get("STATSD_URL").split(':') statsd_client = statsd.Client(ip, int(port)) else: statsd_client = None def instrument(name): def instrument_wrapper(fn): @tornado.gen.coroutine def fn_wrapper(*args, **kwargs): def send_duration(): duration = (datetime.datetime.now() - start).total_seconds() statsd_client.timing("{}.duration".format(name), int(duration * 1000)) start = datetime.datetime.now() ftr_result = fn(*args, **kwargs) try: result = yield tornado.gen.maybe_future(ftr_result) except Exception as e: if statsd_client: statsd_client.incr("{}.exceptions.{}".format( name, e.__class__.__name__.lower())) send_duration() raise e else: if statsd_client: send_duration() statsd_client.incr("{}.success".format(name)) raise tornado.gen.Return(result) return fn_wrapper return instrument_wrapper
import os import datetime import tornado.gen import statsd if os.environ.get("STATSD_URL", None): ip, port = os.environ.get("STATSD_URL").split(':') statsd_client = statsd.Client(ip, int(port)) else: statsd_client = None def instrument(name): def instrument_wrapper(fn): @tornado.gen.coroutine def fn_wrapper(*args, **kwargs): def send_duration(): duration = (datetime.datetime.now() - start).total_seconds() statsd_client.timing("{}.duration".format(name), int(duration * 1000)) start = datetime.datetime.now() ftr_result = fn(*args, **kwargs) try: result = yield ftr_result except Exception as e: if statsd_client: statsd_client.incr("{}.exceptions.{}".format( name, e.__class__.__name__.lower())) send_duration() raise e else: if statsd_client: send_duration() statsd_client.incr("{}.success".format(name)) raise tornado.gen.Return(result) return fn_wrapper return instrument_wrapper
Add js static analysis as recognised test option
<?php namespace SimplyTestable\WebClientBundle\Model; class TestOptions { private $testTypes = array(); private $testTypeMap = array( 'html-validation' => 'HTML validation', 'css-validation' => 'CSS validation', 'js-static-analysis' => 'JS static analysis' ); /** * * @param string $testType */ public function addTestType($testType) { if (!$this->hasTestType($testType)) { $this->testTypes[] = $testType; } } /** * * @param string $testType * @return boolean */ public function hasTestType($testType) { return in_array($testType, $this->testTypes); } /** * * @return boolean */ public function hasTestTypes() { return count($this->testTypes) > 0; } /** * * @return array */ public function getTestTypes() { return $this->testTypes; } /** * * @return array */ public function getAbsoluteTestTypes() { $absoluteTestTypes = array(); foreach ($this->testTypeMap as $testTypeKey => $testTypeName) { if ($this->hasTestType($testTypeName)) { $absoluteTestTypes[$testTypeKey] = 1; } else { $absoluteTestTypes[$testTypeKey] = 0; } } return $absoluteTestTypes; } }
<?php namespace SimplyTestable\WebClientBundle\Model; class TestOptions { private $testTypes = array(); private $testTypeMap = array( 'html-validation' => 'HTML validation', 'css-validation' => 'CSS validation' ); /** * * @param string $testType */ public function addTestType($testType) { if (!$this->hasTestType($testType)) { $this->testTypes[] = $testType; } } /** * * @param string $testType * @return boolean */ public function hasTestType($testType) { return in_array($testType, $this->testTypes); } /** * * @return boolean */ public function hasTestTypes() { return count($this->testTypes) > 0; } /** * * @return array */ public function getTestTypes() { return $this->testTypes; } /** * * @return array */ public function getAbsoluteTestTypes() { $absoluteTestTypes = array(); foreach ($this->testTypeMap as $testTypeKey => $testTypeName) { if ($this->hasTestType($testTypeName)) { $absoluteTestTypes[$testTypeKey] = 1; } else { $absoluteTestTypes[$testTypeKey] = 0; } } return $absoluteTestTypes; } }
Change to support name change
package com.boundary.camel.component.url; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Ignore; import org.junit.Test; import com.boundary.camel.component.common.ServiceStatus; public class UrlComponentTest extends CamelTestSupport { @Test public void testHttp() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.await(5, TimeUnit.SECONDS); mock.assertIsSatisfied(); List <Exchange> receivedExchanges = mock.getReceivedExchanges(); for(Exchange e: receivedExchanges) { UrlResult result = e.getIn().getBody(UrlResult.class); assertTrue("check http status",result.getStatus() == ServiceStatus.SUCCESS); } } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { from("http://foo?host=localhost&delay=5") .to("mock:result"); } }; } }
package com.boundary.camel.component.http; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Ignore; import org.junit.Test; import com.boundary.camel.component.common.ServiceStatus; import com.boundary.camel.component.port.PortResult; public class HttpComponentTest extends CamelTestSupport { @Test public void testHttp() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.await(5, TimeUnit.SECONDS); mock.assertIsSatisfied(); List <Exchange> receivedExchanges = mock.getReceivedExchanges(); for(Exchange e: receivedExchanges) { HttpInfo status = e.getIn().getBody(HttpInfo.class); assertTrue("check http status",status.getStatus() == ServiceStatus.SUCCESS); } } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { from("http://foo?host=localhost&delay=5") .to("mock:result"); } }; } }
Use MutationObserver for expanded stories and jQuery for collapsed ones
var storyListener = function (modal) { var observer = new MutationObserver(function (mutations) { mutations.forEach(handleMutationEvents); }); var handleMutationEvents = function handleMutationEvents(mutation) { Array.prototype.forEach.call(mutation.addedNodes, addListenersInNode); addListenersInNode(mutation.target); } var addListenersInNode = function styleLabelsInNode(node) { if (nodeIsElement(node)) { console.log(findFinishButtons(node)); addListenerToButtons(findFinishButtons(node)); } } var nodeIsElement = function nodeIsElement(node) { return (typeof node.querySelectorAll !== 'undefined'); } var findFinishButtons = function findLabelsInNode(node) { return node.querySelectorAll('.button.finish.autosaves'); } var addListenerToButtons = function addListenerToButtons(buttons) { Array.prototype.forEach.call(buttons, function(button) { button.addEventListener('click', promptListener, false); function promptListener() { modal.modal('show'); button.removeEventListener('click', promptListener, false); } }); } var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); var config = { attributes: true, characterData: true, childList: true, subtree: true }; observer.observe(document, config); } }, 10); $('body').on('click', '.finish.button', function (e) { modal.modal('show') }) };
var storyListener = function (modal) { var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); var observer = new MutationObserver(function (mutations) { mutations.forEach(handleMutationEvents); }); // configuration of the observer: var config = { attributes: true, characterData: true, childList: true, subtree: true }; observer.observe(document, config); var handleMutationEvents = function handleMutationEvents(mutation) { Array.prototype.forEach.call(mutation.addedNodes, addListenersInNode); addListenersInNode(mutation.target); } var addListenersInNode = function styleLabelsInNode(node) { if (nodeIsElement(node)) { addListenerToButtons(findFinishButtons(node)); } } var nodeIsElement = function nodeIsElement(node) { return (typeof node.querySelectorAll !== 'undefined'); } var findFinishButtons = function findLabelsInNode(node) { return node.querySelectorAll('.button.finish'); } var addListenerToButtons = function addListenerToButtons(buttons) { Array.prototype.forEach.call(buttons, function(button) { button.addEventListener('click', promptListener, false); function promptListener() { modal.modal('show'); button.removeEventListener('click', promptListener, false); } }); } } }, 10); };
Update shoppingcart setup to use updated tax calculation
<?php class CustomisableProductShoppingCart extends Extension { /** * Augment setup to get item price * */ public function augmentSetup() { foreach($this->owner->Items as $item) { if($item->Customisations && is_array($item->Customisations)) { $base_price = $item->Price->RAW(); $customisations = ArrayList::create(); foreach($item->Customisations as $customisation) { if($customisation['Price']) $base_price += $customisation['Price']; $customisations->add($customisation); } $item->Customisations = $customisations; $item->Price->setValue($base_price); } // If tax rate set work out tax if($item->TaxRate) { $item->Tax = new Currency("Tax"); $item->Tax->setValue((($item->Price->RAW() - $item->Discount->RAW()) / 100) * $item->TaxRate); } } } public function onBeforeSave($items) { // Convert customisations back to an array foreach($this->owner->items as $item) { if($item->Customisations && is_object($item->Customisations)) { $customisations = array(); foreach($item->Customisations as $customisation) { $customisations[] = array( "Title" => $customisation->Title, "Value" => $customisation->Value, "Price" => $customisation->Price ); } $item->Customisations = $customisations; } } } }
<?php class CustomisableProductShoppingCart extends Extension { /** * Augment setup to get item price * */ public function augmentSetup() { foreach($this->owner->Items as $item) { if($item->Customisations && is_array($item->Customisations)) { $base_price = $item->Price->RAW(); $customisations = ArrayList::create(); foreach($item->Customisations as $customisation) { if($customisation['Price']) $base_price += $customisation['Price']; $customisations->add($customisation); } $item->Customisations = $customisations; $item->Price->setValue($base_price); } // If tax rate set work out tax if($item->TaxRate) { $tax = new Currency("Tax"); $tax->setValue(($item->Price->RAW() / 100) * $item->TaxRate); $item->Tax = $tax; } } } public function onBeforeSave($items) { // Convert customisations back to an array foreach($this->owner->items as $item) { if($item->Customisations && is_object($item->Customisations)) { $customisations = array(); foreach($item->Customisations as $customisation) { $customisations[] = array( "Title" => $customisation->Title, "Value" => $customisation->Value, "Price" => $customisation->Price ); } $item->Customisations = $customisations; } } } }
Fix ReferenceError in saveAs polyfill
var save = (function() { "use strict"; // saveAs from https://gist.github.com/MrSwitch/3552985 var saveAs = window.saveAs || (window.navigator.msSaveBlob ? function (b, n) { return window.navigator.msSaveBlob(b, n); } : false) || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs || (function () { // URL's window.URL = window.URL || window.webkitURL; if (!window.URL) { return false; } return function (blob, name) { var url = URL.createObjectURL(blob); // Test for download link support if ("download" in document.createElement('a')) { var a = document.createElement('a'); a.setAttribute('href', url); a.setAttribute('download', name); // Create Click event var clickEvent = document.createEvent("MouseEvent"); clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); // dispatch click event to simulate download a.dispatchEvent(clickEvent); } else { // fallover, open resource in new tab. window.open(url, '_blank', ''); } }; })(); function save (text, fileName) { var blob = new Blob([text], { type: 'text/plain' }); saveAs(blob, fileName || 'subtitle.srt'); } return save; })();
var save = (function() { "use strict"; // saveAs from https://gist.github.com/MrSwitch/3552985 var saveAs = window.saveAs || (window.navigator.msSaveBlob ? function (b, n) { return window.navigator.msSaveBlob(b, n); } : false) || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs || (function () { // URL's window.URL = window.URL || window.webkitURL; if (!window.URL) { return false; } return function (blob, name) { var url = URL.createObjectURL(blob); // Test for download link support if ("download" in document.createElement('a')) { var a = document.createElement('a'); a.setAttribute('href', url); a.setAttribute('download', name); // Create Click event var clickEvent = document.createEvent("MouseEvent"); clickEvent.initMouseEvent("click", true, true, window, 0, event.screenX, event.screenY, event.clientX, event.clientY, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey, 0, null); // dispatch click event to simulate download a.dispatchEvent(clickEvent); } else { // fallover, open resource in new tab. window.open(url, '_blank', ''); } }; })(); function save (text, fileName) { var blob = new Blob([text], { type: 'text/plain' }); saveAs(blob, fileName || 'subtitle.srt'); } return save; })();
Introduce scope_types in pause server policy oslo.policy introduced the scope_type feature which can control the access level at system-level and project-level. - https://docs.openstack.org/oslo.policy/latest/user/usage.html#setting-scope - http://specs.openstack.org/openstack/keystone-specs/specs/keystone/queens/system-scope.html Appropriate scope_type for nova case: - https://specs.openstack.org/openstack/nova-specs/specs/ussuri/approved/policy-defaults-refresh.html#scope This commit introduce scope_type for pause server API policies as: - ['system', 'project'] for pause/unpause policy. Also adds the test case with scope_type enabled and verify we pass and fail the policy check with expected context. Partial implement blueprint policy-defaults-refresh Change-Id: I828248ec42c71d67c8d9463d987d0afe54989c74
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base POLICY_ROOT = 'os_compute_api:os-pause-server:%s' pause_server_policies = [ policy.DocumentedRuleDefault( name=POLICY_ROOT % 'pause', check_str=base.RULE_ADMIN_OR_OWNER, description="Pause a server", operations=[ { 'path': '/servers/{server_id}/action (pause)', 'method': 'POST' } ], scope_types=['system', 'project'] ), policy.DocumentedRuleDefault( name=POLICY_ROOT % 'unpause', check_str=base.RULE_ADMIN_OR_OWNER, description="Unpause a paused server", operations=[ { 'path': '/servers/{server_id}/action (unpause)', 'method': 'POST' } ], scope_types=['system', 'project'] ), ] def list_rules(): return pause_server_policies
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base POLICY_ROOT = 'os_compute_api:os-pause-server:%s' pause_server_policies = [ policy.DocumentedRuleDefault( POLICY_ROOT % 'pause', base.RULE_ADMIN_OR_OWNER, "Pause a server", [ { 'path': '/servers/{server_id}/action (pause)', 'method': 'POST' } ] ), policy.DocumentedRuleDefault( POLICY_ROOT % 'unpause', base.RULE_ADMIN_OR_OWNER, "Unpause a paused server", [ { 'path': '/servers/{server_id}/action (unpause)', 'method': 'POST' } ] ), ] def list_rules(): return pause_server_policies
Change symbols generation and checks
var LOCK = false; function print(text, nextAction) { if (text) { LOCK = true; var display = document.getElementById("display"); display.innerHTML = display.innerHTML + text.substr(0, 1); display.scrollTop = display.scrollHeight; var newText = text.substring(1, text.length); window.setTimeout(function () { print(newText, nextAction); }, 50); } else { LOCK = false; if (nextAction) { nextAction(); } } } function generateTask() { var randomChar = String.fromCharCode(Math.floor(Math.random() * 26) + 65); window.setTimeout(function () { var message = "\nPlease, press key '" + randomChar + "'\n" print(message, function () { document.onkeydown = function (e) { var keyCode = (e || event).keyCode; var ch = String.fromCharCode(keyCode); if (keyCode >= 0 && keyCode <= 127) { if (!LOCK) { if (ch == randomChar) { document.onkeydown = undefined; print("OK... \n", generateTask); } else { print("Wrong!!! \n" + message); } } return false; } return true; } }); }, Math.floor(Math.random() * 10000)); }
var LOCK = false; function print(text, nextAction) { if (text) { LOCK = true; var display = document.getElementById("display"); display.innerHTML = display.innerHTML + text.substr(0, 1); display.scrollTop = display.scrollHeight; var newText = text.substring(1, text.length); window.setTimeout(function () { print(newText, nextAction); }, 50); } else { LOCK = false; if (nextAction) { nextAction(); } } } function generateTask() { var randomChar = String.fromCharCode(Math.floor(Math.random() * 27) + 65); window.setTimeout(function () { var message = "\nPlease, press key '" + randomChar + "'\n" print(message, function () { document.onkeydown = function (e) { e = e || event; var ch = String.fromCharCode(e.keyCode); if (ch >= 'A' && ch <= 'Z') { if (!LOCK) { if (ch == randomChar) { document.onkeydown = undefined; print("OK... \n", generateTask); } else { print("Wrong!!! \n" + message); } } return false; } return true; } }); }, Math.floor(Math.random() * 10000)); }
Fix unicode error in series
import simplejson from django.utils.html import escape def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name): """Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object.""" # Escape all the character strings to make them HTML safe. render_to = escape(render_to.encode('ascii', 'ignore')) if render_to else 'render_to' title = escape(title.encode('ascii', 'ignore')) if title else 'title' x_axis_title = escape(x_axis_title.encode('ascii', 'ignore')) if x_axis_title else 'x axis' y_axis_title = escape(y_axis_title.encode('ascii', 'ignore')) if y_axis_title else 'y axis' # Categories (dimensions) come from the use. Escape them too. categories = [escape(c.encode('ascii', 'ignore')) for c in categories] hco = { "chart": { "renderTo": render_to, "type": 'column' }, "title": { "text": title }, "xAxis": { "title": { "text": x_axis_title }, "categories": categories }, "yAxis": { "title": { "text": y_axis_title, } }, "series": [{ "name": series_name, "data": series, }] } return simplejson.dumps(hco, use_decimal=True)
import simplejson from django.utils.html import escape def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name): """Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object.""" # Escape all the character strings to make them HTML safe. render_to = escape(render_to) if render_to else render_to title = escape(title) if title else title x_axis_title = escape(x_axis_title) if x_axis_title else x_axis_title y_axis_title = escape(y_axis_title) if y_axis_title else y_axis_title # Categories (dimensions) come from the use. Escape them too. categories = [escape(c) for c in categories] hco = { "chart": { "renderTo": render_to, "type": 'column' }, "title": { "text": title }, "xAxis": { "title": { "text": x_axis_title }, "categories": categories }, "yAxis": { "title": { "text": y_axis_title, } }, "series": [{ "name": series_name, "data": series, }] } return simplejson.dumps(hco, use_decimal=True)
Add entry point for readme
#!/usr/bin/env node import yargs from 'yargs'; import { head, pipe, cond, equals, prop } from 'ramda'; import { reject } from 'bluebird'; import build from './build'; import run from './run'; import init from './init'; import publish from './publish'; import boilerplate from './boilerplate'; import readme from './readme'; const commandEquals = value => pipe(prop('_'), head, equals(value)); const executeCommand = cond([ [commandEquals('init'), init], [commandEquals('build'), build], [commandEquals('run'), run], [commandEquals('publish'), publish], [commandEquals('boilerplate'), boilerplate], [commandEquals('readme'), readme] ]); function cli(args) { executeCommand(args) .catch(err => { console.log('Ooooops, something went wrong...'); console.log(new String(err).valueOf()); process.exit(1); }); } cli(yargs .usage('Usage: $0 [init|build|run|publish]') .command('init', 'Initialize a blank extension project') .command('build', 'Generate a .rung package') .command('publish', 'Publishes the extension to the Rung store') .command('run', 'Execute the current extension') .command('boilerplate', 'Generates the boilerplate files for your extension') .command('readme', 'Generates the README.md file to publish') .option('o', { alias: 'output', describe: 'Where to save the built package', type: 'string' }) .strict() .demandCommand(1) .recommendCommands() .version() .argv);
#!/usr/bin/env node import yargs from 'yargs'; import { head, pipe, cond, equals, prop } from 'ramda'; import { reject } from 'bluebird'; import build from './build'; import run from './run'; import init from './init'; import publish from './publish'; import boilerplate from './boilerplate'; const commandEquals = value => pipe(prop('_'), head, equals(value)); const executeCommand = cond([ [commandEquals('init'), init], [commandEquals('build'), build], [commandEquals('run'), run], [commandEquals('publish'), publish], [commandEquals('boilerplate'), boilerplate] ]); function cli(args) { executeCommand(args) .catch(err => { console.log('Ooooops, something went wrong...'); console.log(new String(err).valueOf()); process.exit(1); }); } cli(yargs .usage('Usage: $0 [init|build|run|publish]') .command('init', 'Initialize a blank extension project') .command('build', 'Generate a .rung package') .command('publish', 'Publishes the extension to the Rung store') .command('run', 'Execute the current extension') .command('boilerplate', 'Generates the boilerplate files for your extension') .option('o', { alias: 'output', describe: 'Where to save the built package', type: 'string' }) .strict() .demandCommand(1) .recommendCommands() .version() .argv);
Fix AMD define syntax (I hope).
/*globals define, module, window */ // This module contains functions for converting milliseconds // to and from CSS time strings. (function () { 'use strict'; var regex = /^([\-\+]?[0-9]+(\.[0-9]+)?)(m?s)$/, functions = { from: from, to: to }; exportFunctions(); // Public function `from`. // // Returns the number of milliseconds represented by a // CSS time string. function from (cssTime) { var matches = regex.exec(cssTime); if (matches === null) { throw new Error('Invalid CSS time'); } return parseFloat(matches[1]) * (matches[3] === 's' ? 1000 : 1); } // Public function `to`. // // Returns a CSS time string representing the number // of milliseconds passed in the arguments. function to (milliseconds) { if (typeof milliseconds !== 'number' || isNaN(milliseconds)) { throw new Error('Invalid milliseconds'); } return milliseconds + 'ms'; } function exportFunctions () { if (typeof define === 'function' && define.amd) { define(function () { return functions; }); } else if (typeof module === 'object' && module !== null) { module.exports = functions; } else { window.cssTime = functions; } } }());
/*globals define, module, window */ // This module contains functions for converting milliseconds // to and from CSS time strings. (function () { 'use strict'; var regex = /^([\-\+]?[0-9]+(\.[0-9]+)?)(m?s)$/, functions = { from: from, to: to }; exportFunctions(); // Public function `from`. // // Returns the number of milliseconds represented by a // CSS time string. function from (cssTime) { var matches = regex.exec(cssTime); if (matches === null) { throw new Error('Invalid CSS time'); } return parseFloat(matches[1]) * (matches[3] === 's' ? 1000 : 1); } // Public function `to`. // // Returns a CSS time string representing the number // of milliseconds passed in the arguments. function to (milliseconds) { if (typeof milliseconds !== 'number' || isNaN(milliseconds)) { throw new Error('Invalid milliseconds'); } return milliseconds + 'ms'; } function exportFunctions () { if (typeof define === 'function' && define.amd) { define(['css-time'], functions); } else if (typeof module === 'object' && module !== null) { module.exports = functions; } else { window.cssTime = functions; } } }());
command: Fix comparaison of command (== 0x11) for half lx I assume author @circuitdb wanted this in: https://github.com/miroRucka/bh1750/pull/3 Change-Id: Ic8666c0b735a970f0ff82fedc4e654969a1a0076 Origin: https://github.com/miroRucka/bh1750/pull/12 Signed-off-by: Philippe Coval <[email protected]>
var i2c = require('i2c'); var _ = require('lodash'); var utils = require('./utils'); var BH1750 = function (opts) { this.options = _.extend({}, { address: 0x23, device: '/dev/i2c-1', command: 0x10, length: 2 }, opts); this.verbose = this.options.verbose || false; this.wire = new i2c(this.options.address, {device: this.options.device}); }; BH1750.prototype.readLight = function (cb) { var self = this; if (!utils.exists(cb)) { throw new Error("Invalid param"); } self.wire.readBytes(self.options.command, self.options.length, function (err, res) { if (utils.exists(err)) { if (self.verbose) console.error("error: I/O failure on BH1750 - command: ", self.options.command); return cb(err, null); } var hi = res.readUInt8(0); var lo = res.readUInt8(1); var lux = ((hi << 8) + lo)/1.2; if (self.options.command === 0x11) { lux = lux/2; } cb(null, lux); }); }; module.exports = BH1750;
var i2c = require('i2c'); var _ = require('lodash'); var utils = require('./utils'); var BH1750 = function (opts) { this.options = _.extend({}, { address: 0x23, device: '/dev/i2c-1', command: 0x10, length: 2 }, opts); this.verbose = this.options.verbose || false; this.wire = new i2c(this.options.address, {device: this.options.device}); }; BH1750.prototype.readLight = function (cb) { var self = this; if (!utils.exists(cb)) { throw new Error("Invalid param"); } self.wire.readBytes(self.options.command, self.options.length, function (err, res) { if (utils.exists(err)) { if (self.verbose) console.error("error: I/O failure on BH1750 - command: ", self.options.command); return cb(err, null); } var hi = res.readUInt8(0); var lo = res.readUInt8(1); var lux = ((hi << 8) + lo)/1.2; if (self.options.command = 0x11) { lux = lux/2; } cb(null, lux); }); }; module.exports = BH1750;
Fix filters in storeConfig: they where shared across multiple stores Problem was that storeConfig is an object and thus modified by reference
Ext.define('Densa.overrides.HasMany', { override: 'Ext.data.association.HasMany', /** * Allow filters in storeConfig * * Original overrides filters with filter */ createStore: function() { var that = this, associatedModel = that.associatedModel, storeName = that.storeName, foreignKey = that.foreignKey, primaryKey = that.primaryKey, filterProperty = that.filterProperty, autoLoad = that.autoLoad, storeConfig = that.storeConfig || {}; return function() { var me = this, config, filter, modelDefaults = {}; if (me[storeName] === undefined) { if (filterProperty) { filter = { property : filterProperty, value : me.get(filterProperty), exactMatch: true }; } else { filter = { property : foreignKey, value : me.get(primaryKey), exactMatch: true }; } var localStoreConfig = Ext.clone(storeConfig); if (!localStoreConfig.filters) localStoreConfig.filters = []; localStoreConfig.filters.push(filter); modelDefaults[foreignKey] = me.get(primaryKey); config = Ext.apply({}, localStoreConfig, { model : associatedModel, remoteFilter : false, modelDefaults: modelDefaults, disableMetaChangeEvent: true }); me[storeName] = Ext.data.AbstractStore.create(config); if (autoLoad) { me[storeName].load(); } } return me[storeName]; }; } });
Ext.define('Densa.overrides.HasMany', { override: 'Ext.data.association.HasMany', /** * Allow filters in storeConfig * * Original overrides filters with filter */ createStore: function() { var that = this, associatedModel = that.associatedModel, storeName = that.storeName, foreignKey = that.foreignKey, primaryKey = that.primaryKey, filterProperty = that.filterProperty, autoLoad = that.autoLoad, storeConfig = that.storeConfig || {}; return function() { var me = this, config, filter, modelDefaults = {}; if (me[storeName] === undefined) { if (filterProperty) { filter = { property : filterProperty, value : me.get(filterProperty), exactMatch: true }; } else { filter = { property : foreignKey, value : me.get(primaryKey), exactMatch: true }; } if (!storeConfig.filters) storeConfig.filters = []; storeConfig.filters.push(filter); modelDefaults[foreignKey] = me.get(primaryKey); config = Ext.apply({}, storeConfig, { model : associatedModel, remoteFilter : false, modelDefaults: modelDefaults, disableMetaChangeEvent: true }); me[storeName] = Ext.data.AbstractStore.create(config); if (autoLoad) { me[storeName].load(); } } return me[storeName]; }; } });
Revert "revert part of 27cd680" c491bbc2302ac7c95c180d31845c643804fa30d3
import copy import os from subprocess import STDOUT, run as _run, CalledProcessError, TimeoutExpired # This env stuff is to catch glibc errors, because # it apparently prints to /dev/tty instead of stderr. # (see http://stackoverflow.com/a/27797579) ENV = copy.copy(os.environ) ENV["LIBC_FATAL_STDERR_"] = "1" def run(cmd, input_data=None, timeout=None): status = 'success' try: result = _run( cmd, stderr=STDOUT, timeout=timeout, input=input_data, env=ENV, check=True) except CalledProcessError as err: status = 'called process error' result = err.output if err.output else str(err) except TimeoutExpired as err: status = 'timed out after {} seconds'.format(timeout) result = err.output if err.output else str(err) except FileNotFoundError as err: status = 'not found' result = str(err) except ProcessLookupError as err: try: status, result = run(cmd, input_data=input_data, timeout=timeout) except: status = 'process lookup error' result = str(err) try: if not isinstance(result, str): result = str(result, 'utf-8') except UnicodeDecodeError: result = str(result, 'cp437') return (status, result)
import shlex import copy import os from subprocess import STDOUT, run as _run, CalledProcessError, TimeoutExpired # This env stuff is to catch glibc errors, because # it apparently prints to /dev/tty instead of stderr. # (see http://stackoverflow.com/a/27797579) ENV = copy.copy(os.environ) ENV["LIBC_FATAL_STDERR_"] = "1" def run(cmd, input_data=None, timeout=None): # Stringified commands are passed in from the spec files. # Otherwise, it needs to be an array. if isinstance(cmd, str): cmd = shlex.split(cmd) status = 'success' try: result = _run( cmd, stderr=STDOUT, timeout=timeout, input=input_data, env=ENV, check=True) except CalledProcessError as err: status = 'called process error' result = err.output if err.output else str(err) except TimeoutExpired as err: status = 'timed out after {} seconds'.format(timeout) result = err.output if err.output else str(err) except FileNotFoundError as err: status = 'not found' result = str(err) except ProcessLookupError as err: try: status, result = run(cmd, input_data=input_data, timeout=timeout) except: status = 'process lookup error' result = str(err) try: if not isinstance(result, str): result = str(result, 'utf-8') except UnicodeDecodeError: result = str(result, 'cp437') return (status, result)
Comment out logger until resolved properly
# -*- coding: utf-8 -*- import logging from django.core.exceptions import PermissionDenied from tastypie.resources import ModelResource, ALL from tastypie.authorization import Authorization from apps.authentication.models import OnlineUser as User from apps.api.rfid.auth import RfidAuthentication class UserResource(ModelResource): class Meta(object): queryset = User.objects.all() resource_name = 'user' fields = ['username', 'first_name', 'last_name', 'rfid', ] allowed_update_fields = ['rfid'] allowed_methods = ['get'] detail_allowed_methods = ['get', 'patch'] authorization = Authorization() authentication = RfidAuthentication() filtering = { "username": ALL, "rfid": ALL, } def update_in_place(self, request, original_bundle, new_data): """ Override to restrict patching of user fields to those specified in allowed_update_fields """ if set(new_data.keys()) - set(self._meta.allowed_update_fields): raise PermissionDenied( 'Kun oppdatering av %s er tillatt.' % ', '.join(self._meta.allowed_update_fields) ) # logging.getLogger(__name__).debug('User patched: %s' % unicode(original_bundle)) return super(UserResource, self).update_in_place(request, original_bundle, new_data)
# -*- coding: utf-8 -*- import logging from django.core.exceptions import PermissionDenied from tastypie.resources import ModelResource, ALL from tastypie.authorization import Authorization from apps.authentication.models import OnlineUser as User from apps.api.rfid.auth import RfidAuthentication class UserResource(ModelResource): class Meta(object): queryset = User.objects.all() resource_name = 'user' fields = ['username', 'first_name', 'last_name', 'rfid', ] allowed_update_fields = ['rfid'] allowed_methods = ['get'] detail_allowed_methods = ['get', 'patch'] authorization = Authorization() authentication = RfidAuthentication() filtering = { "username": ALL, "rfid": ALL, } def update_in_place(self, request, original_bundle, new_data): """ Override to restrict patching of user fields to those specified in allowed_update_fields """ if set(new_data.keys()) - set(self._meta.allowed_update_fields): raise PermissionDenied( 'Kun oppdatering av %s er tillatt.' % ', '.join(self._meta.allowed_update_fields) ) logging.getLogger(__name__).debug('User patched: %s' % repr(original_bundle)) return super(UserResource, self).update_in_place(request, original_bundle, new_data)
Handle empty fastq_screen files properly.
import sys import os header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] with open(fi) as screen_results: results = {} for line in screen_results: fields = line.strip().split() if len(fields) and fields[0][0] != '#' and fields[0] != 'Library': if fields[0] == '%Hit_no_libraries:': results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads']) continue results[fields[0] + '_single'] = int(fields[4]) results[fields[0] + '_multiple'] = int(fields[6]) results['no_reads'] = int(fields[1]) if not len(results): data = ['0'] * 5 else: try: data = [results['Mouse_single'], results['Mouse_multiple'], results['Human_single'] + results['Human_multiple']] except: sys.exit('Malformed file: {0}'.format(fi)) data.append(results['no_reads'] - sum(data) - results['unmapped']) data.append(results['unmapped']) data = map(lambda i:str(i / float(sum(data))),data) data = [sample] + data print '\t'.join(data)
import sys import os header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] with open(fi) as screen_results: results = {} for line in screen_results: fields = line.strip().split() if len(fields) and fields[0][0] != '#' and fields[0] != 'Library': if fields[0] == '%Hit_no_libraries:': results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads']) continue results[fields[0] + '_single'] = int(fields[4]) results[fields[0] + '_multiple'] = int(fields[6]) results['no_reads'] = int(fields[1]) try: data = [results['Mouse_single'], results['Mouse_multiple'], results['Human_single'] + results['Human_multiple']] except: sys.exit('Malformed file: {0}'.format(fi)) data.append(results['no_reads'] - sum(data) - results['unmapped']) data.append(results['unmapped']) data = map(lambda i:str(i / float(sum(data))),data) data = [sample] + data print '\t'.join(data)
Add the 401 Unauthorized when no username is detected, thus no user is logged in. This is the most basic form of permissions, where any user can log in and do anything.
from django.shortcuts import render from django.core import serializers from inventory.models import Item from decimal import Decimal import json from django.utils import simplejson # Create your views here. from django.http import HttpResponse from inventory.models import Item def index(request): if request.method == 'GET': list_of_items = Item.objects.all() data = serializers.serialize("json", list_of_items) return HttpResponse(data, content_type="application/json") if request.method == 'POST': if request.user.username: data = simplejson.loads(request.body.decode(), parse_float=Decimal)['fields'] items = Item.objects.filter(itemId=data['itemId']) if items: for o in items: o.count = data['count'] o.save() else: item = Item(itemId=data['itemId'], count=data['count'], name=data['name'], short=data['short'], desc=data['desc']) item.save() return HttpResponse({}, content_type="application/json") else: return HttpResponse('Unauthorized', status=401) def detail(request, item_id): if request.method == 'GET': item = Item.objects.filter(itemId=item_id) data = serializers.serialize("json", item) return HttpResponse(data, content_type="application/json") if request.method == 'DELETE': if request.user.username: Item.objects.filter(itemId=item_id).delete() return HttpResponse({}, content_type="application/json") else: return HttpResponse('Unauthorized', status=401)
from django.shortcuts import render from django.core import serializers from inventory.models import Item from decimal import Decimal import json from django.utils import simplejson # Create your views here. from django.http import HttpResponse from inventory.models import Item def index(request): if request.method == 'GET': list_of_items = Item.objects.all() data = serializers.serialize("json", list_of_items) return HttpResponse(data, content_type="application/json") if request.method == 'POST': data = simplejson.loads(request.body.decode(), parse_float=Decimal)['fields'] items = Item.objects.filter(itemId=data['itemId']) if items: for o in items: o.count = data['count'] o.save() else: item = Item(itemId=data['itemId'], count=data['count'], name=data['name'], short=data['short'], desc=data['desc']) item.save() return HttpResponse({}, content_type="application/json") def detail(request, item_id): if request.method == 'GET': item = Item.objects.filter(itemId=item_id) data = serializers.serialize("json", item) return HttpResponse(data, content_type="application/json") if request.method == 'DELETE': Item.objects.filter(itemId=item_id).delete() return HttpResponse({}, content_type="application/json")
Remove extraneous logging and bad param
import requests import urllib import urlparse from st2actions.runners.pythonrunner import Action class ActiveCampaignAction(Action): def run(self, **kwargs): if kwargs['api_key'] is None: kwargs['api_key'] = self.config['api_key'] return self._get_request(kwargs) def _get_request(self, params): url = urlparse.urljoin(self.config['url'], 'admin/api.php') headers = {} headers['Content-Type'] = 'application/x-www-form-urlencoded' params = self._format_params(params) data = urllib.urlencode(params) response = requests.get(url=url, headers=headers, params=data) results = response.json() if results['result_code'] is not 1: failure_reason = ('Failed to perform action: %s \ (status code: %s)' % (response.text, response.status_code)) self.logger.exception(failure_reason) raise Exception(failure_reason) return results def _format_params(self, params): output = {} for k, v in params.iteritems(): if isinstance(v, dict): print type(v) for pk, pv in v.iteritems(): param_name = "%s[%s]" % (k, pk) output[param_name] = pv else: output[k] = v return output
import requests import urllib import urlparse from st2actions.runners.pythonrunner import Action class ActiveCampaignAction(Action): def run(self, **kwargs): if kwargs['api_key'] is None: kwargs['api_key'] = self.config['api_key'] return self._get_request(kwargs) def _get_request(self, params): url = urlparse.urljoin(self.config['url'], 'admin/api.php') headers = {} headers['Content-Type'] = 'application/x-www-form-urlencoded' params = self._format_params(params) data = urllib.urlencode(params) self.logger.info(data) response = requests.get(url=url, headers=headers, params=data) results = response.json() if results['result_code'] is not 1: failure_reason = ('Failed to perform action %s: %s \ (status code: %s)' % (end_point, response.text, response.status_code)) self.logger.exception(failure_reason) raise Exception(failure_reason) return results def _format_params(self, params): output = {} for k, v in params.iteritems(): if isinstance(v, dict): print type(v) for pk, pv in v.iteritems(): param_name = "%s[%s]" % (k, pk) output[param_name] = pv else: output[k] = v return output
Remove old code that was never documented or used.
<?php namespace Illuminate\Foundation\Testing; use Mockery; use PHPUnit_Framework_TestCase; abstract class TestCase extends PHPUnit_Framework_TestCase { use ApplicationTrait, AssertionsTrait, CrawlerTrait; /** * The callbacks that should be run before the application is destroyed. * * @var array */ protected $beforeApplicationDestroyedCallbacks = []; /** * Creates the application. * * Needs to be implemented by subclasses. * * @return \Symfony\Component\HttpKernel\HttpKernelInterface */ abstract public function createApplication(); /** * Setup the test environment. * * @return void */ public function setUp() { if (!$this->app) { $this->refreshApplication(); } } /** * Clean up the testing environment before the next test. * * @return void */ public function tearDown() { if (class_exists('Mockery')) { Mockery::close(); } if ($this->app) { foreach ($this->beforeApplicationDestroyedCallbacks as $callback) { call_user_func($callback); } $this->app->flush(); $this->app = null; } } /** * Register a callback to be run before the application is destroyed. * * @param callable $callback * @return void */ protected function beforeApplicationDestroyed(callable $callback) { $this->beforeApplicationDestroyedCallbacks[] = $callback; } }
<?php namespace Illuminate\Foundation\Testing; use Mockery; use PHPUnit_Framework_TestCase; abstract class TestCase extends PHPUnit_Framework_TestCase { use ApplicationTrait, AssertionsTrait, CrawlerTrait; /** * The Eloquent factory instance. * * @var \Illuminate\Database\Eloquent\Factory */ protected $factory; /** * The callbacks that should be run before the application is destroyed. * * @var array */ protected $beforeApplicationDestroyedCallbacks = []; /** * Creates the application. * * Needs to be implemented by subclasses. * * @return \Symfony\Component\HttpKernel\HttpKernelInterface */ abstract public function createApplication(); /** * Setup the test environment. * * @return void */ public function setUp() { if (!$this->app) { $this->refreshApplication(); } if (!$this->factory) { $this->factory = $this->app->make('Illuminate\Database\Eloquent\Factory'); } } /** * Clean up the testing environment before the next test. * * @return void */ public function tearDown() { if (class_exists('Mockery')) { Mockery::close(); } if ($this->app) { foreach ($this->beforeApplicationDestroyedCallbacks as $callback) { call_user_func($callback); } $this->app->flush(); $this->app = null; } } /** * Register a callback to be run before the application is destroyed. * * @param callable $callback * @return void */ protected function beforeApplicationDestroyed(callable $callback) { $this->beforeApplicationDestroyedCallbacks[] = $callback; } }
Comment out isomorphic fetch because of error message
const submitAjaxFormRequest = function(formObjectName) { return { type: 'SUBMIT_AJAX_FORM_REQUEST', formObjectName } } const submitAjaxFormFailure = function(error, formObjectName) { return { type: 'SUBMIT_AJAX_FORM_FAILURE', error, formObjectName } } const submitAjaxFormSuccess = function(response, formObjectName) { return { type: 'SUBMIT_AJAX_FORM_SUCCESS', response, formObjectName } } export default function submitAjaxForm(url, data, formObject) { const formObjectName = formObject.constructor.name return function(dispatch) { dispatch(submitAjaxFormRequest(formObjectName)) //const fetch = require('isomorphic-fetch') // regular import breaks in SSR return fetch(url + '.json', { method: (data.get('_method')), body: data, credentials: 'same-origin' }).then( function(response) { const { status, statusText } = response if (status >= 400) { dispatch(submitAjaxFormFailure(response, formObjectName)) throw new Error(`Submit Ajax Form Error ${status}: ${statusText}`) } return response.json() } ).then(json => { console.log('json', json) dispatch(submitAjaxFormSuccess(json, formObjectName)) }) } }
const submitAjaxFormRequest = function(formObjectName) { return { type: 'SUBMIT_AJAX_FORM_REQUEST', formObjectName } } const submitAjaxFormFailure = function(error, formObjectName) { return { type: 'SUBMIT_AJAX_FORM_FAILURE', error, formObjectName } } const submitAjaxFormSuccess = function(response, formObjectName) { return { type: 'SUBMIT_AJAX_FORM_SUCCESS', response, formObjectName } } export default function submitAjaxForm(url, data, formObject) { const formObjectName = formObject.constructor.name return function(dispatch) { dispatch(submitAjaxFormRequest(formObjectName)) const fetch = require('isomorphic-fetch') // regular import breaks in SSR return fetch(url + '.json', { method: (data.get('_method')), body: data, credentials: 'same-origin' }).then( function(response) { const { status, statusText } = response if (status >= 400) { dispatch(submitAjaxFormFailure(response, formObjectName)) throw new Error(`Submit Ajax Form Error ${status}: ${statusText}`) } return response.json() } ).then(json => { console.log('json', json) dispatch(submitAjaxFormSuccess(json, formObjectName)) }) } }
Drop the should in spec names
<?php namespace spec\Raekke\Utils; use PHPSpec2\ObjectBehavior; class Collection extends ObjectBehavior { function it_behaves_like_an_array() { $this->shouldHaveType('Countable'); $this->shouldHaveType('IteratorAggregate'); } function it_returns_default_value_if_key_isnt_set() { $this->get('key0', 'default0')->shouldReturn('default0'); } function it_allows_to_recieve_remove_and_get_elements() { $this->has('key0')->shouldReturn(false); $this->get('key0')->shouldReturn(null); $this->set('key0', 'value0'); $this->has('key0')->shouldReturn(true); $this->get('key0')->shouldReturn('value0'); $this->remove('key0'); $this->has('key0')->shouldReturn(false); $this->get('key0')->shouldReturn(null); } /** * @param ArrayIterator $iterator */ function it_allows_to_get_all_values_at_once($iterator) { $this->all()->shouldReturnAnInstanceOf('ArrayIterator'); $this->set('key0', 'value0'); $iterator = $this->all(); $iterator->count()->shouldReturn(1); $iterator = $this->getIterator(); $iterator->count()->shouldReturn(1); } }
<?php namespace spec\Raekke\Utils; use PHPSpec2\ObjectBehavior; class Collection extends ObjectBehavior { function it_should_behave_like_an_array() { $this->shouldHaveType('Countable'); $this->shouldHaveType('IteratorAggregate'); } function it_returns_default_value_if_key_isnt_set() { $this->get('key0', 'default0')->shouldReturn('default0'); } function it_should_allow_to_recieve_remove_and_get_elements() { $this->has('key0')->shouldReturn(false); $this->get('key0')->shouldReturn(null); $this->set('key0', 'value0'); $this->has('key0')->shouldReturn(true); $this->get('key0')->shouldReturn('value0'); $this->remove('key0'); $this->has('key0')->shouldReturn(false); $this->get('key0')->shouldReturn(null); } /** * @param ArrayIterator $iterator */ function it_should_allow_to_get_all_values_at_once($iterator) { $this->all()->shouldReturnAnInstanceOf('ArrayIterator'); $this->set('key0', 'value0'); $iterator = $this->all(); $iterator->count()->shouldReturn(1); $iterator = $this->getIterator(); $iterator->count()->shouldReturn(1); } }
Fix error in cachebuster for workspace show sidebar
chorus.views.WorkspaceShowSidebar = chorus.views.Sidebar.extend({ constructorName: "WorkspaceShowSidebarView", className:"workspace_show_sidebar", subviews: { ".workspace_member_list": "workspaceMemberList" }, setup:function () { this.bindings.add(this.model, "image:change", this.render); this.model.members().fetch(); this.bindings.add(this.model.members(), "reset", this.render); this.workspaceMemberList = new chorus.views.WorkspaceMemberList(); this.workspaceMemberList.setWorkspace(this.model); }, additionalContext:function () { return { workspaceAdmin:this.model.workspaceAdmin(), imageUrl:this.model.imageUrl() + "&buster=" + chorus.cachebuster(), hasImage:this.model.hasImage(), hasSandbox:!!this.model.sandbox(), currentUserIsMember: this.model.currentUserIsMember() }; }, postRender:function () { var self = this; this.$(".workspace_image").load(function () { self.$(".after_image").removeClass("hidden"); }); this.$('.workspace_image').load(_.bind(this.recalculateScrolling, this)); this._super('postRender'); } });
chorus.views.WorkspaceShowSidebar = chorus.views.Sidebar.extend({ constructorName: "WorkspaceShowSidebarView", className:"workspace_show_sidebar", subviews: { ".workspace_member_list": "workspaceMemberList" }, setup:function () { this.bindings.add(this.model, "image:change", this.render); this.model.members().fetch(); this.bindings.add(this.model.members(), "reset", this.render); this.workspaceMemberList = new chorus.views.WorkspaceMemberList(); this.workspaceMemberList.setWorkspace(this.model); }, additionalContext:function () { return { workspaceAdmin:this.model.workspaceAdmin(), imageUrl:this.model.imageUrl() + "&buster=" + chorus.cachebuster, hasImage:this.model.hasImage(), hasSandbox:!!this.model.sandbox(), currentUserIsMember: this.model.currentUserIsMember() }; }, postRender:function () { var self = this; this.$(".workspace_image").load(function () { self.$(".after_image").removeClass("hidden"); }); this.$('.workspace_image').load(_.bind(this.recalculateScrolling, this)); this._super('postRender'); } });
Fix silly close error, wrong connection
#! /usr/bin/env python from pika import BlockingConnection, ConnectionParameters from psycopg2 import connect RABBIT_MQ_HOST = '54.76.183.35' RABBIT_MQ_PORT = 5672 POSTGRES_HOST = 'microservices.cc9uedlzx2lk.eu-west-1.rds.amazonaws.com' POSTGRES_DATABASE = 'micro' POSTGRES_USER = 'microservices' POSTGRES_PASSWORD = 'microservices' def store(ch, method, properties, body): topic, content = method.routing_key, body conn = connect(host=POSTGRES_HOST, database=POSTGRES_DATABASE, user=POSTGRES_USER, password=POSTGRES_PASSWORD) cursor = conn.cursor() cursor.execute('INSERT INTO facts VALUES (%s, now(), %s);', (topic, content)) conn.commit() cursor.close() conn.close() print 'Recorded topic %s, content %s' % (topic, content) connection = BlockingConnection(ConnectionParameters(host=RABBIT_MQ_HOST, port=RABBIT_MQ_PORT)) channel = connection.channel() channel.exchange_declare(exchange='alex2', type='topic') result = channel.queue_declare(exclusive=True) queue = result.method.queue channel.queue_bind(exchange='alex2', queue=queue, routing_key='*') channel.basic_consume(store, queue=queue, no_ack=True) channel.start_consuming()
#! /usr/bin/env python from pika import BlockingConnection, ConnectionParameters from psycopg2 import connect RABBIT_MQ_HOST = '54.76.183.35' RABBIT_MQ_PORT = 5672 POSTGRES_HOST = 'microservices.cc9uedlzx2lk.eu-west-1.rds.amazonaws.com' POSTGRES_DATABASE = 'micro' POSTGRES_USER = 'microservices' POSTGRES_PASSWORD = 'microservices' def store(ch, method, properties, body): topic, content = method.routing_key, body conn = connect(host=POSTGRES_HOST, database=POSTGRES_DATABASE, user=POSTGRES_USER, password=POSTGRES_PASSWORD) cursor = conn.cursor() cursor.execute('INSERT INTO facts VALUES (%s, now(), %s);', (topic, content)) conn.commit() cursor.close() connection.close() print 'Recorded topic %s, content %s' % (topic, content) connection = BlockingConnection(ConnectionParameters(host=RABBIT_MQ_HOST, port=RABBIT_MQ_PORT)) channel = connection.channel() channel.exchange_declare(exchange='alex2', type='topic') result = channel.queue_declare(exclusive=True) queue = result.method.queue channel.queue_bind(exchange='alex2', queue=queue, routing_key='*') channel.basic_consume(store, queue=queue, no_ack=True) channel.start_consuming()
Fix display mode for block formulas
var katex = require("katex"); module.exports = { book: { assets: "./static", js: [], css: [ "katex.min.css" ] }, ebook: { assets: "./static", css: [ "katex.min.css" ] }, blocks: { math: { shortcuts: { parsers: ["markdown", "asciidoc", "restructuredtext"], start: "$$", end: "$$" }, process: function(blk) { var tex = blk.body; var isInline = !(tex[0] == "\n"); var output = katex.renderToString(tex, { displayMode: !isInline }); if (!isInline) { output = '<div style="text-align: center;">'+output+'</div>'; } return output; } } } };
var katex = require("katex"); module.exports = { book: { assets: "./static", js: [], css: [ "katex.min.css" ] }, ebook: { assets: "./static", css: [ "katex.min.css" ] }, blocks: { math: { shortcuts: { parsers: ["markdown", "asciidoc", "restructuredtext"], start: "$$", end: "$$" }, process: function(blk) { var tex = blk.body; var isInline = !(tex[0] == "\n"); var output = katex.renderToString(tex); if (!isInline) { output = '<div style="text-align: center;">'+output+'</div>'; } return output; } } } };
Add more characters to escaping
<?php /* * This file is part of Alom Graphviz. * (c) Alexandre Salomé <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Alom\Graphviz; /** * Base class for Graphviz instructions. * * @author Alexandre Salomé <[email protected]> */ abstract class BaseInstruction implements InstructionInterface { /** * Renders an inline assignment (without indent or end return line). * * It will handle escaping, according to the value. * * @param string $name A name * * @param string $value A value */ protected function renderInlineAssignment($name, $value) { return sprintf('%s=%s', $this->escape($name), $this->escape($value)); } /** * Escapes a value if needed. * * @param string $value The value to set * * @return string The escaped string */ protected function escape($value) { if ($this->needsEscaping($value)) { return '"'.str_replace('"', '""', $value).'"'; } else { return $value; } } /** * Tests if a string needs escaping. * * @return boolean Result of test */ protected function needsEscaping($value) { return preg_match('/[ "#:\\/\\.,]/', $value) || in_array($value, array('graph', 'node', 'edge')) || empty($value); } }
<?php /* * This file is part of Alom Graphviz. * (c) Alexandre Salomé <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Alom\Graphviz; /** * Base class for Graphviz instructions. * * @author Alexandre Salomé <[email protected]> */ abstract class BaseInstruction implements InstructionInterface { /** * Renders an inline assignment (without indent or end return line). * * It will handle escaping, according to the value. * * @param string $name A name * * @param string $value A value */ protected function renderInlineAssignment($name, $value) { return sprintf('%s=%s', $this->escape($name), $this->escape($value)); } /** * Escapes a value if needed. * * @param string $value The value to set * * @return string The escaped string */ protected function escape($value) { if ($this->needsEscaping($value)) { return '"'.str_replace('"', '""', $value).'"'; } else { return $value; } } /** * Tests if a string needs escaping. * * @return boolean Result of test */ protected function needsEscaping($value) { return preg_match('/[ "#:]/', $value) || in_array($value, array('graph', 'node', 'edge')) || empty($value); } }
Add request parameter to backend.authenticate Without this, the signature of our custom backend does not match that of the function call. This signature is tested in django.contrib.auth.authenticate here: https://github.com/django/django/blob/fdf209eab8949ddc345aa0212b349c79fc6fdebb/django/contrib/auth/__init__.py#L69 and `request` was added to that signature in Django 1.11 in https://github.com/django/django/commit/4b9330ccc04575f9e5126529ec355a450d12e77c. With this, the Concord users are authenticated correctly.
# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end for Single Sign On providers. Before we can call django.contrib.auth.login on an SSO user, we must first authenticate them. This must be done using a custom authentication back- end, which sets the backend attribute on the user model. This class should be instantiated with an SSO provider user model, such as ItsiUser or ConcordUser, before it can be used. """ def __init__(self, model, field): self.SSOUserModel = model self.SSOField = field def authenticate(self, request=None, sso_id=None): if sso_id is not None: try: query = {self.SSOField: sso_id} user = self.SSOUserModel.objects.get(**query).user return user except ObjectDoesNotExist: return None return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None class ItsiAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ItsiAuthenticationBackend, self).__init__( ItsiUser, 'itsi_id') class ConcordAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ConcordAuthenticationBackend, self).__init__( ConcordUser, 'concord_id')
# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end for Single Sign On providers. Before we can call django.contrib.auth.login on an SSO user, we must first authenticate them. This must be done using a custom authentication back- end, which sets the backend attribute on the user model. This class should be instantiated with an SSO provider user model, such as ItsiUser or ConcordUser, before it can be used. """ def __init__(self, model, field): self.SSOUserModel = model self.SSOField = field def authenticate(self, sso_id=None): if sso_id is not None: try: query = {self.SSOField: sso_id} user = self.SSOUserModel.objects.get(**query).user return user except ObjectDoesNotExist: return None return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None class ItsiAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ItsiAuthenticationBackend, self).__init__( ItsiUser, 'itsi_id') class ConcordAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ConcordAuthenticationBackend, self).__init__( ConcordUser, 'concord_id')
Update for compat w/ djangorestframework 3.2 Change request.QUERY_PARAMS to request.query_params
""" Provides JSONP rendering support. """ from __future__ import unicode_literals from rest_framework.renderers import JSONRenderer class JSONPRenderer(JSONRenderer): """ Renderer which serializes to json, wrapping the json output in a callback function. """ media_type = 'application/javascript' format = 'jsonp' callback_parameter = 'callback' default_callback = 'callback' charset = 'utf-8' def get_callback(self, renderer_context): """ Determine the name of the callback to wrap around the json output. """ request = renderer_context.get('request', None) params = request and request.query_params or {} return params.get(self.callback_parameter, self.default_callback) def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders into jsonp, wrapping the json output in a callback function. Clients may set the callback function name using a query parameter on the URL, for example: ?callback=exampleCallbackName """ renderer_context = renderer_context or {} callback = self.get_callback(renderer_context) json = super(JSONPRenderer, self).render(data, accepted_media_type, renderer_context) return callback.encode(self.charset) + b'(' + json + b');'
""" Provides JSONP rendering support. """ from __future__ import unicode_literals from rest_framework.renderers import JSONRenderer class JSONPRenderer(JSONRenderer): """ Renderer which serializes to json, wrapping the json output in a callback function. """ media_type = 'application/javascript' format = 'jsonp' callback_parameter = 'callback' default_callback = 'callback' charset = 'utf-8' def get_callback(self, renderer_context): """ Determine the name of the callback to wrap around the json output. """ request = renderer_context.get('request', None) params = request and request.QUERY_PARAMS or {} return params.get(self.callback_parameter, self.default_callback) def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders into jsonp, wrapping the json output in a callback function. Clients may set the callback function name using a query parameter on the URL, for example: ?callback=exampleCallbackName """ renderer_context = renderer_context or {} callback = self.get_callback(renderer_context) json = super(JSONPRenderer, self).render(data, accepted_media_type, renderer_context) return callback.encode(self.charset) + b'(' + json + b');'
Update tail command tests to check for backslashes
<?php namespace Spatie\Tail\Tests; class TailCommandTest extends TestCase { /** @test */ public function it_will_throw_an_exception_if_the_given_environment_is_not_configured() { $this->expectExceptionMessageMatches('/^No configuration set/'); $this->artisan('tail', [ 'environment' => 'non-existing-environment', ]); } /** @test */ public function the_tail_command_is_correct() { $this ->artisan('tail', [ '--debug' => true, ]) ->expectsOutput('\\tail -f -n 0 "`\\ls -t | \\head -1`"'); } /** @test */ public function the_tail_command_with_file_is_correct() { $this ->artisan('tail', [ '--debug' => true, '--file' => 'file.log', ]) ->expectsOutput('\\tail -f -n 0 "file.log"'); } /** @test */ public function the_command_when_grepping_is_correct() { $this ->artisan('tail', [ '--debug' => true, '--grep' => 'test', ]) ->expectsOutput('\\tail -f -n 0 "`\\ls -t | \\head -1`" | \\grep "test"'); } }
<?php namespace Spatie\Tail\Tests; class TailCommandTest extends TestCase { /** @test */ public function it_will_throw_an_exception_if_the_given_environment_is_not_configured() { $this->expectExceptionMessageMatches('/^No configuration set/'); $this->artisan('tail', [ 'environment' => 'non-existing-environment', ]); } /** @test */ public function the_tail_command_is_correct() { $this ->artisan('tail', [ '--debug' => true, ]) ->expectsOutput('tail -f -n 0 "`ls -t | head -1`"'); } /** @test */ public function the_tail_command_with_file_is_correct() { $this ->artisan('tail', [ '--debug' => true, '--file' => 'file.log', ]) ->expectsOutput('tail -f -n 0 "file.log"'); } /** @test */ public function the_command_when_grepping_is_correct() { $this ->artisan('tail', [ '--debug' => true, '--grep' => 'test', ]) ->expectsOutput('tail -f -n 0 "`ls -t | head -1`" | grep "test"'); } }
Add support for boolean type git-svn-id: 7e8def7d4256e953abb468098d8cb9b4faff0c63@5739 12255794-1b5b-4525-b599-b0510597569d
package com.arondor.common.reflection.reflect.instantiator; import java.util.HashMap; import java.util.Map; public class FastPrimitiveConverter { private interface PrimitiveConverter { Object convert(String value); } private final Map<String, PrimitiveConverter> primitiveConverterMap = new HashMap<String, FastPrimitiveConverter.PrimitiveConverter>(); public FastPrimitiveConverter() { primitiveConverterMap.put("java.lang.String", new PrimitiveConverter() { public Object convert(String value) { return value; } }); primitiveConverterMap.put("long", new PrimitiveConverter() { public Object convert(String value) { return Long.parseLong(value); } }); primitiveConverterMap.put("int", new PrimitiveConverter() { public Object convert(String value) { return Integer.parseInt(value); } }); primitiveConverterMap.put("boolean", new PrimitiveConverter() { public Object convert(String value) { return Boolean.parseBoolean(value); } }); } public Object convert(String value, String primitiveClass) { PrimitiveConverter converter = primitiveConverterMap.get(primitiveClass); if (converter == null) { throw new IllegalArgumentException("Not supported : primitiveClass=" + primitiveClass); } return converter.convert(value); } }
package com.arondor.common.reflection.reflect.instantiator; import java.util.HashMap; import java.util.Map; public class FastPrimitiveConverter { private interface PrimitiveConverter { Object convert(String value); } private final Map<String, PrimitiveConverter> primitiveConverterMap = new HashMap<String, FastPrimitiveConverter.PrimitiveConverter>(); public FastPrimitiveConverter() { primitiveConverterMap.put("java.lang.String", new PrimitiveConverter() { public Object convert(String value) { return value; } }); primitiveConverterMap.put("long", new PrimitiveConverter() { public Object convert(String value) { return Long.parseLong(value); } }); primitiveConverterMap.put("int", new PrimitiveConverter() { public Object convert(String value) { return Integer.parseInt(value); } }); } public Object convert(String value, String primitiveClass) { PrimitiveConverter converter = primitiveConverterMap.get(primitiveClass); if (converter == null) { throw new IllegalArgumentException("Not supported : primitiveClass=" + primitiveClass); } return converter.convert(value); } }
Set Sequencer's HighWaterMark to 0
package bench.pubsub; import org.zeromq.ZMQ; /** * This sequencer simply reads from a PULL socket and forwards the * message to the PUB socket. */ public class ZeroMQSequencer { public static void main(String[] args) throws Exception { new Thread(new Sequencer()).start(); } public static class Sequencer implements Runnable { @Override public void run() { // Prepare our context and publisher ZMQ.Context context = ZMQ.context(2); ZMQ.Socket publisher = context.socket(ZMQ.PUB); publisher.setAffinity(1); publisher.setHWM(0); publisher.bind("tcp://*:5556"); //publisher.bind("ipc://weather"); ZMQ.Socket incoming = context.socket(ZMQ.PULL); incoming.setHWM(0); incoming.setAffinity(2); incoming.bind("tcp://*:5557"); System.out.println("Sequencer is alive"); ZMQ.proxy(incoming, publisher, null); // while (! Thread.currentThread().isInterrupted()) { // byte[] data = incoming.recv(0); // //System.out.printf("Received message with %d bytes\n", data.length); // publisher.send(data, 0); // } publisher.close(); incoming.close(); context.term(); } } }
package bench.pubsub; import org.zeromq.ZMQ; /** * This sequencer simply reads from a PULL socket and forwards the * message to the PUB socket. */ public class ZeroMQSequencer { public static void main (String[] args) throws Exception { new Thread(new Sequencer()).start(); } public static class Sequencer implements Runnable { public void run() { // Prepare our context and publisher ZMQ.Context context = ZMQ.context(2); ZMQ.Socket publisher = context.socket(ZMQ.PUB); publisher.setAffinity(1); //publisher.setSndHWM(100000); publisher.bind("tcp://*:5556"); //publisher.bind("ipc://weather"); ZMQ.Socket incoming = context.socket(ZMQ.PULL); //incoming.setRcvHWM(100000); incoming.setAffinity(2); incoming.bind("tcp://*:5557"); ZMQ.proxy(incoming, publisher, null); // while (! Thread.currentThread().isInterrupted()) { // byte[] data = incoming.recv(0); // //System.out.printf("Received message with %d bytes\n", data.length); // publisher.send(data, 0); // } publisher.close(); incoming.close(); context.term(); } } }
Fix name of macosx backend.
#! /usr/bin/env python # Last Change: Mon Dec 08 03:00 PM 2008 J from os.path import join import os import warnings from setuphelp import info_factory, NotFoundError def configuration(parent_package='', top_path=None, package_name='soundio'): from numpy.distutils.misc_util import Configuration config = Configuration(package_name, parent_package, top_path) alsa_info = info_factory('alsa', ['asound'], ['alsa/asoundlib.h'], classname='AlsaInfo')() try: alsa_config = alsa_info.get_info(2) config.add_extension("_alsa_backend", sources = ["alsa/_alsa_backend.c"], extra_info=alsa_config) except NotFoundError: warnings.warn("Alsa not found - alsa backend not build") core_audio_info = info_factory('CoreAudio', [], [], frameworks=["CoreAudio"], classname='CoreAudioInfo')() try: core_audio_config = core_audio_info.get_info(2) config.add_extension("macosx_backend", sources=["macosx/macosx_backend.c"], extra_info=core_audio_config) except NotFoundError: warnings.warn("CoreAudio not found - CoreAudio backend not build") return config if __name__ == "__main__": from numpy.distutils.core import setup #setup(**configuration(top_path='').todict()) #setup(**configuration(top_path='')) setup(configuration=configuration)
#! /usr/bin/env python # Last Change: Mon Dec 08 03:00 PM 2008 J from os.path import join import os import warnings from setuphelp import info_factory, NotFoundError def configuration(parent_package='', top_path=None, package_name='soundio'): from numpy.distutils.misc_util import Configuration config = Configuration(package_name, parent_package, top_path) alsa_info = info_factory('alsa', ['asound'], ['alsa/asoundlib.h'], classname='AlsaInfo')() try: alsa_config = alsa_info.get_info(2) config.add_extension("_alsa_backend", sources = ["alsa/_alsa_backend.c"], extra_info=alsa_config) except NotFoundError: warnings.warn("Alsa not found - alsa backend not build") core_audio_info = info_factory('CoreAudio', [], [], frameworks=["CoreAudio"], classname='CoreAudioInfo')() try: core_audio_config = core_audio_info.get_info(2) config.add_extension("maxosx_backend", sources=["macosx/macosx_backend.c"], extra_info=core_audio_config) except NotFoundError: warnings.warn("CoreAudio not found - CoreAudio backend not build") return config if __name__ == "__main__": from numpy.distutils.core import setup #setup(**configuration(top_path='').todict()) #setup(**configuration(top_path='')) setup(configuration=configuration)
Update path to work on all SOs
'use strict' const path = require('path') const webpack = require('webpack') const validate = require('webpack-validator') const ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = validate({ entry: path.join('.', 'src', 'index.js'), output: { path: 'dist', filename: '<%= camelName %>.js', libraryTarget: 'umd' }, module: { preLoaders: [ { test: /\.js$/, loader: 'eslint', exclude: /node_modules/ } ], loaders: [ { test: /\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\.css?$/, loader: ExtractTextPlugin.extract('style', 'css'), include: path.resolve(__dirname, '..') } ] }, externals: { 'react': 'react', 'react-dom': 'react-dom' }, plugins: [ new ExtractTextPlugin('<%= camelName %>.css'), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': '"production"' } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurrenceOrderPlugin() ] })
'use strict' const path = require('path') const webpack = require('webpack') const validate = require('webpack-validator') const ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = validate({ entry: './src/index.js', output: { path: 'dist', filename: '<%= camelName %>.js', libraryTarget: 'umd' }, module: { preLoaders: [ { test: /\.js$/, loader: 'eslint', exclude: /node_modules/ } ], loaders: [ { test: /\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\.css?$/, loader: ExtractTextPlugin.extract('style', 'css'), include: path.resolve(__dirname, '..') } ] }, externals: { 'react': 'react', 'react-dom': 'react-dom' }, plugins: [ new ExtractTextPlugin('<%= camelName %>.css'), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': '"production"' } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurrenceOrderPlugin() ] })
Remove effect classes after animations complete so they can be added again if needed
(function ($) { $.fn.animateCSS = function (effect, delay, callback) { // Return this to maintain chainability return this.each(function () { // Cache $(this) for speed var $this = $(this); // Check if delay exists or if it's a callback if (!delay || typeof delay == 'function') { // If it's a callback, move it to callback so we can call it later callback = delay; // Set the delay to 0 for the setTimeout delay = 0; } // Start a counter so we can delay the animation if required var animation = setTimeout(function () { // Add the animation effect with classes $this.addClass('animated ' + effect); // Check if the elemenr has been hidden to start with if ($this.css('visibility') == 'hidden') { // If it has, show it (after the class has been added) $this.css({ 'visibility': 'visible' }); } // If the element is hidden if ($this.is(':hidden')) { // Show it $this.show(); } // Event triggered when the animation has finished $this.bind('animationend webkitAnimationEnd oAnimationEnd', function () { // Remove the classes so they can be added again later $this.removeClass('animated ' + effect); // Add a callback event if (typeof callback == 'function') { // Execute the callback callback.call(this); } }); // Specify the delay }, delay); }); }; })(jQuery);
(function ($) { $.fn.animateCSS = function (effect, delay, callback) { // Return this to maintain chainability return this.each(function () { // Cache $(this) for speed var $this = $(this); // Check if delay exists or if it's a callback if (!delay || typeof delay == 'function') { // If it's a callback, move it to callback so we can call it later callback = delay; // Set the delay to 0 for the setTimeout delay = 0; } // Start a counter so we can delay the animation if required var animation = setTimeout(function () { // Add the animation effect with classes $this.addClass('animated ' + effect); // Check if the elemenr has been hidden to start with if ($this.css('visibility') == 'hidden') { // If it has, show it (after the class has been added) $this.css({ 'visibility': 'visible' }); } // If the element is hidden if ($this.is(':hidden')) { // Show it $this.show(); } // Event triggered when the animation has finished $this.bind('animationend webkitAnimationEnd oAnimationEnd', function () { // Add a callback event if (typeof callback == 'function') { // Execute the callback callback.call(this); } }); // Specify the delay }, delay); }); }; })(jQuery);