text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix super call for Python 2.7
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super().get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context
Fix custom collection comparison matcher
customMatchers = { toEqualCollection : function(util, customEqualityTesters) { return { compare : function(actual, expected) { var result = {}; var actualArray = _.toArray(actual); var expectedArray = expected.find({}).fetch(); result.pass = util.equals(actualArray, expectedArray, customEqualityTesters); return result; } }; }, toBeFoundExactlyInCollection : function(util, customEqualityTesters) { return { compare : function(actual, expected) { var result = {}; var expectedItem = expected.findOne(actual); if (_.isUndefined(expectedItem)) { result.pass = false; result.message = 'Expected ' + JSON.stringify(actual) + ' to be found in collection ' + JSON.stringify(expected.find({}).fetch()); } else { delete expectedItem._id; result.pass = util.equals(actual, expectedItem, customEqualityTesters); } if (!result.pass) { result.message = 'Expected ' + JSON.stringify(actual) + ' to be found in collection ' + JSON.stringify(expected.find({}).fetch()); } return result; } }; }, toDeepEqual: function(util, customEqualityTesters) { return { compare: function(actual, expected) { var result = {}; result.pass = _.isEqual(actual, expected); return result; } }; } };
customMatchers = { toEqualCollection : function(util, customEqualityTesters) { return { compare : function(actual, expected) { var result = {}; var expectedArray = expected.find({}).fetch(); result.pass = util.equals(actual, expectedArray, customEqualityTesters); return result; } }; }, toBeFoundExactlyInCollection : function(util, customEqualityTesters) { return { compare : function(actual, expected) { var result = {}; var expectedItem = expected.findOne(actual); if (_.isUndefined(expectedItem)) { result.pass = false; result.message = 'Expected ' + JSON.stringify(actual) + ' to be found in collection ' + JSON.stringify(expected.find({}).fetch()); } else { delete expectedItem._id; result.pass = util.equals(actual, expectedItem, customEqualityTesters); } if (!result.pass) { result.message = 'Expected ' + JSON.stringify(actual) + ' to be found in collection ' + JSON.stringify(expected.find({}).fetch()); } return result; } }; }, toDeepEqual: function(util, customEqualityTesters) { return { compare: function(actual, expected) { var result = {}; result.pass = _.isEqual(actual, expected); return result; } }; } };
Fix check for Wells/Calabretta convention
from __future__ import absolute_import def check(header, convention=None, dimensions=[0, 1]): ix = dimensions[0] + 1 iy = dimensions[1] + 1 ctypex = header['CTYPE%i' % ix] crvaly = header['CRVAL%i' % iy] # Check for CRVAL2!=0 for CAR projection if ctypex[4:] == '-CAR' and crvaly != 0: if convention in ['wells', 'calabretta']: if convention == 'wells': try: crpixy = header['CRPIX%i' % iy] cdelty = header['CDELT%i' % iy] except: raise Exception("Need CDELT to be present for wells convention") crpixy = crpixy - crvaly / cdelty header.update('CRPIX%i' % iy, crpixy) header.update('CRVAL%i' % iy, 0.0) else: pass else: raise Exception('''WARNING: projection is Plate Caree (-CAR) and CRVAL2 is not zero. This can be intepreted either according to Wells (1981) or Calabretta (2002). The former defines the projection as rectilinear regardless of the value of CRVAL2, whereas the latter defines the projection as rectilinear only when CRVAL2 is zero. You will need to specify the convention to assume by setting either convention='wells' or convention='calabretta' when initializing the FITSFigure instance. ''') return header
from __future__ import absolute_import def check(header, convention=None, dimensions=[0, 1]): ix = dimensions[0] + 1 iy = dimensions[1] + 1 ctypex = header['CTYPE%i' % ix] crvaly = header['CRVAL%i' % iy] crpixy = header['CRPIX%i' % iy] cdelty = header['CDELT%i' % iy] # Check for CRVAL2!=0 for CAR projection if ctypex[4:] == '-CAR' and crvaly != 0: if convention in ['wells', 'calabretta']: if convention == 'wells': crpixy = crpixy - crvaly / cdelty header.update('CRPIX%i' % iy, crpixy) header.update('CRVAL%i' % iy, 0.0) else: pass else: raise Exception('''WARNING: projection is Plate Caree (-CAR) and CRVAL2 is not zero. This can be intepreted either according to Wells (1981) or Calabretta (2002). The former defines the projection as rectilinear regardless of the value of CRVAL2, whereas the latter defines the projection as rectilinear only when CRVAL2 is zero. You will need to specify the convention to assume by setting either convention='wells' or convention='calabretta' when initializing the FITSFigure instance. ''') return header
Fix bug where list rows are not cleaned up
var _ = require('lodash'); module.exports = function($templateRequest, $compile, $interpolate) { typeCounts = {}; return { restrict: 'E', link: function($scope, $element, $attrs) { var type = $scope.type, newScope = $scope.$new(); var templates = [ '/templates/' + $attrs.type + '.html', '/templates/' + $attrs.type + '-' + $attrs.id + '.html' ]; newScope.$watch($attrs.data, function(data) { _.extend(newScope, data); }); typeCounts[type] = typeCounts[type] || 0 function tryToLoadNextTemplate() { $templateRequest(templates.pop(), true).then(function(template) { $element.append($compile(template)(newScope)); }, function(response) { if (templates.length === 0) { throw new Error('No template could be loaded for widget ' + $attrs.type); } tryToLoadNextTemplate(); }); }; tryToLoadNextTemplate(); } } }
var _ = require('lodash'); module.exports = function($templateRequest, $compile, $interpolate) { typeCounts = {}; return { restrict: 'E', link: function($scope, $element, $attrs) { var type = $scope.type, newScope = $scope.$new(); var templates = [ '/templates/' + $attrs.type + '.html', '/templates/' + $attrs.type + '-' + $attrs.id + '.html' ]; newScope.$watch($attrs.data, function(data) { _.merge(newScope, data); }); typeCounts[type] = typeCounts[type] || 0 function tryToLoadNextTemplate() { $templateRequest(templates.pop(), true).then(function(template) { $element.append($compile(template)(newScope)); }, function(response) { if (templates.length === 0) { throw new Error('No template could be loaded for widget ' + $attrs.type); } tryToLoadNextTemplate(); }); }; tryToLoadNextTemplate(); } } }
Change the topic name used in the test
require('./harness'); var testName = __filename.replace(__dirname+'/','').replace('.js',''); connection.addListener('ready', function () { puts("connected to " + connection.serverProperties.product); var callbacksCalled = 0; connection.exchange('node.'+testName+'.exchange', {type: 'topic'}, function(exchange) { connection.queue( 'node.'+testName+'.queue', { durable: false, autoDelete : true }, function (queue) { puts("Queue ready"); // main test for callback queue.bind(exchange, 'node.'+testName+'.topic.bindCallback.outer', function(q) { puts("First queue bind callback called"); callbacksCalled++; q.bind(exchange, 'node.'+testName+'.topic.bindCallback.inner', function() { puts("Second queue bind callback called"); callbacksCalled++; }); }); setTimeout(function() { assert.ok(callbacksCalled == 2, "Callback was not called"); puts("Cascaded queue bind callback succeeded"); connection.destroy();}, 2000); }); }); });
require('./harness'); var testName = __filename.replace(__dirname+'/','').replace('.js',''); connection.addListener('ready', function () { puts("connected to " + connection.serverProperties.product); var callbacksCalled = 0; connection.exchange('node.'+testName+'.exchange', {type: 'topic'}, function(exchange) { connection.queue( 'node.'+testName+'.queue', { durable: false, autoDelete : true }, function (queue) { puts("Queue ready"); // main test for callback queue.bind(exchange, 'node.'+testName+'.topic.bindCallback1', function(q) { puts("First queue bind callback called"); callbacksCalled++; q.bind(exchange, 'node.'+testName+'.topic.bindCallback2', function() { puts("Second queue bind callback called"); callbacksCalled++; }); }); setTimeout(function() { assert.ok(callbacksCalled == 2, "Callback was not called"); puts("Cascaded queue bind callback succeeded"); connection.destroy();}, 2000); }); }); });
Fix deprecation warning in Java unit test
package com.genymobile.scrcpy; import org.junit.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 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 } }
Fix masonry item alignment issue
import React from 'react'; import { StyleSheet, View, Text, Image } from 'react-native'; import { SharedElementTransition } from 'react-native-navigation'; const SHOW_DURATION = 240; const HIDE_DURATION = 200; class Item extends React.Component { static navigatorStyle = { navBarHidden: true, drawUnderNavBar: true }; render() { return ( <View style={styles.container}> <SharedElementTransition sharedElementId={this.props.sharedImageId} showDuration={SHOW_DURATION} hideDuration={HIDE_DURATION} animateClipBounds showInterpolation={{ type: 'linear', easing: 'FastInSlowOut', }} hideInterpolation={{ type: 'linear', easing: 'FastOutSlowIn', }} > <Image style={styles.image} source={this.props.image} /> </SharedElementTransition> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#ffffff', justifyContent: 'center', }, image: { width: 400, height: 400, } }); export default Item;
import React from 'react'; import { StyleSheet, View, Text, Image } from 'react-native'; import { SharedElementTransition } from 'react-native-navigation'; const SHOW_DURATION = 240; const HIDE_DURATION = 200; class Item extends React.Component { static navigatorStyle = { navBarHidden: true, drawUnderNavBar: true }; render() { return ( <View style={styles.container}> <SharedElementTransition sharedElementId={this.props.sharedImageId} showDuration={SHOW_DURATION} hideDuration={HIDE_DURATION} animateClipBounds showInterpolation={{ type: 'linear', easing: 'FastInSlowOut', }} hideInterpolation={{ type: 'linear', easing: 'FastOutSlowIn', }} > <Image style={styles.image} source={this.props.image} /> </SharedElementTransition> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#ffffff', alignItems: 'center', justifyContent: 'center', }, image: { width: 400, height: 400, } }); export default Item;
FIX redirect to checkout after guest login
var ValidationService = require("services/ValidationService"); var ApiService = require("services/ApiService"); Vue.component("guest-login", { props: [ "template" ], data: function() { return { email: "" }; }, created: function() { this.$options.template = this.template; }, methods: { validate: function() { ValidationService.validate($("#guest-login-form-" + this._uid)) .done(function() { this.sendEMail(); }.bind(this)) .fail(function(invalidFields) { ValidationService.markInvalidFields(invalidFields, "error"); }); }, sendEMail: function() { ApiService.post("/rest/io/guest", {email: this.email}) .done(function() { window.location.href = "/checkout"; }); } } });
var ValidationService = require("services/ValidationService"); var ApiService = require("services/ApiService"); Vue.component("guest-login", { props: [ "template" ], data: function() { return { email: "" }; }, created: function() { this.$options.template = this.template; }, methods: { validate: function() { ValidationService.validate($("#guest-login-form-" + this._uid)) .done(function() { this.sendEMail(); }.bind(this)) .fail(function(invalidFields) { ValidationService.markInvalidFields(invalidFields, "error"); }); }, sendEMail: function() { ApiService.post("/rest/io/guest", {email: this.email}) .done(function(response) { window.location.href("/checkout"); }); } } });
Refresh layout header on login-changed event Refresh layout header on login-changed event so that the header correctly shows the logged-in user when following an invitation link.
isic.views.LayoutHeaderView = isic.View.extend({ events: { 'mouseenter .dropdown': function (event) { $(event.currentTarget).addClass('open'); }, 'mouseleave .dropdown': function (event) { $(event.currentTarget).removeClass('open'); }, 'click .dropdown': function (event) { $(event.currentTarget).removeClass('open'); } }, initialize: function (settings) { this.render(); girder.events.on('g:login', this.render, this); girder.events.on('g:login-changed', this.render, this); }, render: function () { this.$el.html(isic.templates.layoutHeader({ currentUser: girder.currentUser })); // Specify trigger for tooltip to ensure that tooltip hides when button // is clicked. See http://stackoverflow.com/a/33585981/2522042. this.$('a[title]').tooltip({ placement: 'bottom', trigger: 'hover', delay: {show: 300} }); new isic.views.LayoutHeaderUserView({ el: this.$('.isic-current-user-wrapper'), parentView: this }).render(); } });
isic.views.LayoutHeaderView = isic.View.extend({ events: { 'mouseenter .dropdown': function (event) { $(event.currentTarget).addClass('open'); }, 'mouseleave .dropdown': function (event) { $(event.currentTarget).removeClass('open'); }, 'click .dropdown': function (event) { $(event.currentTarget).removeClass('open'); } }, initialize: function (settings) { this.render(); girder.events.on('g:login', this.render, this); }, render: function () { this.$el.html(isic.templates.layoutHeader({ currentUser: girder.currentUser })); // Specify trigger for tooltip to ensure that tooltip hides when button // is clicked. See http://stackoverflow.com/a/33585981/2522042. this.$('a[title]').tooltip({ placement: 'bottom', trigger: 'hover', delay: {show: 300} }); new isic.views.LayoutHeaderUserView({ el: this.$('.isic-current-user-wrapper'), parentView: this }).render(); } });
Use MediaType instead of user-written string
package <%=packageName%>.web.rest; import <%=packageName%>.security.AuthoritiesConstants; import <%=packageName%>.service.AuditEventService; import <%=packageName%>.web.propertyeditors.LocaleDateTimeEditor; import org.joda.time.LocalDateTime; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.http.MediaType; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import java.util.List; /** * REST controller for getting the audit events. */ @RestController @RequestMapping("/app") public class AuditResource { @Inject private AuditEventService auditEventService; @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("yyyy-MM-dd", false)); } @RequestMapping(value = "/rest/audits/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @RolesAllowed(AuthoritiesConstants.ADMIN) public List<AuditEvent> findAll() { return auditEventService.findAll(); } @RequestMapping(value = "/rest/audits/byDates", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @RolesAllowed(AuthoritiesConstants.ADMIN) public List<AuditEvent> findByDates(@RequestParam(value = "fromDate") LocalDateTime fromDate, @RequestParam(value = "toDate") LocalDateTime toDate) { return auditEventService.findByDates(fromDate, toDate); } }
package <%=packageName%>.web.rest; import <%=packageName%>.security.AuthoritiesConstants; import <%=packageName%>.service.AuditEventService; import <%=packageName%>.web.propertyeditors.LocaleDateTimeEditor; import org.joda.time.LocalDateTime; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import java.util.List; /** * REST controller for getting the audit events. */ @RestController @RequestMapping("/app") public class AuditResource { @Inject private AuditEventService auditEventService; @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("yyyy-MM-dd", false)); } @RequestMapping(value = "/rest/audits/all", method = RequestMethod.GET, produces = "application/json") @RolesAllowed(AuthoritiesConstants.ADMIN) public List<AuditEvent> findAll() { return auditEventService.findAll(); } @RequestMapping(value = "/rest/audits/byDates", method = RequestMethod.GET, produces = "application/json") @RolesAllowed(AuthoritiesConstants.ADMIN) public List<AuditEvent> findByDates(@RequestParam(value = "fromDate") LocalDateTime fromDate, @RequestParam(value = "toDate") LocalDateTime toDate) { return auditEventService.findByDates(fromDate, toDate); } }
Fix bug that dropped RSS item titles
"use strict"; var components = require("server-components"); var truncateHtml = require("truncate-html"); var moment = require("moment"); var feedparser = require('feedparser-promised'); var cache = require("memory-cache"); function getRss(url) { var cachedResult = cache.get(url); if (cachedResult) return Promise.resolve(cachedResult); else { return feedparser.parse(url) .catch((e) => { console.error('Feed error from ' + url, e) return []; }) .then((result) => { cache.put(url, result, 1000 * 60 * 10); return result; }); } } var RssSource = components.newElement(); RssSource.createdCallback = function () { var url = this.getAttribute("url"); var icon = this.getAttribute("icon"); var sourceTitle = this.getAttribute("title"); return getRss(url).then((items) => { this.dispatchEvent(new components.dom.CustomEvent('items-ready', { items: items.map((item) => { var title = (item.title && item.title.match(/\w/)) ? item.title : "Post on " + sourceTitle; return { title: title, icon: icon, timestamp: moment(item.pubDate).unix(), description: truncateHtml(item.description, 600), url: item.link }; }), bubbles: true })); }); }; components.registerElement("rss-source", { prototype: RssSource });
"use strict"; var components = require("server-components"); var truncateHtml = require("truncate-html"); var moment = require("moment"); var feedparser = require('feedparser-promised'); var cache = require("memory-cache"); function getRss(url) { var cachedResult = cache.get(url); if (cachedResult) return Promise.resolve(cachedResult); else { return feedparser.parse(url) .catch((e) => { console.error('Feed error from ' + url, e) return []; }) .then((result) => { cache.put(url, result, 1000 * 60 * 10); return result; }); } } var RssSource = components.newElement(); RssSource.createdCallback = function () { var url = this.getAttribute("url"); var icon = this.getAttribute("icon"); var sourceTitle = this.getAttribute("title"); return getRss(url).then((items) => { this.dispatchEvent(new components.dom.CustomEvent('items-ready', { items: items.map((item) => { var title = (item.title && item.title.match(/\w/)) ? title : "Post on " + sourceTitle; return { title: title, icon: icon, timestamp: moment(item.pubDate).unix(), description: truncateHtml(item.description, 600), url: item.link }; }), bubbles: true })); }); }; components.registerElement("rss-source", { prototype: RssSource });
Add getFirst method to customers service (saas-185)
'use strict'; (function() { angular.module('ncsaas') .service('customersService', ['RawCustomer', customersService]); function customersService(RawCustomer) { /*jshint validthis: true */ var vm = this; vm.getCustomersList = getCustomersList; vm.createCustomer = createCustomer; vm.getCustomer = getCustomer; vm.getFirst = getFirst; function getFirst() { return RawCustomer.getFirst().$promise; } function getCustomersList() { return RawCustomer.query(); } function createCustomer() { return new RawCustomer(); } function getCustomer(uuid) { return RawCustomer.get({customerUUID: uuid}); } } })(); (function() { angular.module('ncsaas') .factory('RawCustomer', ['ENV', '$resource', RawCustomer]); function RawCustomer(ENV, $resource) { function getFirst(data) { var customers = angular.fromJson(data); if (customers.length > 0) { return customers[0]; } else { return undefined; } } return $resource(ENV.apiEndpoint + 'api/customers/:customerUUID/', {customerUUID:'@uuid'}, { getFirst: { method: 'GET', transformResponse: getFirst }, update: { method: 'PUT' } } ); } })();
'use strict'; (function() { angular.module('ncsaas') .service('customersService', ['RawCustomer', customersService]); function customersService(RawCustomer) { /*jshint validthis: true */ var vm = this; vm.getCustomersList = getCustomersList; vm.createCustomer = createCustomer; vm.getCustomer = getCustomer; function getCustomersList() { return RawCustomer.query(); } function createCustomer() { return new RawCustomer(); } function getCustomer(uuid) { return RawCustomer.get({customerUUID: uuid}); } } })(); (function() { angular.module('ncsaas') .factory('RawCustomer', ['ENV', '$resource', RawCustomer]); function RawCustomer(ENV, $resource) { function getFirst(data) { var customers = angular.fromJson(data); if (customers.length > 0) { return customers[0]; } else { return undefined; } } return $resource(ENV.apiEndpoint + 'api/customers/:customerUUID/', {customerUUID:'@uuid'}, { getFirst: { method: 'GET', transformResponse: getFirst }, update: { method: 'PUT' } } ); } })();
Fix unset type_options in list form_filters config
<?php declare(strict_types=1); namespace AlterPHP\EasyAdminExtensionBundle\Helper; use Symfony\Component\Form\FormFactory; use Symfony\Component\Form\FormInterface; use Symfony\Component\HttpFoundation\RequestStack; /** * This file is part of the EasyAdmin Extension package. */ class ListFormFiltersHelper { /** * @var FormFactory */ private $formFactory; /** * @var RequestStack */ private $requestStack; /** * @var FormInterface */ private $listFiltersForm; /** * @param FormFactory $formFactory */ public function __construct(FormFactory $formFactory, RequestStack $requestStack) { $this->formFactory = $formFactory; $this->requestStack = $requestStack; } public function getListFiltersForm(array $formFilters): FormInterface { if (!isset($this->listFiltersForm)) { $formBuilder = $this->formFactory->createNamedBuilder('form_filters'); foreach ($formFilters as $name => $config) { $formBuilder->add( $name, isset($config['type']) ? $config['type'] : null, array_merge( array('required' => false), isset($config['type_options']) ? $config['type_options'] : [] ) ); } $this->listFiltersForm = $formBuilder->setMethod('GET')->getForm(); $this->listFiltersForm->handleRequest($this->requestStack->getCurrentRequest()); } return $this->listFiltersForm; } }
<?php declare(strict_types=1); namespace AlterPHP\EasyAdminExtensionBundle\Helper; use Symfony\Component\Form\FormFactory; use Symfony\Component\Form\FormInterface; use Symfony\Component\HttpFoundation\RequestStack; /** * This file is part of the EasyAdmin Extension package. */ class ListFormFiltersHelper { /** * @var FormFactory */ private $formFactory; /** * @var RequestStack */ private $requestStack; /** * @var FormInterface */ private $listFiltersForm; /** * @param FormFactory $formFactory */ public function __construct(FormFactory $formFactory, RequestStack $requestStack) { $this->formFactory = $formFactory; $this->requestStack = $requestStack; } public function getListFiltersForm(array $formFilters): FormInterface { if (!isset($this->listFiltersForm)) { $formBuilder = $this->formFactory->createNamedBuilder('form_filters'); foreach ($formFilters as $name => $config) { $formBuilder->add( $name, isset($config['type']) ? $config['type'] : null, array_merge( array('required' => false), $config['type_options'] ) ); } $this->listFiltersForm = $formBuilder->setMethod('GET')->getForm(); $this->listFiltersForm->handleRequest($this->requestStack->getCurrentRequest()); } return $this->listFiltersForm; } }
Change func_code to __code__ to work with python 3
import inspect from . import fields from .utils import fn_name_to_pretty_description class BaseActions(object): """ Classes that hold a collection of actions to use with the rules engine should inherit from this. """ @classmethod def get_all_actions(cls): methods = inspect.getmembers(cls) return [{'name': m[0], 'description': m[1].description, 'params': m[1].params } for m in methods if getattr(m[1], 'is_rule_action', False)] def rule_action(description=None, params=None): """ Decorator to make a function into a rule action """ def wrapper(func): # Verify field name is valid valid_fields = [getattr(fields, f) for f in dir(fields) \ if f.startswith("FIELD_")] for param_name, field_type in params.items(): if param_name not in func.__code__.co_varnames: raise AssertionError("Unknown parameter name {0} specified for action {1}".format(param_name, func.__name__)) if field_type not in valid_fields: raise AssertionError("Unknown field type {0} specified for"\ " action {1} param {2}".format( field_type, func.__name__, param_name)) func.is_rule_action = True func.description = description \ or fn_name_to_pretty_description(func.__name__) func.params = params return func return wrapper
import inspect from . import fields from .utils import fn_name_to_pretty_description class BaseActions(object): """ Classes that hold a collection of actions to use with the rules engine should inherit from this. """ @classmethod def get_all_actions(cls): methods = inspect.getmembers(cls) return [{'name': m[0], 'description': m[1].description, 'params': m[1].params } for m in methods if getattr(m[1], 'is_rule_action', False)] def rule_action(description=None, params=None): """ Decorator to make a function into a rule action """ def wrapper(func): # Verify field name is valid valid_fields = [getattr(fields, f) for f in dir(fields) \ if f.startswith("FIELD_")] for param_name, field_type in params.items(): if param_name not in func.func_code.co_varnames: raise AssertionError("Unknown parameter name {0} specified for action {1}".format(param_name, func.__name__)) if field_type not in valid_fields: raise AssertionError("Unknown field type {0} specified for"\ " action {1} param {2}".format( field_type, func.__name__, param_name)) func.is_rule_action = True func.description = description \ or fn_name_to_pretty_description(func.__name__) func.params = params return func return wrapper
Update lock should be last
'use strict'; angular.module('repicbro.services') .factory('PostsManager', function ($rootScope, Posts) { var posts = [], current = null, index = 0, latest = '', updating = false; var broadcastCurrentUpdate = function (current) { $rootScope.$broadcast('PostsManager.CurrentUpdate', current); }; var next = function () { console.log('next'); checkSize(); current = posts[++index]; broadcastCurrentUpdate(current); }; var prev = function () { console.log('prev'); current = posts[--index]; broadcastCurrentUpdate(current); }; var checkSize = function () { if (posts.length - index < 50 && !updating) { getPosts(); } }; var getPosts = function () { console.log('Get posts'); updating = true; Posts.get('funny', latest, function (data) { latest = data.data.name; angular.forEach(data.data.children, function (p) { posts.push(p.data); }); current = posts[index]; broadcastCurrentUpdate(current); updating = false; }); }; getPosts(); return { posts: posts, current: current, next: next, prev: prev }; });
'use strict'; angular.module('repicbro.services') .factory('PostsManager', function ($rootScope, Posts) { var posts = [], current = null, index = 0, latest = '', updating = false; var broadcastCurrentUpdate = function (current) { $rootScope.$broadcast('PostsManager.CurrentUpdate', current); }; var next = function () { console.log('next'); checkSize(); current = posts[++index]; broadcastCurrentUpdate(current); }; var prev = function () { console.log('prev'); current = posts[--index]; broadcastCurrentUpdate(current); }; var checkSize = function () { if (posts.length - index < 50 && !updating) { getPosts(); } }; var getPosts = function () { console.log('Get posts'); updating = true; Posts.get('funny', latest, function (data) { latest = data.data.name; angular.forEach(data.data.children, function (p) { posts.push(p.data); }); current = posts[index]; updating = false; broadcastCurrentUpdate(current); }); }; getPosts(); return { posts: posts, current: current, next: next, prev: prev }; });
Add additional check for count
<?php /* * This file is part of Mannequin. * * (c) 2017 Last Call Media, Rob Bayliss <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace LastCall\Mannequin\Drupal\Drupal; use Drupal\Core\Template\TwigTransTokenParser; use Twig\Node\Expression\Binary\GreaterBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Node\IfNode; use Twig\Node\Node; use Twig\Token; /** * Parser to nullify trans tokens. */ class MannequinDrupalTransTokenParser extends TwigTransTokenParser { public function parse(Token $token) { $node = parent::parse($token); $lineno = $node->getTemplateLine(); // Convert plural into a simple if/else statement. if ($node->hasNode('plural') && $node->hasNode('count')) { return new IfNode( new Node([ new GreaterBinary( $node->getNode('count'), new ConstantExpression(1, $lineno), $lineno ), $node->getNode('plural') ] ), $node->getNode('body'), $lineno ); } return $node->getNode('body'); } }
<?php /* * This file is part of Mannequin. * * (c) 2017 Last Call Media, Rob Bayliss <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace LastCall\Mannequin\Drupal\Drupal; use Drupal\Core\Template\TwigTransTokenParser; use Twig\Node\Expression\Binary\GreaterBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Node\IfNode; use Twig\Node\Node; use Twig\Token; /** * Parser to nullify trans tokens. */ class MannequinDrupalTransTokenParser extends TwigTransTokenParser { public function parse(Token $token) { $node = parent::parse($token); $lineno = $node->getTemplateLine(); // Convert plural into a simple if/else statement. if ($node->hasNode('plural')) { return new IfNode( new Node([ new GreaterBinary( $node->getNode('count'), new ConstantExpression(1, $lineno), $lineno ), $node->getNode('plural') ] ), $node->getNode('body'), $lineno ); } return $node->getNode('body'); } }
Use division_id in place of bounary_id
import os import logging import unicodecsv from billy.core import settings, db from billy.bin.commands import BaseCommand logger = logging.getLogger('billy') class LoadDistricts(BaseCommand): name = 'loaddistricts' help = 'Load in the Open States districts' def add_args(self): self.add_argument('path', metavar='PATH', type=str, help='path to the manual data') def handle(self, args): path = args.path for file_ in os.listdir(path): if not file_.endswith(".csv"): continue abbr, _ = file_.split(".csv") self.load_districts(abbr, os.path.join(path, file_)) def load_districts(self, abbr, dist_filename): if os.path.exists(dist_filename): db.districts.remove({'abbr': abbr}) with open(dist_filename, 'r') as fd: dist_csv = unicodecsv.DictReader(fd) for dist in dist_csv: dist['_id'] = '%(abbr)s-%(chamber)s-%(name)s' % dist # dist['boundary_id'] = dist['boundary_id'] % dist dist['boundary_id'] = dist['division_id'] # Stop-gap dist['num_seats'] = int(dist['num_seats']) db.districts.save(dist, safe=True) else: logging.getLogger('billy').warning("%s not found, continuing without " "districts" % dist_filename)
import os import logging import unicodecsv from billy.core import settings, db from billy.bin.commands import BaseCommand logger = logging.getLogger('billy') class LoadDistricts(BaseCommand): name = 'loaddistricts' help = 'Load in the Open States districts' def add_args(self): self.add_argument('path', metavar='PATH', type=str, help='path to the manual data') def handle(self, args): path = args.path for file_ in os.listdir(path): if not file_.endswith(".csv"): continue abbr, _ = file_.split(".csv") self.load_districts(abbr, os.path.join(path, file_)) def load_districts(self, abbr, dist_filename): if os.path.exists(dist_filename): db.districts.remove({'abbr': abbr}) with open(dist_filename, 'r') as fd: dist_csv = unicodecsv.DictReader(fd) for dist in dist_csv: dist['_id'] = '%(abbr)s-%(chamber)s-%(name)s' % dist dist['boundary_id'] = dist['boundary_id'] % dist dist['num_seats'] = int(dist['num_seats']) db.districts.save(dist, safe=True) else: logging.getLogger('billy').warning("%s not found, continuing without " "districts" % dist_filename)
Allow the callback parameter name to be changed in the constructor. Signed-off-by: Jason Lewis <[email protected]>
<?php namespace Dingo\Api\Http\ResponseFormat; class JsonpResponseFormat extends JsonResponseFormat { /** * Name of JSONP callback paramater. * * @var string */ protected $callbackName = 'callback'; /** * Create a new JSONP response formatter instance. * * @param string $callbackName * @return void */ public function __construct($callbackName = 'callback') { $this->callbackName = $callbackName; } /** * Determine if a callback is valid. * * @return bool */ protected function hasValidCallback() { return $this->request->query->has($this->callbackName); } /** * Get the callback from the query string. * * @return string */ protected function getCallback() { return $this->request->query->get($this->callbackName); } /** * Get the response content type. * * @return string */ public function getContentType() { if ($this->hasValidCallback()) { return 'application/javascript'; } return parent::getContentType(); } /** * Encode the content to its JSON representation. * * @param string $content * @return string */ protected function encode($content) { if ($this->hasValidCallback()) { return sprintf('%s(%s);', $this->getCallback(), json_encode($content)); } return parent::encode($content); } }
<?php namespace Dingo\Api\Http\ResponseFormat; class JsonpResponseFormat extends JsonResponseFormat { /** * Name of JSONP callback paramater. * * @var string */ protected $callbackName = 'callback'; /** * Determine if a callback is valid. * * @return bool */ protected function hasValidCallback() { return $this->request->query->has($this->callbackName); } /** * Get the callback from the query string. * * @return string */ protected function getCallback() { return $this->request->query->get($this->callbackName); } /** * Get the response content type. * * @return string */ public function getContentType() { if ($this->hasValidCallback()) { return 'application/javascript'; } return parent::getContentType(); } /** * Encode the content to its JSON representation. * * @param string $content * @return string */ protected function encode($content) { if ($this->hasValidCallback()) { return sprintf('%s(%s);', $this->getCallback(), json_encode($content)); } return parent::encode($content); } }
Allow canary build to fail for now (embroider compatibility issue)
'use strict'; const getChannelURL = require('ember-source-channel-url'); module.exports = async function () { return { useYarn: true, scenarios: [ { name: 'ember-release', npm: { devDependencies: { 'ember-source': await getChannelURL('release'), }, }, }, { name: 'ember-beta', npm: { devDependencies: { 'ember-source': await getChannelURL('beta'), }, }, }, { name: 'ember-canary', allowedToFail: true, npm: { devDependencies: { 'ember-source': await getChannelURL('canary'), }, }, }, // The default `.travis.yml` runs this scenario via `npm test`, // not via `ember try`. It's still included here so that running // `ember try:each` manually or from a customized CI config will run it // along with all the other scenarios. { name: 'ember-default', npm: { devDependencies: {}, }, }, { name: 'ember-default-with-jquery', env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true, }), }, npm: { devDependencies: { '@ember/jquery': '^0.5.1', }, }, }, ], }; };
'use strict'; const getChannelURL = require('ember-source-channel-url'); module.exports = async function () { return { useYarn: true, scenarios: [ { name: 'ember-release', npm: { devDependencies: { 'ember-source': await getChannelURL('release'), }, }, }, { name: 'ember-beta', npm: { devDependencies: { 'ember-source': await getChannelURL('beta'), }, }, }, { name: 'ember-canary', npm: { devDependencies: { 'ember-source': await getChannelURL('canary'), }, }, }, // The default `.travis.yml` runs this scenario via `npm test`, // not via `ember try`. It's still included here so that running // `ember try:each` manually or from a customized CI config will run it // along with all the other scenarios. { name: 'ember-default', npm: { devDependencies: {}, }, }, { name: 'ember-default-with-jquery', env: { EMBER_OPTIONAL_FEATURES: JSON.stringify({ 'jquery-integration': true, }), }, npm: { devDependencies: { '@ember/jquery': '^0.5.1', }, }, }, ], }; };
Add hold all function to dicebag
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") i = 0 while (i<int(lst_notation[0])): die1 = Die(int(lst_notation[1])) self.dice.append(die1) i = i +1 def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) def hold_all(self, held): for obj in self.dice: obj.change_held(held) def get_dice_roll(self): return self.dice_roll
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") i = 0 while (i<int(lst_notation[0])): die1 = Die(int(lst_notation[1])) self.dice.append(die1) i = i +1 def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) def get_dice_roll(self): return self.dice_roll
Fix Sauce Labs username and key
var util = require('util'); var request = require('superagent'); module.exports = { local: { dontReportSauceLabs: true }, reporter: function(results, done) { var passed = results.failed === 0 && results.errors === 0; console.log('Final result: "{ passed: ' + passed + ' }"'); console.log(this); console.log(results); if (!this.dontReportSauceLabs) { var userName = this.test_settings.username; var accessKey = this.test_settings.access_key; var baseUrl = 'https://saucelabs.com/rest/v1/'; console.log('Sending final result to Saucelabs...'); if (userName && accessKey) { request .put(baseUrl + userName + '/jobs/' + this.client.sessionId) .send({ passed: true }) .auth(userName, accessKey) .end(function(error, res){ if (error) { console.log('ERROR sending verdict'); console.log(error); } else { console.log('Verdict sent to Sauce Labs, response:' + res.res.statusMessage); } done(); }); } else { console.log('Username or access key missing, username: ' + userName); done(); } } else { console.log('Local testing. Not notifying Saucelabs.'); } } };
var util = require('util'); var request = require('superagent'); module.exports = { local: { dontReportSauceLabs: true }, reporter: function(results, done) { var passed = results.failed === 0 && results.errors === 0; console.log('Final result: "{ passed: ' + passed + ' }"'); if (!this.dontReportSauceLabs) { var userName = this.client.options.username; var accessKey = this.client.options.accessKey; var baseUrl = 'https://saucelabs.com/rest/v1/'; console.log('Sending final result to Saucelabs...'); if (userName && accessKey) { request .put(baseUrl + userName + '/jobs/' + this.client.sessionId) .send({ passed: true }) .auth(userName, accessKey) .end(function(error, res){ if (error) { console.log('ERROR sending verdict'); console.log(error); } else { console.log('Verdict sent to Sauce Labs, response:' + res.res.statusMessage); } done(); }); } else { console.log('Username or access key missing, username: ' + userName); done(); } } else { console.log('Local testing. Not notifying Saucelabs.'); } } };
Update installer autocreate for games with no icon
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'].startswith('Game Works'): appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'] == 'Game Works': appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
Change docstrings and function names.
#!/usr/bin/env python # -*- coding: utf-8 -*- # (C) 2015 Jean Nassar # Released under BSD version 4 """ Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz. """ import rospy from sensor_msgs.msg import Image class ImageFeature(object): """ A ROS image Publisher/Subscriber. """ def __init__(self): self.image_subscriber = rospy.Subscriber("/ardrone/image_raw", Image, self.image_callback, queue_size=1) self.image_pub = rospy.Publisher("/output/slow_image_raw", Image, queue_size=1) rospy.logdebug("Subscribed to /ardrone/image_raw") self.count = 0 def frame_callback(self, frame): """ Callback function of subscribed topic. """ # Publish every fifteenth frame if not self.count % 15: self.image_pub.publish(frame) self.count += 1 def main(): """Initialize and cleanup ROS node.""" rospy.init_node("framerate_reducer", anonymous=True) ImageFeature() rospy.loginfo("Reducing framerate") rospy.spin() if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # (C) 2015 Jean Nassar # Released under BSD version 4 """ Reduce /ardrone_camera framerate to 2 Hz. """ import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError class ImageFeature(object): """ A ROS image Publisher/Subscriber. """ def __init__(self): self.subscriber = rospy.Subscriber("/ardrone/image_raw", Image, self.callback, queue_size=1) self.image_pub = rospy.Publisher("/output/slow_image_raw", Image, queue_size=1) self.bridge = CvBridge() rospy.logdebug("Subscribed to /ardrone_camera/image_raw.") self.count = 0 def callback(self, ros_data): """ Callback function of subscribed topic. """ # Publish every fifteenth frame if not self.count % 15: try: image = self.bridge.imgmsg_to_cv2(ros_data, "bgr8") self.image_pub.publish(self.bridge.cv2_to_imgmsg(image, "bgr8")) except CvBridgeError as e: rospy.logerr(e) self.count += 1 def main(): """Initialize and cleanup ROS node.""" rospy.init_node("image_feature", anonymous=True) ImageFeature() rospy.loginfo("Starting feature detection.") rospy.spin() if __name__ == "__main__": main()
Call the callback if the credential isn't found.
const fs = require('fs'); const passport = require('passport'); const JWTStrategy = require('passport-jwt').Strategy; const extractors = require('./extractors'); const services = require('../../services'); module.exports = function (params) { const secretOrKey = params.secretOrPubKeyFile ? fs.readFileSync(params.secretOrPubKeyFile) : params.secretOrPubKey; const extractor = extractors[params.jwtExtractor](params.jwtExtractorField); passport.use(new JWTStrategy({ secretOrKey, jwtFromRequest: extractor, audience: params.audience, issuer: params.issuer }, (jwtPayload, done) => { if (!jwtPayload) { return done(null, false); } if (!params.checkCredentialExistence) { return done(null, { id: 'anonymous' }); } if (!jwtPayload.sub) { return done(null, false); } services.credential.getCredential(jwtPayload.sub, 'jwt') .then(credential => { if (!credential || !credential.isActive) { return done(null, false); } return credential.consumerId; }) .then(services.auth.validateConsumer) .then((consumer) => { if (!consumer) { return done(null, false); } return done(null, consumer); }).catch(done); })); return function (req, res, next) { params.session = false; passport.authenticate('jwt', params, params.getCommonAuthCallback(req, res, next))(req, res, next); }; };
const fs = require('fs'); const passport = require('passport'); const JWTStrategy = require('passport-jwt').Strategy; const extractors = require('./extractors'); const services = require('../../services'); module.exports = function (params) { const secretOrKey = params.secretOrPubKeyFile ? fs.readFileSync(params.secretOrPubKeyFile) : params.secretOrPubKey; const extractor = extractors[params.jwtExtractor](params.jwtExtractorField); passport.use(new JWTStrategy({ secretOrKey, jwtFromRequest: extractor, audience: params.audience, issuer: params.issuer }, (jwtPayload, done) => { if (!jwtPayload) { return done(null, false); } if (!params.checkCredentialExistence) { return done(null, { id: 'anonymous' }); } if (!jwtPayload.sub) { return done(null, false); } services.credential.getCredential(jwtPayload.sub, 'jwt') .then(credential => { if (!credential || !credential.isActive) { return false; } return credential.consumerId; }) .then(services.auth.validateConsumer) .then((consumer) => { if (!consumer) { return done(null, false); } return done(null, consumer); }).catch(done); })); return function (req, res, next) { params.session = false; passport.authenticate('jwt', params, params.getCommonAuthCallback(req, res, next))(req, res, next); }; };
Fix first functional test class
<?php namespace Bolt\Extension\Leskis\BoltSendEmailForNewContent\Tests; use Bolt\Tests\BoltUnitTest; use Bolt\Extension\Leskis\BoltSendEmailForNewContent\BoltSendEmailForNewContentExtension; /** * BoltSendEmailForNewContent testing class. * * @author Nicolas Béhier-Dévigne */ class ExtensionTest extends BoltUnitTest { /** * Ensure that the BoltSendEmailForNewContent extension loads correctly. */ public function testExtensionBasics() { $app = $this->getApp(false); $extension = new BoltSendEmailForNewContentExtension($app); $name = $extension->getName(); $this->assertSame($name, 'BoltSendEmailForNewContent'); $this->assertInstanceOf('\Bolt\Extension\ExtensionInterface', $extension); } public function testExtensionComposerJson() { $composerJson = json_decode(file_get_contents(dirname(__DIR__) . '/composer.json'), true); // Check that the 'bolt-class' key correctly matches an existing class $this->assertArrayHasKey('bolt-class', $composerJson['extra']); $this->assertTrue(class_exists($composerJson['extra']['bolt-class'])); // Check that the 'bolt-assets' key points to the correct directory $this->assertArrayHasKey('bolt-assets', $composerJson['extra']); $this->assertSame('web', $composerJson['extra']['bolt-assets']); } }
<?php namespace Bolt\Extension\Leskis\BoltFieldGeojson\Tests; use Bolt\Tests\BoltUnitTest; use Bolt\Extension\Leskis\BoltFieldGeojson\BoltFieldGeojsonExtension; /** * BoltFieldGeojson testing class. * * @author Nicolas Béhier-Dévigne */ class ExtensionTest extends BoltUnitTest { /** * Ensure that the BoltSendEmailForNewContent extension loads correctly. */ public function testExtensionBasics() { $app = $this->getApp(false); $extension = new BoltSendEmailForNewContentExtension($app); $name = $extension->getName(); $this->assertSame($name, 'BoltSendEmailForNewContent'); $this->assertInstanceOf('\Bolt\Extension\ExtensionInterface', $extension); } public function testExtensionComposerJson() { $composerJson = json_decode(file_get_contents(dirname(__DIR__) . '/composer.json'), true); // Check that the 'bolt-class' key correctly matches an existing class $this->assertArrayHasKey('bolt-class', $composerJson['extra']); $this->assertTrue(class_exists($composerJson['extra']['bolt-class'])); // Check that the 'bolt-assets' key points to the correct directory $this->assertArrayHasKey('bolt-assets', $composerJson['extra']); $this->assertSame('web', $composerJson['extra']['bolt-assets']); } }
Fix copy/pasta mistake and use ID from configuration yaml
<?php namespace Grav\Plugin; use Grav\Common\Plugin; class Pingdom_RUMPlugin extends Plugin { /** * @return array */ public static function getSubscribedEvents() { return [ 'onAssetsInitialized' => ['onAssetsInitialized', 0] ]; } /** * Add GoSquared JS in assets initialisation */ public function onAssetsInitialized() { /** * Ok, we're ready to go */ $prumid = trim($this->config->get('plugins.pingdom_rum.prumid')); if ($prumid) { $gsjs = <<<PingdomRUMJS var _prum = [['id', '$prumid'], ['mark', 'firstbyte', (new Date()).getTime()]]; (function() { var s = document.getElementsByTagName('script')[0] , p = document.createElement('script'); p.async = 'async'; p.src = '//rum-static.pingdom.net/prum.min.js'; s.parentNode.insertBefore(p, s); })(); PingdomRUMJS; $this->grav['assets']->addInlineJs($gsjs); } } }
<?php namespace Grav\Plugin; use Grav\Common\Plugin; class Pingdom_RUMPlugin extends Plugin { /** * @return array */ public static function getSubscribedEvents() { return [ 'onAssetsInitialized' => ['onAssetsInitialized', 0] ]; } /** * Add GoSquared JS in assets initialisation */ public function onAssetsInitialized() { /** * Ok, we're ready to go */ $prumid = trim($this->config->get('plugins.pingdom_rum.prumid')); if ($prumid) { $gsjs = <<<PingdomRUMJS var _prum = [['id', '5519be67abe53d310131abbc'], ['mark', 'firstbyte', (new Date()).getTime()]]; (function() { var s = document.getElementsByTagName('script')[0] , p = document.createElement('script'); p.async = 'async'; p.src = '//rum-static.pingdom.net/prum.min.js'; s.parentNode.insertBefore(p, s); })(); PingdomRUMJS; $this->grav['assets']->addInlineJs($gsjs); } } }
Fix misconfiguration in static root path computation
import os AUTOCLAVE_APP_NAME = "autoclave" AUTOCLAVE_USER_NAME = AUTOCLAVE_APP_NAME AUTOCLAVE_DEPLOY_ROOT = os.path.join("/opt", AUTOCLAVE_APP_NAME) AUTOCLAVE_DEPLOY_SRC_ROOT = os.path.join(AUTOCLAVE_DEPLOY_ROOT, "src") AUTOCLAVE_API_ROOT = "/api" AUTOCLAVE_CELERY_WORKER_SERVICE_NAME = AUTOCLAVE_APP_NAME + "-celery" AUTOCLAVE_DATA_ROOT = "/data" AUTOCLAVE_REDIS_DB_PATH = os.path.join(AUTOCLAVE_DATA_ROOT, "redis") AUTOCLAVE_MONGO_DB_PATH = os.path.join(AUTOCLAVE_DATA_ROOT, "mongo") AUTOCLAVE_APP_TCP_PORT = 5353 AUTOCLAVE_DATABASE_HOST = "127.0.0.1" AUTOCLAVE_DEPLOYMENT_FRONTEND_TCP_PORT = 80 AUTOCLAVE_STATIC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "static")) AUTOCLAVE_TESTING_FRONTEND_TCP_PORT = 8080
import os AUTOCLAVE_APP_NAME = "autoclave" AUTOCLAVE_USER_NAME = AUTOCLAVE_APP_NAME AUTOCLAVE_DEPLOY_ROOT = os.path.join("/opt", AUTOCLAVE_APP_NAME) AUTOCLAVE_DEPLOY_SRC_ROOT = os.path.join(AUTOCLAVE_DEPLOY_ROOT, "src") AUTOCLAVE_API_ROOT = "/api" AUTOCLAVE_CELERY_WORKER_SERVICE_NAME = AUTOCLAVE_APP_NAME + "-celery" AUTOCLAVE_DATA_ROOT = "/data" AUTOCLAVE_REDIS_DB_PATH = os.path.join(AUTOCLAVE_DATA_ROOT, "redis") AUTOCLAVE_MONGO_DB_PATH = os.path.join(AUTOCLAVE_DATA_ROOT, "mongo") AUTOCLAVE_APP_TCP_PORT = 5353 AUTOCLAVE_DATABASE_HOST = "127.0.0.1" AUTOCLAVE_DEPLOYMENT_FRONTEND_TCP_PORT = 80 AUTOCLAVE_STATIC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "static")) AUTOCLAVE_TESTING_FRONTEND_TCP_PORT = 8080
Fix typo in field name
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5): user_tokens = tweet.user.social_auth.all()[0].tokens api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=user_tokens['oauth_token'], access_token_secret=user_tokens['oauth_token_secret'],) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trails += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
Add extra condition to show "user joined" notification If you open the page and without clicking anything you go to other app, then you won't get the notification => I don't know how to solve this. If you open the page and without clicking anything you go to other tab, then you won't get the notification => It should be fixed with this change because in that case visibilityState === 'hidden'. (Disclaimer: Didn't test it inside opentok-meet but in my own app)
const push = require('push.js'); angular.module('opentok-meet').factory('Push', () => push); angular.module('opentok-meet').factory('NotificationService', ['$window', 'OTSession', 'Push', function NotificationService($window, OTSession, Push) { let focused = true; $window.addEventListener('blur', () => { focused = false; }); $window.addEventListener('focus', () => { focused = true; }); const notifyOnConnectionCreated = () => { if (!OTSession.session) { OTSession.on('init', notifyOnConnectionCreated); } else { OTSession.session.on('connectionCreated', (event) => { const visible = $window.document.visibilityState === 'visible'; if ((!focused || !visible) && event.connection.connectionId !== OTSession.session.connection.connectionId) { Push.create('New Participant', { body: 'Someone joined your meeting', icon: '/icon.png', tag: 'new-participant', timeout: 5000, onClick() { $window.focus(); this.close(); }, }); } }); } }; return { init() { if (Push.Permission.has()) { notifyOnConnectionCreated(); } else { try { Push.Permission.request(() => { notifyOnConnectionCreated(); }, (err) => { console.warn(err); }); } catch (err) { console.warn(err); } } }, }; }, ]);
const push = require('push.js'); angular.module('opentok-meet').factory('Push', () => push); angular.module('opentok-meet').factory('NotificationService', ['$window', 'OTSession', 'Push', function NotificationService($window, OTSession, Push) { let focused = true; $window.addEventListener('blur', () => { focused = false; }); $window.addEventListener('focus', () => { focused = true; }); const notifyOnConnectionCreated = () => { if (!OTSession.session) { OTSession.on('init', notifyOnConnectionCreated); } else { OTSession.session.on('connectionCreated', (event) => { if (!focused && event.connection.connectionId !== OTSession.session.connection.connectionId) { Push.create('New Participant', { body: 'Someone joined your meeting', icon: '/icon.png', tag: 'new-participant', timeout: 5000, onClick() { $window.focus(); this.close(); }, }); } }); } }; return { init() { if (Push.Permission.has()) { notifyOnConnectionCreated(); } else { try { Push.Permission.request(() => { notifyOnConnectionCreated(); }, (err) => { console.warn(err); }); } catch (err) { console.warn(err); } } }, }; }, ]);
Add extend_list method to OratioIgnoreParser To make oratioignoreparser.py easily testable using unit tests.
import os import re class OratioIgnoreParser(): def __init__(self): self.ignored_paths = ["oratiomodule.tar.gz"] def load(self, oratio_ignore_path): with open(oratio_ignore_path, "r") as f: self.ignored_paths.extend([line.strip() for line in f]) def extend_list(self, ignored_paths_list): self.ignored_paths.extend(ignored_paths_list) def should_be_ignored(self, filepath): for ig in self.ignored_paths: compiled_regex = re.compile( '^' + re.escape(ig).replace('\\*', '.*') + '$' ) if compiled_regex.search(filepath) or \ compiled_regex.search(filepath.split('/')[-1]): return True return False def list_files(self, directory): filepaths = [] ignored_files = [] for root, dirs, files in os.walk("."): for name in files: relative_path = os.path.join(root, name) if relative_path.startswith("./"): relative_path = relative_path[2:] if not self.should_be_ignored(relative_path): filepaths.append(relative_path) else: ignored_files.append(relative_path) return filepaths, ignored_files
import os import re class OratioIgnoreParser(): def __init__(self): self.ignored_paths = ["oratiomodule.tar.gz"] def load(self, oratio_ignore_path): with open(oratio_ignore_path, "r") as f: self.ignored_paths.extend([line.strip() for line in f]) def should_be_ignored(self, filepath): for ig in self.ignored_paths: compiled_regex = re.compile( '^' + re.escape(ig).replace('\\*', '.*') + '$' ) if compiled_regex.search(filepath) or \ compiled_regex.search(filepath.split('/')[-1]): return True return False def list_files(self, directory): filepaths = [] ignored_files = [] for root, dirs, files in os.walk("."): for name in files: relative_path = os.path.join(root, name) if relative_path.startswith("./"): relative_path = relative_path[2:] if not self.should_be_ignored(relative_path): filepaths.append(relative_path) else: ignored_files.append(relative_path) return filepaths, ignored_files
ADD auto submit after select search
/** * Created by sylva on 30/05/2017. */ $(document).ready(function () { $('#lastFMSearch').autocomplete({ source: function( request, response ) { $.ajax({ url: "https://ws.audioscrobbler.com/2.0/?method=artist.search&artist="+$('#lastFMSearch').val()+"&api_key=f6734ae2b9887488059fc9507f2c6c60&format=json&limit=10", dataType: "json", success: function(data) { var results = []; for(var cptArtist = 0; cptArtist < data.results.artistmatches.artist.length; cptArtist++) { results.push({ label: data.results.artistmatches.artist[cptArtist].name, icon: data.results.artistmatches.artist[cptArtist].image[1]["#text"] }) } response(results); } }); }, select: function( event, ui ) { $("#lastFMSearch").parent().submit(); }, minLength: 2 } ) .autocomplete( "instance" )._renderItem = function( ul, item ) { return $( "<li>" ) .append( "<div><img src='"+item.icon+"'>" + item.label + "</div>" ) .appendTo( ul ); }; });
/** * Created by sylva on 30/05/2017. */ $(document).ready(function () { $('#lastFMSearch').autocomplete({ source: function( request, response ) { $.ajax({ url: "https://ws.audioscrobbler.com/2.0/?method=artist.search&artist="+$('#lastFMSearch').val()+"&api_key=f6734ae2b9887488059fc9507f2c6c60&format=json&limit=10", dataType: "json", success: function(data) { var results = []; for(var cptArtist = 0; cptArtist < data.results.artistmatches.artist.length; cptArtist++) { results.push({ label: data.results.artistmatches.artist[cptArtist].name, icon: data.results.artistmatches.artist[cptArtist].image[1]["#text"] }) } response(results); } }); }, minLength: 2 } ) .autocomplete( "instance" )._renderItem = function( ul, item ) { return $( "<li>" ) .append( "<div><img src='"+item.icon+"'>" + item.label + "</div>" ) .appendTo( ul ); }; });
Add support for monitor deletion
# # Copyright (c) 2014 NSONE, Inc. # # License under The MIT License (MIT). See LICENSE in project root. # from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) def delete(self, jobid, callback=None, errback=None): return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback)
# # Copyright (c) 2014 NSONE, Inc. # # License under The MIT License (MIT). See LICENSE in project root. # from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback)
Use context.unload instead of controller.unload
var TextInput, TextArea (function() { var factory = function(tag) { return { controller: function(args) { var oldValue, element, composing, setComposing = function() { composing = true }, resetComposing = function() { composing = false }, onInput = function(e) { if (!composing && e.target.value !== oldValue) { if (args && args.ontextchange) { args.ontextchange({ currentTarget: element, target: element }) } oldValue = e.target.value } } return { config: function(elem, isInitialized, context) { if (!isInitialized) { element = elem oldValue = element.value element.addEventListener('compositionstart', setComposing) element.addEventListener('compositionend', resetComposing) element.addEventListener('input', onInput) context.onunload = function() { element.removeEventListener('compositionstart', setComposing) element.removeEventListener('compositionend', resetComposing) element.removeEventListener('input', onInput) } } } } }, view: function(ctrl, args) { var myargs = {} for (key in args) myargs[key] = args[key] myargs.config = ctrl.config return m(tag, myargs) } } } TextInput = factory('input') TextArea = factory('textarea') })()
var TextInput, TextArea (function() { var factory = function(tag) { return { controller: function(args) { var oldValue, element, composing, setComposing = function() { composing = true }, resetComposing = function() { composing = false }, onInput = function(e) { if (!composing && e.target.value !== oldValue) { if (args && args.ontextchange) { args.ontextchange({ currentTarget: element, target: element }) } oldValue = e.target.value } } return { config: function(elem, isInitialized) { if (!isInitialized) { element = elem oldValue = element.value element.addEventListener('compositionstart', setComposing) element.addEventListener('compositionend', resetComposing) element.addEventListener('input', onInput) } }, onunload: function() { element.removeEventListener('compositionstart', setComposing) element.removeEventListener('compositionend', resetComposing) element.removeEventListener('input', onInput) }, oninput: onInput } }, view: function(ctrl, args) { var myargs = {} for (key in args) myargs[key] = args[key] myargs.config = ctrl.config return m(tag, myargs) } } } TextInput = factory('input') TextArea = factory('textarea') })()
Exit with 1 if there's a difference
from __future__ import print_function import argparse import sys from . import diff RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() out = format_output(first, second) print(out, end='') if out: sys.exit(1)
from __future__ import print_function from . import diff import argparse RED = '\033[1;31m' GREEN = '\033[1;32m' END = '\033[0m' def format_option(opt): """Return a formatted option in the form name=value.""" return '{}={}\n'.format(opt.option, opt.value) def format_output(first, second, color=True): """Return a string showing the differences between two ini strings.""" diffs = diff(first, second) sections = set() out = '' for d in diffs: if d.first.section not in sections: out += '[{}]\n'.format(d.first.section) sections.add(d.first.section) if d.first.value is not None: if color: out += RED out += '-' + format_option(d.first) if color: out += END if d.second.value is not None: if color: out += GREEN out += '+' + format_option(d.second) if color: out += END return out def main(): """Run the main CLI.""" parser = argparse.ArgumentParser() parser.add_argument('first', type=argparse.FileType('r')) parser.add_argument('second', type=argparse.FileType('r')) args = parser.parse_args() first = args.first.read() second = args.second.read() print(format_output(first, second), end='')
Change value to c to make figuring out its HTML less confusing.
$(document).ready(function() { var data = {}; $('#testform').render({ ifaces: ['viewform'], form: { widgets: [ { ifaces: ['composite_field'], name: 'composite', widgets: [ { ifaces: ['composite_field'], name: 'composite', widgets: [ { ifaces: ['textline_field'], name: 'a', title: 'A' }, { ifaces: ['integer_field'], name: 'b', title: 'B' } ] }, { ifaces: ['integer_field'], name: 'c', title: 'C' } ] } ] } }); });
$(document).ready(function() { var data = {}; $('#testform').render({ ifaces: ['viewform'], form: { widgets: [ { ifaces: ['composite_field'], name: 'composite', widgets: [ { ifaces: ['composite_field'], name: 'composite', widgets: [ { ifaces: ['textline_field'], name: 'a', title: 'A' }, { ifaces: ['integer_field'], name: 'b', title: 'B' } ] }, { ifaces: ['integer_field'], name: 'b', title: 'B' } ] } ] } }); });
Fix but with reset always triggering
let videoImage = document.getElementById('video_image'); videoImage.src = `http://${document.domain}:8080/?action=stream`; let cameraJoystick = { zone: videoImage, color: 'red' }; let cameraJoystickManager = nipplejs.create(cameraJoystick); const clickTimeout = 500; var lastStartClick = Date.now(); cameraJoystickManager.on('added', function (evt, nipple) { nipple.on('move', function (evt, arg) { var json = JSON.stringify({ joystickType: 'camera', angle: arg.angle.radian, MessageType: 'movement', distance: arg.distance }); serverSocket.send(json); }); nipple.on('start', function () { if (Date.now() - lastStartClick < clickTimeout) { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'reset' }); serverSocket.send(json); } else { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'start' }); serverSocket.send(json); } lastStartClick = Date.now(); }); nipple.on('end', function () { var json = JSON.stringify({ joystickType: 'camera', MessageType: 'stop' }); serverSocket.send(json); }); });
let videoImage = document.getElementById('video_image'); videoImage.src = `http://${document.domain}:8080/?action=stream`; let cameraJoystick = { zone: videoImage, color: 'red' }; let cameraJoystickManager = nipplejs.create(cameraJoystick); const clickTimeout = 500; var lastStartClick = Date.now(); cameraJoystickManager.on('added', function (evt, nipple) { nipple.on('move', function (evt, arg) { var json = JSON.stringify({ joystickType: 'camera', angle: arg.angle.radian, MessageType: 'movement', distance: arg.distance }); serverSocket.send(json); }); nipple.on('start', function () { if (lastStartClick - Date.now() < clickTimeout) { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'reset' }); serverSocket.send(json); } else { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'start' }); serverSocket.send(json); } lastStartClick = Date.now(); }); nipple.on('end', function () { var json = JSON.stringify({ joystickType: 'camera', MessageType: 'stop' }); serverSocket.send(json); }); });
Remove debug printing from test case
import os from xml.etree import ElementTree from utils import with_app, pretty_print_xml #============================================================================= # Tests @with_app(buildername="xml", srcdir="basics") def test_basics(app, status, warning): app.build() tree = ElementTree.parse(app.outdir / "index.xml") # Verify that 2 traceables are found. assert len(tree.findall(".//target")) == 2 assert len(tree.findall(".//index")) == 2 assert len(tree.findall(".//admonition")) == 2 assert len(tree.findall(".//admonition")) == 2 # Verify that child-parent relationship are made. assert len(tree.findall(".//field_list")) == 2 parent_fields, child_fields = tree.findall(".//field_list") for field in parent_fields: field_name = field.findall("./field_name")[0] if field_name.text == "child": break else: assert False, "Parent's child field not found!" for field in child_fields: field_name = field.findall("./field_name")[0] if field_name.text == "parent": break else: assert False, "Child's parent field not found!" # Verify that a warning is emitted for unknown traceable tag. assert (warning.getvalue().find( "WARNING: Traceables: no traceable with tag" " 'NONEXISTENT' found!") > 0)
import os from xml.etree import ElementTree from utils import with_app, pretty_print_xml #============================================================================= # Tests @with_app(buildername="xml", srcdir="basics") def test_basics(app, status, warning): app.build() tree = ElementTree.parse(app.outdir / "index.xml") pretty_print_xml(tree.getroot()) # Verify that 2 traceables are found. assert len(tree.findall(".//target")) == 2 assert len(tree.findall(".//index")) == 2 assert len(tree.findall(".//admonition")) == 2 assert len(tree.findall(".//admonition")) == 2 # Verify that child-parent relationship are made. assert len(tree.findall(".//field_list")) == 2 parent_fields, child_fields = tree.findall(".//field_list") for field in parent_fields: field_name = field.findall("./field_name")[0] if field_name.text == "child": break else: assert False, "Parent's child field not found!" for field in child_fields: field_name = field.findall("./field_name")[0] if field_name.text == "parent": break else: assert False, "Child's parent field not found!" # Verify that a warning is emitted for unknown traceable tag. assert (warning.getvalue().find( "WARNING: Traceables: no traceable with tag" " 'NONEXISTENT' found!") > 0)
Remove odata part in the accept - Office365 is not happy
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter\Office365; use GuzzleHttp\Client as Guzzle; use CalendArt\AbstractCalendar, CalendArt\Adapter\AdapterInterface; /** * Office365 Adapter - He knows how to dialog with office 365's calendars ! * * This requires to have an OAuth2 token established with the following scopes : * - Calendar.read * - Calendar.write * * @author Baptiste Clavié <[email protected]> */ class Office365Adapter implements AdapterInterface { /** @param string $token access token delivered by azure's oauth system */ public function __construct($token) { $this->guzzle = new Guzzle(['base_url' => 'https://outlook.office365.com/api/v1.0/me/', 'defaults' => ['exceptions' => false, 'headers' => ['Authorization' => sprintf('Bearer %s', $token), 'Content-Type' => 'application/json', 'Accept' => 'application/json']]]); } /** {@inheritDoc} */ public function getCalendarApi() { } /** {@inheritDoc} */ public function getEventApi() { } }
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter\Office365; use GuzzleHttp\Client as Guzzle; use CalendArt\AbstractCalendar, CalendArt\Adapter\AdapterInterface; /** * Office365 Adapter - He knows how to dialog with office 365's calendars ! * * This requires to have an OAuth2 token established with the following scopes : * - Calendar.read * - Calendar.write * * @author Baptiste Clavié <[email protected]> */ class Office365Adapter implements AdapterInterface { /** @param string $token access token delivered by azure's oauth system */ public function __construct($token) { $this->guzzle = new Guzzle(['base_url' => 'https://outlook.office365.com/api/v1.0/me/', 'defaults' => ['exceptions' => false, 'headers' => ['Authorization' => sprintf('Bearer %s', $token), 'Content-Type' => 'application/json', 'Accept' => 'application/json;odata=verbose']]]); } /** {@inheritDoc} */ public function getCalendarApi() { } /** {@inheritDoc} */ public function getEventApi() { } }
Fix default sidebar search label.
<div id="sidebar"> <div id="leftbar"> <div class="sidebartext"> <ul> <?php if (!dynamic_sidebar("Footer Left")) { ?> <li><ul><?php wp_list_bookmarks(); ?></ul></li> <li> <h2>Meta</h2> <?php wp_meta(); ?> <ul> <li><a href="<?php bloginfo("rss_url"); ?>">RSS feed</a></li> <li><a href="https://github.com/mikemcquaid/NightSkyLine/">Using NightSkyLine theme</a></li> <li><a href="http://wordpress.org" rel="external"> Powered by WordPress </a></li> </ul> </li> <?php } ?> </ul> </div> </div> <div id="rightbar"> <div class="sidebartext"> <ul> <?php if (!dynamic_sidebar("Footer Right")) { ?> <li class="widget_search"> <h2>Search</h2> <?php get_search_form(); ?> </li> <?php } ?> </ul> </div> </div> <div id="clearbar"></div> </div>
<div id="sidebar"> <div id="leftbar"> <div class="sidebartext"> <ul> <?php if (!dynamic_sidebar("Footer Left")) { ?> <li><ul><?php wp_list_bookmarks(); ?></ul></li> <li> <h2>Meta</h2> <?php wp_meta(); ?> <ul> <li><a href="<?php bloginfo("rss_url"); ?>">RSS feed</a></li> <li><a href="https://github.com/mikemcquaid/NightSkyLine/">Using NightSkyLine theme</a></li> <li><a href="http://wordpress.org" rel="external"> Powered by WordPress </a></li> </ul> </li> <?php } ?> </ul> </div> </div> <div id="rightbar"> <div class="sidebartext"> <ul> <?php if (!dynamic_sidebar("Footer Right")) { ?> <li> <h2>Search</h2> <?php get_search_form(); ?> </li> <?php } ?> </ul> </div> </div> <div id="clearbar"></div> </div>
Fix Route Declaration of Settings
<?php namespace LaravelFlare\Settings; use Illuminate\Routing\Router; use LaravelFlare\Flare\Admin\Modules\ModuleAdmin; class SettingsModule extends ModuleAdmin { /** * Admin Section Icon. * * Font Awesome Defined Icon, eg 'user' = 'fa-user' * * @var string */ protected $icon = 'cog'; /** * Title of Admin Section. * * @var string */ protected $title = 'Settings'; /** * Title of Admin Section. * * @var string */ protected $pluralTitle = 'Settings'; /** * The Controller to be used by the Pages Module. * * @var string */ protected $controller = '\LaravelFlare\Settings\Http\Controllers\SettingsAdminController'; /** * Register the routes for this Admin Section. * * @param \Illuminate\Routing\Router $router */ public function registerRoutes(Router $router) { $router->group(['prefix' => $this->urlPrefix(), 'namespace' => get_called_class(), 'as' => $this->urlPrefix()], function ($router) { $router->get('{panel?}', '\LaravelFlare\Settings\Http\Controllers\SettingsAdminController@getIndex')->name('settings'); $router->post('{panel?}', '\LaravelFlare\Settings\Http\Controllers\SettingsAdminController@postIndex')->name('settings'); }); } /** * Menu Items. * * @return array */ public function menuItems() { return \Flare::settings()->menu(); } }
<?php namespace LaravelFlare\Settings; use Illuminate\Routing\Router; use LaravelFlare\Flare\Admin\Modules\ModuleAdmin; class SettingsModule extends ModuleAdmin { /** * Admin Section Icon. * * Font Awesome Defined Icon, eg 'user' = 'fa-user' * * @var string */ protected $icon = 'cog'; /** * Title of Admin Section. * * @var string */ protected $title = 'Settings'; /** * Title of Admin Section. * * @var string */ protected $pluralTitle = 'Settings'; /** * The Controller to be used by the Pages Module. * * @var string */ protected $controller = '\LaravelFlare\Settings\Http\Controllers\SettingsAdminController'; /** * Register the routes for the Settings Panel(s). * * @param \Illuminate\Routing\Router $router * * @return */ public function registerRoutes(Router $router) { $router->get('settings/{panel?}', '\LaravelFlare\Settings\Http\Controllers\SettingsAdminController@getIndex')->name('settings'); $router->post('settings/{panel?}', '\LaravelFlare\Settings\Http\Controllers\SettingsAdminController@postIndex')->name('settings'); } /** * Menu Items. * * @return array */ public function menuItems() { return \Flare::settings()->menu(); } }
Use the github repo as the project url
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() setup( author="Pinax Team", author_email="[email protected]", description="a liking app for Django", name="pinax-likes", long_description=read("README.rst"), version="1.3.1", url="http://github.com/pinax/pinax-likes/", license="MIT", packages=find_packages(), install_requires=[ "django-appconf>=0.6", ], package_data={ "pinax.likes": [ "templates/pinax/likes/*", ] }, test_suite="runtests.runtests", tests_require=[ ], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False, )
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() setup( author="Pinax Team", author_email="[email protected]", description="a liking app for Django", name="pinax-likes", long_description=read("README.rst"), version="1.3.1", url="http://pinax-likes.rtfd.org/", license="MIT", packages=find_packages(), install_requires=[ "django-appconf>=0.6", ], package_data={ "pinax.likes": [ "templates/pinax/likes/*", ] }, test_suite="runtests.runtests", tests_require=[ ], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False, )
Remove Box wrapping List component
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import List from './List'; import CSSClassnames from '../utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.ACCORDION; export default class Accordion extends Component { constructor(props) { super(props); this._activatePanel = this._activatePanel.bind(this); this.state = { activeIndex: props.initialIndex }; } _activatePanel (index) { this.setState({activeIndex: index}); } render () { const { animate, className, children, openMulti, ...props } = this.props; const classes = classnames( CLASS_ROOT, className ); const accordionChildren = React.Children.map(children, (child, index) => { return React.cloneElement(child, { id: 'accordion-panel-' + index, isOpen: !openMulti ? (this.state.activeIndex === index) : null, onTitleClick: () => { this._activatePanel(index); }, animate }); }); return ( <List role="tablist" className={classes} {...props} > {accordionChildren} </List> ); } }; Accordion.propTypes = { animate: PropTypes.bool, colorIndex: PropTypes.string }; Accordion.defaultProps = { openMulti: false, animate: true };
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import Box from './Box'; import List from './List'; import CSSClassnames from '../utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.ACCORDION; export default class Accordion extends Component { constructor(props) { super(props); this._activatePanel = this._activatePanel.bind(this); this.state = { activeIndex: props.initialIndex }; } _activatePanel (index) { this.setState({activeIndex: index}); } render () { const { animate, className, children, colorIndex, openMulti } = this.props; const classes = classnames( CLASS_ROOT, className ); const accordionChildren = React.Children.map(children, (child, index) => { return React.cloneElement(child, { id: 'accordion-panel-' + index, isOpen: !openMulti ? (this.state.activeIndex === index) : null, onTitleClick: () => { this._activatePanel(index); }, animate }); }); return ( <Box role="tablist" className={classes} colorIndex={colorIndex} separator="top"> <List> {accordionChildren} </List> </Box> ); } }; Accordion.propTypes = { animate: PropTypes.bool, colorIndex: PropTypes.string }; Accordion.defaultProps = { openMulti: false, animate: true };
Make the digestion of the google geo result standardized
angular .module('app') .factory('googleMapsService', ['$rootScope', '$q', function($rootScope, $q) { var methods = {}; methods.geo = function(address, type) { var geocoder = new google.maps.Geocoder(); var geoData = {}; var handleResult = function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var location = results[0].geometry.location; geoData.lng = location.lng(); geoData.lat = location.lat(); $rootScope.$broadcast('event:geo-location-success', geoData, type); } else { $rootScope.$broadcast('event:geo-location-failure', geoData, type); //alert('Geocode was not successful for the following reason: ' + status); } }; geocoder.geocode({ 'address': address }, handleResult); }; return methods; } ]);
angular .module('app') .factory('googleMapsService', ['$rootScope', '$q', function($rootScope, $q) { /* // Load the Google Maps scripts Asynchronously (function(d){ var js, id = 'google-maps', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"; ref.parentNode.insertBefore(js, ref); }(document)); */ var methods = {}; methods.geo = function(address, type) { //var deferred = $q.defer(); var geocoder = new google.maps.Geocoder(); var geoData = {}; var handleResult = function(results, status) { if (status == google.maps.GeocoderStatus.OK) { console.log(results[0]); geoData.lat = results[0].geometry.location.mb; // mb geoData.lng = results[0].geometry.location.nb; // nb // @todo why is this the new format? // did things change on the Google API side? if (!geoData.lat || !geoData.lng) { geoData.lat = results[0].geometry.location.ob; // mb geoData.lng = results[0].geometry.location.pb; // nb } if (!geoData.lat || !geoData.lng) { $rootScope.$broadcast('event:geo-location-failure'); } else { $rootScope.$broadcast('event:geo-location-success', geoData, type); } } else { $rootScope.$broadcast('event:geo-location-failure', geoData, type); //alert('Geocode was not successful for the following reason: ' + status); } }; geocoder.geocode({ 'address': address }, handleResult); //return deferred.promise; }; return methods; } ]);
Allow null as defining class.
/* * Copyright (C) 2008, 2010 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 13. October 2008 by Joerg Schaible */ package com.thoughtworks.xstream.core.util; public final class FastField { private final String name; private final Class declaringClass; public FastField(Class definedIn, String name) { this.name = name; this.declaringClass = definedIn; } public String getName() { return this.name; } public Class getDeclaringClass() { return this.declaringClass; } public boolean equals(Object obj) { if (this == obj) { return true; } if (this == null) { return false; } if (obj.getClass() == FastField.class) { final FastField field = (FastField)obj; if ((declaringClass == null && field.declaringClass != null) || (declaringClass != null && field.declaringClass == null)) { return false; } return name.equals(field.getName()) && (declaringClass == null || declaringClass.equals(field.getDeclaringClass())); } return false; } public int hashCode() { return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode()); } public String toString() { return (declaringClass == null ? "" : declaringClass.getName() + ".") + name; } }
/* * Copyright (C) 2008 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 13. October 2008 by Joerg Schaible */ package com.thoughtworks.xstream.core.util; public final class FastField { private final String name; private final Class declaringClass; public FastField(Class definedIn, String name) { this.name = name; this.declaringClass = definedIn; } public String getName() { return this.name; } public Class getDeclaringClass() { return this.declaringClass; } public boolean equals(Object obj) { if (this == obj) { return true; } if (this == null) { return false; } if (obj.getClass() == FastField.class) { final FastField field = (FastField)obj; return name.equals(field.getName()) && declaringClass.equals(field.getDeclaringClass()); } return false; } public int hashCode() { return name.hashCode() ^ declaringClass.hashCode(); } public String toString() { return declaringClass.getName() + "[" + name + "]"; } }
Create commands for labextension and nbextension
from setuptools import setup from setupbase import create_cmdclass, install_npm cmdclass = create_cmdclass(['labextension', 'nbextension']) cmdclass['labextension'] = install_npm('labextension') cmdclass['nbextension'] = install_npm('nbextension') setup_args = dict( name = '{{cookiecutter.extension_name}}', version = '0.18.0', packages = ['{{cookiecutter.extension_name}}'], author = '{{cookiecutter.author_name}}', author_email = '{{cookiecutter.author_email}}', url = 'http://jupyter.org', license = 'BSD', platforms = "Linux, Mac OS X, Windows", keywords = ['ipython', 'jupyter'], classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], cmdclass = cmdclass, install_requires = [ 'jupyterlab>=0.18.0', 'notebook>=4.3.0', 'ipython>=1.0.0' ] ) if __name__ == '__main__': setup(**setup_args)
from setuptools import setup from setupbase import create_cmdclass, install_npm cmdclass = create_cmdclass(['js']) cmdclass['js'] = install_npm() setup_args = dict( name = '{{cookiecutter.extension_name}}', version = '0.18.0', packages = ['{{cookiecutter.extension_name}}'], author = '{{cookiecutter.author_name}}', author_email = '{{cookiecutter.author_email}}', url = 'http://jupyter.org', license = 'BSD', platforms = "Linux, Mac OS X, Windows", keywords = ['ipython', 'jupyter'], classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], cmdclass = cmdclass, install_requires = [ 'jupyterlab>=0.18.0', 'notebook>=4.3.0', 'ipython>=1.0.0' ] ) if __name__ == '__main__': setup(**setup_args)
Replace string.trimEnd with string.trimRight for Node 8.
// @ts-check "use strict"; const { addErrorContext, isBlankLine } = require("../helpers"); const { flattenedLists } = require("./cache"); const quotePrefixRe = /^[>\s]*/; module.exports = { "names": [ "MD032", "blanks-around-lists" ], "description": "Lists should be surrounded by blank lines", "tags": [ "bullet", "ul", "ol", "blank_lines" ], "function": function MD032(params, onError) { const { lines } = params; flattenedLists().filter((list) => !list.nesting).forEach((list) => { const firstIndex = list.open.map[0]; if (!isBlankLine(lines[firstIndex - 1])) { const line = lines[firstIndex]; const quotePrefix = line.match(quotePrefixRe)[0].trimRight(); addErrorContext( onError, firstIndex + 1, line.trim(), null, null, null, { "insertText": `${quotePrefix}\n` }); } const lastIndex = list.lastLineIndex - 1; if (!isBlankLine(lines[lastIndex + 1])) { const line = lines[lastIndex]; const quotePrefix = line.match(quotePrefixRe)[0].trimRight(); addErrorContext( onError, lastIndex + 1, line.trim(), null, null, null, { "lineNumber": lastIndex + 2, "insertText": `${quotePrefix}\n` }); } }); } };
// @ts-check "use strict"; const { addErrorContext, isBlankLine } = require("../helpers"); const { flattenedLists } = require("./cache"); const quotePrefixRe = /^[>\s]*/; module.exports = { "names": [ "MD032", "blanks-around-lists" ], "description": "Lists should be surrounded by blank lines", "tags": [ "bullet", "ul", "ol", "blank_lines" ], "function": function MD032(params, onError) { const { lines } = params; flattenedLists().filter((list) => !list.nesting).forEach((list) => { const firstIndex = list.open.map[0]; if (!isBlankLine(lines[firstIndex - 1])) { const line = lines[firstIndex]; const quotePrefix = line.match(quotePrefixRe)[0].trimEnd(); addErrorContext( onError, firstIndex + 1, line.trim(), null, null, null, { "insertText": `${quotePrefix}\n` }); } const lastIndex = list.lastLineIndex - 1; if (!isBlankLine(lines[lastIndex + 1])) { const line = lines[lastIndex]; const quotePrefix = line.match(quotePrefixRe)[0].trimEnd(); addErrorContext( onError, lastIndex + 1, line.trim(), null, null, null, { "lineNumber": lastIndex + 2, "insertText": `${quotePrefix}\n` }); } }); } };
Add simple test for coverage.
""" Tests utility scripts """ import os from django.test import TestCase, RequestFactory from django.test.utils import override_settings import pivot from pivot.utils import get_latest_term, is_more_recent from pivot.templatetags.pivot_extras import year_select_tab TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__), 'test', 'test_resources', 'csvfiles/',) class UtilsTest(TestCase): @override_settings(CSV_ROOT=TEST_CSV_PATH) def test_get_latest_term(self): self.assertEquals(get_latest_term(), 'au12') @override_settings(CSV_ROOT=TEST_CSV_PATH) def test_is_more_recent_true(self): self.assertTrue(is_more_recent('au19', 'au18')) @override_settings(CSV_ROOT=TEST_CSV_PATH) def test_is_more_recent_false(self): self.assertFalse(is_more_recent('au18', 'au19')) @override_settings(CSV_ROOT=TEST_CSV_PATH) def test_pivot_extras(self): template = """ <a href=".?num_qtrs=8&end_yr=12&end_qtr=AU"> <strong>Last 2 Years</strong> <br> <span> AU10 - AU12 </span> </a> """ html = year_select_tab(8) self.assertEqual(html, template)
""" Tests utility scripts """ import os from django.test import TestCase, RequestFactory from django.test.utils import override_settings import pivot from pivot.utils import get_latest_term, is_more_recent from pivot.templatetags.pivot_extras import year_select_tab TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__), 'test', 'test_resources', 'csvfiles/',) class UtilsTest(TestCase): @override_settings(CSV_ROOT=TEST_CSV_PATH) def test_get_latest_term(self): self.assertEquals(get_latest_term(), 'au12') @override_settings(CSV_ROOT=TEST_CSV_PATH) def test_is_more_recent_true(self): self.assertTrue(is_more_recent('au19', 'au18')) @override_settings(CSV_ROOT=TEST_CSV_PATH) def test_pivot_extras(self): template = """ <a href=".?num_qtrs=8&end_yr=12&end_qtr=AU"> <strong>Last 2 Years</strong> <br> <span> AU10 - AU12 </span> </a> """ html = year_select_tab(8) self.assertEqual(html, template)
Add Helper singleton class for querying/adding notification to db.
package org.zeropage.apps.zeropage.database.notification; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.zeropage.apps.zeropage.notification.Notification; import java.util.ArrayList; import java.util.List; public class NotificationHistory { private static NotificationHistory sInstance; private SQLiteDatabase mDatabase; public synchronized static NotificationHistory getInstance(Context context) { if (sInstance == null) { sInstance = new NotificationHistory(context.getApplicationContext()); } return sInstance; } private NotificationHistory(Context context) { mDatabase = new NotificationOpenHelper(context).getWritableDatabase(); } public void addToHistory(Notification newNotification) { ContentValues values = NotificationTable.getContentValues(newNotification); mDatabase.insert(NotificationTable.NAME, null, values); } public List<Notification> getAllHistory() { List<Notification> notifications = new ArrayList<>(); try (NotificationCursorWrapper wrapper = queryHistory(null, null)) { wrapper.moveToFirst(); while (!wrapper.isAfterLast()) { notifications.add(wrapper.getNotification()); wrapper.moveToNext(); } } return notifications; } private NotificationCursorWrapper queryHistory(String whereClause, String[] whereArgs) { Cursor cursor = mDatabase.query(NotificationTable.NAME, null, whereClause, whereArgs, null, null, null, null); return new NotificationCursorWrapper(cursor); } }
package org.zeropage.apps.zeropage.database.notification; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.zeropage.apps.zeropage.notification.Notification; import java.util.ArrayList; import java.util.List; public class NotificationHistory { private static NotificationHistory sInstance; private SQLiteDatabase mDatabase; public NotificationHistory getInstance(Context context) { sInstance = new Notifi } private NotificationHistory(Context context) { mDatabase = new NotificationOpenHelper(context).getWritableDatabase(); } public void addToHistory(Notification newNotification) { ContentValues values = NotificationTable.getContentValues(newNotification); mDatabase.insert(NotificationTable.NAME, null, values); } public List<Notification> getAllHistory() { List<Notification> notifications = new ArrayList<>(); try (NotificationCursorWrapper wrapper = queryHistory(null, null)) { wrapper.moveToFirst(); while (!wrapper.isAfterLast()) { notifications.add(wrapper.getNotification()); wrapper.moveToNext(); } } return notifications; } private NotificationCursorWrapper queryHistory(String whereClause, String[] whereArgs) { Cursor cursor = mDatabase.query(NotificationTable.NAME, null, whereClause, whereArgs, null, null, null, null); return new NotificationCursorWrapper(cursor); } }
Fix for angular-jwt injecting authorization header
'use strict'; angular.module('mean.admin').controller('ThemesController', ['$scope', 'Global', '$rootScope', '$http', function($scope, Global, $rootScope, $http) { $scope.global = Global; $scope.themes = []; $scope.init = function() { $http({ method: 'GET', url: 'http://api.bootswatch.com/3/', skipAuthorization: true }). success(function(data, status, headers, config) { $scope.themes = data.themes; }). error(function(data, status, headers, config) { }); }; $scope.changeTheme = function(theme) { // Will add preview options soon // $('link').attr('href', theme.css); // $scope.selectedTheme = theme; $('.progress-striped').show(); $http.get('/api/admin/themes?theme=' + theme.css). success(function(data, status, headers, config) { if (data) window.location.reload(); }). error(function(data, status, headers, config) { alert('error'); $('.progress-striped').hide(); }); }; $scope.defaultTheme = function() { $http.get('/api/admin/themes/defaultTheme'). success(function(data, status, headers, config) { if (data) window.location.reload(); }). error(function(data, status, headers, config) { alert('error'); }); }; } ]);
'use strict'; angular.module('mean.admin').controller('ThemesController', ['$scope', 'Global', '$rootScope', '$http', function($scope, Global, $rootScope, $http) { $scope.global = Global; $scope.themes = []; $scope.init = function() { $http({ method: 'GET', url: 'http://api.bootswatch.com/3/' }). success(function(data, status, headers, config) { $scope.themes = data.themes; }). error(function(data, status, headers, config) { }); }; $scope.changeTheme = function(theme) { // Will add preview options soon // $('link').attr('href', theme.css); // $scope.selectedTheme = theme; $('.progress-striped').show(); $http.get('/api/admin/themes?theme=' + theme.css). success(function(data, status, headers, config) { if (data) window.location.reload(); }). error(function(data, status, headers, config) { alert('error'); $('.progress-striped').hide(); }); }; $scope.defaultTheme = function() { $http.get('/api/admin/themes/defaultTheme'). success(function(data, status, headers, config) { if (data) window.location.reload(); }). error(function(data, status, headers, config) { alert('error'); }); }; } ]);
Fix for 'CreateListFromArrayLike called on non-object'
if (!window['$']) var $ = function a(){} (function a(){ $.get('https://api.github.com/repos/KaMeHb-UA/LeNode/releases/latest', function(data, status){ if (status != 'success') a(); else { $('a[rel="download"]').attr('href', data.assets[0].browser_download_url); $('#latest-version').html(data.tag_name); $('*[rel="release-description"]').html(data.name); } }, 'json'); })(); document.addEventListener('DOMContentLoaded', function(){ 'use strict'; var actions = { log : function(){ console.log.apply(null, arguments); console.log(this); }, hide : function(){ this.css('display', 'none') }, detach : function(){ this.detach(arguments ? arguments[0] : undefined) }, remove : function(){ this.remove(arguments ? arguments[0] : undefined) } }; $('*[__click]').each(function(i,e){ var e = $(e); e.click(function(){ actions[e.attr('__click')].apply(e, (function(a){ if (a){ try{ return JSON.parse(a); } catch(e){ return a; } } else return []; })(e.attr('__click_data'))); }); }); });
if (!window['$']) var $ = function a(){} (function a(){ $.get('https://api.github.com/repos/KaMeHb-UA/LeNode/releases/latest', function(data, status){ if (status != 'success') a(); else { $('a[rel="download"]').attr('href', data.assets[0].browser_download_url); $('#latest-version').html(data.tag_name); $('*[rel="release-description"]').html(data.name); } }, 'json'); })(); document.addEventListener('DOMContentLoaded', function(){ 'use strict'; var actions = { log : function(){ console.log.apply(null, arguments); console.log(this); }, hide : function(){ this.css('display', 'none') }, detach : function(){ this.detach(arguments ? arguments[0] : undefined) }, remove : function(){ this.remove(arguments ? arguments[0] : undefined) } }; $('*[__click]').each(function(i,e){ var e = $(e); e.click(function(){ actions[e.attr('__click')].apply(e, (function(a){ if (a){ try{ return JSON.parse(a); } catch(e){ return a; } } })(e.attr('__click_data'))); }); }); });
Update URL for new cross-platform endpoint
const autoUpdater = require('electron').autoUpdater const Menu = require('electron').Menu var state = 'checking' exports.initialize = function () { autoUpdater.on('checking-for-update', function () { state = 'checking' exports.updateMenu() }) autoUpdater.on('update-available', function () { state = 'checking' exports.updateMenu() }) autoUpdater.on('update-downloaded', function () { state = 'installed' exports.updateMenu() }) autoUpdater.on('update-not-available', function () { state = 'no-update' exports.updateMenu() }) autoUpdater.on('error', function () { state = 'no-update' exports.updateMenu() }) autoUpdater.setFeedURL('https://electron-api-demos.githubapp.com/updates') autoUpdater.checkForUpdates() } exports.updateMenu = function () { var menu = Menu.getApplicationMenu() if (!menu) return menu.items.forEach(function (item) { if (item.submenu) { item.submenu.items.forEach(function (item) { switch (item.key) { case 'checkForUpdate': item.visible = state === 'no-update' break case 'checkingForUpdate': item.visible = state === 'checking' break case 'restartToUpdate': item.visible = state === 'installed' break } }) } }) }
const autoUpdater = require('electron').autoUpdater const Menu = require('electron').Menu var state = 'checking' exports.initialize = function () { autoUpdater.on('checking-for-update', function () { state = 'checking' exports.updateMenu() }) autoUpdater.on('update-available', function () { state = 'checking' exports.updateMenu() }) autoUpdater.on('update-downloaded', function () { state = 'installed' exports.updateMenu() }) autoUpdater.on('update-not-available', function () { state = 'no-update' exports.updateMenu() }) autoUpdater.on('error', function () { state = 'no-update' exports.updateMenu() }) autoUpdater.setFeedURL('https://electron-api-demos.githubapp.com/mac') autoUpdater.checkForUpdates() } exports.updateMenu = function () { var menu = Menu.getApplicationMenu() if (!menu) return menu.items.forEach(function (item) { if (item.submenu) { item.submenu.items.forEach(function (item) { switch (item.key) { case 'checkForUpdate': item.visible = state === 'no-update' break case 'checkingForUpdate': item.visible = state === 'checking' break case 'restartToUpdate': item.visible = state === 'installed' break } }) } }) }
Fix first id being 0
<?php namespace Backend\Modules\ContentBlocks\ContentBlock; use Backend\Core\Language\Locale; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Query; class ContentBlockRepository extends EntityRepository { /** * @param Locale $locale * * @return Query */ public function getDataGridQuery(Locale $locale) { return $this->getEntityManager() ->createQueryBuilder() ->select('cb.id, cb.title, cb.isHidden') ->from(ContentBlock::class, 'cb') ->where('cb.status = ?1 AND cb.locale = ?2') ->setParameters([Status::active(), $locale]) ->getQuery(); } /** * @param Locale $locale * * @return int */ public function getNextIdForLanguage(Locale $locale) { return (int) $this->getEntityManager() ->createQueryBuilder() ->select('MAX(cb.id) as id') ->from(ContentBlock::class, 'cb') ->where('cb.locale = :locale') ->setParameter('locale', $locale) ->getQuery() ->getSingleScalarResult() + 1; } }
<?php namespace Backend\Modules\ContentBlocks\ContentBlock; use Backend\Core\Language\Locale; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Query; class ContentBlockRepository extends EntityRepository { /** * @param Locale $locale * * @return Query */ public function getDataGridQuery(Locale $locale) { return $this->getEntityManager() ->createQueryBuilder() ->select('cb.id, cb.title, cb.isHidden') ->from(ContentBlock::class, 'cb') ->where('cb.status = ?1 AND cb.locale = ?2') ->setParameters([Status::active(), $locale]) ->getQuery(); } /** * @param Locale $locale * * @return int */ public function getNextIdForLanguage(Locale $locale) { return (int) $this->getEntityManager() ->createQueryBuilder() ->select('MAX(cb.id) + 1 as id') ->from(ContentBlock::class, 'cb') ->where('cb.locale = :locale') ->setParameter('locale', $locale) ->getQuery() ->getSingleScalarResult(); } }
Fix dropdown width in adresses settings
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { msgid, c } from 'ttag'; import { SimpleDropdown, DropdownMenu } from 'react-components'; const MemberAddresses = ({ member, addresses }) => { const list = addresses.map(({ ID, Email }) => ( <div key={ID} className="w100 flex flex-nowrap pl1 pr1 pt0-5 pb0-5"> {Email} </div> )); const n = list.length; const addressesTxt = ` ${c('Info').ngettext(msgid`address`, `addresses`, n)}`; const contentDropDown = ( <> {n} <span className="nomobile">{addressesTxt}</span> </> ); // trick for responsive and mobile display return ( <> <SimpleDropdown className="pm-button--link" content={contentDropDown}> <div className="dropDown-item pt0-5 pb0-5 pl1 pr1 flex"> <Link className="pm-button w100 aligncenter" to={`/settings/addresses/${member.ID}`}>{c('Link') .t`Manage`}</Link> </div> <DropdownMenu>{list}</DropdownMenu> </SimpleDropdown> </> ); }; MemberAddresses.propTypes = { member: PropTypes.object.isRequired, addresses: PropTypes.array.isRequired, }; export default MemberAddresses;
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { msgid, c } from 'ttag'; import { SimpleDropdown, DropdownMenu } from 'react-components'; const MemberAddresses = ({ member, addresses }) => { const list = addresses.map(({ ID, Email }) => ( <div key={ID} className="inbl w100 pt0-5 pb0-5 pl1 pr1 ellipsis"> {Email} </div> )); const n = list.length; const addressesTxt = ` ${c('Info').ngettext(msgid`address`, `addresses`, n)}`; const contentDropDown = ( <> {n} <span className="nomobile">{addressesTxt}</span> </> ); // trick for responsive and mobile display return ( <> <SimpleDropdown className="pm-button--link" content={contentDropDown}> <DropdownMenu>{list}</DropdownMenu> <div className="alignright p1"> <Link className="pm-button" to={`/settings/addresses/${member.ID}`}>{c('Link').t`Manage`}</Link> </div> </SimpleDropdown> </> ); }; MemberAddresses.propTypes = { member: PropTypes.object.isRequired, addresses: PropTypes.array.isRequired, }; export default MemberAddresses;
LB-1458: Check on admin all POST, PUT, DELETE URLs to use my Cleared a console.log
define([ 'angular', 'lib/livedesk/scripts/js/manage-feeds/manage-feeds', 'lib/livedesk/scripts/js/manage-feeds/services/providers-blogs-data', 'lib/livedesk/scripts/js/manage-feeds/services/all-blog-sources' ],function(ngular, feeds){ feeds.factory('chainedBlogsData', ['$http', '$q','providersBlogsData','allBlogSources', function($http, $q, providersBlogsData, allBlogSources){ return { getData: function(providersUrl, sourcesUrl) { var deffered = $q.defer(); providersBlogsData.getData(providersUrl).then(function(chains){ allBlogSources.getData(sourcesUrl).then(function(sources){ for ( var i = 0; i < chains.length; i++ ) { for ( var j = 0; j < chains[i].blogList.length; j++ ) { var chained = false; var sourceId = -1; for ( var k = 0; k < sources.length; k ++ ) { if ( sources[k].URI.href == chains[i].blogList[j].href ) { chained = true; sourceId = sources[k].Id break; } } chains[i].blogList[j].chained = chained; chains[i].blogList[j].sourceId = sourceId; } } deffered.resolve(chains); }); }); return deffered.promise; } } }]); });
define([ 'angular', 'lib/livedesk/scripts/js/manage-feeds/manage-feeds', 'lib/livedesk/scripts/js/manage-feeds/services/providers-blogs-data', 'lib/livedesk/scripts/js/manage-feeds/services/all-blog-sources' ],function(ngular, feeds){ feeds.factory('chainedBlogsData', ['$http', '$q','providersBlogsData','allBlogSources', function($http, $q, providersBlogsData, allBlogSources){ return { getData: function(providersUrl, sourcesUrl) { var deffered = $q.defer(); providersBlogsData.getData(providersUrl).then(function(chains){ allBlogSources.getData(sourcesUrl).then(function(sources){ console.log('chains ', chains); for ( var i = 0; i < chains.length; i++ ) { for ( var j = 0; j < chains[i].blogList.length; j++ ) { var chained = false; var sourceId = -1; for ( var k = 0; k < sources.length; k ++ ) { if ( sources[k].URI.href == chains[i].blogList[j].href ) { chained = true; sourceId = sources[k].Id break; } } chains[i].blogList[j].chained = chained; chains[i].blogList[j].sourceId = sourceId; } } deffered.resolve(chains); }); }); return deffered.promise; } } }]); });
Extend tabs to allow callbacks for unrouted tab navigation
import classNames from 'classnames/dedupe'; import {Link} from 'react-router'; import React from 'react'; class PageHeaderTabs extends React.Component { render() { let {props: {tabs}} = this; let tabElements = tabs.map(function (tab, index) { let {isActive, callback} = tab; let classes = classNames('menu-tabbed-item', {active: isActive}); let linkClasses = classNames('menu-tabbed-item-label', {active: isActive}); let innerLinkSpan = <span className="menu-tabbed-item-label-text">{tab.label}</span>; let link = tab.callback == null ? <Link className={linkClasses} to={tab.routePath}>{innerLinkSpan}</Link> : <a className={linkClasses} onClick={callback}>{innerLinkSpan}</a>; return ( <li className={classes} key={index}> {link} </li> ); }); return ( <div className="page-header-navigation"> <ul className="menu-tabbed"> {tabElements} </ul> </div> ); } } PageHeaderTabs.defaultProps = { tabs: [] }; PageHeaderTabs.propTypes = { tabs: React.PropTypes.arrayOf( React.PropTypes.shape({ isActive: React.PropTypes.bool, label: React.PropTypes.node.isRequired, routePath: React.PropTypes.string, callback: React.PropTypes.func }) ) }; module.exports = PageHeaderTabs;
import classNames from 'classnames/dedupe'; import {Link} from 'react-router'; import React from 'react'; class PageHeaderTabs extends React.Component { render() { let {props: {tabs}} = this; let tabElements = tabs.map(function (tab, index) { let {isActive, callback} = tab; let classes = classNames('menu-tabbed-item', {active: isActive}); let linkClasses = classNames('menu-tabbed-item-label', {active: isActive}); let innerLinkSpan = <span className="menu-tabbed-item-label-text">{tab.label}</span>; return ( <li className={classes} key={index}> <Link className={linkClasses} to={tab.routePath}> <span className="tab-item-label-text"> {tab.label} </span> </Link> </li> ); }); return ( <div className="page-header-navigation"> <ul className="menu-tabbed"> {tabElements} </ul> </div> ); } } PageHeaderTabs.defaultProps = { tabs: [] }; PageHeaderTabs.propTypes = { tabs: React.PropTypes.arrayOf( React.PropTypes.shape({ isActive: React.PropTypes.bool, label: React.PropTypes.node.isRequired, routePath: React.PropTypes.string.isRequired }) ) }; module.exports = PageHeaderTabs;
Add admin label and icon to account general view
import React from "react"; import { capitalize, map } from "lodash-es"; import { connect } from "react-redux"; import { Label } from "react-bootstrap"; import { Flex, FlexItem, Identicon, Icon } from "../../base"; import ChangePassword from "./Password"; import Email from "./Email"; export const AccountGeneral = ({ id, groups, hash, isAdmin }) => { const groupLabels = map(groups, groupId => <Label key={groupId} style={{marginRight: "3px"}}> {capitalize(groupId)} </Label> ); const adminLabel = ( <Label key="virtool-admin" bsStyle="primary" style={{marginRight: "3px"}}> Administrator </Label> ); return ( <div> <Flex alignItems="stretch" style={{marginBottom: "15px"}}> <FlexItem> <Identicon hash={hash} /> </FlexItem> <FlexItem pad={10}> <h5> <strong> {id} {isAdmin ? <Icon name="user-shield" bsStyle="primary" /> : null} </strong> </h5> <div> {isAdmin ? adminLabel : null} {groupLabels} </div> </FlexItem> </Flex> <Email /> <ChangePassword /> </div> ); }; const mapStateToProps = (state) => ({ id: state.account.id, hash: state.account.identicon, groups: state.account.groups, isAdmin: state.account.administrator }); export default connect(mapStateToProps)(AccountGeneral);
import React from "react"; import { capitalize, map } from "lodash-es"; import { connect } from "react-redux"; import { Label } from "react-bootstrap"; import { Flex, FlexItem, Identicon } from "../../base"; import ChangePassword from "./Password"; import Email from "./Email"; export const AccountGeneral = ({ id, groups, hash }) => { const groupLabels = map(groups, groupId => <Label key={groupId} style={{marginRight: "3px"}}> {capitalize(groupId)} </Label> ); return ( <div> <Flex alignItems="stretch" style={{marginBottom: "15px"}}> <FlexItem> <Identicon hash={hash} /> </FlexItem> <FlexItem pad={10}> <h5> <strong> {id} </strong> </h5> <div> {groupLabels} </div> </FlexItem> </Flex> <Email /> <ChangePassword /> </div> ); }; const mapStateToProps = (state) => ({ id: state.account.id, hash: state.account.identicon, groups: state.account.groups }); export default connect(mapStateToProps)(AccountGeneral);
Initialize char_length with a number And make var name `file` less ambiguous by using `file_name` instead. Signed-off-by: Stefan Marr <[email protected]>
class SourceCoordinate(object): _immutable_fields_ = ['_start_line', '_start_column', '_char_idx'] def __init__(self, start_line, start_column, char_idx): self._start_line = start_line self._start_column = start_column self._char_idx = char_idx def get_start_line(self): return self._start_line def get_start_column(self): return self._start_column class SourceSection(object): _immutable_fields_ = ['_source', '_identifier', '_coord', '_char_length'] def __init__(self, source = None, identifier = None, coord = None, char_length = 0, file_name = None, source_section = None): if source_section: self._source = source_section._source self._coord = source_section._coord self._char_length = source_section._char_length self._file = source_section._file else: self._source = source self._coord = coord self._char_length = char_length self._file = file_name self._identifier = identifier def __str__(self): return "%s:%d:%d" % (self._file, self._coord.get_start_line(), self._coord.get_start_column())
class SourceCoordinate(object): _immutable_fields_ = ['_start_line', '_start_column', '_char_idx'] def __init__(self, start_line, start_column, char_idx): self._start_line = start_line self._start_column = start_column self._char_idx = char_idx def get_start_line(self): return self._start_line def get_start_column(self): return self._start_column class SourceSection(object): _immutable_fields_ = ['_source', '_identifier', '_coord', '_char_length'] def __init__(self, source = None, identifier = None, coord = None, char_length = None, file = None, source_section = None): if source_section: self._source = source_section._source self._coord = source_section._coord self._char_length = source_section._char_length self._file = source_section._file else: self._source = source self._coord = coord self._char_length = char_length self._file = file self._identifier = identifier def __str__(self): return "%s:%d:%d" % (self._file, self._coord.get_start_line(), self._coord.get_start_column())
Change of function name due to deprecation.
import pandas as PD INFO_LINK = 'http://ds.iris.edu/files/earthscope/usarray/_US-MT-StationList.txt' """Full URL link to USArray MT site information text file.""" HEADER = 'VNET NET STA SITE DESCRIPTION LAT LON ELEV START END STATUS INSTALL CERT' """Header line of data file.""" def get_info_map(info_link=INFO_LINK): """ Return a :class:`DataFrame` containing the information provided at *info_link*, a link to a tab delineated text file containing information for each USArray MT site. """ df = PD.read_csv(info_link, sep='\t', skiprows=1, names=['vnet', 'net', 'sta', 'location', 'lat', 'lon', 'elev', 'start', 'end', 'status', 'install', 'cert'], parse_dates=[7, 8], index_col=2) return df
import pandas as PD INFO_LINK = 'http://ds.iris.edu/files/earthscope/usarray/_US-MT-StationList.txt' """Full URL link to USArray MT site information text file.""" HEADER = 'VNET NET STA SITE DESCRIPTION LAT LON ELEV START END STATUS INSTALL CERT' """Header line of data file.""" def get_info_map(info_link=INFO_LINK): """ Return a :class:`DataFrame` containing the information provided at *info_link*, a link to a tab delineated text file containing information for each USArray MT site. """ df = PD.read_table(info_link, sep='\t', skiprows=1, names=['vnet', 'net', 'sta', 'location', 'lat', 'lon', 'elev', 'start', 'end', 'status', 'install', 'cert'], parse_dates=[7, 8], index_col=2) return df
Fix the issue where the mock is persisting calls
import mock import github3 import unittest def build_url(self, *args, **kwargs): # We want to assert what is happening with the actual calls to the # Internet. We can proxy this. return github3.session.GitHubSession().build_url(*args, **kwargs) class UnitHelper(unittest.TestCase): # Sub-classes must assign the class to this during definition described_class = None # Sub-classes must also assign a dictionary to this during definition example_data = {} def create_mocked_session(self): MockedSession = mock.create_autospec(github3.session.GitHubSession) return MockedSession() def create_session_mock(self, *args): session = self.create_mocked_session() base_attrs = ['headers', 'auth'] attrs = dict( (key, mock.Mock()) for key in set(args).union(base_attrs) ) session.configure_mock(**attrs) session.delete.return_value = None session.get.return_value = None session.patch.return_value = None session.post.return_value = None session.put.return_value = None return session def setUp(self): self.session = self.create_session_mock() self.instance = self.described_class(self.example_data, self.session) # Proxy the build_url method to the class so it can build the URL and # we can assert things about the call that will be attempted to the # internet self.described_class._build_url = build_url
import mock import github3 import unittest MockedSession = mock.create_autospec(github3.session.GitHubSession) def build_url(self, *args, **kwargs): # We want to assert what is happening with the actual calls to the # Internet. We can proxy this. return github3.session.GitHubSession().build_url(*args, **kwargs) class UnitHelper(unittest.TestCase): # Sub-classes must assign the class to this during definition described_class = None # Sub-classes must also assign a dictionary to this during definition example_data = {} def create_session_mock(self, *args): session = MockedSession() base_attrs = ['headers', 'auth'] attrs = dict( (key, mock.Mock()) for key in set(args).union(base_attrs) ) session.configure_mock(**attrs) session.delete.return_value = None session.get.return_value = None session.patch.return_value = None session.post.return_value = None session.put.return_value = None return session def setUp(self): self.session = self.create_session_mock() self.instance = self.described_class(self.example_data, self.session) # Proxy the build_url method to the class so it can build the URL and # we can assert things about the call that will be attempted to the # internet self.described_class._build_url = build_url
Correct paths to database and translations
<?php namespace Niku\Cms; use Illuminate\Support\ServiceProvider; class CmsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // Register migrations $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); // Register translations $this->loadTranslationsFrom(__DIR__.'/../translations', 'niku-cms'); // Register config $this->publishes([ __DIR__.'/../config/'. 'niku-cms.php' => config_path('niku-cms.php'), ], 'niku-cms'); // Register Vue components $this->publishes([ __DIR__.'/../resources/assets/js/' => base_path('resources/assets/js/vendor/niku-cms'), __DIR__.'/../resources/assets/css/' => base_path('resources/assets/sass/vendor/niku-cms'), ], 'niku-cms'); // Register views $this->loadViewsFrom(__DIR__.'/../resources/views', 'niku-cms'); // Register copying views $this->publishes([ __DIR__.'/../resources/views' => resource_path('views/vendor/niku-cms'), ], 'niku-cms'); } /** * Register the application services. * * @return void */ public function register() { include __DIR__.'/routes.php'; } }
<?php namespace Niku\Cms; use Illuminate\Support\ServiceProvider; class CmsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // Register migrations $this->loadMigrationsFrom(__DIR__.'/database/migrations'); // Register translations $this->loadTranslationsFrom(__DIR__.'/translations', 'niku-cms'); // Register config $this->publishes([ __DIR__.'/../config/'. 'niku-cms.php' => config_path('niku-cms.php'), ], 'niku-cms'); // Register Vue components $this->publishes([ __DIR__.'/../resources/assets/js/' => base_path('resources/assets/js/vendor/niku-cms'), __DIR__.'/../resources/assets/css/' => base_path('resources/assets/sass/vendor/niku-cms'), ], 'niku-cms'); // Register views $this->loadViewsFrom(__DIR__.'/../resources/views', 'niku-cms'); // Register copying views $this->publishes([ __DIR__.'/../resources/views' => resource_path('views/vendor/niku-cms'), ], 'niku-cms'); } /** * Register the application services. * * @return void */ public function register() { include __DIR__.'/routes.php'; } }
Include subdirectories in pip install
import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'name': 'clouseau', 'description': 'A silly git repo inspector', 'long_description': None , # Needs to be restructed text # os.path.join(os.path.dirname(__file__), 'README.md').read() 'author': 'bill shelton', 'url': 'https://github.com/cfpb/clouseau', 'download_url': 'http://tbd.com', 'author_email': '[email protected]', 'version': '0.2.0', 'install_requires': ['jinja2','nose','nose-progressive'], 'packages': ['clouseau','tests'], 'package_data': {'clouseau': ['clients/*.py', 'patterns/*.txt', 'templates/*.html']}, 'py_modules': [], 'scripts': ['bin/clouseau', 'bin/clouseau_thin'], 'keywords': ['git', 'pii', 'security', 'search', 'sensitive information'], 'classifiers': [ 'Development Status :: -0 - Pre-Natal', 'Environment :: Console', 'Intended Audience :: Developers, Security Engineers', 'Programming Language: Python 2.7', 'Operating System :: OSX', 'Operating System :: Linux', ] } setup(**config)
import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'name': 'clouseau', 'description': 'A silly git repo inspector', 'long_description': None , # Needs to be restructed text # os.path.join(os.path.dirname(__file__), 'README.md').read() 'author': 'bill shelton', 'url': 'https://github.com/cfpb/clouseau', 'download_url': 'http://tbd.com', 'author_email': '[email protected]', 'version': '0.2.0', 'install_requires': ['jinja2','nose','nose-progressive'], 'packages': ['clouseau','tests'], 'py_modules': [], 'scripts': ['bin/clouseau', 'bin/clouseau_thin'], 'keywords': ['git', 'pii', 'security', 'search', 'sensitive information'], 'classifiers': [ 'Development Status :: -0 - Pre-Natal', 'Environment :: Console', 'Intended Audience :: Developers, Security Engineers', 'Programming Language: Python 2.7', 'Operating System :: OSX', 'Operating System :: Linux', ] } setup(**config)
Revert "travis? are you here?" This reverts commit a5a924a2df9ba4a47a4b3998a1495f8801668092.
<?php namespace Step\Acceptance; class EmailMan extends \AcceptanceTester { /** * Go to email settings */ public function gotoEmailSettings() { $I = new NavigationBar($this->getScenario()); $I->clickUserMenuItem('#admin_link'); $I->click('#mass_Email_config'); } /** * Populate email settings * * @param $name */ public function createEmailSettings() { $I = new NavigationBar($this->getScenario()); $EditView = new EditView($this->getScenario()); $faker = $this->getFaker(); $I->clickUserMenuItem('#admin_link'); $I->click('#mass_Email_config'); $I->fillField('#notify_fromname', $faker->name()); $I->fillField('#notify_fromaddress', $faker->email); $I->click('#gmail-button'); $I->checkOption('#mail_smtpauth_req'); $I->fillField('#mail_smtpuser', $faker->email); $I->executeJS('SUGAR.util.setEmailPasswordEdit(\'mail_smtppass\')'); $I->fillField('#mail_smtppass', $faker->email); $I->checkOption('#notify_allow_default_outbound'); $EditView->clickSaveButton(); } }
<?php namespace Step\Acceptance; class EmailMan extends \AcceptanceTester { /** * Go to email settings */ public function gotoEmailSettings() { $I = new NavigationBar($this->getScenario()); $I->clickUserMenuItem('#admin_link'); $I->click('#mass_Email_config'); } /** * Populate email settings * * @param $name */ public function createEmailSettings() { $I = new NavigationBar($this->getScenario()); $EditView = new EditView($this->getScenario()); $faker = $this->getFaker(); $I->clickUserMenuItem('#admin_link'); $I->click('#mass_Email_config'); $I->fillField('#notify_fromname', $faker->name()); $I->fillField('#notify_fromaddress', $faker->email); $I->click('#gmail-button'); $I->checkOption('#mail_smtpauth_req'); $I->fillField('#mail_smtpuser', $faker->email); $I->executeJS('SUGAR.util.setEmailPasswordEdit(\'mail_smtppass\')'); $I->fillField('#mail_smtppass', $faker->email); $I->checkOption('#notify_allow_default_outbound'); $EditView->clickSaveButton(); } }
Fix newline output of downloaded srt
from termcolor import colored from .parser import Addic7edParser from .file_crawler import FileCrawler from .logger import init_logger from .config import Config def addic7ed(): try: init_logger() Config.load() main() except (EOFError, KeyboardInterrupt, SystemExit): print(colored("\nBye!", "yellow")) exit(0) def main(): crawler = FileCrawler() parser = Addic7edParser() for filename, ep in crawler.episodes.items(): subs = parser.parse(**ep.infos) print(ep) if not subs: print(colored("No subtitles for %s" % filename, "red"), end="\n\n") continue for i, sub in enumerate(subs): print("[%s] %s" % (colored(i, "yellow"), sub)) if Config.dry_run: print() continue else: version = input('Download number? ') if not version: print(colored("Nothing to do!", "yellow"), end="\n\n") continue try: if Config.rename != "sub": filename = subs[int(version)].download() if filename and Config.rename == "video": print(ep.rename(filename)) else: filename = subs[int(version)].download("%s.srt" % ep.filename) print(colored("Downloaded %s subtitle file" % filename, "green"), end="\n\n") except Exception as e: print(colored(e, "red"), end="\n\n")
from termcolor import colored from .parser import Addic7edParser from .file_crawler import FileCrawler from .logger import init_logger from .config import Config def addic7ed(): try: init_logger() Config.load() main() except (EOFError, KeyboardInterrupt, SystemExit): print(colored("\nBye!", "yellow")) exit(0) def main(): crawler = FileCrawler() parser = Addic7edParser() for filename, ep in crawler.episodes.items(): subs = parser.parse(**ep.infos) print(ep) if not subs: print(colored("No subtitles for %s" % filename, "red"), end="\n\n") continue for i, sub in enumerate(subs): print("[%s] %s" % (colored(i, "yellow"), sub)) if Config.dry_run: print() continue else: version = input('Download number? ') if not version: print(colored("Nothing to do!", "yellow"), end="\n\n") continue try: if Config.rename != "sub": filename = subs[int(version)].download() if filename and Config.rename == "video": print(ep.rename(filename), end="\n\n") else: filename = subs[int(version)].download("%s.srt" % ep.filename) print(colored("Downloaded %s subtitle file" % filename, "green")) except Exception as e: print(colored(e, "red"), end="\n\n")
Remove default form submit behavior
"use strict"; var React = require('react'); module.exports = React.createClass({ displayName: 'Home', getInitialState: function(){ return {};//getStateFromStores(); }, render: function() { //var self = this; //var props = this.props; //var state = this.state; return React.DOM.div({className: 'home'}, [ React.DOM.form({ onSubmit: function(e){ e.preventDefault(); } }, [ // mode switch React.DOM.div({className: 'mode-switch'}, [ React.DOM.label({}, [ 'Je me sépare', React.DOM.input({ type: 'radio', id: 'give-away', name: 'give-search' }) ]), React.DOM.label({}, [ 'Je récupère', React.DOM.input({ type: 'radio', id: 'search-for', name: 'give-search' }) ]) ]), React.DOM.label({}, [ 'Quoi ? ', React.DOM.input({ type: 'text', id: 'what' }) ]), React.DOM.div({className: 'submit-group'}, [ React.DOM.button({ type: "submit" }, "Aller en déchèterie"), React.DOM.button({ type: "submit" }, "Voir les personnes qui cherchent (21)"), React.DOM.button({ type: "submit" }, "Déposer une annonce") ]) ]) ]) } });
"use strict"; var React = require('react'); module.exports = React.createClass({ displayName: 'Home', getInitialState: function(){ return {};//getStateFromStores(); }, render: function() { //var self = this; //var props = this.props; //var state = this.state; return React.DOM.div({className: 'home'}, [ React.DOM.form({}, [ // mode switch React.DOM.div({className: 'mode-switch'}, [ React.DOM.label({}, [ 'Je me sépare', React.DOM.input({ type: 'radio', id: 'give-away', name: 'give-search' }) ]), React.DOM.label({}, [ 'Je récupère', React.DOM.input({ type: 'radio', id: 'search-for', name: 'give-search' }) ]) ]), React.DOM.label({}, [ 'Quoi ? ', React.DOM.input({ type: 'text', id: 'what' }) ]), React.DOM.div({className: 'submit-group'}, [ React.DOM.button({ type: "submit" }, "Aller en déchèterie"), React.DOM.button({ type: "submit" }, "Voir les personnes qui cherchent (21)"), React.DOM.button({ type: "submit" }, "Déposer une annonce") ]) ]) ]) } });
Fix an error when number of predictor columns is less than max_features.
import numbers from sklearn.ensemble import RandomForestClassifier as RandomForest from sklearn.preprocessing import Imputer from numpy import isnan import Orange.data import Orange.classification def replace_nan(X, imp_model): # Default scikit Imputer # Use Orange imputer when implemented if isnan(X).sum(): X = imp_model.transform(X) return X class RandomForestLearner(Orange.classification.SklFitter): def __init__(self, n_estimators=10, max_features="auto", random_state=None, max_depth=3, max_leaf_nodes=5): self.params = vars() def fit(self, X, Y, W): self.imputer = Imputer() self.imputer.fit(X) X = replace_nan(X, self.imputer) params = dict(self.params) max_features = params["max_features"] if isinstance(max_features, numbers.Integral) and \ X.shape[1] < max_features: params["max_features"] = X.shape[1] rf_model = RandomForest(**params) rf_model.fit(X, Y.ravel()) return RandomForestClassifier(rf_model, self.imputer) class RandomForestClassifier(Orange.classification.SklModel): def __init__(self, clf, imp): self.clf = clf self.imputer = imp def predict(self, X): X = replace_nan(X, imp_model=self.imputer) value = self.clf.predict(X) prob = self.clf.predict_proba(X) return value, prob
# import numpy from sklearn.ensemble import RandomForestClassifier as RandomForest from sklearn.preprocessing import Imputer from numpy import isnan import Orange.data import Orange.classification def replace_nan(X, imp_model): # Default scikit Imputer # Use Orange imputer when implemented if isnan(X).sum(): X = imp_model.transform(X) return X # TODO: implement sending a single decision tree class RandomForestLearner(Orange.classification.SklFitter): def __init__(self, n_estimators=10, max_features="auto", random_state=None, max_depth=3, max_leaf_nodes=5): self.params = vars() def fit(self, X, Y, W): self.imputer = Imputer() self.imputer.fit(X) X = replace_nan(X, self.imputer) rf_model = RandomForest(**self.params) rf_model.fit(X, Y.ravel()) return RandomForestClassifier(rf_model, self.imputer) class RandomForestClassifier(Orange.classification.SklModel): def __init__(self, clf, imp): self.clf = clf self.imputer = imp def predict(self, X): X = replace_nan(X, imp_model=self.imputer) value = self.clf.predict(X) prob = self.clf.predict_proba(X) return value, prob
Add more information to the product sale track call
import db from '.'; import analytics from '../components/stats'; const trackProductUsage = transactionProduct => { let product = null; let customer = null; let transaction = null; db.Product.findOne({ where: { id: transactionProduct.productId } }) .then(result => { product = result; return result; }) .then(() => db.Transaction.findOne({ where: { id: transactionProduct.transactionId } }) ) .then(result => { if (result) { transaction = result; return result; } return Promise.resolve(); }) .then(() => transaction.getCustomer()) .then(result => { customer = result; return result; }) .then(() => { if (product && customer && transaction) { return analytics.track({ userId: customer.id, event: 'product_sale', properties: { systemId: product.systemId, username: customer.username, displayName: customer.displayName, sellerId: transaction.sellerId, transactionId: transaction.id, productId: product.id, name: product.name, type: product.type, count: Number(transactionProduct.count) }, context: { app: 'abacash' } }); } }); }; export default function(sequelize, DataTypes) { return sequelize.define('transactionProduct', { count: { type: DataTypes.INTEGER, allowNull: false } }, { hooks: { afterCreate: transactionProduct => trackProductUsage(transactionProduct), afterBulkCreate: transactionProducts => transactionProducts.map(transactionProduct => trackProductUsage(transactionProduct)) } }); }
import db from '.'; import analytics from '../components/stats'; const trackProductUsage = transactionProduct => { db.Product.findOne({ where: { id: transactionProduct.productId } }) .then(product => { if (product) { return analytics.track({ anonymousId: 'system', event: 'product_sale', properties: { productId: product.id, name: product.name, type: product.type, count: Number(transactionProduct.count) }, context: { app: 'abacash' } }); } }); }; export default function(sequelize, DataTypes) { return sequelize.define('transactionProduct', { count: { type: DataTypes.INTEGER, allowNull: false } }, { hooks: { afterCreate: transactionProduct => trackProductUsage(transactionProduct), afterBulkCreate: transactionProducts => transactionProducts.map(transactionProduct => trackProductUsage(transactionProduct)) } }); }
Add Check if the network exists
import { Window } from '../Util'; import _each from 'lodash/each'; export default class Share { /** * Share Constructor. * * @param {String} selector */ constructor(selector = 'data-social') { this.networks = {}; this.selector = selector; } /** * Register a (or multiple) new network. * * @param {String} network * @param {Object} instance */ register(network, instance) { if (typeof network === 'object') { return network.forEach((n, i) => this.register(n, i)); } this.networks[network] = instance; return this; } /** * Boot the map of social media networks. */ boot() { _each(this.networks, (Instance, network) => { this.networks[network] = new Instance(this); }); this.registerEvents(); } /** * Register the click event. */ registerEvents() { const elements = document.querySelectorAll(`[${this.selector}]`); _each(elements, element => { element.addEventListener('click', () => this.onClick(element)); }); } /** * Open the sharing window. * * @param {String} element */ onClick(element) { const network = this.networks[element.getAttribute(this.selector)]; if (network) { Window.open(network.url); } } }
import { Window } from '../Util'; import _each from 'lodash/each'; export default class Share { /** * Share Constructor. * * @param {String} selector */ constructor(selector = 'data-social') { this.networks = {}; this.selector = selector; } /** * Register a (or multiple) new network. * * @param {String} network * @param {Object} instance */ register(network, instance) { if (typeof network === 'object') { return network.forEach((n, i) => this.register(n, i)); } this.networks[network] = instance; return this; } /** * Boot the map of social media networks. */ boot() { _each(this.networks, (Instance, network) => { this.networks[network] = new Instance(this); }); this.registerEvents(); } /** * Register the click event. */ registerEvents() { const elements = document.querySelectorAll(`[${this.selector}]`); _each(elements, element => { element.addEventListener('click', () => this.onClick(element)); }); } /** * Open the sharing window. * * @param {String} element */ onClick(element) { const network = this.networks[element.getAttribute(this.selector)]; Window.open(network.url); } }
Remove unused import / stale comment
package org.commcare.android.adapters; import android.os.Parcel; import android.os.Parcelable; import android.view.View; /** * Created by jschweers on 9/2/2015. */ public class ListItemViewStriper implements ListItemViewModifier, Parcelable { private int mOddColor; private int mEvenColor; public ListItemViewStriper(int oddColor, int evenColor) { super(); mOddColor = oddColor; mEvenColor = evenColor; } protected ListItemViewStriper(Parcel in) { mOddColor = in.readInt(); mEvenColor = in.readInt(); } public static final Creator<ListItemViewStriper> CREATOR = new Creator<ListItemViewStriper>() { @Override public ListItemViewStriper createFromParcel(Parcel in) { return new ListItemViewStriper(in); } @Override public ListItemViewStriper[] newArray(int size) { return new ListItemViewStriper[size]; } }; @Override public void modify(View view, int position) { if (position % 2 == 0) { view.setBackgroundColor(mEvenColor); } else { view.setBackgroundColor(mOddColor); } } @Override public int describeContents() { return mOddColor ^ mEvenColor; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mOddColor); dest.writeInt(mEvenColor); } }
package org.commcare.android.adapters; import android.annotation.SuppressLint; import android.os.Parcel; import android.os.Parcelable; import android.view.View; /** * Created by jschweers on 9/2/2015. */ public class ListItemViewStriper implements ListItemViewModifier, Parcelable { private int mOddColor; private int mEvenColor; public ListItemViewStriper(int oddColor, int evenColor) { super(); mOddColor = oddColor; mEvenColor = evenColor; } protected ListItemViewStriper(Parcel in) { mOddColor = in.readInt(); mEvenColor = in.readInt(); } public static final Creator<ListItemViewStriper> CREATOR = new Creator<ListItemViewStriper>() { @Override public ListItemViewStriper createFromParcel(Parcel in) { return new ListItemViewStriper(in); } @Override public ListItemViewStriper[] newArray(int size) { return new ListItemViewStriper[size]; } }; @Override public void modify(View view, int position) { if (position % 2 == 0) { view.setBackgroundColor(mEvenColor); } else { view.setBackgroundColor(mOddColor); } } @Override public int describeContents() { return mOddColor ^ mEvenColor; } @Override public void writeToParcel(Parcel dest, int flags) { // do nothing dest.writeInt(mOddColor); dest.writeInt(mEvenColor); } }
Fix dangerous default mutable value
from flask_seguro.products import Products from flask import current_app as app class Cart: def __init__(self, cart_dict=None): cart_dict = cart_dict or {} if cart_dict == {}: self.total = 0 self.subtotal = 0 self.items = [] else: self.total = cart_dict["total"] self.subtotal = cart_dict["subtotal"] self.items = cart_dict["items"] self.extra_amount = float(app.config['EXTRA_AMOUNT']) def to_dict(self): return {"total": self.total, "subtotal": self.subtotal, "items": self.items, "extra_amount": self.extra_amount} def change_item(self, item_id, operation): product = Products().get_one(item_id) if product: if operation == 'add': self.items.append(product) elif operation == 'remove': cart_product = filter( lambda x: x['id'] == product['id'], self.items) self.items.remove(cart_product[0]) self.update() return True else: return False def update(self): subtotal = float(0) total = float(0) for product in self.items: subtotal += float(product["price"]) if subtotal > 0: total = subtotal + self.extra_amount self.subtotal = subtotal self.total = total
from flask_seguro.products import Products from flask import current_app as app class Cart: def __init__(self, cart_dict={}): if cart_dict == {}: self.total = 0 self.subtotal = 0 self.items = [] else: self.total = cart_dict["total"] self.subtotal = cart_dict["subtotal"] self.items = cart_dict["items"] self.extra_amount = float(app.config['EXTRA_AMOUNT']) def to_dict(self): return {"total": self.total, "subtotal": self.subtotal, "items": self.items, "extra_amount": self.extra_amount} def change_item(self, item_id, operation): product = Products().get_one(item_id) if product: if operation == 'add': self.items.append(product) elif operation == 'remove': cart_product = filter( lambda x: x['id'] == product['id'], self.items) self.items.remove(cart_product[0]) self.update() return True else: return False def update(self): subtotal = float(0) total = float(0) for product in self.items: subtotal += float(product["price"]) if subtotal > 0: total = subtotal + self.extra_amount self.subtotal = subtotal self.total = total
Rename `users` relationship to `members` to be a more accurate description
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Team extends Model { use SoftDeletes; /** * The attributes that are not mass assignable. * * @var array */ protected $guarded = [ 'id', 'deleted_at', 'created_at', 'updated_at' ]; /** * Get the Users that are members of this Team */ public function members() { return $this->belongsToMany('App\User'); } /** * Get all of the team's attendance. */ public function attendance() { return $this->morphMany('App\Attendance', 'attendable'); } /** * Scope a query to only include attendable teams * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeAttendable($query) { return $query->where('attendable', true); } /** * Scope a query to only include visible (non-hidden) teams * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeVisible($query) { return $query->where('hidden', false); } }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Team extends Model { use SoftDeletes; /** * The attributes that are not mass assignable. * * @var array */ protected $guarded = [ 'id', 'deleted_at', 'created_at', 'updated_at' ]; /** * Get the Users that are members of this Team */ public function users() { return $this->belongsToMany('App\User'); } /** * Get all of the team's attendance. */ public function attendance() { return $this->morphMany('App\Attendance', 'attendable'); } /** * Scope a query to only include attendable teams * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeAttendable($query) { return $query->where('attendable', true); } /** * Scope a query to only include visible (non-hidden) teams * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ public function scopeVisible($query) { return $query->where('hidden', false); } }
Allow user to save search result movies to favorites
package me.maxdev.popularmoviesapp.data; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import javax.inject.Inject; public class FavoritesService { private final Context context; @Inject public FavoritesService(Context context) { this.context = context.getApplicationContext(); } public void addToFavorites(Movie movie) { context.getContentResolver().insert(MoviesContract.MovieEntry.CONTENT_URI, movie.toContentValues()); ContentValues contentValues = new ContentValues(); contentValues.put(MoviesContract.COLUMN_MOVIE_ID_KEY, movie.getId()); context.getContentResolver().insert(MoviesContract.Favorites.CONTENT_URI, contentValues); } public void removeFromFavorites(Movie movie) { context.getContentResolver().delete( MoviesContract.Favorites.CONTENT_URI, MoviesContract.COLUMN_MOVIE_ID_KEY + " = " + movie.getId(), null ); } public boolean isFavorite(Movie movie) { boolean favorite = false; Cursor cursor = context.getContentResolver().query( MoviesContract.Favorites.CONTENT_URI, null, MoviesContract.COLUMN_MOVIE_ID_KEY + " = " + movie.getId(), null, null ); if (cursor != null) { favorite = cursor.getCount() != 0; cursor.close(); } return favorite; } }
package me.maxdev.popularmoviesapp.data; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import javax.inject.Inject; public class FavoritesService { private final Context context; @Inject public FavoritesService(Context context) { this.context = context.getApplicationContext(); } public void addToFavorites(Movie movie) { ContentValues contentValues = new ContentValues(); contentValues.put(MoviesContract.COLUMN_MOVIE_ID_KEY, movie.getId()); context.getContentResolver().insert(MoviesContract.Favorites.CONTENT_URI, contentValues); } public void removeFromFavorites(Movie movie) { context.getContentResolver().delete( MoviesContract.Favorites.CONTENT_URI, MoviesContract.COLUMN_MOVIE_ID_KEY + " = " + movie.getId(), null ); } public boolean isFavorite(Movie movie) { boolean favorite = false; Cursor cursor = context.getContentResolver().query( MoviesContract.Favorites.CONTENT_URI, null, MoviesContract.COLUMN_MOVIE_ID_KEY + " = " + movie.getId(), null, null ); if (cursor != null) { favorite = cursor.getCount() != 0; cursor.close(); } return favorite; } }
Set app requirements to Symfony 5
<?php declare(strict_types=1); /* * This file is part of SolidInvoice project. * * (c) Pierre du Plessis <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace SolidInvoice; use Symfony\Requirements\SymfonyRequirements; /** * @codeCoverageIgnore */ class AppRequirements extends SymfonyRequirements { public function __construct() { parent::__construct(dirname(__DIR__), '5.0.0'); $this->addRequirement( extension_loaded('openssl'), 'openssl must be loaded', 'Install and enable the <strong>Openssl</strong> extension.' ); $this->addRecommendation( extension_loaded('mbstring'), 'mbstring extension is required to generate PDF invoices and quotes', 'Install the PHP mbstring extension' ); $this->addRecommendation( extension_loaded('gd'), 'GD extension is required to generate PDF invoices and quotes', 'Install the PHP GD extension' ); } public function addRecommendation($fulfilled, $testMessage, $helpHtml, $helpText = null) { if ('PDO should be installed' === $testMessage || preg_match('#PDO should have some drivers installed#', $testMessage)) { return parent::addRequirement($fulfilled, $testMessage, $helpHtml, $helpText); } return parent::addRecommendation($fulfilled, $testMessage, $helpHtml, $helpText); } }
<?php declare(strict_types=1); /* * This file is part of SolidInvoice project. * * (c) Pierre du Plessis <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace SolidInvoice; use Symfony\Requirements\SymfonyRequirements; /** * @codeCoverageIgnore */ class AppRequirements extends SymfonyRequirements { public function __construct() { parent::__construct(dirname(__DIR__), '4.0.0'); $this->addRequirement( extension_loaded('openssl'), 'openssl must be loaded', 'Install and enable the <strong>Openssl</strong> extension.' ); $this->addRecommendation( extension_loaded('mbstring'), 'mbstring extension is required to generate PDF invoices and quotes', 'Install the PHP mbstring extension' ); $this->addRecommendation( extension_loaded('gd'), 'GD extension is required to generate PDF invoices and quotes', 'Install the PHP GD extension' ); } public function addRecommendation($fulfilled, $testMessage, $helpHtml, $helpText = null) { if ('PDO should be installed' === $testMessage || preg_match('#PDO should have some drivers installed#', $testMessage)) { return parent::addRequirement($fulfilled, $testMessage, $helpHtml, $helpText); } return parent::addRecommendation($fulfilled, $testMessage, $helpHtml, $helpText); } }
Fix for broken last version jquery destination
module.exports = function (grunt) { grunt.initConfig({ karma: { options: { basePath: '', frameworks: ['mocha', 'sinon-chai'], files: [ { pattern: 'spec/fixtures/*.html', included: true }, 'bower_components/jquery/dist/jquery.js', 'bower_components/modula/lib/modula.js', 'bower_components/sugar/release/sugar-full.development.js', 'bower_components/underscore/underscore.js', 'bower_components/backbone/backbone.js', 'src/vtree_src/nodes_cache.coffee', 'src/vtree_src/view_hooks.coffee', 'src/vtree_src/view_node.coffee', 'src/vtree_src/view_wrapper.coffee', 'src/vtree_src/tree_manager.coffee', 'src/vtree.coffee', 'spec/**/*_spec.coffee' ], exclude: [], reporters: ['progress'], port: 9876, colors: true, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: false, coffeePreprocessor: { options: { bare: false } } }, dev: { reporters: ['dots'] }, release: { singleRun: true }, ci: { singleRun: true, browsers: ['PhantomJS'] } } }); grunt.loadNpmTasks('grunt-karma'); };
module.exports = function (grunt) { grunt.initConfig({ karma: { options: { basePath: '', frameworks: ['mocha', 'sinon-chai'], files: [ { pattern: 'spec/fixtures/*.html', included: true }, 'bower_components/jquery/jquery.js', 'bower_components/modula/lib/modula.js', 'bower_components/sugar/release/sugar-full.development.js', 'bower_components/underscore/underscore.js', 'bower_components/backbone/backbone.js', 'src/vtree_src/nodes_cache.coffee', 'src/vtree_src/view_hooks.coffee', 'src/vtree_src/view_node.coffee', 'src/vtree_src/view_wrapper.coffee', 'src/vtree_src/tree_manager.coffee', 'src/vtree.coffee', 'spec/**/*_spec.coffee' ], exclude: [], reporters: ['progress'], port: 9876, colors: true, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: false, coffeePreprocessor: { options: { bare: false } } }, dev: { reporters: ['dots'] }, release: { singleRun: true }, ci: { singleRun: true, browsers: ['PhantomJS'] } } }); grunt.loadNpmTasks('grunt-karma'); };
Fix PHP 7.2 Compatibility Check
<?php namespace Mollie\Api; use Mollie\Api\Exceptions\IncompatiblePlatform; class CompatibilityChecker { /** * @var string */ public const MIN_PHP_VERSION = "7.2"; /** * @throws IncompatiblePlatform * @return void */ public function checkCompatibility() { if (! $this->satisfiesPhpVersion()) { throw new IncompatiblePlatform( "The client requires PHP version >= " . self::MIN_PHP_VERSION . ", you have " . PHP_VERSION . ".", IncompatiblePlatform::INCOMPATIBLE_PHP_VERSION ); } if (! $this->satisfiesJsonExtension()) { throw new IncompatiblePlatform( "PHP extension json is not enabled. Please make sure to enable 'json' in your PHP configuration.", IncompatiblePlatform::INCOMPATIBLE_JSON_EXTENSION ); } } /** * @return bool * @codeCoverageIgnore */ public function satisfiesPhpVersion() { return (bool)version_compare(PHP_VERSION, self::MIN_PHP_VERSION, ">="); } /** * @return bool * @codeCoverageIgnore */ public function satisfiesJsonExtension() { // Check by extension_loaded if (function_exists('extension_loaded') && extension_loaded('json')) { return true; } elseif (function_exists('json_encode')) { return true; } return false; } }
<?php namespace Mollie\Api; use Mollie\Api\Exceptions\IncompatiblePlatform; class CompatibilityChecker { /** * @var string */ public const MIN_PHP_VERSION = "7.0"; /** * @throws IncompatiblePlatform * @return void */ public function checkCompatibility() { if (! $this->satisfiesPhpVersion()) { throw new IncompatiblePlatform( "The client requires PHP version >= " . self::MIN_PHP_VERSION . ", you have " . PHP_VERSION . ".", IncompatiblePlatform::INCOMPATIBLE_PHP_VERSION ); } if (! $this->satisfiesJsonExtension()) { throw new IncompatiblePlatform( "PHP extension json is not enabled. Please make sure to enable 'json' in your PHP configuration.", IncompatiblePlatform::INCOMPATIBLE_JSON_EXTENSION ); } } /** * @return bool * @codeCoverageIgnore */ public function satisfiesPhpVersion() { return (bool)version_compare(PHP_VERSION, self::MIN_PHP_VERSION, ">="); } /** * @return bool * @codeCoverageIgnore */ public function satisfiesJsonExtension() { // Check by extension_loaded if (function_exists('extension_loaded') && extension_loaded('json')) { return true; } elseif (function_exists('json_encode')) { return true; } return false; } }
Return COMSPEC as the shell for Windows
# -*- coding: utf-8 -*- from __future__ import absolute_import # Import python libs import os # Import third party libs import yaml import logging # Import salt libs import salt.utils.files import salt.utils.platform log = logging.getLogger(__name__) def shell(): ''' Return the default shell to use on this system ''' # Provides: # shell if salt.utils.platform.is_windows(): env_var = 'COMSPEC' default = r'C:\Windows\system32\cmd.exe' else: env_var = 'SHELL' default = '/bin/sh' return {'shell': os.environ.get(env_var, default)} def config(): ''' Return the grains set in the grains file ''' if 'conf_file' not in __opts__: return {} if os.path.isdir(__opts__['conf_file']): gfn = os.path.join( __opts__['conf_file'], 'grains' ) else: gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'grains' ) if os.path.isfile(gfn): with salt.utils.files.fopen(gfn, 'rb') as fp_: try: return yaml.safe_load(fp_.read()) except Exception: log.warning("Bad syntax in grains file! Skipping.") return {} return {}
# -*- coding: utf-8 -*- from __future__ import absolute_import # Import python libs import os # Import third party libs import yaml import logging # Import salt libs import salt.utils.files log = logging.getLogger(__name__) def shell(): ''' Return the default shell to use on this system ''' # Provides: # shell return {'shell': os.environ.get('SHELL', '/bin/sh')} def config(): ''' Return the grains set in the grains file ''' if 'conf_file' not in __opts__: return {} if os.path.isdir(__opts__['conf_file']): gfn = os.path.join( __opts__['conf_file'], 'grains' ) else: gfn = os.path.join( os.path.dirname(__opts__['conf_file']), 'grains' ) if os.path.isfile(gfn): with salt.utils.files.fopen(gfn, 'rb') as fp_: try: return yaml.safe_load(fp_.read()) except Exception: log.warning("Bad syntax in grains file! Skipping.") return {} return {}
Fix order for 'first to complete' calculation
from optparse import make_option import sys from django.core.management.base import BaseCommand from challenge.models import Challenge, UserChallenge from resources.models import Resource from django.conf import settings from django.db.models import Avg, Max, Min, Count class Command(BaseCommand): args = "" help = "Update challenge total_questions and total_resources (post db import)" def handle(self, *args, **options): from wallextend.models import add_extended_wallitem challenges = Challenge.objects.filter(userchallenge__status=2).distinct() for challenge in challenges: userchallenge = challenge.userchallenge_set.order_by('completed')[0] add_extended_wallitem(challenge.wall,userchallenge.user,created_at=userchallenge.completed,template_name='challenge_1stcomplete.html',extra_context={ 'body':'is the first to complete!', 'challenge': challenge, 'userchallenge': userchallenge, })
from optparse import make_option import sys from django.core.management.base import BaseCommand from challenge.models import Challenge, UserChallenge from resources.models import Resource from django.conf import settings from django.db.models import Avg, Max, Min, Count class Command(BaseCommand): args = "" help = "Update challenge total_questions and total_resources (post db import)" def handle(self, *args, **options): from wallextend.models import add_extended_wallitem challenges = Challenge.objects.filter(userchallenge__status=2).distinct() for challenge in challenges: userchallenge = challenge.userchallenge_set.order_by('-completed')[0] add_extended_wallitem(challenge.wall,userchallenge.user,created_at=userchallenge.completed,template_name='challenge_1stcomplete.html',extra_context={ 'body':'is the first to complete!', 'challenge': challenge, 'userchallenge': userchallenge, })
Send data using traces format to realtime analysis.
'use strict'; var sessions = require('../sessions'); var kafkaConsumer = function (kafkaConfig) { var kafka = require('../services/kafka')(kafkaConfig.uri); var players = require('../players'); return { addTraces: function (playerId, versionId, gameplayId, data) { return sessions.find({ versionId: sessions.toObjectID(versionId), start : { $ne : null }, end: null }, false).then(function (sessions) { if (!sessions) { return false; } return players.findById(playerId) .then(function (player) { if (!player) { return false; } var allowedSessions = []; for (var i = 0; i < sessions.length; ++i) { var session = sessions[i]; if (!session.allowAnonymous) { if (!session.students || session.students.indexOf(player.name) === -1) { continue; } } allowedSessions.push(session._id.toString()); } if (allowedSessions.length > 0) { var traces = []; for(i = 0; i < data.length; ++i) { traces.push(data[i].object.definition.extensions); } var promises = []; for (i = 0; i < allowedSessions.length; ++i) { promises.push(kafka.send(allowedSessions[i], traces)); } return promises; } return false; }); }); } }; }; module.exports = kafkaConsumer;
'use strict'; var sessions = require('../sessions'); var kafkaConsumer = function (kafkaConfig) { var kafka = require('../services/kafka')(kafkaConfig.uri); var players = require('../players'); return { addTraces: function (playerId, versionId, gameplayId, data) { return sessions.find({ versionId: sessions.toObjectID(versionId), end: null }, false).then(function (sessions) { if (!sessions) { return false; } return players.findById(playerId) .then(function(player) { if(!player) { return false; } var promises = []; for(var i = 0; i < sessions.length; ++i) { var session = sessions[i]; if(!session.allowAnonymous) { if (!session.students || session.students.indexOf(player.name) === -1) { continue; } } promises.push(kafka.send(session._id.toString(), data)); } return promises; }); }); } }; }; module.exports = kafkaConsumer;
Replace class with new name.
<?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\Bundle\FrameworkBundle\Test; use Symfony\Bundle\FrameworkBundle\KernelBrowser; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; /** * WebTestCase is the base class for functional tests. * * @author Fabien Potencier <[email protected]> */ abstract class WebTestCase extends KernelTestCase { /** * Creates a KernelBrowser. * * @param array $options An array of options to pass to the createKernel method * @param array $server An array of server parameters * * @return KernelBrowser A KernelBrowser instance */ protected static function createClient(array $options = [], array $server = []) { $kernel = static::bootKernel($options); try { $client = $kernel->getContainer()->get('test.client'); } catch (ServiceNotFoundException $e) { if (class_exists(KernelBrowser::class)) { throw new \LogicException('You cannot create the client used in functional tests if the "framework.test" config is not set to true.'); } throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit"'); } $client->setServerParameters($server); return $client; } }
<?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\Bundle\FrameworkBundle\Test; use Symfony\Bundle\FrameworkBundle\KernelBrowser; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; /** * WebTestCase is the base class for functional tests. * * @author Fabien Potencier <[email protected]> */ abstract class WebTestCase extends KernelTestCase { /** * Creates a KernelBrowser. * * @param array $options An array of options to pass to the createKernel method * @param array $server An array of server parameters * * @return KernelBrowser A KernelBrowser instance */ protected static function createClient(array $options = [], array $server = []) { $kernel = static::bootKernel($options); try { $client = $kernel->getContainer()->get('test.client'); } catch (ServiceNotFoundException $e) { if (class_exists(Client::class)) { throw new \LogicException('You cannot create the client used in functional tests if the "framework.test" config is not set to true.'); } throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit"'); } $client->setServerParameters($server); return $client; } }
:white_check_mark: Delete user after dashboard test
<?php namespace Tests\Feature; use Tests\TestCase; use App\User; class StatusTest extends TestCase { /** * Test the home page returns a 200 status code (OK) * * @return void */ public function testHomePage() { $response = $this->get('/'); $response->assertStatus(200); } /** * Test the login page redirects to GitHub * * @return void */ public function testLoginPage() { $response = $this->get('login'); parse_str(parse_url($response->headers->get('location'))['query'], $query); $response->assertRedirect('https://github.com/login/oauth/authorize?client_id='.env('GITHUB_ID').'&scope=user%3Aemail%2Cadmin%3Aorg&redirect_uri='.env('GITHUB_CALLBACK').'&response_type=code&state='.$query['state']); } /** * Test the dashboard page redirects to login * * @return void */ public function testDashboardAuth() { $response = $this->get('dashboard'); $response->assertRedirect('login'); } /** * Test the dashboard returns a 200 status code when logged in (OK) * * @return void */ public function testDashboard() { $user = factory(User::class)->create(); $response = $this->actingAs($user) ->get('dashboard'); $response->assertStatus(200); $user->delete(); } }
<?php namespace Tests\Feature; use Tests\TestCase; use App\User; class StatusTest extends TestCase { /** * Test the home page returns a 200 status code (OK) * * @return void */ public function testHomePage() { $response = $this->get('/'); $response->assertStatus(200); } /** * Test the login page redirects to GitHub * * @return void */ public function testLoginPage() { $response = $this->get('login'); parse_str(parse_url($response->headers->get('location'))['query'], $query); $response->assertRedirect('https://github.com/login/oauth/authorize?client_id='.env('GITHUB_ID').'&scope=user%3Aemail%2Cadmin%3Aorg&redirect_uri='.env('GITHUB_CALLBACK').'&response_type=code&state='.$query['state']); } /** * Test the dashboard page redirects to login * * @return void */ public function testDashboardAuth() { $response = $this->get('dashboard'); $response->assertRedirect('login'); } /** * Test the dashboard returns a 200 status code when logged in (OK) * * @return void */ public function testDashboard() { $user = factory(User::class)->create(); $response = $this->actingAs($user) ->get('dashboard'); $response->assertStatus(200); } }
Sort tests, to verify they are complete Signed-off-by: Stefan Marr <[email protected]>
import unittest from parameterized import parameterized from som.vm.universe import Universe class SomTest(unittest.TestCase): @parameterized.expand([ ("Array" ,), ("Block" ,), ("ClassLoading" ,), ("ClassStructure",), ("Closure" ,), ("Coercion" ,), ("CompilerReturn",), ("DoesNotUnderstand",), ("Double" ,), ("Empty" ,), ("Global" ,), ("Hash" ,), ("Integer" ,), ("Preliminary" ,), ("Reflection" ,), ("SelfBlock" ,), ("SpecialSelectors",), ("Super" ,), ("Set",), ("String" ,), ("Symbol" ,), ("System" ,), ("Vector" ,)]) def test_som_test(self, test_name): args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name] u = Universe(True) u.interpret(args) self.assertEquals(0, u.last_exit_code()) import sys if 'pytest' in sys.modules: # hack to make pytest not to collect the unexpanded test method delattr(SomTest, "test_som_test")
import unittest from parameterized import parameterized from som.vm.universe import Universe class SomTest(unittest.TestCase): @parameterized.expand([ ("ClassStructure",), ("Array" ,), ("Block" ,), ("ClassLoading" ,), ("Closure" ,), ("Coercion" ,), ("CompilerReturn",), ("Double" ,), ("DoesNotUnderstand",), ("Empty" ,), ("Global" ,), ("Hash" ,), ("Integer" ,), ("Preliminary" ,), ("Reflection" ,), ("SelfBlock" ,), ("Set",), ("SpecialSelectors",), ("Super" ,), ("String" ,), ("Symbol" ,), ("System" ,), ("Vector" ,)]) def test_som_test(self, test_name): args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name] u = Universe(True) u.interpret(args) self.assertEquals(0, u.last_exit_code()) import sys if 'pytest' in sys.modules: # hack to make pytest not to collect the unexpanded test method delattr(SomTest, "test_som_test")
Move configuration details to docs
""" homeassistant.components.device_tracker.owntracks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OwnTracks platform for the device tracker. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.owntracks.html """ import json import logging import homeassistant.components.mqtt as mqtt DEPENDENCIES = ['mqtt'] LOCATION_TOPIC = 'owntracks/+/+' def setup_scanner(hass, config, see): """ Set up a OwnTracksks tracker. """ def owntracks_location_update(topic, payload, qos): """ MQTT message received. """ # Docs on available data: # http://owntracks.org/booklet/tech/json/#_typelocation try: data = json.loads(payload) except ValueError: # If invalid JSON logging.getLogger(__name__).error( 'Unable to parse payload as JSON: %s', payload) return if not isinstance(data, dict) or data.get('_type') != 'location': return parts = topic.split('/') kwargs = { 'dev_id': '{}_{}'.format(parts[1], parts[2]), 'host_name': parts[1], 'gps': (data['lat'], data['lon']), } if 'acc' in data: kwargs['gps_accuracy'] = data['acc'] if 'batt' in data: kwargs['battery'] = data['batt'] see(**kwargs) mqtt.subscribe(hass, LOCATION_TOPIC, owntracks_location_update, 1) return True
""" homeassistant.components.device_tracker.owntracks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OwnTracks platform for the device tracker. device_tracker: platform: owntracks """ import json import logging import homeassistant.components.mqtt as mqtt DEPENDENCIES = ['mqtt'] LOCATION_TOPIC = 'owntracks/+/+' def setup_scanner(hass, config, see): """ Set up a OwnTracksks tracker. """ def owntracks_location_update(topic, payload, qos): """ MQTT message received. """ # Docs on available data: # http://owntracks.org/booklet/tech/json/#_typelocation try: data = json.loads(payload) except ValueError: # If invalid JSON logging.getLogger(__name__).error( 'Unable to parse payload as JSON: %s', payload) return if not isinstance(data, dict) or data.get('_type') != 'location': return parts = topic.split('/') kwargs = { 'dev_id': '{}_{}'.format(parts[1], parts[2]), 'host_name': parts[1], 'gps': (data['lat'], data['lon']), } if 'acc' in data: kwargs['gps_accuracy'] = data['acc'] if 'batt' in data: kwargs['battery'] = data['batt'] see(**kwargs) mqtt.subscribe(hass, LOCATION_TOPIC, owntracks_location_update, 1) return True
Move signup form before login for responsive screens
import React, { Component } from 'react'; import SignupForm from './SignupForm'; import LoginForm from '../common/LoginForm'; class Intro extends Component { render() { return ( <div className="intro-section"> <div className="container"> <div className="row"> <div className="col-lg-6 col-md-6 col-sm-6 col-lg-offset-3 col-md-offset-3 col-sm-offset-3"> <div className="container form-container well text-center"> <h4>Μίλα ανώνυμα με άλλους φοιτητές</h4> <hr/> <SignupForm /> </div> <div className="container form-container well text-center" id="login-form"> <h4>Σύνδεση</h4> <hr/> <LoginForm /> </div> </div> </div> </div> </div> ); } } export default Intro;
import React, { Component } from 'react'; import SignupForm from './SignupForm'; import LoginForm from '../common/LoginForm'; class Intro extends Component { render() { return ( <div className="intro-section"> <div className="container"> <div className="row"> <div className="col-lg-6 col-md-6 col-sm-6 col-lg-offset-3 col-md-offset-3 col-sm-offset-3"> <div className="container form-container well text-center" id="login-form"> <h4>Σύνδεση</h4> <hr/> <LoginForm /> </div> <div className="container form-container well text-center"> <h4>Εγγραφή</h4> <hr/> <SignupForm /> </div> </div> </div> </div> </div> ); } } export default Intro;
Send all sensor data to Azure IoTHub
var GrovePi = require('node-grovepi').GrovePi; var GrovePiSensors = require('./GrovePiSensors'); var Commands = GrovePi.commands; var Board = GrovePi.board; var DeviceCommunication = require('./DeviceCommunication'); var deviceCommunication = new DeviceCommunication(onInit = () => { var board = new Board({ debug: true, onError: function (err) { console.log('!!!! Error occurred !!!!') console.log(err) }, onInit: function (res) { if (res) { console.log('GrovePi Version :: ' + board.version()) var grovePiSensors = new GrovePiSensors(); while (true) { var sensorsData = grovePiSensors.getAllSensorsData(); var dataToSend = JSON.stringify({ deviceId: 'vunvulearaspberry', msgType: sensorData, sensorInf:{ temp: sensorsData.temp, humidity: sensorsData.humidity, distance: sensorsData.distance, light: sensorsData.light } }); deviceCommunication.sendMessage(dataToSend); } } } }) board.init(); });
var GrovePi = require('node-grovepi').GrovePi; var GrovePiSensors = require('./GrovePiSensors'); var Commands = GrovePi.commands; var Board = GrovePi.board; var DeviceCommunication = require('./DeviceCommunication'); var deviceCommunication = new DeviceCommunication(onInit = () => { var board = new Board({ debug: true, onError: function (err) { console.log('!!!! Error occurred !!!!') console.log(err) }, onInit: function (res) { if (res) { console.log('GrovePi Version :: ' + board.version()) var grovePiSensors = new GrovePiSensors(); while (true) { var sensorsData = grovePiSensors.getAllSensorsData(); var dataToSend = JSON.stringify({ deviceId: 'vunvulearaspberry', temperature: sensorsData.temp }); deviceCommunication.sendMessage(dataToSend); } } } }) board.init(); });
Fix mobile and wifi check logic
package com.breadwallet.tools.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * Created by byfieldj on 2/15/18. * <p> * <p> * Reusable class to quick check whether user is connect to Wifi or mobile data */ public class BRConnectivityStatus { private Context mContext; public static final int NO_NETWORK = 0; public static final int WIFI_ON = 1; public static final int MOBILE_ON = 2; public static final int MOBILE_WIFI_ON = 3; public BRConnectivityStatus(Context context) { this.mContext = context; } // Returns true if connected to wifi, false if connected to mobile data public int isMobileDataOrWifiConnected() { ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netinfo = cm.getActiveNetworkInfo(); if (netinfo != null && netinfo.isConnectedOrConnecting()) { android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); // Mobile Data is on only if ((mobile != null && mobile.isConnectedOrConnecting()) && (wifi == null || !wifi.isConnectedOrConnecting())) { return MOBILE_ON; // Wifi is on only } else if (wifi != null && wifi.isConnectedOrConnecting() && (mobile == null || !mobile.isConnectedOrConnecting())) { return WIFI_ON; // Both mobile and wifi is on } else if (mobile != null && wifi != null && mobile.isConnectedOrConnecting() && wifi.isConnectedOrConnecting()) { return MOBILE_WIFI_ON; } } return NO_NETWORK; } }
package com.breadwallet.tools.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * Created by byfieldj on 2/15/18. * <p> * <p> * Reusable class to quick check whether user is connect to Wifi or mobile data */ public class BRConnectivityStatus { private Context mContext; public BRConnectivityStatus(Context context) { this.mContext = context; } // Returns true if connected to wifi, false if connected to mobile data public boolean isWifiOrMobileDataConntected() { ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netinfo = cm.getActiveNetworkInfo(); if (netinfo != null && netinfo.isConnectedOrConnecting()) { android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) { return true; } else { return false; } } else { return false; } } }
Add docstrings in Delegated class
from .base import AuthenticationBase class Delegated(AuthenticationBase): """Delegated authentication endpoints. Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def __init__(self, domain): self.domain = domain def get_token(self, client_id, target, api_type, grant_type, id_token=None, refresh_token=None): """Obtain a delegation token. """ if id_token and refresh_token: raise ValueError('Only one of id_token or refresh_token ' 'can be None') data = { 'client_id': client_id, 'grant_type': grant_type, 'target': target, 'scope': 'openid', 'api_type': api_type, } if id_token: data.update({'id_token': id_token}) elif refresh_token: data.update({'refresh_token': refresh_token}) else: raise ValueError('Either id_token or refresh_token must ' 'have a value') return self.post( 'https://%s/delegation' % self.domain, headers={'Content-Type': 'application/json'}, data=data )
from .base import AuthenticationBase class Delegated(AuthenticationBase): def __init__(self, domain): self.domain = domain def get_token(self, client_id, target, api_type, grant_type, id_token=None, refresh_token=None): if id_token and refresh_token: raise ValueError('Only one of id_token or refresh_token ' 'can be None') data = { 'client_id': client_id, 'grant_type': grant_type, 'target': target, 'scope': 'openid', 'api_type': api_type, } if id_token: data.update({'id_token': id_token}) elif refresh_token: data.update({'refresh_token': refresh_token}) else: raise ValueError('Either id_token or refresh_token must ' 'have a value') return self.post( 'https://%s/delegation' % self.domain, headers={'Content-Type': 'application/json'}, data=data )
Add logout url and regirect to main page after successful login.
package bj.pranie.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import javax.sql.DataSource; /** * Created by Sebastian Sokolowski on 13.10.16. */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired CustomAuthenticationProvider customAuthenticationProvider; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/logout", "/week", "/week/*", "/wm/*/*/*/*", "/user/registration", "/user/restore", "/images/*", "/js/*").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/week") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .permitAll(); } @Autowired @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(customAuthenticationProvider); } }
package bj.pranie.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import javax.sql.DataSource; /** * Created by Sebastian Sokolowski on 13.10.16. */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired CustomAuthenticationProvider customAuthenticationProvider; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/week", "/week/*", "/wm/*/*/*/*", "/user/registration", "/user/restore", "/images/*", "/js/*").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/week") .permitAll() .and() .logout() .permitAll(); } @Autowired @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(customAuthenticationProvider); } }
Change in the implementation of normal distribution
import numpy class dist: normal, random = range(2) # Monte carlo simulation data def montecarlo(callback, samples, **kwargs): """ generate random samples based on values """ vals = {} for var in kwargs: if isinstance(kwargs[var], tuple): (minVal, maxVal, distribution) = kwargs[var] if distribution == dist.normal: vals[var] = normal(samples, minVal, maxVal) elif distribution == dist.random: if isinstance(minVal, float) or isinstance(maxVal, float): vals[var] = randomFloat(samples, minVal, maxVal) else: vals[var] = randomInt(samples, minVal, maxVal) else: vals[var] = kwargs[var] for i in xrange(samples): callVals = {} for var in vals: if isinstance(vals[var], numpy.ndarray): callVals[var] = vals[var][i] else: callVals[var] = vals[var] callback(**callVals) def normal(samples, minVal, maxVal): # Normal distribution from 0 to 2 distribution = numpy.random.standard_normal(samples) + 1 # From 0 to (maxVal - minVal) distribution *= (maxVal - minVal) / 2. # From minVal to maxVal distribution += minVal return distribution def randomFloat(samples, minVal, maxVal): return numpy.random.uniform(minVal, maxVal, samples) def randomInt(samples, minVal, maxVal): return numpy.random.randint(minVal, maxVal, samples)
import numpy class dist: normal, random = range(2) # Monte carlo simulation data def montecarlo(callback, samples, **kwargs): """ generate random samples based on values """ vals = {} for var in kwargs: if isinstance(kwargs[var], tuple): (minVal, maxVal, distribution) = kwargs[var] if distribution == dist.normal: vals[var] = normal(samples, minVal, maxVal) elif distribution == dist.random: if isinstance(minVal, float) or isinstance(maxVal, float): vals[var] = randomFloat(samples, minVal, maxVal) else: vals[var] = randomInt(samples, minVal, maxVal) else: vals[var] = kwargs[var] for i in xrange(samples): callVals = {} for var in vals: if isinstance(vals[var], numpy.ndarray): callVals[var] = vals[var][i] else: callVals[var] = vals[var] callback(**callVals) def normal(samples, minVal, maxVal): mean = (maxVal + minVal) / 2. deviation = (mean - minVal) / 3. return numpy.random.normal(mean, deviation, samples) def randomFloat(samples, minVal, maxVal): return numpy.random.uniform(minVal, maxVal, samples) def randomInt(samples, minVal, maxVal): return numpy.random.randint(minVal, maxVal, samples)
Fix commander fragment using wrong fragment manager
package fr.corenting.edcompanion.fragments; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.BindView; import butterknife.ButterKnife; import fr.corenting.edcompanion.R; import fr.corenting.edcompanion.adapters.CommanderFragmentPagerAdapter; public class CommanderFragment extends Fragment { public static final String COMMANDER_FRAGMENT = "commander_fragment"; @BindView(R.id.viewPager) public ViewPager viewPager; @BindView(R.id.tabLayout) public TabLayout tabLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_commander, container, false); ButterKnife.bind(this, v); // Setup tablayout and viewpager viewPager.setAdapter(new CommanderFragmentPagerAdapter(getChildFragmentManager(), getContext())); tabLayout.setupWithViewPager(viewPager); // Style tabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); tabLayout.setTabTextColors(getResources().getColor(R.color.tabTextSelected), getResources().getColor(R.color.tabText)); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } }
package fr.corenting.edcompanion.fragments; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.BindView; import butterknife.ButterKnife; import fr.corenting.edcompanion.R; import fr.corenting.edcompanion.adapters.CommanderFragmentPagerAdapter; public class CommanderFragment extends Fragment { public static final String COMMANDER_FRAGMENT = "commander_fragment"; @BindView(R.id.viewPager) public ViewPager viewPager; @BindView(R.id.tabLayout) public TabLayout tabLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_commander, container, false); ButterKnife.bind(this, v); // Setup tablayout and viewpager viewPager.setAdapter(new CommanderFragmentPagerAdapter(getFragmentManager(), getContext())); tabLayout.setupWithViewPager(viewPager); // Style tabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); tabLayout.setTabTextColors(getResources().getColor(R.color.tabTextSelected), getResources().getColor(R.color.tabText)); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } }
Change description for help and version
package com.crowdin.cli.commands.parts; import com.crowdin.cli.utils.MessageSource; import com.crowdin.cli.utils.Utils; import picocli.CommandLine; import java.util.ResourceBundle; @CommandLine.Command( name = "crowdin", versionProvider = Command.VersionProvider.class, synopsisHeading = "%n@|underline SYNOPSIS|@:%n", descriptionHeading = "%n@|underline DESCRIPTION|@:%n", parameterListHeading = "%n@|underline PARAMETERS|@:%n", optionListHeading = "%n@|underline OPTIONS|@:%n", commandListHeading = "%n@|underline COMMANDS|@:%n", usageHelpAutoWidth = true ) public abstract class Command implements Runnable { @CommandLine.Option(names = {"-V", "--version"}, versionHelp = true, description = "Print version information and exit") boolean versionInfoRequested; @CommandLine.Option(names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit") boolean usageHelpRequested; @CommandLine.Option(names = {"--no-progress"}, description = "Disable progress on executing command") protected boolean noProgress; @CommandLine.Option(names = {"-v", "--verbose"}, description = "Provide more information on the command processing") protected boolean isVerbose; @CommandLine.Option(names = {"--debug"}, hidden = true) protected boolean debug; protected static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE; @Override public void run() { } public static class VersionProvider implements CommandLine.IVersionProvider { @Override public String[] getVersion() throws Exception { return new String[] {Utils.getAppVersion()}; } } }
package com.crowdin.cli.commands.parts; import com.crowdin.cli.utils.MessageSource; import com.crowdin.cli.utils.Utils; import picocli.CommandLine; import java.util.ResourceBundle; @CommandLine.Command( name = "crowdin", versionProvider = Command.VersionProvider.class, mixinStandardHelpOptions = true, synopsisHeading = "%n@|underline SYNOPSIS|@:%n", descriptionHeading = "%n@|underline DESCRIPTION|@:%n", parameterListHeading = "%n@|underline PARAMETERS|@:%n", optionListHeading = "%n@|underline OPTIONS|@:%n", commandListHeading = "%n@|underline COMMANDS|@:%n", usageHelpAutoWidth = true ) public abstract class Command implements Runnable { @CommandLine.Option(names = {"--no-progress"}, description = "Disable progress on executing command") protected boolean noProgress; @CommandLine.Option(names = {"-v", "--verbose"}, description = "Provide more information on the command processing") protected boolean isVerbose; @CommandLine.Option(names = {"--debug"}, hidden = true) protected boolean debug; protected static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE; @Override public void run() { } public static class VersionProvider implements CommandLine.IVersionProvider { @Override public String[] getVersion() throws Exception { return new String[] {Utils.getAppVersion()}; } } }
Throw a ValueError if we get a non-JID for the JID
import os import json import datetime from pupa.core import db from pupa.models import Organization from pupa.models.utils import DatetimeValidator from pupa.models.schemas.jurisdiction import schema as jurisdiction_schema def import_jurisdiction(org_importer, jurisdiction): obj = jurisdiction.get_db_object() obj['_type'] = 'jurisdiction' obj['_id'] = jurisdiction.jurisdiction_id if not obj['_id'].startswith("ocd-jurisdiction/"): raise ValueError("The Jurisdiction appears to have an ID that does not" " begin with 'ocd-jurisdiction'. I found '%s'" % ( jurisdiction.jurisdiction_id)) obj['latest_update'] = datetime.datetime.utcnow() # validate jurisdiction validator = DatetimeValidator() try: validator.validate(obj, jurisdiction_schema) except ValueError as ve: raise ve db.jurisdictions.save(obj) # create organization(s) (TODO: if there are multiple chambers this isn't right) org = Organization(name=jurisdiction.name, classification='legislature', jurisdiction_id=jurisdiction.jurisdiction_id) if jurisdiction.other_names: org.other_names = jurisdiction.other_names if jurisdiction.parent_id: org.parent_id = jurisdiction.parent_id org_importer.import_object(org) # create parties for party in jurisdiction.parties: org = Organization(**{'classification': 'party', 'name': party['name'], 'parent_id': None}) org_importer.import_object(org)
import os import json import datetime from pupa.core import db from pupa.models import Organization from pupa.models.utils import DatetimeValidator from pupa.models.schemas.jurisdiction import schema as jurisdiction_schema def import_jurisdiction(org_importer, jurisdiction): obj = jurisdiction.get_db_object() obj['_type'] = 'jurisdiction' obj['_id'] = jurisdiction.jurisdiction_id obj['latest_update'] = datetime.datetime.utcnow() # validate jurisdiction validator = DatetimeValidator() try: validator.validate(obj, jurisdiction_schema) except ValueError as ve: raise ve db.jurisdictions.save(obj) # create organization(s) (TODO: if there are multiple chambers this isn't right) org = Organization(name=jurisdiction.name, classification='legislature', jurisdiction_id=jurisdiction.jurisdiction_id) if jurisdiction.other_names: org.other_names = jurisdiction.other_names if jurisdiction.parent_id: org.parent_id = jurisdiction.parent_id org_importer.import_object(org) # create parties for party in jurisdiction.parties: org = Organization(**{'classification': 'party', 'name': party['name'], 'parent_id': None}) org_importer.import_object(org)
Make approved fields nullable and remigrate
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateWorksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('works', function(Blueprint $table) { $table->increments('workID'); $table->integer('catID')->unsigned(); $table->integer('typeID')->unsigned(); $table->string('url',1000); $table->jsonb('info'); $table->hstore('tags'); $table->boolean('approved'); $table->integer('subID')->unsigned(); $table->integer('appID')->unsigned()->nullable(); $table->dateTime('subDate'); $table->dateTime('appDate')->nullable(); $table->softDeletes(); $table->timestamps(); // $table->foreign('catID')->references('catID')->on('categories'); // $table->foreign('infoID')->references('infoID')->on('info'); // $table->foreign('subID')->references('userID')->on('users'); // $table->foreign('appID')->references('userID')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::dropIfExists('works'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateWorksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('works', function(Blueprint $table) { $table->increments('workID'); $table->integer('catID')->unsigned(); $table->integer('typeID')->unsigned(); $table->string('url',1000); $table->jsonb('info'); $table->hstore('tags'); $table->boolean('approved'); $table->integer('subID')->unsigned(); $table->integer('appID')->unsigned(); $table->dateTime('subDate'); $table->dateTime('appDate'); $table->softDeletes(); $table->timestamps(); // $table->foreign('catID')->references('catID')->on('categories'); // $table->foreign('infoID')->references('infoID')->on('info'); // $table->foreign('subID')->references('userID')->on('users'); // $table->foreign('appID')->references('userID')->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::dropIfExists('works'); } }
Make hive_primary_DIMENSION.id primary key, so autoincrement works.
""" HiveDB client access via SQLAlchemy """ import sqlalchemy as sq metadata = sq.MetaData() hive_primary = sq.Table( 'hive_primary_DIMENSION', metadata, sq.Column('id', sq.Integer, primary_key=True), sq.Column('node', sq.SmallInteger, nullable=False, index=True, ), sq.Column('secondary_index_count', sq.Integer, nullable=False), # Hive_ERD.png says "date", but I think you want time too sq.Column('last_updated', sq.DateTime, nullable=False, index=True, ), sq.Column('read_only', sq.Boolean, nullable=False, default=False), sq.UniqueConstraint('id', 'node'), ) hive_secondary = sq.Table( 'hive_secondary_RESOURCE_COLUMN', metadata, sq.Column('id', sq.Integer, nullable=True, index=True, ), sq.Column('pkey', sq.Integer, sq.ForeignKey("hive_primary_TODO.id"), nullable=False, index=True, ), ) def dynamic_table(table, metadata, name): """ Access C{table} under new C{metadata} with new C{name}. """ new = metadata.tables.get(name, None) if new is not None: return new new = sq.Table( name, metadata, *[c.copy() for c in table.columns]) return new
""" HiveDB client access via SQLAlchemy """ import sqlalchemy as sq metadata = sq.MetaData() hive_primary = sq.Table( 'hive_primary_DIMENSION', metadata, sq.Column('id', sq.Integer, nullable=False, index=True, ), sq.Column('node', sq.SmallInteger, nullable=False, index=True, ), sq.Column('secondary_index_count', sq.Integer, nullable=False), # Hive_ERD.png says "date", but I think you want time too sq.Column('last_updated', sq.DateTime, nullable=False, index=True, ), sq.Column('read_only', sq.Boolean, nullable=False, default=False), sq.UniqueConstraint('id', 'node'), ) hive_secondary = sq.Table( 'hive_secondary_RESOURCE_COLUMN', metadata, sq.Column('id', sq.Integer, nullable=True, index=True, ), sq.Column('pkey', sq.Integer, sq.ForeignKey("hive_primary_TODO.id"), nullable=False, index=True, ), ) def dynamic_table(table, metadata, name): """ Access C{table} under new C{metadata} with new C{name}. """ new = metadata.tables.get(name, None) if new is not None: return new new = sq.Table( name, metadata, *[c.copy() for c in table.columns]) return new
Load clients and impostors data
import argparse import numpy def load_default(): print "TODO: load default scores" return None, None def get_data(): """ Get scores data. If there are no arguments in command line load default """ parser = argparse.ArgumentParser(description="Solve the ROC curve") parser.add_argument("-c", "--clients", type=argparse.FileType('r'), help="Clients filename", metavar="C", dest="clients_file") parser.add_argument("-i", "--impersonators", type=argparse.FileType('r'), help="Impersonators filename", metavar="I", dest="impersonators_file") try: args = parser.parse_args() if args.impersonators_file is None or args.clients_file is None: load_default() else: c_id, c_score = numpy.loadtxt(args.clients_file, unpack=True) i_id, i_score = numpy.loadtxt(args.impersonators_file, unpack=True) return c_score, i_score except SystemExit: #TODO: load default scores filenames print "Default" load_default() def solve_roc(): scores = [] c_score, i_score = get_data() scores = zip(['c']*len(c_score),c_score) print len(scores) scores.extend(zip(['i']*len(i_score),i_score)) print len(scores) if __name__ == "__main__": solve_roc()
import argparse import numpy def load_default(): print "TODO: load default scores" return None, None def get_data(): """ Get scores data. If there are no arguments in command line load default """ parser = argparse.ArgumentParser(description="Solve the ROC curve") parser.add_argument("-c", "--clients", type=argparse.FileType('r'), help="Clients filename", metavar="C", dest="clients_file") parser.add_argument("-i", "--impersonators", type=argparse.FileType('r'), help="Impersonators filename", metavar="I", dest="impersonators_file") try: args = parser.parse_args() if args.impersonators_file is None or args.clients_file is None: load_default() else: c_id, c_score = numpy.loadtxt(args.clients_file, unpack=True) i_id, i_score = numpy.loadtxt(args.impersonators_file, unpack=True) return c_score, i_score except SystemExit: #TODO: load default scores filenames print "Default" load_default() def solve_roc(): c_score, i_score = get_data() print c_score if __name__ == "__main__": solve_roc()
Remove backref in main migration
# -*- coding: utf-8 -*- """Get public registrations for staff members. python -m scripts.staff_public_regs """ from collections import defaultdict import logging from modularodm import Q from website.models import Node, User from website.app import init_app logger = logging.getLogger('staff_public_regs') STAFF_GUIDS = [ 'jk5cv', # Jeff 'cdi38', # Brian 'edb8y', # Johanna 'hsey5', # Courtney '5hdme', # Melissa ] def main(): init_app(set_backends=True, routes=False) staff_registrations = defaultdict(list) users = [User.load(each) for each in STAFF_GUIDS] for registration in Node.find(Q('is_registration', 'eq', True) & Q('is_public', 'eq', True)): for user in users: if registration in user.contributed: staff_registrations[user._id].append(registration) for uid in staff_registrations: user = User.load(uid) user_regs = staff_registrations[uid] logger.info('{} ({}) on {} Public Registrations:'.format( user.fullname, user._id, len(user_regs)) ) for registration in user_regs: logger.info('\t{} ({}): {}'.format(registration.title, registration._id, registration.absolute_url) ) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """Get public registrations for staff members. python -m scripts.staff_public_regs """ from collections import defaultdict import logging from modularodm import Q from website.models import Node, User from website.app import init_app logger = logging.getLogger('staff_public_regs') STAFF_GUIDS = [ 'jk5cv', # Jeff 'cdi38', # Brian 'edb8y', # Johanna 'hsey5', # Courtney '5hdme', # Melissa ] def main(): init_app(set_backends=True, routes=False) staff_registrations = defaultdict(list) users = [User.load(each) for each in STAFF_GUIDS] for registration in Node.find(Q('is_registration', 'eq', True) & Q('is_public', 'eq', True)): for user in users: if registration in user.node__contributed: staff_registrations[user._id].append(registration) for uid in staff_registrations: user = User.load(uid) user_regs = staff_registrations[uid] logger.info('{} ({}) on {} Public Registrations:'.format( user.fullname, user._id, len(user_regs)) ) for registration in user_regs: logger.info('\t{} ({}): {}'.format(registration.title, registration._id, registration.absolute_url) ) if __name__ == '__main__': main()
Debug flag to insert tank into game board
import Queue import json import EBQP from . import world from . import types from . import consts from . import loc class GameRequestHandler: def __init__(self): self.world = None self.responses = { EBQP.new: self.respond_new, } def process(self, request): request_pieces = request.split(EBQP.packet_delimiter, 1) command = request_pieces[0] params = request_pieces[1].strip() if len(request_pieces) > 1 else '' try: json_args = json.loads(params) except Exception as e: return "process:failure:bad json" if command in self.responses: return self.responses[command](json_args) else: return "process:failure:unsupported command" def respond_new(self, args): uids = args['uids'] self.world = world.World(uids) if 'debug' in args: self.world.add_unit(uids[0], types.new_unit('Tank', consts.RED, loc.Loc(3, 3))) self.responses = { EBQP.view: self.respond_view, EBQP.move: self.respond_move, } return 'new:success' def respond_view(self, args): return 'view:success:%s' % self.world.to_json() #TODO def respond_move(self, args): return 'move:failure:unimplemented'
import Queue import json import EBQP from . import world from . import types from . import consts from . import loc class GameRequestHandler: def __init__(self): self.world = None self.responses = { EBQP.new: self.respond_new, } def process(self, request): request_pieces = request.split(EBQP.packet_delimiter, 1) command = request_pieces[0] params = request_pieces[1].strip() if len(request_pieces) > 1 else '' try: json_args = json.loads(params) except Exception as e: return "process:failure:bad json" if command in self.responses: return self.responses[command](json_args) else: return "process:failure:unsupported command" def respond_new(self, args): uids = args['uids'] self.world = world.World(uids) self.world.add_unit(uids[0], types.new_unit('Tank', consts.RED, loc.Loc(3, 3))) self.responses = { EBQP.view: self.respond_view, EBQP.move: self.respond_move, } return 'new:success' def respond_view(self, args): return 'view:success:%s' % self.world.to_json() #TODO def respond_move(self, args): return 'move:failure:unimplemented'
Make default saving option relative Saving workflows with wd=True only works when you use a working dir. Since this is optional, it makes more sense to use relative paths (and assume the user uses the nlppln CWL_PATH to save their workflows).
from scriptcwl import WorkflowGenerator as WFGenerator from .utils import CWL_PATH class WorkflowGenerator(WFGenerator): def __init__(self, working_dir=None): WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir) self.load(step_file='https://raw.githubusercontent.com/nlppln/' 'edlib-align/master/align.cwl') self.load(step_file='https://raw.githubusercontent.com/nlppln/' 'pattern-docker/master/pattern.cwl') def save(self, fname, validate=True, wd=False, inline=False, relative=True, pack=False, encoding='utf-8'): """Save workflow to file For nlppln, the default is to save workflows with relative paths. """ super(WorkflowGenerator, self).save(fname, validate=validate, wd=wd, inline=inline, relative=relative, pack=pack, encoding=encoding)
from scriptcwl import WorkflowGenerator as WFGenerator from .utils import CWL_PATH class WorkflowGenerator(WFGenerator): def __init__(self, working_dir=None): WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir) self.load(step_file='https://raw.githubusercontent.com/nlppln/' 'edlib-align/master/align.cwl') self.load(step_file='https://raw.githubusercontent.com/nlppln/' 'pattern-docker/master/pattern.cwl') def save(self, fname, validate=True, wd=True, inline=False, relative=False, pack=False, encoding='utf-8'): """Save workflow to file For nlppln, the default is to use a working directory (and save steps using the ``wd`` option). """ super(WorkflowGenerator, self).save(fname, validate=validate, wd=wd, inline=inline, relative=relative, pack=pack, encoding=encoding)
Test Utils: Cleans up the code
"""Utilities for tests. """ import errno import codecs import os import re def strip_ansi(string): """Strip ANSI encoding from given string. Parameters ---------- string : str String from which encoding needs to be removed Returns ------- str Encoding free string """ pattern = r'(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]' return re.sub(pattern, '', string, flags=re.I) def remove_file(filename): """Removes file silently. Parameters ---------- filename : str File name to be removed Raises ------ Exception If given file is not deletable """ try: os.remove(filename) except OSError as e: if e.errno != errno.ENOENT: raise Exception(e) def decode_utf_8_text(text): """Decodes the text from utf-8 format. Parameters ---------- text : str Text to be decoded Returns ------- str Decoded text """ try: return codecs.decode(text, 'utf-8') except: return text def encode_utf_8_text(text): """Encodes the text to utf-8 format Parameters ---------- text : str Text to be encoded Returns ------- str Encoded text """ try: return codecs.encode(text, 'utf-8') except: return text
"""Utilities for tests. """ import codecs import codecs import os import re def strip_ansi(string): """Strip ANSI encoding from given string. Parameters ---------- string : str String from which encoding needs to be removed Returns ------- str Encoding free string """ pattern = r'(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]' return re.sub(pattern, '', string, flags=re.I) def remove_file(filename): """Removes file silently. Parameters ---------- filename : str File name to be removed Raises ------ Exception If given file is not deletable """ try: os.remove(filename) except OSError as e: if e.errno != errno.ENOENT: raise Exception(e) def decode_utf_8_text(text): """Decodes the text from utf-8 format. Parameters ---------- text : str Text to be decoded Returns ------- str Decoded text """ try: return codecs.decode(text, 'utf-8') except: return text def encode_utf_8_text(text): """Encodes the text to utf-8 format Parameters ---------- text : str Text to be encoded Returns ------- str Encoded text """ try: return codecs.encode(text, 'utf-8') except: return text
Prepare test hashing for complex types.
# Copyright (c) 2016-2018 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. import hashlib class CallJob(object): """ Base class for jobs that call SUTs and can find new issues. """ def __init__(self, config, db, listener): self.config = config self.db = db self.listener = listener # expects self.sut_section and self.fuzzer_name to be set by descendants def add_issue(self, issue, new_issues): test = issue['test'] # Save issue details. issue.update(dict(sut=self.sut_section, fuzzer=self.fuzzer_name, test=test, reduced=False, reported=False)) # Generate default hash ID for the test if does not exist. if 'id' not in issue or not issue['id']: hasher = hashlib.md5() hasher.update(test if isinstance(test, bytes) else str(test).encode('utf-8')) issue['id'] = hasher.hexdigest() # Save new issues. if self.db.add_issue(issue): new_issues.append(issue) self.listener.new_issue(issue=issue)
# Copyright (c) 2016 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. import hashlib class CallJob(object): """ Base class for jobs that call SUTs and can find new issues. """ def __init__(self, config, db, listener): self.config = config self.db = db self.listener = listener # expects self.sut_section and self.fuzzer_name to be set by descendants def add_issue(self, issue, new_issues): test = issue['test'] # Save issue details. issue.update(dict(sut=self.sut_section, fuzzer=self.fuzzer_name, test=test, reduced=False, reported=False)) # Generate default hash ID for the test if does not exist. if 'id' not in issue or not issue['id']: hasher = hashlib.md5() hasher.update(test) issue['id'] = hasher.hexdigest() # Save new issues. if self.db.add_issue(issue): new_issues.append(issue) self.listener.new_issue(issue=issue)
Fix resolution of dependencies in a regular install of lexicon distribution
""" This module takes care of finding information about the runtime of Lexicon: * what are the providers installed, and available * what is the version of Lexicon """ import pkgutil import pkg_resources from lexicon import providers def find_providers(): """Find all providers registered in Lexicon, and their availability""" providers_list = sorted({modname for (_, modname, _) in pkgutil.iter_modules(providers.__path__) if modname != 'base'}) try: distribution = pkg_resources.get_distribution('dns-lexicon') except pkg_resources.DistributionNotFound: return {provider: True for provider in providers_list} else: return {provider: _resolve_requirements(provider, distribution) for provider in providers_list} def lexicon_version(): """Retrieve current Lexicon version""" try: return pkg_resources.get_distribution('dns-lexicon').version except pkg_resources.DistributionNotFound: return 'unknown' def _resolve_requirements(provider, distribution): try: requirements = distribution.requires([provider]) except pkg_resources.UnknownExtra: # No extra for this provider return True else: # Extra is defined try: for requirement in requirements: pkg_resources.get_distribution(requirement.name) except (pkg_resources.DistributionNotFound, pkg_resources.VersionConflict): # At least one extra requirement is not fulfilled return False return True
""" This module takes care of finding information about the runtime of Lexicon: * what are the providers installed, and available * what is the version of Lexicon """ import pkgutil import pkg_resources from lexicon import providers def find_providers(): """Find all providers registered in Lexicon, and their availability""" providers_list = sorted({modname for (_, modname, _) in pkgutil.iter_modules(providers.__path__) if modname != 'base'}) try: distribution = pkg_resources.get_distribution('dns-lexicon') except pkg_resources.DistributionNotFound: return {provider: True for provider in providers_list} else: return {provider: _resolve_requirements(provider, distribution) for provider in providers_list} def lexicon_version(): """Retrieve current Lexicon version""" try: return pkg_resources.get_distribution('dns-lexicon').version except pkg_resources.DistributionNotFound: return 'unknown' def _resolve_requirements(provider, distribution): try: requirements = distribution.requires([provider]) except pkg_resources.UnknownExtra: # No extra for this provider return True else: # Extra is defined try: for requirement in requirements: pkg_resources.get_distribution(requirement) except (pkg_resources.DistributionNotFound, pkg_resources.VersionConflict): # At least one extra requirement is not fulfilled return False return True
Return more relations when a discussion is created
<?php namespace Flarum\Api\Actions\Discussions; use Flarum\Core\Commands\StartDiscussionCommand; use Flarum\Core\Commands\ReadDiscussionCommand; use Flarum\Api\Actions\BaseAction; use Flarum\Api\Actions\ApiParams; use Flarum\Api\Serializers\DiscussionSerializer; class CreateAction extends BaseAction { /** * Start a new discussion. * * @return Response */ protected function run(ApiParams $params) { // By default, the only required attributes of a discussion are the // title and the content. We'll extract these from the rbaseequest data // and pass them through to the StartDiscussionCommand. $title = $params->get('data.title'); $content = $params->get('data.content'); $user = $this->actor->getUser(); $command = new StartDiscussionCommand($title, $content, $user, app('flarum.forum')); $discussion = $this->dispatch($command, $params); // After creating the discussion, we assume that the user has seen all // of the posts in the discussion; thus, we will mark the discussion // as read if they are logged in. if ($user->exists) { $command = new ReadDiscussionCommand($discussion->id, $user, 1); $this->dispatch($command, $params); } $serializer = new DiscussionSerializer(['posts', 'startUser', 'lastUser', 'startPost', 'lastPost']); $document = $this->document()->setData($serializer->resource($discussion)); return $this->respondWithDocument($document); } }
<?php namespace Flarum\Api\Actions\Discussions; use Flarum\Core\Commands\StartDiscussionCommand; use Flarum\Core\Commands\ReadDiscussionCommand; use Flarum\Api\Actions\BaseAction; use Flarum\Api\Actions\ApiParams; use Flarum\Api\Serializers\DiscussionSerializer; class CreateAction extends BaseAction { /** * Start a new discussion. * * @return Response */ protected function run(ApiParams $params) { // By default, the only required attributes of a discussion are the // title and the content. We'll extract these from the rbaseequest data // and pass them through to the StartDiscussionCommand. $title = $params->get('data.title'); $content = $params->get('data.content'); $user = $this->actor->getUser(); $command = new StartDiscussionCommand($title, $content, $user, app('flarum.forum')); $discussion = $this->dispatch($command, $params); // After creating the discussion, we assume that the user has seen all // of the posts in the discussion; thus, we will mark the discussion // as read if they are logged in. if ($user->exists) { $command = new ReadDiscussionCommand($discussion->id, $user, 1); $this->dispatch($command, $params); } $serializer = new DiscussionSerializer(['posts']); $document = $this->document()->setData($serializer->resource($discussion)); return $this->respondWithDocument($document); } }