diff --git "a/validation.csv" "b/validation.csv" new file mode 100644--- /dev/null +++ "b/validation.csv" @@ -0,0 +1,162158 @@ +text,positive,negative +Add contributing author to article query,"export default ` + id + title + search_title + social_title + description + search_description + social_description + thumbnail_image + thumbnail_title + social_image + published_at + slug + layout + featured + channel_id + partner_channel_id + indexable + keywords + published + postscript + is_super_article + is_super_sub_article + super_article { + partner_link + partner_link_title + partner_logo + partner_logo_link + partner_fullscreen_header_logo + secondary_partner_logo + secondary_logo_text + secondary_logo_link + footer_blurb + footer_title + related_articles + } + email_metadata { + headline + author + credit_line + credit_url + image_url + } + authors { + image_url + twitter_handle + name + id + bio + } + contributing_authors { + name + } + vertical { + name + id + } + hero_section { + ...Image + ...Video + ...on FeatureHeader { + type + title + url + } + } + sections { + ... on Text { + type + body + } + ... on Embed { + type + url + height + mobile_height + layout + } + ...Video + ... on Callout { + type + } + ... on ImageCollection { + type + layout + images { + ...Artwork + ...Image + } + } + ... on ImageSet { + type + title + layout + images { + ...Image + ...Artwork + } + } + } +` +","export default ` + id + title + search_title + social_title + description + search_description + social_description + thumbnail_image + thumbnail_title + social_image + published_at + slug + layout + featured + channel_id + partner_channel_id + indexable + keywords + published + postscript + is_super_article + is_super_sub_article + super_article { + partner_link + partner_link_title + partner_logo + partner_logo_link + partner_fullscreen_header_logo + secondary_partner_logo + secondary_logo_text + secondary_logo_link + footer_blurb + footer_title + related_articles + } + email_metadata { + headline + author + credit_line + credit_url + image_url + } + authors { + image_url + twitter_handle + name + id + bio + } + vertical { + name + id + } + hero_section { + ...Image + ...Video + ...on FeatureHeader { + type + title + url + } + } + sections { + ... on Text { + type + body + } + ... on Embed { + type + url + height + mobile_height + layout + } + ...Video + ... on Callout { + type + } + ... on ImageCollection { + type + layout + images { + ...Artwork + ...Image + } + } + ... on ImageSet { + type + title + layout + images { + ...Image + ...Artwork + } + } + } +` +" +Refactor calculating date string into nice method,"(function(){ + 'use strict'; + + angular.module('events') + .service('eventService', ['$q', '$http', '$filter', 'ApiUrl', EventService]); + + /** + * Events DataService + * Events embedded, hard-coded data model; acts asynchronously to simulate + * remote data service call(s). + * + * @returns {{loadAll: Function}} + * @constructor + */ + function EventService($q, $http, $filter, ApiUrl){ + + var getQueryDateString = function(startDate){ + /*copy startDate b/c manipulations we need to make will affect the UI if we don't*/ + var queryDate = new Date(startDate); + + /*get the offset in hours from UTC*/ + var offsetHours = queryDate.getTimezoneOffset() / 60; + + /* set the time to midnight of the day we want to retrieve data for */ + queryDate.setHours(offsetHours,0,0,0); + + return $filter('date')(queryDate,'yyyy-MM-ddTHH:mm:ss') + 'Z'; + } + + this.get = function(startDate, pageSize, pageStart) { + var deferredEvents = $q.defer(); + + + var config = { + params: { + size : pageSize || 50, + start : pageStart || 0 + } + }; + + $http.get(ApiUrl.get() + 'startDate/' + getQueryDateString(startDate), config) + .then(function(data) { + deferredEvents.resolve(data); + }, function(reason) { + deferredEvents.reject(reason); + }); + + return deferredEvents.promise; + }; + } + +})(); +","(function(){ + 'use strict'; + + angular.module('events') + .service('eventService', ['$q', '$http', '$filter', 'ApiUrl', EventService]); + + /** + * Events DataService + * Events embedded, hard-coded data model; acts asynchronously to simulate + * remote data service call(s). + * + * @returns {{loadAll: Function}} + * @constructor + */ + function EventService($q, $http, $filter, ApiUrl){ + + this.get = function(startDate, pageSize, pageStart) { + var deferredEvents = $q.defer(); + + /*copy startDate b/c manipulations we need to make will affect the UI if we don't*/ + var queryDate = new Date(startDate); + + /*get the offset in hours from UTC*/ + var offsetHours = queryDate.getTimezoneOffset() / 60; + + /* set the time to midnight of the day we want to retrieve data for */ + queryDate.setHours(offsetHours,0,0,0); + + var isoQueryDate = $filter('date')(queryDate,'yyyy-MM-ddTHH:mm:ss'); + + var config = { + params: { + size : pageSize || 50, + start : pageStart || 0 + } + }; + + $http.get(ApiUrl.get() + 'startDate/' + isoQueryDate + 'Z', config) + .then(function(data) { + deferredEvents.resolve(data); + }, function(reason) { + deferredEvents.reject(reason); + }); + + return deferredEvents.promise; + }; + } + +})(); +" +search: Change the CreateOrUpdateSearchService and it's response,"package search + +import ""github.com/jen20/riviera/azure"" + +type CreateOrUpdateSearchServiceResponse struct { + ID *string `mapstructure:""id""` + Name *string `mapstructure:""name""` + Location *string `mapstructure:""location""` + Tags *map[string]*string `mapstructure:""tags""` + Sku *string `json:""sku,omitempty""` + ReplicaCount *string `json:""replicaCount,omitempty""` + PartitionCount *string `json:""partitionCount,omitempty""` + Status *string `mapstructure:""status""` + StatusDetails *string `mapstructure:""statusDetails""` + ProvisioningStatus *string `mapstructure:""provisioningStatus""` +} + +type CreateOrUpdateSearchService struct { + Name string `json:""-""` + ResourceGroupName string `json:""-""` + Location string `json:""-"" riviera:""location""` + Tags map[string]*string `json:""-"" riviera:""tags""` + Sku *string `json:""sku,omitempty""` + ReplicaCount *string `json:""replicaCount,omitempty""` + PartitionCount *string `json:""partitionCount,omitempty""` +} + +func (s CreateOrUpdateSearchService) APIInfo() azure.APIInfo { + return azure.APIInfo{ + APIVersion: apiVersion, + Method: ""PUT"", + URLPathFunc: searchServiceDefaultURLPath(s.ResourceGroupName, s.Name), + ResponseTypeFunc: func() interface{} { + return &CreateOrUpdateSearchServiceResponse{} + }, + } +} +","package search + +import ""github.com/jen20/riviera/azure"" + +type CreateOrUpdateSearchServiceResponse struct { + ID *string `mapstructure:""id""` + Name *string `mapstructure:""name""` + Location *string `mapstructure:""location""` + Tags *map[string]*string `mapstructure:""tags""` +} + +type CreateOrUpdateSearchService struct { + Name string `json:""-""` + ResourceGroupName string `json:""-""` + Location string `json:""-"" riviera:""location""` + Tags map[string]*string `json:""-"" riviera:""tags""` + Sku *string `json:""sku,omitempty""` + ReplicaCount *string `json:""replicaCount,omitempty""` + PartitionCount *string `json:""partitionCount,omitempty""` + Status *string `mapstructure:""status""` + StatusDetails *string `mapstructure:""statusDetails""` + ProvisioningStatus *string `mapstructure:""provisioningStatus""` +} + +func (s CreateOrUpdateSearchService) APIInfo() azure.APIInfo { + return azure.APIInfo{ + APIVersion: apiVersion, + Method: ""PUT"", + URLPathFunc: searchServiceDefaultURLPath(s.ResourceGroupName, s.Name), + ResponseTypeFunc: func() interface{} { + return &CreateOrUpdateSearchServiceResponse{} + }, + } +} +" +Add some air to the code,"angular.module('ngJustGage', []) + .directive('justGage', ['$timeout', function ($timeout) { + return { + restrict: 'EA', + scope: { + id: '@', + class: '@', + min: '=', + max: '=', + title: '@', + value: '=', + options: '=' + }, + template: '
', + link: function (scope, element, attrs) { + $timeout(function () { + var options = { + id: scope.id + '-justgage', + min: scope.min, + max: scope.max, + title: scope.title, + value: scope.value + }; + + if (scope.options) { + for (var key in scope.options) { + options[key] = scope.options[key]; + } + } + + var graph = new JustGage(options); + + scope.$watch('max', function (updatedMax) { + if (updatedMax !== undefined) { + graph.refresh(scope.value, updatedMax); + } + }, true); + + scope.$watch('value', function (updatedValue) { + if (updatedValue !== undefined) { + graph.refresh(updatedValue); + } + }, true); + }); + } + }; + }]); +","angular.module('ngJustGage', []) + .directive('justGage', ['$timeout', function ($timeout) { + return { + restrict: 'EA', + scope: { + id: '@', + class: '@', + min: '=', + max: '=', + title: '@', + value: '=', + options: '=' + }, + template: '
', + link: function (scope, element, attrs) { + $timeout(function () { + var options = { + id: scope.id + '-justgage', + min: scope.min, + max: scope.max, + title: scope.title, + value: scope.value + }; + if (scope.options) { + for (var key in scope.options) { + options[key] = scope.options[key]; + } + } + var graph = new JustGage(options); + + scope.$watch('max', function (updatedMax) { + if (updatedMax !== undefined) { + graph.refresh(scope.value, updatedMax); + } + }, true); + + scope.$watch('value', function (updatedValue) { + if (updatedValue !== undefined) { + graph.refresh(updatedValue); + } + }, true); + }); + } + }; + }]); +" +Add hook to get DOM from Angular,"define(function(require) { + var module = require(""ui/modules"").get(""kibana-chord""); + + module.controller(""ChordController"", function($scope, Private, $element) { + var div = $element[0]; + + $scope.$watch(""esResponse"", function(response) { + $scope.dataDump = JSON.stringify(response, null, 2); + }); + }); + + function ChordProvider(Private) { + var TemplateVisType = Private(require(""ui/template_vis_type/TemplateVisType"")); + var Schemas = Private(require(""ui/Vis/Schemas"")); + + return new TemplateVisType({ + name: ""chord"", + title: ""Chord Diagram"", + icon: ""fa-pie-chart"", // TODO make this look like a chord diagram + description: ""Visualize network flows with a Chord Diagram."", + requiresSearch: true, + template: require(""plugins/kibana-chord/chord.html""), + schemas: new Schemas([ + { + group: ""metrics"", + name: ""weight"", + title: ""Chord Weight"", + min: 1, + max: 1, + aggFilter: [""count"", ""sum""] + }, + { + group: ""buckets"", + name: ""src"", + title: ""Chord Sources"", + min: 1, + max: 1, + aggFilter: ""terms"" + }, + { + group: ""buckets"", + name: ""dest"", + title: ""Chord Destinations"", + min: 1, + max: 1, + aggFilter: ""terms"" + } + ]) + }); + } + + require(""ui/registry/vis_types"").register(ChordProvider); + + return ChordProvider; + +}); +","define(function(require) { + var module = require(""ui/modules"").get(""kibana-chord""); + + module.controller(""ChordController"", function($scope, Private) { + $scope.$watch(""esResponse"", function(response) { + $scope.dataDump = JSON.stringify(response, null, 2); + }); + }); + + function ChordProvider(Private) { + var TemplateVisType = Private(require(""ui/template_vis_type/TemplateVisType"")); + var Schemas = Private(require(""ui/Vis/Schemas"")); + + return new TemplateVisType({ + name: ""chord"", + title: ""Chord Diagram"", + icon: ""fa-pie-chart"", // TODO make this look like a chord diagram + description: ""Visualize network flows with a Chord Diagram."", + requiresSearch: true, + template: require(""plugins/kibana-chord/chord.html""), + schemas: new Schemas([ + { + group: ""metrics"", + name: ""weight"", + title: ""Chord Weight"", + min: 1, + max: 1, + aggFilter: [""count"", ""sum""] + }, + { + group: ""buckets"", + name: ""src"", + title: ""Chord Sources"", + min: 1, + max: 1, + aggFilter: ""terms"" + }, + { + group: ""buckets"", + name: ""dest"", + title: ""Chord Destinations"", + min: 1, + max: 1, + aggFilter: ""terms"" + } + ]) + }); + } + + require(""ui/registry/vis_types"").register(ChordProvider); + + return ChordProvider; + +}); +" +"BB-4210: Add validation functionality to RuleEditorComponent +- extended typeahead plugin; +- changed autocomplete init script; +- added typeahead behavior ащк empty value;","define(function(require) { + 'use strict'; + + var $ = require('jquery'); + require('bootstrap'); + + /** + * This customization allows to define own focus, click, render, show, lookup functions for Typeahead + */ + var Typeahead; + var origTypeahead = $.fn.typeahead.Constructor; + var origFnTypeahead = $.fn.typeahead; + + Typeahead = function(element, options) { + var opts = $.extend({}, $.fn.typeahead.defaults, options); + this.focus = opts.focus || this.focus; + this.render = opts.render || this.render; + this.show = opts.show || this.show; + this.lookup = opts.lookup || this.lookup; + origTypeahead.apply(this, arguments); + }; + + Typeahead.prototype = origTypeahead.prototype; + Typeahead.prototype.constructor = Typeahead; + + $.fn.typeahead = function(option) { + return this.each(function() { + var $this = $(this); + var data = $this.data('typeahead'); + var options = typeof option === 'object' && option; + if (!data) { + $this.data('typeahead', (data = new Typeahead(this, options))); + } + if (typeof option === 'string') { + data[option](); + } + }); + }; + + $.fn.typeahead.defaults = origFnTypeahead.defaults; + $.fn.typeahead.Constructor = Typeahead; + $.fn.typeahead.noConflict = origFnTypeahead.noConflict; +}); +","define(function(require) { + 'use strict'; + + var $ = require('jquery'); + require('bootstrap'); + + /** + * This customization allows to define own click, render, show functions for Typeahead + */ + var Typeahead; + var origTypeahead = $.fn.typeahead.Constructor; + var origFnTypeahead = $.fn.typeahead; + + Typeahead = function(element, options) { + var opts = $.extend({}, $.fn.typeahead.defaults, options); + this.click = opts.click || this.click; + this.render = opts.render || this.render; + this.show = opts.show || this.show; + origTypeahead.apply(this, arguments); + }; + + Typeahead.prototype = origTypeahead.prototype; + Typeahead.prototype.constructor = Typeahead; + + $.fn.typeahead = function(option) { + return this.each(function() { + var $this = $(this); + var data = $this.data('typeahead'); + var options = typeof option === 'object' && option; + if (!data) { + $this.data('typeahead', (data = new Typeahead(this, options))); + } + if (typeof option === 'string') { + data[option](); + } + }); + }; + + $.fn.typeahead.defaults = origFnTypeahead.defaults; + $.fn.typeahead.Constructor = Typeahead; + $.fn.typeahead.noConflict = origFnTypeahead.noConflict; +}); +" +Increase perfs when loading a product's page,"'use strict'; + +var set_taxon_select = function(selector){ + if ($(selector).length > 0) { + $(selector).select2({ + placeholder: Spree.translations.taxon_placeholder, + multiple: true, + initSelection: function (element, callback) { + var url = Spree.url(Spree.routes.taxons_search, { + ids: element.val(), + without_children: true, + token: Spree.api_key + }); + return $.getJSON(url, null, function (data) { + return callback(data['taxons']); + }); + }, + ajax: { + url: Spree.routes.taxons_search, + datatype: 'json', + data: function (term, page) { + return { + per_page: 50, + page: page, + without_children: true, + q: { + name_cont: term + }, + token: Spree.api_key + }; + }, + results: function (data, page) { + var more = page < data.pages; + return { + results: data['taxons'], + more: more + }; + } + }, + formatResult: function (taxon) { + return taxon.pretty_name; + }, + formatSelection: function (taxon) { + return taxon.pretty_name; + } + }); + } +} + +$(document).ready(function () { + set_taxon_select('#product_taxon_ids') +}); +","'use strict'; + +var set_taxon_select = function(selector){ + if ($(selector).length > 0) { + $(selector).select2({ + placeholder: Spree.translations.taxon_placeholder, + multiple: true, + initSelection: function (element, callback) { + var url = Spree.url(Spree.routes.taxons_search, { + ids: element.val(), + token: Spree.api_key + }); + return $.getJSON(url, null, function (data) { + return callback(data['taxons']); + }); + }, + ajax: { + url: Spree.routes.taxons_search, + datatype: 'json', + data: function (term, page) { + return { + per_page: 50, + page: page, + without_children: true, + q: { + name_cont: term + }, + token: Spree.api_key + }; + }, + results: function (data, page) { + var more = page < data.pages; + return { + results: data['taxons'], + more: more + }; + } + }, + formatResult: function (taxon) { + return taxon.pretty_name; + }, + formatSelection: function (taxon) { + return taxon.pretty_name; + } + }); + } +} + +$(document).ready(function () { + set_taxon_select('#product_taxon_ids') +}); +" +Change package name to tingbot-python for submission to PyPI,"#!/usr/bin/env python +# -*- coding: utf-8 -*- + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +with open('README.rst') as readme_file: + readme = readme_file.read() + +requirements = [ + 'pyzmq', + 'docopt', + 'virtualenv', + 'requests', + 'Pillow', +] + +setup( + name='tingbot-python', + version='0.3.0', + description=""Python APIs to write apps for Tingbot"", + long_description=readme, + author=""Joe Rickerby"", + author_email='joerick@mac.com', + url='https://github.com/tingbot/tingbot-python', + packages=[ + 'tingbot', + 'tbtool' + ], + package_dir={'tingbot': 'tingbot', + 'tbtool': 'tbtool'}, + include_package_data=True, + install_requires=requirements, + license=""BSD"", + zip_safe=False, + keywords='tingbot', + classifiers=[ + 'Intended Audience :: Developers', + 'Natural Language :: English', + ""Programming Language :: Python :: 2"", + 'Programming Language :: Python :: 2.7', + ], + entry_points={ + 'console_scripts': [ + 'tbtool = tbtool.__main__:main', + ], + }, + test_suite='tests', + tests_require=['httpretty','mock'], +) +","#!/usr/bin/env python +# -*- coding: utf-8 -*- + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +with open('README.rst') as readme_file: + readme = readme_file.read() + +requirements = [ + 'pyzmq', + 'docopt', + 'virtualenv', + 'requests', + 'Pillow', +] + +setup( + name='tingbot', + version='0.3.0', + description=""Python APIs to write apps for Tingbot"", + long_description=readme, + author=""Joe Rickerby"", + author_email='joerick@mac.com', + url='https://github.com/tingbot/tingbot-python', + packages=[ + 'tingbot', + 'tbtool' + ], + package_dir={'tingbot': 'tingbot', + 'tbtool': 'tbtool'}, + include_package_data=True, + install_requires=requirements, + license=""BSD"", + zip_safe=False, + keywords='tingbot', + classifiers=[ + 'Intended Audience :: Developers', + 'Natural Language :: English', + ""Programming Language :: Python :: 2"", + 'Programming Language :: Python :: 2.7', + ], + entry_points={ + 'console_scripts': [ + 'tbtool = tbtool.__main__:main', + ], + }, + test_suite='tests', + tests_require=['httpretty','mock'], +) +" +Add carriage return for symmetry,"import getpass +from distutils.command import upload as orig + + +class upload(orig.upload): + """""" + Override default upload behavior to obtain password + in a variety of different ways. + """""" + + def finalize_options(self): + orig.upload.finalize_options(self) + # Attempt to obtain password. Short circuit evaluation at the first + # sign of success. + self.password = ( + self.password or + self._load_password_from_keyring() or + self._prompt_for_password() + ) + + def _load_password_from_keyring(self): + """""" + Attempt to load password from keyring. Suppress Exceptions. + """""" + try: + keyring = __import__('keyring') + password = keyring.get_password(self.repository, self.username) + except Exception: + password = None + finally: + return password + + def _prompt_for_password(self): + """""" + Prompt for a password on the tty. Suppress Exceptions. + """""" + password = None + try: + while not password: + password = getpass.getpass() + except (Exception, KeyboardInterrupt): + password = None + finally: + return password +","import getpass +from distutils.command import upload as orig + + +class upload(orig.upload): + """""" + Override default upload behavior to obtain password + in a variety of different ways. + """""" + + def finalize_options(self): + orig.upload.finalize_options(self) + # Attempt to obtain password. Short circuit evaluation at the first + # sign of success. + self.password = ( + self.password or self._load_password_from_keyring() or + self._prompt_for_password() + ) + + def _load_password_from_keyring(self): + """""" + Attempt to load password from keyring. Suppress Exceptions. + """""" + try: + keyring = __import__('keyring') + password = keyring.get_password(self.repository, self.username) + except Exception: + password = None + finally: + return password + + def _prompt_for_password(self): + """""" + Prompt for a password on the tty. Suppress Exceptions. + """""" + password = None + try: + while not password: + password = getpass.getpass() + except (Exception, KeyboardInterrupt): + password = None + finally: + return password +" +Add getDimensions to Bike model,"const imageSize = require('image-size') + +module.exports = function (sequelize, DataTypes) { + const Bike = sequelize.define('Bike', { + id: { + primaryKey: true, + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4 + }, + name: { + type: DataTypes.STRING, + allowNull: false, + validate: { + notEmpty: true + } + }, + width: { + type: DataTypes.INTEGER, + allowNull: false + }, + height: { + type: DataTypes.INTEGER, + allowNull: false + }, + size: { + type: DataTypes.INTEGER, + allowNull: false, + validate: { + max: 5000000, + min: 0 + } + }, + type: { + type: DataTypes.ENUM([ + 'image/png', + 'image/jpeg' + ]), + allowNull: false, + validate: { + isIn: [['image/png', 'image/jpeg']] + } + }, + BikeshedId: { + type: DataTypes.UUID, + allowNull: false + } + }, { + classMethods: { + associate (models) { + Bike.belongsTo(models.Bikeshed) + Bike.hasMany(models.Rating) + }, + + /** + * Get dimensions + * Returns width and height + * @param {string} File path + * @returns {Promise} File dimensions promise + */ + getDimensions (path) { + return new Promise((resolve, reject) => { + imageSize(path, (err, result) => { + err ? reject(err) : resolve(result) + }) + }) + }, + } + } + }) + + return Bike +} +","module.exports = function (sequelize, DataTypes) { + const Bike = sequelize.define('Bike', { + id: { + primaryKey: true, + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4 + }, + name: { + type: DataTypes.STRING, + allowNull: false, + validate: { + notEmpty: true + } + }, + width: { + type: DataTypes.INTEGER, + allowNull: false + }, + height: { + type: DataTypes.INTEGER, + allowNull: false + }, + size: { + type: DataTypes.INTEGER, + allowNull: false, + validate: { + max: 5000000, + min: 0 + } + }, + type: { + type: DataTypes.ENUM([ + 'image/png', + 'image/jpeg' + ]), + allowNull: false, + validate: { + isIn: [['image/png', 'image/jpeg']] + } + }, + BikeshedId: { + type: DataTypes.UUID, + allowNull: false + } + }, { + classMethods: { + associate (models) { + Bike.belongsTo(models.Bikeshed) + Bike.hasMany(models.Rating) + } + } + }) + + return Bike +} +" +Fix error in docstring example.,"__all__ = ( + 'Category', +) + + +class Category(tuple): + """""" + This type acts as tuple with one key difference - two instances of it are + equal only when they have the same type. This allows you to easily mitigate + collisions when using common types (like string) in a dict or as a Wiring + :term:`specification`. + + Example:: + + from wiring import Graph, Category + + class Public(Category): + pass + + class Secret(Category): + pass + + graph = Graph() + graph.register_instance(Public('database', 1), 'db://public/1') + graph.register_instance(Secret('database', 1), 'db://private/1') + + assert Public('database', 1) != Private('database', 1) + assert ( + graph.get(Public('database', 1)) + != graph.get(Private('database', 1)) + ) + """""" + + def __new__(cls, *args): + return super(Category, cls).__new__(cls, args) + + def __repr__(self): + return type(self).__name__ + super(Category, self).__repr__() + + def __str__(self): + return repr(self) + + def __eq__(self, other): + return ( + type(self) == type(other) and super(Category, self).__eq__(other) + ) + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(( + type(self), + super(Category, self).__hash__() + )) +","__all__ = ( + 'Category', +) + + +class Category(tuple): + """""" + This type acts as tuple with one key difference - two instances of it are + equal only when they have the same type. This allows you to easily mitigate + collisions when using common types (like string) in a dict or as a Wiring + :term:`specification`. + + Example:: + + from wiring import Graph, Category + + class Public(Category): + pass + + class Secret(Category): + pass + + graph = Graph() + graph.register_instance(Public('database', 1), 'db://public/1') + graph.register_instance(Private('database', 1), 'db://private/1') + + assert Public('database', 1) != Private('database', 1) + assert ( + graph.get(Public('database', 1)) + != graph.get(Private('database', 1)) + ) + """""" + + def __new__(cls, *args): + return super(Category, cls).__new__(cls, args) + + def __repr__(self): + return type(self).__name__ + super(Category, self).__repr__() + + def __str__(self): + return repr(self) + + def __eq__(self, other): + return ( + type(self) == type(other) and super(Category, self).__eq__(other) + ) + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(( + type(self), + super(Category, self).__hash__() + )) +" +Send promise from API request,"var server = 'http://localhost:3000'; + +module.exports = { + login: (username, password) => { + return + fetch(server + '/login', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + username: username, + password: password + }) + }); + }, + + signup: (username, password, teacherOrStudent) => { + return + fetch(server + '/signup', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + username: username, + password: password, + type: teacherOrStudent + }) + }); + }, + + getLessons: (classId) => { + return fetch(server + '/teachers/lessons/' + classId); + }, + + getLessonData: (lessonId) => { + return fetch(server + '/teachers/polls/' + lessonId); + }, + + startPoll: (pollObject, lessonId) => { + + return fetch(server + '/teachers/polls', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + pollObject: pollObject, + lessonId: lessonId + }) + }); + } +} + +","var server = 'http://localhost:3000'; + +module.exports = { + login: (username, password) => { + return + fetch(server + '/login', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + username: username, + password: password + }) + }); + }, + + signup: (username, password, teacherOrStudent) => { + return + fetch(server + '/signup', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + username: username, + password: password, + type: teacherOrStudent + }) + }); + }, + + getLessons: (classId) => { + return fetch(server + '/teachers/lessons/' + classId); + }, + + getLessonData: (lessonId) => { + return fetch(server + '/teachers/polls/' + lessonId); + }, + + startPoll: (pollObject, lessonId) => { + console.log(""start poll info::::::::::::"") + console.log(pollObject, lessonId); + + + return fetch(server + '/teachers/polls', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + pollObject: pollObject, + lessonId: lessonId + }) + }).then((resp) => { + console.log(""CATCH ME::::::::"", resp); + }); + } +} + +" +"Add PySerial to the test requirements + +It is needed for the doctests.","import sys +from setuptools import setup +from setuptools.command.test import test as TestCommand +import schunk + +class PyTest(TestCommand): + def finalize_options(self): + TestCommand.finalize_options(self) + self.test_args = '--doctest-modules --ignore setup.py' + self.test_suite = True + + def run_tests(self): + # import here, cause outside the eggs aren't loaded + import pytest + errno = pytest.main(self.test_args) + sys.exit(errno) + + +setup( + name=""SchunkMotionProtocol"", + version=schunk.__version__, + py_modules=['schunk'], + + author=""Matthias Geier"", + author_email=""Matthias.Geier@gmail.com"", + description=""Schunk Motion Protocol for Python"", + long_description=open('README.rst').read(), + license=""MIT"", + keywords=""Schunk serial servo motor"".split(), + url=""http://schunk.rtfd.org/"", + download_url=""https://github.com/spatialaudio/schunk/releases/"", + platforms='any', + classifiers=[ + ""Development Status :: 3 - Alpha"", + ""License :: OSI Approved :: MIT License"", + ""Operating System :: OS Independent"", + ""Programming Language :: Python"", + ""Programming Language :: Python :: 2"", + ""Programming Language :: Python :: 3"", + ""Topic :: Scientific/Engineering"", + ], + + tests_require=['pytest', 'pyserial'], + cmdclass={'test': PyTest}, +) +","import sys +from setuptools import setup +from setuptools.command.test import test as TestCommand +import schunk + +class PyTest(TestCommand): + def finalize_options(self): + TestCommand.finalize_options(self) + self.test_args = '--doctest-modules --ignore setup.py' + self.test_suite = True + + def run_tests(self): + # import here, cause outside the eggs aren't loaded + import pytest + errno = pytest.main(self.test_args) + sys.exit(errno) + + +setup( + name=""SchunkMotionProtocol"", + version=schunk.__version__, + py_modules=['schunk'], + + author=""Matthias Geier"", + author_email=""Matthias.Geier@gmail.com"", + description=""Schunk Motion Protocol for Python"", + long_description=open('README.rst').read(), + license=""MIT"", + keywords=""Schunk serial servo motor"".split(), + url=""http://schunk.rtfd.org/"", + download_url=""https://github.com/spatialaudio/schunk/releases/"", + platforms='any', + classifiers=[ + ""Development Status :: 3 - Alpha"", + ""License :: OSI Approved :: MIT License"", + ""Operating System :: OS Independent"", + ""Programming Language :: Python"", + ""Programming Language :: Python :: 2"", + ""Programming Language :: Python :: 3"", + ""Topic :: Scientific/Engineering"", + ], + + tests_require=['pytest'], + cmdclass={'test': PyTest}, +) +" +Replace concrete Application class with Contract,"commands([ + GenerateModelCommand::class, + ]); + + $this->app->tag([ + ExistenceCheckerProcessor::class, + FieldProcessor::class, + NamespaceProcessor::class, + RelationProcessor::class, + CustomPropertyProcessor::class, + TableNameProcessor::class, + CustomPrimaryKeyProcessor::class, + ], self::PROCESSOR_TAG); + + $this->app->bind(EloquentModelBuilder::class, function (Application $app) { + return new EloquentModelBuilder($app->tagged(self::PROCESSOR_TAG)); + }); + } +}","commands([ + GenerateModelCommand::class, + ]); + + $this->app->tag([ + ExistenceCheckerProcessor::class, + FieldProcessor::class, + NamespaceProcessor::class, + RelationProcessor::class, + CustomPropertyProcessor::class, + TableNameProcessor::class, + CustomPrimaryKeyProcessor::class, + ], self::PROCESSOR_TAG); + + $this->app->bind(EloquentModelBuilder::class, function (Application $app) { + return new EloquentModelBuilder($app->tagged(self::PROCESSOR_TAG)); + }); + } +}" +Fix tests for Preprocess constructors,"import unittest +from mock import Mock, MagicMock, patch + +import Orange + + +class TestPreprocess(unittest.TestCase): + def test_read_data_calls_reader(self): + class MockPreprocessor(Orange.preprocess.preprocess.Preprocess): + __init__ = Mock(return_value=None) + __call__ = Mock() + @classmethod + def reset(cls): + cls.__init__.reset_mock() + cls.__call__.reset_mock() + + table = Mock(Orange.data.Table) + MockPreprocessor(table, 1, 2, a=3) + MockPreprocessor.__init__.assert_called_with(1, 2, a=3) + MockPreprocessor.__call__.assert_called_with(table) + MockPreprocessor.reset() + + MockPreprocessor(1, 2, a=3) + MockPreprocessor.__init__.assert_called_with(1, 2, a=3) + self.assertEqual(MockPreprocessor.__call__.call_count, 0) + + MockPreprocessor(a=3) + MockPreprocessor.__init__.assert_called_with(a=3) + self.assertEqual(MockPreprocessor.__call__.call_count, 0) + + MockPreprocessor() + MockPreprocessor.__init__.assert_called_with() + self.assertEqual(MockPreprocessor.__call__.call_count, 0) +","import unittest +from mock import Mock, MagicMock, patch + +import Orange + + +class TestPreprocess(unittest.TestCase): + def test_read_data_calls_reader(self): + class MockPreprocessor(Orange.preprocess.preprocess.Preprocess): + __init__ = Mock() + __call__ = Mock() + @classmethod + def reset(cls): + cls.__init__.reset_mock() + cls.__call__.reset_mock() + return MockPreprocessor + + table = Mock(Orange.data.Table) + MockPreprocessor(table, 1, 2, a=3) + MockPreprocessor.__init__.assert_called_with(1, 2, {'a': 3}) + MockPreprocessor.__call__.assert_called_with(table) + MockPreprocessor.reset() + + MockPreprocessor = create_mock() + MockPreprocessor(1, 2, a=3) + MockPreprocessor.__init__.assert_called_with(1, 2, a=3) + self.assertEqual(MockPreprocessor.__call__.call_count(), 0) + + MockPreprocessor = create_mock() + MockPreprocessor(a=3) + MockPreprocessor.__init__.assert_called_with(a=3) + self.assertEqual(MockPreprocessor.__call__.call_count(), 0) + + MockPreprocessor = create_mock() + MockPreprocessor() + MockPreprocessor.__init__.assert_called_with() + self.assertEqual(MockPreprocessor.__call__.call_count(), 0) +" +Correct fallback for tag name,"from __future__ import absolute_import + +from sentry.api.serializers import Serializer, register +from sentry.models import GroupTagKey, TagKey + + +@register(GroupTagKey) +class GroupTagKeySerializer(Serializer): + def get_attrs(self, item_list, user): + tag_labels = { + t.key: t.get_label() + for t in TagKey.objects.filter( + project=item_list[0].project, + key__in=[i.key for i in item_list] + ) + } + + result = {} + for item in item_list: + try: + label = tag_labels[item.key] + except KeyError: + if item.key.startswith('sentry:'): + label = item.key.split('sentry:', 1)[-1] + else: + label = item.key + result[item] = { + 'name': label, + } + return result + + def serialize(self, obj, attrs, user): + if obj.key.startswith('sentry:'): + key = obj.key.split('sentry:', 1)[-1] + else: + key = obj.key + + return { + 'name': attrs['name'], + 'key': key, + 'uniqueValues': obj.values_seen, + } +","from __future__ import absolute_import + +from sentry.api.serializers import Serializer, register +from sentry.models import GroupTagKey, TagKey + + +@register(GroupTagKey) +class GroupTagKeySerializer(Serializer): + def get_attrs(self, item_list, user): + tag_labels = { + t.key: t.get_label() + for t in TagKey.objects.filter( + project=item_list[0].project, + key__in=[i.key for i in item_list] + ) + } + + result = {} + for item in item_list: + try: + label = tag_labels[item.key] + except KeyError: + label = item.value + result[item] = { + 'name': label, + } + return result + + def serialize(self, obj, attrs, user): + if obj.key.startswith('sentry:'): + key = obj.key.split('sentry:', 1)[-1] + else: + key = obj.key + + return { + 'name': attrs['name'], + 'key': key, + 'uniqueValues': obj.values_seen, + } +" +Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt),"import unittest +import os +from selenium import webdriver +from time import sleep + +class TestClaimsLogin(unittest.TestCase): + + def setUp(self): + self.driver = webdriver.PhantomJS() + self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') + + def test_verify_main_screen_loaded(self): + self.driver.get('http://%s/eclaim/login/' % self.ip) + + self.driver.find_element_by_id('id_user_name').send_keys(""implementer"") + self.driver.find_element_by_id('id_password').send_keys(""eclaim_implementer"") + self.driver.find_element_by_css_selector('button.btn.btn-primary').click() + self.driver.implicitly_wait(30) + greeting = self.driver.find_element_by_id(""user-greeting"") + self.assertTrue(greeting.is_displayed()) + self.assertTrue('Hello, Implementer' in greeting.text) + # import ipdb; ipdb.set_trace() + self.driver.execute_script(""set_language('ms')"") + sleep(5) + self.assertEqual(self.driver.find_element_by_id(""logo"").text, + u'Staff Claims') + + def tearDown(self): + self.driver.get('http://%s/eclaim/logout' % self.ip) + self.driver.quit() + +if __name__ == '__main__': + unittest.main(verbosity=2) +","import unittest +import os +from selenium import webdriver +from time import sleep + +class TestClaimsLogin(unittest.TestCase): + + def setUp(self): + self.driver = webdriver.PhantomJS() + self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') + + def test_verify_main_screen_loaded(self): + self.driver.get('http://%s/eclaim/login/' % self.ip) + + self.driver.find_element_by_id('id_user_name').send_keys(""implementer"") + self.driver.find_element_by_id('id_password').send_keys(""eclaim_implementer"") + self.driver.find_element_by_css_selector('button.btn.btn-primary').click() + self.driver.implicitly_wait(30) + greeting = self.driver.find_element_by_id(""user-greeting"") + self.assertTrue(greeting.is_displayed()) + self.assertIn(greeting.text, u'Hello, Implementer') + # import ipdb; ipdb.set_trace() + self.driver.execute_script(""set_language('ms')"") + sleep(5) + self.assertEqual(self.driver.find_element_by_id(""logo"").text, + u'Staff Claims') + + def tearDown(self): + self.driver.get('http://%s/eclaim/logout' % self.ip) + self.driver.quit() + +if __name__ == '__main__': + unittest.main(verbosity=2) +" +Add newline to end of file,"function checkWindowSize(){ + var w = document.documentElement.clientWidth; + var panel = document.getElementById(""help-panel""); + if (w < 978) { + panel.style.position = ""static""; + panel.style.width = ""auto""; + } else if (w >= 978 && w < 1184) { + panel.style.position = ""fixed""; + panel.style.width = ""250px""; + unfix(); + } else { + panel.style.position = ""fixed""; + panel.style.width = ""275px""; + unfix(); + } +} + +function unfix() { + if (document.readyState === ""complete"") { + var panel = document.getElementById(""help-panel""); + if (panel.style.position !== ""static"") { + var panelRect = panel.getBoundingClientRect(); + var yOffset = document.body.clientHeight - 600 - panelRect.height - 95; + if (window.pageYOffset > yOffset) { + panel.style.top = """" + yOffset + ""px""; + panel.style.position = ""absolute""; + } else if (window.pageYOffset < yOffset) { + panel.style.top = ""95px""; + panel.style.position = ""fixed""; + } + } + } +} + +window.addEventListener(""resize"", checkWindowSize); +window.addEventListener(""scroll"", unfix); + +$(document).ready(function() { + checkWindowSize(); +}); +","function checkWindowSize(){ + var w = document.documentElement.clientWidth; + var panel = document.getElementById(""help-panel""); + if (w < 978) { + panel.style.position = ""static""; + panel.style.width = ""auto""; + } else if (w >= 978 && w < 1184) { + panel.style.position = ""fixed""; + panel.style.width = ""250px""; + unfix(); + } else { + panel.style.position = ""fixed""; + panel.style.width = ""275px""; + unfix(); + } +} + +function unfix() { + if (document.readyState === ""complete"") { + var panel = document.getElementById(""help-panel""); + if (panel.style.position !== ""static"") { + var panelRect = panel.getBoundingClientRect(); + var yOffset = document.body.clientHeight - 600 - panelRect.height - 95; + if (window.pageYOffset > yOffset) { + panel.style.top = """" + yOffset + ""px""; + panel.style.position = ""absolute""; + } else if (window.pageYOffset < yOffset) { + panel.style.top = ""95px""; + panel.style.position = ""fixed""; + } + } + } +} + +window.addEventListener(""resize"", checkWindowSize); +window.addEventListener(""scroll"", unfix); + +$(document).ready(function() { + checkWindowSize(); +});" +Fix string formatting bug in fork_statics man. command,"import logging +import os +import shutil + +from django.conf import settings +from django.core.management.base import BaseCommand, CommandError + + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand): + """""" + Copy Oscar's statics into local project so they can be used as a base for + styling a new site. + """""" + args = '' + help = ""Copy Oscar's static files"" + + def handle(self, *args, **options): + # Determine where to copy to + folder = args[0] if args else 'static' + if not folder.startswith('/'): + destination = os.path.join(os.getcwd(), folder) + else: + destination = folder + if os.path.exists(destination): + raise CommandError( + ""The folder %s already exists - aborting!"" % destination) + + source = os.path.realpath( + os.path.join(os.path.dirname(__file__), '../../static')) + print ""Copying Oscar's static files to %s"" % (destination,) + shutil.copytree(source, destination) + + # Check if this new folder is in STATICFILES_DIRS + if destination not in settings.STATICFILES_DIRS: + print (""You need to add %s to STATICFILES_DIRS in order for your "" + ""local overrides to be picked up"") % destination +","import logging +import os +import shutil + +from django.db.models import get_model +from django.conf import settings +from django.core.management.base import BaseCommand, CommandError + +ProductAlert = get_model('customer', 'ProductAlert') + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand): + """""" + Copy Oscar's statics into local project so they can be used as a base for + styling a new site. + """""" + args = '' + help = ""Copy Oscar's static files"" + + def handle(self, *args, **options): + # Determine where to copy to + folder = args[0] if args else 'static' + if not folder.startswith('/'): + destination = os.path.join(os.getcwd(), folder) + else: + destination = folder + if os.path.exists(destination): + raise CommandError( + ""The folder %s already exists - aborting!"" % destination) + + source = os.path.realpath( + os.path.join(os.path.dirname(__file__), '../../static')) + print ""Copying Oscar's static files to %s"" % (source, destination) + shutil.copytree(source, destination) + + # Check if this new folder is in STATICFILES_DIRS + if destination not in settings.STATICFILES_DIRS: + print (""You need to add %s to STATICFILES_DIRS in order for your "" + ""local overrides to be picked up"") % destination +" +Split out template config for readability,"var metalsmith = require('metalsmith'); +var markdown = require('metalsmith-pandoc'); +var templates = require('metalsmith-templates'); +var serve = require('metalsmith-serve'); +var watch = require('metalsmith-watch'); +var moment = require('moment'); +var i18n = require('i18next'); +var headings = require('metalsmith-headings'); +var convert = require('metalsmith-convert'); + +//i18n.init({ lng: ""fr-FR"" }); +i18n.init({ lng: ""en-US"" }); +i18n.registerAppHelper(metalsmith); + + +// Image handling: metalsmith-convert config + +var convertConfig = { + src: '**/*.jpg', + target: 'jpg', + resize: { + width: 320, + height: 320, + resizeStyle: 'aspectfit' + } +}; + + +// Template handling: metalsmith-templates config + +var templateConfig = { + engine: 'jade', + moment: moment, + i18n: i18n +} + + +metalsmith(__dirname) + .source('src') + .use(markdown()) + .use(headings('h2')) + .use(templates(templateConfig)) + .use(convert(convertConfig)) + .destination('build') + .use(serve({ + port: 8081 + })) + .use(watch({ + paths: { + ""${source}/**/*"": true, + ""templates/**/*"": ""**/*.md"", + } + })) + .build(function (err) { + if (err) { + throw err; + } + }); +","var metalsmith = require('metalsmith'); +var markdown = require('metalsmith-pandoc'); +var templates = require('metalsmith-templates'); +var serve = require('metalsmith-serve'); +var watch = require('metalsmith-watch'); +var moment = require('moment'); +var i18n = require('i18next'); +var headings = require('metalsmith-headings'); +var convert = require('metalsmith-convert'); + +//i18n.init({ lng: ""fr-FR"" }); +i18n.init({ lng: ""en-US"" }); +i18n.registerAppHelper(metalsmith); + +// Image handling: metalsmith-convert config + +var convertConfig = { + src: '**/*.jpg', + target: 'jpg', + resize: { + width: 320, + height: 320, + resizeStyle: 'aspectfit' + } +}; + + +metalsmith(__dirname) + .source('src') + .use(markdown()) + .use(headings('h2')) + .use(templates({ + engine: 'jade', + moment: moment, + i18n: i18n + })) + .use(convert(convertConfig)) + .destination('build') + .use(serve({ + port: 8081 + })) + .use(watch({ + paths: { + ""${source}/**/*"": true, + ""templates/**/*"": ""**/*.md"", + } + })) + .build(function (err) { + if (err) { + throw err; + } + }); +" +Fix a bug where splitlines was called twice for parse_file,"class Parser(object): + """"""Base class for all parsers to inheret with common interface"""""" + + def iterparse(self, iterator, **kwargs): + """""" + Parses a iterator/generator. Must be implemented by each parser. + + :param value: Iterable containing data + + :return: yeilds parsed data + """""" + raise NotImplementedError('Must implement iterparse method!') + + def parse(self, value, **kwargs): + """""" + Parses a stirng. By default accumlates from the iterparse method. + + :param value: + String containing the data to parse. + + :return: data structure containing parsed data + """""" + result = [] + value = value.splitlines() + for item in self.iterparse(iter(value), **kwargs): + result.append(item) + + if len(result) == 1: + return result[0] + else: + return result + + def parse_file(self, filename, **kwargs): + """""" + Parses lines from a file. By default accumlates from + iterparse_file method by splitting the file by lines. + + :param filename: string with the path to the file. + + :return: data structure containing parsed data + """""" + with open(filename, 'rU') as value: + return self.parse(value.read(), **kwargs) + + def iterparse_file(self, filename, **kwargs): + + def file_generator(fname): + with open(fname, 'rU') as f: + for line in f: + yield line.strip('\r\n') + + generator = file_generator(filename) + for value in self.iterparse(generator, **kwargs): + yield value +","class Parser(object): + """"""Base class for all parsers to inheret with common interface"""""" + + def iterparse(self, iterator, **kwargs): + """""" + Parses a iterator/generator. Must be implemented by each parser. + + :param value: Iterable containing data + + :return: yeilds parsed data + """""" + raise NotImplementedError('Must implement iterparse method!') + + def parse(self, value, **kwargs): + """""" + Parses a stirng. By default accumlates from the iterparse method. + + :param value: + String containing the data to parse. + + :return: data structure containing parsed data + """""" + result = [] + value = value.splitlines() + for item in self.iterparse(iter(value), **kwargs): + result.append(item) + + if len(result) == 1: + return result[0] + else: + return result + + def parse_file(self, filename, **kwargs): + """""" + Parses lines from a file. By default accumlates from + iterparse_file method by splitting the file by lines. + + :param filename: string with the path to the file. + + :return: data structure containing parsed data + """""" + with open(filename, 'rU') as value: + return self.parse(value.read().splitlines(), **kwargs) + + def iterparse_file(self, filename, **kwargs): + + def file_generator(fname): + with open(fname, 'rU') as f: + for line in f: + yield line.strip('\r\n') + + generator = file_generator(filename) + for value in self.iterparse(generator, **kwargs): + yield value +" +Add limit and offset in query string,"const db = require('../db.js'); + +module.exports = (self, offSet) => { + const queryStr = `SELECT teach.teach_id FROM ( + ( + SELECT users_languages_levels.user AS teach_id FROM users_languages_levels + INNER JOIN languages_levels + ON users_languages_levels.languages_levels = languages_levels.id + INNER JOIN languages + ON languages_levels.language = languages.id + INNER JOIN levels + ON languages_levels.level = levels.id + WHERE languages.name IN (${self.willLearn.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') + ) AS teach + INNER JOIN + ( + SELECT users_languages_levels.user AS learn_id FROM users_languages_levels + INNER JOIN languages_levels + ON users_languages_levels.languages_levels = languages_levels.id + INNER JOIN languages + ON languages_levels.language = languages.id + INNER JOIN levels + ON languages_levels.level = levels.id + WHERE languages.name IN (${self.canTeach.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') + ) AS learn + ON teach.teach_id = learn.learn_id + ) + LIMIT 20 + OFFSET ${offSet} + `; + // db.query(); +}; +","const db = require('../db.js'); + +module.exports = (self, offSet) => { + const queryStr = `SELECT teach.teach_id FROM ( + ( + SELECT users_languages_levels.user AS teach_id FROM users_languages_levels + INNER JOIN languages_levels + ON users_languages_levels.languages_levels = languages_levels.id + INNER JOIN languages + ON languages_levels.language = languages.id + INNER JOIN levels + ON languages_levels.level = levels.id + WHERE languages.name IN (${self.willLearn.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') + ) AS teach + INNER JOIN + ( + SELECT users_languages_levels.user AS learn_id FROM users_languages_levels + INNER JOIN languages_levels + ON users_languages_levels.languages_levels = languages_levels.id + INNER JOIN languages + ON languages_levels.language = languages.id + INNER JOIN levels + ON languages_levels.level = levels.id + WHERE languages.name IN (${self.canTeach.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') + ) AS learn + ON teach.teach_id = learn.learn_id + ) + `; + // db.query(); +}; +" +fix(docs): Fix template url for UI docs,"/** + * This file is part of Superdesk. + * + * Copyright 2013, 2014 Sourcefabric z.u. and contributors. + * + * For the full copyright and license information, please see the + * AUTHORS and LICENSE files distributed with this source code, or + * at https://www.sourcefabric.org/superdesk/license + */ + +(function() { + + 'use strict'; + + var app = angular.module('superdesk.docs', []); + + MainDocsView.$inject = ['$location', '$anchorScroll']; + function MainDocsView($location, $anchorScroll) { + return { + templateUrl: '/docs/views/main.html', + link: function(scope, elem, attrs) { + scope.scrollTo = function(id) { + $location.hash(id); + $anchorScroll(); + }; + } + }; + } + + app.directive('sdDocs', MainDocsView); + app.directive('prettyprint', function() { + return { + restrict: 'C', + link: function postLink(scope, element, attrs) { + var langExtension = attrs['class'].match(/\blang(?:uage)?-([\w.]+)(?!\S)/); + if (langExtension) { + langExtension = langExtension[1]; + } + element.html(window.prettyPrintOne(_.escape(element.html()), langExtension, true)); + } + + }; + }); + + return app; + +})(); +","/** + * This file is part of Superdesk. + * + * Copyright 2013, 2014 Sourcefabric z.u. and contributors. + * + * For the full copyright and license information, please see the + * AUTHORS and LICENSE files distributed with this source code, or + * at https://www.sourcefabric.org/superdesk/license + */ + +(function() { + + 'use strict'; + + var app = angular.module('superdesk.docs', []); + + MainDocsView.$inject = ['$location', '$anchorScroll']; + function MainDocsView($location, $anchorScroll) { + return { + templateUrl: 'docs/views/main.html', + link: function(scope, elem, attrs) { + scope.scrollTo = function(id) { + $location.hash(id); + $anchorScroll(); + }; + } + }; + } + + app.directive('sdDocs', MainDocsView); + app.directive('prettyprint', function() { + return { + restrict: 'C', + link: function postLink(scope, element, attrs) { + var langExtension = attrs['class'].match(/\blang(?:uage)?-([\w.]+)(?!\S)/); + if (langExtension) { + langExtension = langExtension[1]; + } + element.html(window.prettyPrintOne(_.escape(element.html()), langExtension, true)); + } + + }; + }); + + return app; + +})(); +" +"Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong. + +--HG-- +extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%4014359","# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here +# has been referenced in documentation. +from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME +from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL +from django.contrib.admin.options import StackedInline, TabularInline +from django.contrib.admin.sites import AdminSite, site + + +def autodiscover(): + """""" + Auto-discover INSTALLED_APPS admin.py modules and fail silently when + not present. This forces an import on them to register any admin bits they + may want. + """""" + + import copy + from django.conf import settings + from django.utils.importlib import import_module + from django.utils.module_loading import module_has_submodule + + for app in settings.INSTALLED_APPS: + mod = import_module(app) + # Attempt to import the app's admin module. + try: + before_import_registry = copy.copy(site._registry) + import_module('%s.admin' % app) + except: + # Reset the model registry to the state before the last import as + # this import will have to reoccur on the next request and this + # could raise NotRegistered and AlreadyRegistered exceptions + # (see #8245). + site._registry = before_import_registry + + # Decide whether to bubble up this error. If the app just + # doesn't have an admin module, we can ignore the error + # attempting to import it, otherwise we want it to bubble up. + if module_has_submodule(mod, 'admin'): + raise +","from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL +from django.contrib.admin.options import StackedInline, TabularInline +from django.contrib.admin.sites import AdminSite, site + + +def autodiscover(): + """""" + Auto-discover INSTALLED_APPS admin.py modules and fail silently when + not present. This forces an import on them to register any admin bits they + may want. + """""" + + import copy + from django.conf import settings + from django.utils.importlib import import_module + from django.utils.module_loading import module_has_submodule + + for app in settings.INSTALLED_APPS: + mod = import_module(app) + # Attempt to import the app's admin module. + try: + before_import_registry = copy.copy(site._registry) + import_module('%s.admin' % app) + except: + # Reset the model registry to the state before the last import as + # this import will have to reoccur on the next request and this + # could raise NotRegistered and AlreadyRegistered exceptions + # (see #8245). + site._registry = before_import_registry + + # Decide whether to bubble up this error. If the app just + # doesn't have an admin module, we can ignore the error + # attempting to import it, otherwise we want it to bubble up. + if module_has_submodule(mod, 'admin'): + raise +" +Simplify now replaces all non alphanumeric chars,"// Structure that will be used throughout the other data +var options, legend, disp, data; + +var util = { + formatDate: d3.time.format(""%Y-%m-%d %H:%M:%S""), + date: function(str) { + return util.formatDate.parse(str); + }, + simplify: function(str) { + return ""l"" + str.replace(/\W/g, '_'); + }, + compareCollections: function(a, b) { + return util.compareDates(new Date(a.StartTime), new Date(b.StartTime)); + }, + compareSeries: function(a, b) { + if(a.sum !== undefined && b.sum !== undefined) + return b.sum - a.sum; + return a.order - b.order; + }, + compareDates: function(a, b) { + if(a < b) + return -1; + if(a > b) + return 1; + return 0; + }, + lunique: function(list) { + return Array.from(new Set(list)).sort(); + }, + range: function(length) { + var arr = []; + for(var i = 0; i < length; i++) { + arr.push(i); + } + return arr; + } +} + +window.onload = initialize; + +function initialize() { + options = new Options(); + options.init(); + + disp = new Display(); + disp.init(); + + data = new Data(); + data.loadCollections(); +} + +","// Structure that will be used throughout the other data +var options, legend, disp, data; + +var util = { + formatDate: d3.time.format(""%Y-%m-%d %H:%M:%S""), + date: function(str) { + return util.formatDate.parse(str); + }, + simplify: function(str) { + return ""l"" + str.replace(/[\s\.#]+/g, '_'); + }, + compareCollections: function(a, b) { + return util.compareDates(new Date(a.StartTime), new Date(b.StartTime)); + }, + compareSeries: function(a, b) { + if(a.sum !== undefined && b.sum !== undefined) + return b.sum - a.sum; + return a.order - b.order; + }, + compareDates: function(a, b) { + if(a < b) + return -1; + if(a > b) + return 1; + return 0; + }, + lunique: function(list) { + return Array.from(new Set(list)).sort(); + }, + range: function(length) { + var arr = []; + for(var i = 0; i < length; i++) { + arr.push(i); + } + return arr; + } +} + +window.onload = initialize; + +function initialize() { + options = new Options(); + options.init(); + + disp = new Display(); + disp.init(); + + data = new Data(); + data.loadCollections(); +} + +" +Change UI gets to use readline instead of read,"from pythonwarrior.config import Config +import time + + +class UI(object): + @staticmethod + def puts(msg): + if Config.out_stream: + return Config.out_stream.write(msg + ""\n"") + + @staticmethod + def puts_with_delay(msg): + result = UI.puts(msg) + if Config.delay: + time.sleep(Config.delay) + return result + + @staticmethod + def write(msg): + if Config.out_stream: + return Config.out_stream.write(msg) + + @staticmethod + def gets(): + if Config.in_stream: + return Config.in_stream.readline() + else: + return '' + + @staticmethod + def request(msg): + UI.write(msg) + return UI.gets().rstrip() + + @staticmethod + def ask(msg): + return UI.request(""%s [yn] "" % msg) == 'y' + + @staticmethod + def choose(item, options): + if len(options) == 1: + response = options[0] + else: + for idx, option in enumerate(options): + if type(option) == list: + UI.puts(""[%d] %s"" % (idx+1, option[-1])) + else: + UI.puts(""[%d] %s"" % (idx+1, option)) + choice = UI.request(""Choose %s by typing the number: "" % item) + response = options[int(choice)-1] + if type(response) == list: + return response[0] + else: + return response +","from pythonwarrior.config import Config +import time + + +class UI(object): + @staticmethod + def puts(msg): + if Config.out_stream: + return Config.out_stream.write(msg + ""\n"") + + @staticmethod + def puts_with_delay(msg): + result = UI.puts(msg) + if Config.delay: + time.sleep(Config.delay) + return result + + @staticmethod + def write(msg): + if Config.out_stream: + return Config.out_stream.write(msg) + + @staticmethod + def gets(): + if Config.in_stream: + return Config.in_stream.read() + else: + return '' + + @staticmethod + def request(msg): + UI.write(msg) + return UI.gets().rstrip() + + @staticmethod + def ask(msg): + return UI.request(""%s [yn] "" % msg) == 'y' + + @staticmethod + def choose(item, options): + if len(options) == 1: + response = options[0] + else: + for idx, option in enumerate(options): + if type(option) == list: + UI.puts(""[%d] %s"" % (idx+1, option[-1])) + else: + UI.puts(""[%d] %s"" % (idx+1, option)) + choice = UI.request(""Choose %s by typing the number: "" % item) + response = options[int(choice)-1] + if type(response) == list: + return response[0] + else: + return response +" +Allow configuration of extensions for types.,"from django.conf import settings + +import xlrd +import os + + +base_loader_error = 'The Loader class can only be used by extending it.' + + +extensions = getattr( + settings, + 'IMPORTER_EXTENSIONS', + { + 'excel': ('.xls', '.xlsx'), + } +) + + +class Loader(object): + def __init__(self, file_info, autoload=True): + self.filename = file_info.path + + if autoload is True: + return self.open() + + def open(self): + raise NotImplementedError(base_loader_error) + + def close(self): + pass + + @classmethod + def sniff(cls, file_info): + raise NotImplementedError(base_loader_error) + + +class ExcelLoader(Loader): + supports_sheets = True + type_name = 'excel' + + def open(self): + self.backend = xlrd.open_workbook(self.filename) + self.sheet_names = self.backend.sheet_names() + self.sheet_count = len(self.sheet_names) + + def sheet_by_name(self, name): + """""" Returns a sheet based on it's name. """""" + + return self.backend.sheet_by_name(name) + + def close(self): + self.backend.release_resources() + + @classmethod + def sniff(cls, file_info): + + # TODO: Find a way to really sniff the file. + if not 'excel' in extensions: return False + return os.path.splitext(file_info.path)[-1] in extensions['excel'] + + +# TODO: Finish Loader for importing from CSV data. +class CSVLoader(Loader): + supports_sheets = False +","import xlrd +import os + + +base_loader_error = 'The Loader class can only be used by extending it.' + + +excel_extensions = [ + '.xls', + '.xlsx', +] + + +class Loader(object): + def __init__(self, file_info, autoload=True): + self.filename = file_info.path + + if autoload is True: + return self.open() + + def open(self): + raise NotImplementedError(base_loader_error) + + def close(self): + pass + + @classmethod + def sniff(cls, file_info): + raise NotImplementedError(base_loader_error) + + +class ExcelLoader(Loader): + supports_sheets = True + type_name = 'excel' + + def open(self): + self.backend = xlrd.open_workbook(self.filename) + self.sheet_names = self.backend.sheet_names() + self.sheet_count = len(self.sheet_names) + + def sheet_by_name(self, name): + """""" Returns a sheet based on it's name. """""" + + return self.backend.sheet_by_name(name) + + def close(self): + self.backend.release_resources() + + @classmethod + def sniff(cls, file_info): + + # TODO: Find a way to really sniff the file. + return os.path.splitext(file_info.path)[-1] in excel_extensions + + +# TODO: Finish Loader for importing from CSV data. +class CSVLoader(Loader): + supports_sheets = False +" +Set to busy when terminating so we don't accidently use it,"messenger = $messenger; + } + + /** + * @param Rpc $rpc + * @return PromiseInterface + */ + public function rpc(Rpc $rpc) + { + $this->busy = true; + return $this->messenger->rpc($rpc)->always(function () { + $this->busy = false; + $this->emit('done', [$this]); + }); + } + + /** + * @return bool + */ + public function isBusy() + { + return $this->busy; + } + + /* + * @return PromiseInterface + */ + public function terminate() + { + $this->busy = true; + $this->emit('terminating', [$this]); + return $this->messenger->softTerminate(); + } +} +","messenger = $messenger; + } + + /** + * @param Rpc $rpc + * @return PromiseInterface + */ + public function rpc(Rpc $rpc) + { + $this->busy = true; + return $this->messenger->rpc($rpc)->always(function () { + $this->busy = false; + $this->emit('done', [$this]); + }); + } + + /** + * @return bool + */ + public function isBusy() + { + return $this->busy; + } + + /* + * @return PromiseInterface + */ + public function terminate() + { + $this->emit('terminating', [$this]); + return $this->messenger->softTerminate(); + } +} +" +"Split chained functions, to ease debugging","package main + +import ( + ""github.com/hoisie/mustache"" + ""github.com/hoisie/web"" + ""github.com/russross/blackfriday"" + ""io/ioutil"" + ""log"" + ""os"" +) + +type Entry struct { + Title string + Body string +} + +func handler(ctx *web.Context, path string) { + if path == """" { + var data = []Entry { + {""Title1"", ""Body 1""}, + {""Title2"", ""Body 2""}, + } + html := mustache.RenderFile(""hello.mustache"", + map[string]interface{}{ + ""entries"": data}) + ctx.WriteString(html) + return + } else { + input, err := ioutil.ReadFile(path) + if err != nil { + ctx.NotFound(""File Not Found\n"" + err.Error()) + return + } + ctx.WriteString(string(blackfriday.MarkdownCommon(input))) + return + } + ctx.Abort(500, ""Server Error"") +} + +func main() { + f, err := os.Create(""server.log"") + if err != nil { + println(err.Error()) + return + } + logger := log.New(f, """", log.Ldate|log.Ltime) + web.Get(""/(.*)"", handler) + web.SetLogger(logger) + web.Config.StaticDir = ""static"" + web.Run("":8080"") +} +","package main + +import ( + ""github.com/hoisie/mustache"" + ""github.com/hoisie/web"" + ""github.com/russross/blackfriday"" + ""io/ioutil"" + ""log"" + ""os"" +) + +type Entry struct { + Title string + Body string +} + +func handler(ctx *web.Context, path string) { + if path == """" { + var data = []Entry { + {""Title1"", ""Body 1""}, + {""Title2"", ""Body 2""}, + } + ctx.WriteString(mustache.RenderFile(""hello.mustache"", + map[string]interface{}{ + ""entries"": data})) + return + } else { + input, err := ioutil.ReadFile(path) + if err != nil { + ctx.NotFound(""File Not Found\n"" + err.Error()) + return + } + ctx.WriteString(string(blackfriday.MarkdownCommon(input))) + return + } + ctx.Abort(500, ""Server Error"") +} + +func main() { + f, err := os.Create(""server.log"") + if err != nil { + println(err.Error()) + return + } + logger := log.New(f, """", log.Ldate|log.Ltime) + web.Get(""/(.*)"", handler) + web.SetLogger(logger) + web.Config.StaticDir = ""static"" + web.Run("":8080"") +} +" +"Add comment to clarify coordinate order + +coordinates are (y,x) in the track.",""""""" Created by Max 12/2/2017 """""" +import pprint + +import numpy as np + + +class TrackParser: + + @staticmethod + def parse_track(path_to_track_file: str) -> np.ndarray: + track = None + with open(path_to_track_file, 'r') as track_file: + lines = track_file.readlines() + dimensions_str = lines[0] + dims = dimensions_str.split(',') + + # (Y,X) coords. + track = np.zeros((int(dims[0]), int(dims[1]))) + + for line_index in range(1, len(lines)): + line = lines[line_index] + for char_index in range(len(line) - 1): + track_value = TrackParser.get_char_value(line[char_index]) + track[line_index-1][char_index] = track_value + + return track + + @staticmethod + def get_char_value(char: str): + if char == '#': + return -1 + elif char == '.': + return 0 + elif char == 'S': + return 1 + elif char == 'F': + return 2 + else: + return -1 + + +# np.set_printoptions(linewidth=500) +# pprint.pprint(TrackParser.parse_track(""tracks/L-track.txt""), width=500) + +",""""""" Created by Max 12/2/2017 """""" +import pprint + +import numpy as np + + +class TrackParser: + + @staticmethod + def parse_track(path_to_track_file: str) -> np.ndarray: + track = None + with open(path_to_track_file, 'r') as track_file: + lines = track_file.readlines() + dimensions_str = lines[0] + dims = dimensions_str.split(',') + + track = np.zeros((int(dims[0]), int(dims[1]))) + + for line_index in range(1, len(lines)): + line = lines[line_index] + for char_index in range(len(line) - 1): + track_value = TrackParser.get_char_value(line[char_index]) + track[line_index-1][char_index] = track_value + + return track + + @staticmethod + def get_char_value(char: str): + if char == '#': + return -1 + elif char == '.': + return 0 + elif char == 'S': + return 1 + elif char == 'F': + return 2 + else: + return -1 + + +np.set_printoptions(linewidth=500) +pprint.pprint(TrackParser.parse_track(""tracks/L-track.txt""), width=500) + +" +Return always null from websocket connection route handlers,"import debugLog from '../debugLog.js' + +export default function httpRoutes(webSocketClients) { + return [ + { + method: 'GET', + path: '/{path*}', + handler(request, h) { + return h.response(null).code(426) + }, + }, + + { + method: 'POST', + options: { + payload: { + parse: false, + }, + }, + path: '/@connections/{connectionId}', + handler(request, h) { + const { + params: { connectionId }, + payload, + url, + } = request + + debugLog(`got POST to ${url}`) + + // TODO, is this correct? + if (!payload) { + return null + } + + const clientExisted = webSocketClients.send( + connectionId, + // payload is a Buffer + payload.toString('utf-8'), + ) + + if (!clientExisted) { + return h.response(null).code(410) + } + + debugLog(`sent data to connection:${connectionId}`) + + return null + }, + }, + + { + method: 'DELETE', + options: { + payload: { + parse: false, + }, + }, + path: '/@connections/{connectionId}', + handler(request, h) { + const { + params: { connectionId }, + url, + } = request + + debugLog(`got DELETE to ${url}`) + + const clientExisted = webSocketClients.close(connectionId) + + if (!clientExisted) { + return h.response(null).code(410) + } + + debugLog(`closed connection:${connectionId}`) + + return h.response(null).code(204) + }, + }, + ] +} +","import debugLog from '../debugLog.js' + +export default function httpRoutes(webSocketClients) { + return [ + { + method: 'GET', + path: '/{path*}', + handler(request, h) { + h.response().code(426) + }, + }, + + { + method: 'POST', + options: { + payload: { + parse: false, + }, + }, + path: '/@connections/{connectionId}', + handler(request, h) { + const { + params: { connectionId }, + payload, + url, + } = request + + debugLog(`got POST to ${url}`) + + if (!payload) { + return '' + } + + const clientExisted = webSocketClients.send( + connectionId, + // payload is a Buffer + payload.toString('utf-8'), + ) + + if (!clientExisted) { + return h.response().code(410) + } + + debugLog(`sent data to connection:${connectionId}`) + + return '' + }, + }, + + { + method: 'DELETE', + options: { + payload: { + parse: false, + }, + }, + path: '/@connections/{connectionId}', + handler(request, h) { + const { + params: { connectionId }, + url, + } = request + + debugLog(`got DELETE to ${url}`) + + const clientExisted = webSocketClients.close(connectionId) + + if (!clientExisted) { + return h.response().code(410) + } + + debugLog(`closed connection:${connectionId}`) + + return h.response().code(204) + }, + }, + ] +} +" +"Fix an intermittent axiom test failure that occurs only in certain environments. + +Fixes #2857 + +Author: glyph + +Reviewer: exarkun, mithrandi + +This change fixes `axiom.test.historic.test_processor1to2.ProcessorUpgradeTest.test_pollingRemoval` to wait until its processor has actually been run before making any assertions."," +from twisted.internet.defer import Deferred + +from axiom.test.historic.stubloader import StubbedTest +from axiom.test.historic.stub_processor1to2 import DummyProcessor + +class ProcessorUpgradeTest(StubbedTest): + def setUp(self): + # Ick, we need to catch the run event of DummyProcessor, and I can't + # think of another way to do it. + self.dummyRun = DummyProcessor.run.im_func + self.calledBack = Deferred() + def dummyRun(calledOn): + self.calledBack.callback(calledOn) + DummyProcessor.run = dummyRun + + return StubbedTest.setUp(self) + + + def tearDown(self): + # Okay this is a pretty irrelevant method on a pretty irrelevant class, + # but we'll fix it anyway. + DummyProcessor.run = self.dummyRun + + return StubbedTest.tearDown(self) + + + def test_pollingRemoval(self): + """""" + Test that processors lose their idleInterval but none of the rest of + their stuff, and that they get scheduled by the upgrader so they can + figure out what state they should be in. + """""" + proc = self.store.findUnique(DummyProcessor) + self.assertEquals(proc.busyInterval, 100) + self.failIfEqual(proc.scheduled, None) + def assertion(result): + self.assertEquals(result, proc) + return self.calledBack.addCallback(assertion) + +"," +from axiom.item import Item +from axiom.attributes import text +from axiom.batch import processor +from axiom.iaxiom import IScheduler + +from axiom.test.historic.stubloader import StubbedTest +from axiom.test.historic.stub_processor1to2 import DummyProcessor + + + +class ProcessorUpgradeTest(StubbedTest): + def setUp(self): + # Ick, we need to catch the run event of DummyProcessor, and I can't + # think of another way to do it. + self.dummyRun = DummyProcessor.run.im_func + self.dummyRunCalls = [] + def dummyRun(calledOn): + self.dummyRunCalls.append(calledOn) + DummyProcessor.run = dummyRun + + return StubbedTest.setUp(self) + + + def tearDown(self): + # Okay this is a pretty irrelevant method on a pretty irrelevant class, + # but we'll fix it anyway. + DummyProcessor.run = self.dummyRun + + return StubbedTest.tearDown(self) + + + def test_pollingRemoval(self): + """""" + Test that processors lose their idleInterval but none of the rest of + their stuff, and that they get scheduled by the upgrader so they can + figure out what state they should be in. + """""" + proc = self.store.findUnique(DummyProcessor) + self.assertEquals(proc.busyInterval, 100) + self.failIfEqual(proc.scheduled, None) + + self.assertEquals(self.dummyRunCalls, [proc]) +" +"Fix admin-api to show that users are retrieved by ip, not username","package org.keycloak.admin.client.resource; + +import org.keycloak.representations.idm.UserRepresentation; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; + +public interface UsersResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + List search(@QueryParam(""username"") String username, + @QueryParam(""firstName"") String firstName, + @QueryParam(""lastName"") String lastName, + @QueryParam(""email"") String email, + @QueryParam(""first"") Integer firstResult, + @QueryParam(""max"") Integer maxResults); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List search(@QueryParam(""search"") String search, + @QueryParam(""first"") Integer firstResult, + @QueryParam(""max"") Integer maxResults); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + Response create(UserRepresentation userRepresentation); + + @Path(""{id}"") + UserResource get(@PathParam(""id"") String id); + +} +","package org.keycloak.admin.client.resource; + +import org.keycloak.representations.idm.UserRepresentation; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; + +public interface UsersResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + public List search(@QueryParam(""username"") String username, + @QueryParam(""firstName"") String firstName, + @QueryParam(""lastName"") String lastName, + @QueryParam(""email"") String email, + @QueryParam(""first"") Integer firstResult, + @QueryParam(""max"") Integer maxResults); + + @GET + @Produces(MediaType.APPLICATION_JSON) + public List search(@QueryParam(""search"") String search, + @QueryParam(""first"") Integer firstResult, + @QueryParam(""max"") Integer maxResults); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + Response create(UserRepresentation userRepresentation); + + @Path(""{username}"") + public UserResource get(@PathParam(""username"") String username); + +} +" +Add file extension to hash,"liveDocx; + } + + public function setLiveDocx(MailMerge $liveDocx) + { + $this->liveDocx = $liveDocx; + } + + public function merge(File $file, \Traversable $data, $outputFile, $format = 'pdf') + { + // Calculate MD5 hash for file; the template must have an extension, + // or LiveDocx will be confused. + $hash = md5_file($file->getPathname()) . '.' . $file->getExtension(); + + $tmpFile = sys_get_temp_dir() . '/' . $hash; + copy($file->getPathname(), $tmpFile); + + // Upload local template to server if it hasn't been uploaded yet + if (!$this->liveDocx->templateExists($hash)) { + $this->liveDocx->uploadTemplate($tmpFile); + } + + $this->liveDocx->setRemoteTemplate($hash); + + foreach ($data as $field => $value) { + $this->liveDocx->assign($field, $value); + } + + $this->liveDocx->createDocument(); + $document = $this->liveDocx->retrieveDocument($format); + file_put_contents($outputFile, $document); + + return $outputFile; + } +}","liveDocx; + } + + public function setLiveDocx(MailMerge $liveDocx) + { + $this->liveDocx = $liveDocx; + } + + public function merge(File $file, \Traversable $data, $outputFile, $format = 'pdf') + { + // Calculate MD5 hash for file + $hash = md5_file($file->getPathname()); + $tmpFile = sys_get_temp_dir() . '/' . $hash; + copy($file->getPathname(), $tmpFile); + + // Upload local template to server if it hasn't been uploaded yet + if (!$this->liveDocx->templateExists($hash)) { + $this->liveDocx->uploadTemplate($tmpFile); + } + + $this->liveDocx->setLocalTemplate($file->getPathname()); + + foreach ($data as $field => $value) { + $this->liveDocx->assign($field, $value); + } + + $this->liveDocx->createDocument(); + $document = $this->liveDocx->retrieveDocument($format); + file_put_contents($outputFile, $document); + + return $outputFile; + } +}" +Move import of the main library.,"import sys +import shutil +import os +from setuptools import setup, find_packages +import subprocess + + +if len(sys.argv) > 0: + if sys.argv[1] in (""install"", ""develop""): + try: + os.mkdir(""/etc/spider/"") + except FileExistsError: + print(""Warning: /etc/spider directory already exists..."") + print(""Copying file to /etc/spider/"") + ret = shutil.copy(""conf/cobwebs.yaml"", ""/etc/spider/cobwebs.yaml"") + print(ret) + subprocess.call([""ls"", ""-l"", ""/etc/spider""]) + + +import cobwebs + + +setup( + + name='cobwebs', + + version=cobwebs.__version__, + + packages=find_packages(), + + author=""Asteroide"", + + author_email=""asteroide__AT__domtombox.net"", + + description=""A house for spider utilities"", + + long_description=open('README.md').read(), + + # install_requires= , + + include_package_data=True, + + url='https://github.com/asteroide/immo_spider', + + classifiers=[ + ""Programming Language :: Python"", + ""Development Status :: 1 - Planning"", + ""License :: OSI Approved"", + ""Natural Language :: French"", + ""Operating System :: OS Independent"", + ""Programming Language :: Python :: 3.5"", + ""Topic :: Internet :: WWW/HTTP :: Indexing/Search"", + ""License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)"" + ], + +) +","import sys +import shutil +import os +from setuptools import setup, find_packages +import cobwebs +import subprocess + + +if len(sys.argv) > 0: + if sys.argv[1] in (""install"", ""develop""): + try: + os.mkdir(""/etc/spider/"") + except FileExistsError: + print(""Warning: /etc/spider directory already exists..."") + print(""Copying file to /etc/spider/"") + ret = shutil.copy(""conf/cobwebs.yaml"", ""/etc/spider/cobwebs.yaml"") + print(ret) + subprocess.call([""ls"", ""-l"", ""/etc/spider""]) + + +setup( + + name='cobwebs', + + version=cobwebs.__version__, + + packages=find_packages(), + + author=""Asteroide"", + + author_email=""asteroide__AT__domtombox.net"", + + description=""A house for spider utilities"", + + long_description=open('README.md').read(), + + # install_requires= , + + include_package_data=True, + + url='https://github.com/asteroide/immo_spider', + + classifiers=[ + ""Programming Language :: Python"", + ""Development Status :: 1 - Planning"", + ""License :: OSI Approved"", + ""Natural Language :: French"", + ""Operating System :: OS Independent"", + ""Programming Language :: Python :: 3.5"", + ""Topic :: Internet :: WWW/HTTP :: Indexing/Search"", + ""License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)"" + ], + +) +" +Add a debugger trigger shortcut to debug plugin,"enabled(){ + this.isDebugging = false; + + this.onKeyDown = (e) => { + // ========================== + // F4 key - toggle debug mode + // ========================== + + if (e.keyCode === 115){ + this.isDebugging = !this.isDebugging; + $("".nav-user-info"").first().css(""background-color"", this.isDebugging ? ""#5A6B75"" : ""#292F33""); + } + + // Debug mode handling + + else if (this.isDebugging){ + e.preventDefault(); + + // =================================== + // N key - simulate popup notification + // S key - simulate sound notification + // =================================== + + if (e.keyCode === 78 || e.keyCode === 83){ + var col = TD.controller.columnManager.getAllOrdered()[0]; + + var prevPopup = col.model.getHasNotification(); + var prevSound = col.model.getHasSound(); + + col.model.setHasNotification(e.keyCode === 78); + col.model.setHasSound(e.keyCode === 83); + + $.publish(""/notifications/new"",[{ + column: col, + items: [ + col.updateArray[Math.floor(Math.random()*col.updateArray.length)] + ] + }]); + + setTimeout(function(){ + col.model.setHasNotification(prevPopup); + col.model.setHasSound(prevSound); + }, 1); + } + + // ======================== + // D key - trigger debugger + // ======================== + + else if (e.keyCode === 68){ + debugger; + } + } + }; +} + +ready(){ + $(document).on(""keydown"", this.onKeyDown); +} + +disabled(){ + $(document).off(""keydown"", this.onKeyDown); +} +","enabled(){ + this.isDebugging = false; + + this.onKeyDown = (e) => { + // ========================== + // F4 key - toggle debug mode + // ========================== + + if (e.keyCode === 115){ + this.isDebugging = !this.isDebugging; + $("".nav-user-info"").first().css(""background-color"", this.isDebugging ? ""#5A6B75"" : ""#292F33""); + } + + // Debug mode handling + + else if (this.isDebugging){ + e.preventDefault(); + + // =================================== + // N key - simulate popup notification + // S key - simulate sound notification + // =================================== + + if (e.keyCode === 78 || e.keyCode === 83){ + var col = TD.controller.columnManager.getAllOrdered()[0]; + + var prevPopup = col.model.getHasNotification(); + var prevSound = col.model.getHasSound(); + + col.model.setHasNotification(e.keyCode === 78); + col.model.setHasSound(e.keyCode === 83); + + $.publish(""/notifications/new"",[{ + column: col, + items: [ + col.updateArray[Math.floor(Math.random()*col.updateArray.length)] + ] + }]); + + setTimeout(function(){ + col.model.setHasNotification(prevPopup); + col.model.setHasSound(prevSound); + }, 1); + } + } + }; +} + +ready(){ + $(document).on(""keydown"", this.onKeyDown); +} + +disabled(){ + $(document).off(""keydown"", this.onKeyDown); +} +" +Fix translation issue on EmailAuthForm,"# -*- coding: utf-8 -*- + +from django import forms +from django.contrib.auth import authenticate +from django.utils.translation import ugettext as _, ugettext_lazy as __ + +class EmailAuthForm(forms.Form): + email = forms.EmailField(required=True, label=__(u""Email"")) + password = forms.CharField(label=__(""Password""), widget=forms.PasswordInput) + + def __init__(self, request=None, *args, **kwargs): + super(EmailAuthForm, self).__init__(*args, **kwargs) + + def _authenticate(self): + email = self.cleaned_data.get('email') + password = self.cleaned_data.get('password') + + error_messages = { + 'invalid_login': _(""Please enter a correct %(email)s and password. "" + ""Note that both fields may be case-sensitive.""), + } + + if email and password: + self.user_cache = authenticate(email=email, password=password) + if self.user_cache is None: + raise forms.ValidationError( + error_messages['invalid_login'], + code='invalid_login', + params={'email': _(u""email"")}, + ) + + def get_user(self): + return self.user_cache + + def clean(self): + self._authenticate() + return self.cleaned_data","# -*- coding: utf-8 -*- + +from django import forms +from django.contrib.auth import authenticate +from django.utils.translation import ugettext as _ + +class EmailAuthForm(forms.Form): + email = forms.EmailField(required=True, label=_(u""Email"")) + password = forms.CharField(label=_(""Password""), widget=forms.PasswordInput) + + def __init__(self, request=None, *args, **kwargs): + super(EmailAuthForm, self).__init__(*args, **kwargs) + + def _authenticate(self): + email = self.cleaned_data.get('email') + password = self.cleaned_data.get('password') + + error_messages = { + 'invalid_login': _(""Please enter a correct %(email)s and password. "" + ""Note that both fields may be case-sensitive.""), + } + + if email and password: + self.user_cache = authenticate(email=email, password=password) + if self.user_cache is None: + raise forms.ValidationError( + error_messages['invalid_login'], + code='invalid_login', + params={'email': _(u""email"")}, + ) + + def get_user(self): + return self.user_cache + + def clean(self): + self._authenticate() + return self.cleaned_data" +"Remove tmp layer after saving + +Add default attributes also to already drawn features","export default { + template: require('./draw-layer-metadata.html'), + bindings: { + layer: '<', + }, + controller: function ($scope, $timeout, HsDrawService, HsMapService) { + 'ngInject'; + this.modalVisible = true; + const vm = this; + $timeout(() => { + vm.title = $scope.$ctrl.layer.get('title'); + vm.path = $scope.$ctrl.layer.get('path'); + }, 0); + angular.extend(vm, { + newLayerPath: '', + attributes: [], + titleChanged() { + vm.layer.set('title', vm.title); + }, + confirm() { + const dic = {}; + + let tmpLayer = HsMapService.findLayerByTitle('tmpDrawLayer') || null; + if (tmpLayer) { + HsMapService.map.removeLayer(tmpLayer) + } + + vm.attributes.forEach((a) => (dic[a.name] = a.value)); + let editorConfig = vm.layer.get('editor'); + if (angular.isUndefined(editorConfig)) { + editorConfig = {}; + vm.layer.set('editor', editorConfig); + } + editorConfig.defaultAttributes = dic; + + vm.layer.getSource().forEachFeature((f)=>{ + f.setProperties(dic) + }) + + HsDrawService.addDrawLayer(vm.layer); + HsDrawService.fillDrawableLayers(); + vm.modalVisible = false; + HsDrawService.tmpDrawLayer = false; + }, + pathChanged() { + vm.layer.set('path', vm.path); + }, + addAttr() { + vm.attributes.push({id: Math.random(), name: '', value: ''}); + }, + }); + }, +}; +","export default { + template: require('./draw-layer-metadata.html'), + bindings: { + layer: '<', + }, + controller: function ($scope, $timeout, HsDrawService) { + 'ngInject'; + this.modalVisible = true; + const vm = this; + $timeout(() => { + vm.title = $scope.$ctrl.layer.get('title'); + vm.path = $scope.$ctrl.layer.get('path'); + }, 0); + angular.extend(vm, { + newLayerPath: '', + attributes: [], + titleChanged() { + vm.layer.set('title', vm.title); + }, + confirm() { + const dic = {}; + vm.attributes.forEach((a) => (dic[a.name] = a.value)); + let editorConfig = vm.layer.get('editor'); + if (angular.isUndefined(editorConfig)) { + editorConfig = {}; + vm.layer.set('editor', editorConfig); + } + editorConfig.defaultAttributes = dic; + HsDrawService.addDrawLayer(vm.layer); + HsDrawService.fillDrawableLayers(); + vm.modalVisible = false; + }, + pathChanged() { + vm.layer.set('path', vm.path); + }, + addAttr() { + vm.attributes.push({id: Math.random(), name: '', value: ''}); + }, + }); + }, +}; +" +Add missing schema declaration to lesson/nugget relation,"package se.kits.gakusei.content.model; + +import com.fasterxml.jackson.annotation.JsonManagedReference; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.List; + +@Entity +@Table(name = ""lessons"", schema = ""contentschema"") +public class Lesson implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String name; + + private String description; + + @ManyToMany + @JsonManagedReference + @JoinTable( + name = ""lessons_nuggets"", + schema = ""contentschema"", + joinColumns = @JoinColumn(name = ""lesson_id"", referencedColumnName = ""id""), + inverseJoinColumns = @JoinColumn(name = ""nugget_id"", referencedColumnName = ""id"")) + private List nuggets; + + public Lesson() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List getNuggets() { + return nuggets; + } + + public void setNuggets(List nuggets) { + this.nuggets = nuggets; + } +} +","package se.kits.gakusei.content.model; + +import com.fasterxml.jackson.annotation.JsonManagedReference; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.List; + +@Entity +@Table(name = ""lessons"", schema = ""contentschema"") +public class Lesson implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String name; + + private String description; + + @ManyToMany + @JsonManagedReference + @JoinTable( + name = ""lessons_nuggets"", + joinColumns = @JoinColumn(name = ""lesson_id"", referencedColumnName = ""id""), + inverseJoinColumns = @JoinColumn(name = ""nugget_id"", referencedColumnName = ""id"")) + private List nuggets; + + public Lesson() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List getNuggets() { + return nuggets; + } + + public void setNuggets(List nuggets) { + this.nuggets = nuggets; + } +} +" +Clean up the autocomplete ajax action,"getContainer()->getParameter('kernel.charset'); + $searchTerm = $this->getRequest()->request->get('term', ''); + $term = ($charset === 'utf-8') + ? \SpoonFilter::htmlspecialchars($searchTerm) : \SpoonFilter::htmlentities($searchTerm); + $limit = (int) $this->get('fork.settings')->get('Search', 'autocomplete_num_items', 10); + + if ($term === '') { + $this->output(Response::HTTP_BAD_REQUEST, null, 'term-parameter is missing.'); + + return; + } + + $url = FrontendNavigation::getUrlForBlock('Search'); + $this->output( + Response::HTTP_OK, + array_map( + function (array $match) use ($url) { + $match['url'] = $url . '?form=search&q=' . $match['term']; + }, + FrontendSearchModel::getStartsWith($term, LANGUAGE, $limit) + ) + ); + } +} +","getContainer()->getParameter('kernel.charset'); + $searchTerm = $this->getRequest()->request->get('term', ''); + $term = ($charset === 'utf-8') ? \SpoonFilter::htmlspecialchars($searchTerm) : \SpoonFilter::htmlentities( + $searchTerm + ); + $limit = (int) $this->get('fork.settings')->get('Search', 'autocomplete_num_items', 10); + + // validate + if ($term === '') { + $this->output(Response::HTTP_BAD_REQUEST, null, 'term-parameter is missing.'); + + return; + } + + // get matches + $matches = FrontendSearchModel::getStartsWith($term, LANGUAGE, $limit); + + // get search url + $url = FrontendNavigation::getUrlForBlock('Search'); + + // loop items and set search url + foreach ($matches as &$match) { + $match['url'] = $url . '?form=search&q=' . $match['term']; + } + + // output + $this->output(Response::HTTP_OK, $matches); + } +} +" +Delete state and add form.,"import React, { Component } from 'react'; +import TextField from 'material-ui/TextField'; +import Card, { CardActions, CardContent } from 'material-ui/Card'; +import Button from 'material-ui/Button'; + +import TaxCalculator from '../libs/TaxCalculator'; + +class TextFields extends Component { + handleSubmit(event) { + event.preventDefault(); + + const formElement = event.target; + const taxInfo = TaxCalculator.getTaxInfo( + formElement.income.value, + formElement.expenses.value + ); + this.props.handleUpdate(taxInfo); + } + + render() { + return ( + +
this.handleSubmit(event)}> + +
+ +
+
+ +
+
+ + + +
+
+ ); + } +} + +export default TextFields; +","import React, { Component } from 'react'; +import TextField from 'material-ui/TextField'; +import Card, { CardActions, CardContent } from 'material-ui/Card'; +import Button from 'material-ui/Button'; + +import TaxCalculator from '../libs/TaxCalculator'; + +class TextFields extends Component { + state = { + income: 0, + expenses: 0 + }; + + calculate() { + const { income, expenses } = this.state; + const taxInfo = TaxCalculator.getTaxInfo(income, expenses); + this.props.handleUpdate(taxInfo); + } + + render() { + return ( + + +
+ this.setState({ income: event.target.value })} + inputProps={{ min: 0, step: 10000 }} + margin=""normal"" + style={{ width: '100%' }} + /> +
+
+ + this.setState({ expenses: event.target.value })} + inputProps={{ min: 0, step: 10000 }} + margin=""normal"" + style={{ width: '100%' }} + /> +
+
+ + + +
+ ); + } +} + +export default TextFields; +" +Raise UnicodeDecodeError exception after logging the exception,"""""""Event tracker backend that saves events to a python logger."""""" + +from __future__ import absolute_import + +import logging +import json + +from django.conf import settings + +from track.backends import BaseBackend +from track.utils import DateTimeJSONEncoder + +log = logging.getLogger('track.backends.logger') +application_log = logging.getLogger('track.backends.application_log') # pylint: disable=invalid-name + + +class LoggerBackend(BaseBackend): + """"""Event tracker backend that uses a python logger. + + Events are logged to the INFO level as JSON strings. + + """""" + + def __init__(self, name, **kwargs): + """"""Event tracker backend that uses a python logger. + + :Parameters: + - `name`: identifier of the logger, which should have + been configured using the default python mechanisms. + + """""" + super(LoggerBackend, self).__init__(**kwargs) + + self.event_logger = logging.getLogger(name) + + def send(self, event): + try: + event_str = json.dumps(event, cls=DateTimeJSONEncoder) + except UnicodeDecodeError: + application_log.exception( + ""UnicodeDecodeError Event_type: %r, Event_source: %r, Page: %r, Referer: %r"", + event.get('event_type'), event.get('event_source'), event.get('page'), event.get('referer') + ) + raise + + # TODO: remove trucation of the serialized event, either at a + # higher level during the emittion of the event, or by + # providing warnings when the events exceed certain size. + event_str = event_str[:settings.TRACK_MAX_EVENT] + + self.event_logger.info(event_str) +","""""""Event tracker backend that saves events to a python logger."""""" + +from __future__ import absolute_import + +import logging +import json + +from django.conf import settings + +from track.backends import BaseBackend +from track.utils import DateTimeJSONEncoder + +log = logging.getLogger('track.backends.logger') +application_log = logging.getLogger('track.backends.application_log') # pylint: disable=invalid-name + + +class LoggerBackend(BaseBackend): + """"""Event tracker backend that uses a python logger. + + Events are logged to the INFO level as JSON strings. + + """""" + + def __init__(self, name, **kwargs): + """"""Event tracker backend that uses a python logger. + + :Parameters: + - `name`: identifier of the logger, which should have + been configured using the default python mechanisms. + + """""" + super(LoggerBackend, self).__init__(**kwargs) + + self.event_logger = logging.getLogger(name) + + def send(self, event): + try: + event_str = json.dumps(event, cls=DateTimeJSONEncoder) + except UnicodeDecodeError: + application_log.exception( + ""UnicodeDecodeError Event_type: %r, Event_source: %r, Page: %r, Referer: %r"", + event.get('event_type'), event.get('event_source'), event.get('page'), event.get('referer') + ) + + # TODO: remove trucation of the serialized event, either at a + # higher level during the emittion of the event, or by + # providing warnings when the events exceed certain size. + event_str = event_str[:settings.TRACK_MAX_EVENT] + + self.event_logger.info(event_str) +" +"scripts: Fix the script to send proper format of compose id + +Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>","#!/bin/env python +# -*- coding: utf8 -*- +"""""" Triggers an upload process with the specified raw.xz URL. """""" + +import argparse +import logging +import logging.config +import multiprocessing.pool + +import fedmsg.config +import fedimg.uploader + +logging.config.dictConfig(fedmsg.config.load_config()['logging']) +log = logging.getLogger('fedmsg') + + +def trigger_upload(compose_id, url, push_notifications): + upload_pool = multiprocessing.pool.ThreadPool(processes=4) + fedimg.uploader.upload(upload_pool, [url], + compose_id=compose_id, + push_notifications=push_notifications) + + +def get_args(): + parser = argparse.ArgumentParser( + description=""Trigger a manual upload process with the "" + ""specified raw.xz URL"") + parser.add_argument( + ""-u"", ""--url"", type=str, help="".raw.xz URL"", required=True) + parser.add_argument( + ""-c"", ""--compose-id"", type=str, help=""compose id of the .raw.xz file"", + required=True) + parser.add_argument( + ""-p"", ""--push-notifications"", + help=""Bool to check if we need to push fedmsg notifications"", + action=""store_true"", required=False) + args = parser.parse_args() + + return args.url, args.compose_id, args.push_notifications + + +def main(): + url, compose_id, push_notifications = get_args() + trigger_upload(url, compose_id, push_notifications) + +if __name__ == '__main__': + main() +","#!/bin/env python +# -*- coding: utf8 -*- +"""""" Triggers an upload process with the specified raw.xz URL. """""" + +import argparse +import logging +import logging.config +import multiprocessing.pool + +import fedmsg.config +import fedimg.uploader + +logging.config.dictConfig(fedmsg.config.load_config()['logging']) +log = logging.getLogger('fedmsg') + + +def trigger_upload(compose_id, url, push_notifications): + upload_pool = multiprocessing.pool.ThreadPool(processes=4) + compose_meta = {'compose_id': compose_id} + fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta, + push_notifications=push_notifications) + + +def get_args(): + parser = argparse.ArgumentParser( + description=""Trigger a manual upload process with the "" + ""specified raw.xz URL"") + parser.add_argument( + ""-u"", ""--url"", type=str, help="".raw.xz URL"", required=True) + parser.add_argument( + ""-c"", ""--compose-id"", type=str, help=""compose id of the .raw.xz file"", + required=True) + parser.add_argument( + ""-p"", ""--push-notifications"", + help=""Bool to check if we need to push fedmsg notifications"", + action=""store_true"", required=False) + args = parser.parse_args() + + return args.url, args.compose_id, args.push_notifications + + +def main(): + url, compose_id, push_notifications = get_args() + trigger_upload(url, compose_id, push_notifications) + +if __name__ == '__main__': + main() +" +Rename test configuration property names clashing with maven deploy,"package io.quarkus.hibernate.validator.test.config; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import javax.inject.Inject; +import javax.validation.constraints.Max; + +import org.eclipse.microprofile.config.Config; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.StringAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.quarkus.test.QuarkusUnitTest; +import io.smallrye.config.ConfigMapping; +import io.smallrye.config.ConfigValidationException; +import io.smallrye.config.SmallRyeConfig; + +public class ConfigMappingValidatorTest { + @RegisterExtension + static final QuarkusUnitTest UNIT_TEST = new QuarkusUnitTest().setArchiveProducer( + () -> ShrinkWrap.create(JavaArchive.class) + .addAsResource(new StringAsset(""validator.server.host=localhost\n""), ""application.properties"")); + + @Inject + Config config; + + @Test + void validator() { + assertThrows(ConfigValidationException.class, + () -> config.unwrap(SmallRyeConfig.class).getConfigMapping(Server.class), + ""validator.server.host must be less than or equal to 3""); + } + + @ConfigMapping(prefix = ""validator.server"") + public interface Server { + @Max(3) + String host(); + } +} +","package io.quarkus.hibernate.validator.test.config; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import javax.inject.Inject; +import javax.validation.constraints.Max; + +import org.eclipse.microprofile.config.Config; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.StringAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.quarkus.test.QuarkusUnitTest; +import io.smallrye.config.ConfigMapping; +import io.smallrye.config.ConfigValidationException; +import io.smallrye.config.SmallRyeConfig; + +public class ConfigMappingValidatorTest { + @RegisterExtension + static final QuarkusUnitTest UNIT_TEST = new QuarkusUnitTest().setArchiveProducer( + () -> ShrinkWrap.create(JavaArchive.class) + .addAsResource(new StringAsset(""server.host=localhost\n""), ""application.properties"")); + + @Inject + Config config; + + @Test + void validator() { + assertThrows(ConfigValidationException.class, + () -> config.unwrap(SmallRyeConfig.class).getConfigMapping(Server.class), + ""server.host must be less than or equal to 3""); + } + + @ConfigMapping(prefix = ""server"") + public interface Server { + @Max(3) + String host(); + } +} +" +Simplify POE server parser in network protocols,"package org.jvirtanen.parity.net.poe; + +import static org.jvirtanen.parity.net.poe.POE.*; + +import com.paritytrading.nassau.MessageListener; +import java.io.IOException; +import java.nio.ByteBuffer; + +/** + * A parser for inbound messages on the server side. + */ +public class POEServerParser implements MessageListener { + + private EnterOrder enterOrder; + private CancelOrder cancelOrder; + + private POEServerListener listener; + + /** + * Create a parser for inbound messages on the server side. + * + * @param listener the message listener + */ + public POEServerParser(POEServerListener listener) { + this.enterOrder = new EnterOrder(); + this.cancelOrder = new CancelOrder(); + + this.listener = listener; + } + + @Override + public void message(ByteBuffer buffer) throws IOException { + byte messageType = buffer.get(); + + switch (messageType) { + case MESSAGE_TYPE_ENTER_ORDER: + enterOrder.get(buffer); + listener.enterOrder(enterOrder); + break; + case MESSAGE_TYPE_CANCEL_ORDER: + cancelOrder.get(buffer); + listener.cancelOrder(cancelOrder); + break; + default: + throw new POEException(""Unknown message type: "" + (char)messageType); + } + } + +} +","package org.jvirtanen.parity.net.poe; + +import static org.jvirtanen.parity.net.poe.POE.*; + +import com.paritytrading.nassau.MessageListener; +import java.io.IOException; +import java.nio.ByteBuffer; + +/** + * A parser for inbound messages on the server side. + */ +public class POEServerParser implements MessageListener { + + private EnterOrder enterOrder; + private CancelOrder cancelOrder; + + private POEServerListener listener; + + /** + * Create a parser for inbound messages on the server side. + * + * @param listener the message listener + */ + public POEServerParser(POEServerListener listener) { + this.enterOrder = new EnterOrder(); + this.cancelOrder = new CancelOrder(); + + this.listener = listener; + } + + @Override + public void message(ByteBuffer buffer) throws IOException { + byte messageType = buffer.get(); + + switch (messageType) { + case MESSAGE_TYPE_ENTER_ORDER: + enterOrder(buffer); + break; + case MESSAGE_TYPE_CANCEL_ORDER: + cancelOrder(buffer); + break; + default: + throw new POEException(""Unknown message type: "" + (char)messageType); + } + } + + private void enterOrder(ByteBuffer buffer) throws IOException { + enterOrder.get(buffer); + + listener.enterOrder(enterOrder); + } + + private void cancelOrder(ByteBuffer buffer) throws IOException { + cancelOrder.get(buffer); + + listener.cancelOrder(cancelOrder); + } + +} +" +Support oembed code from provider or raw file,"renderImage(142, 'full'); + */ +class FastForward_Helpers { + public function renderImage($id, $size = 'thumbnail') { + echo wp_get_attachment_image($id, $size); + } + + public function getImageAllSizes($id, $custom = array()) { + $thumbnail = wp_get_attachment_image_src($id, 'thumbnail'); + $medium = wp_get_attachment_image_src($id, 'medium'); + $large = wp_get_attachment_image_src($id, 'large'); + $full = wp_get_attachment_image_src($id, 'full'); + + if ($custom) { + $customSize = wp_get_attachment_image_src($id, array($custom[0], $custom[1])); + } + + $set = array( + 'thumbnail' => $thumbnail, + 'medium' => $medium, + 'large' => $large, + 'full' => $full, + 'custom' => $customSize + ); + + return $set; + } + + public function getSinglePost($args) { + $args = wp_parse_args($args, array( + 'posts_per_page' => 1 + )); + + $results = get_pages($args); + + return $results[0]; + } + + /** + * Render video from provider or raw video file. + * + * @param string + * @param boolean $echo + */ + public function renderVideo($url, $echo = true) { + $embedCode = wp_oembed_get($url); + + // There is no provider on whitelist or it is raw file. + if (!$embedCode) { + $embedCode = """"; + } + + if ($echo) { + echo $embedCode; + return true; + } else { + return $embedCode; + } + } +} +","renderImage(142, 'full'); + */ +class FastForward_Helpers { + public function renderImage($id, $size = 'thumbnail') { + echo wp_get_attachment_image($id, $size); + } + + public function getImageAllSizes($id, $custom = array()) { + $thumbnail = wp_get_attachment_image_src($id, 'thumbnail'); + $medium = wp_get_attachment_image_src($id, 'medium'); + $large = wp_get_attachment_image_src($id, 'large'); + $full = wp_get_attachment_image_src($id, 'full'); + + if ($custom) { + $customSize = wp_get_attachment_image_src($id, array($custom[0], $custom[1])); + } + + $set = array( + 'thumbnail' => $thumbnail, + 'medium' => $medium, + 'large' => $large, + 'full' => $full, + 'custom' => $customSize + ); + + return $set; + } + + public function getSinglePost($args) { + $args = wp_parse_args($args, array( + 'posts_per_page' => 1 + )); + + $results = get_pages($args); + + return $results[0]; + } +} +" +Support path prefixes for service workers,"import emitter from ""./emitter"" + +let pathPrefix = `/` +if (__PREFIX_PATHS__) { + pathPrefix = __PATH_PREFIX__ +} + +if (`serviceWorker` in navigator) { + navigator.serviceWorker + .register(`${pathPrefix}sw.js`) + .then(function(reg) { + reg.addEventListener(`updatefound`, () => { + // The updatefound event implies that reg.installing is set; see + // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event + const installingWorker = reg.installing + console.log(`installingWorker`, installingWorker) + installingWorker.addEventListener(`statechange`, () => { + switch (installingWorker.state) { + case `installed`: + if (navigator.serviceWorker.controller) { + // At this point, the old content will have been purged and the fresh content will + // have been added to the cache. + // We reload immediately so the user sees the new content. + // This could/should be made configurable in the future. + window.location.reload() + } else { + // At this point, everything has been precached. + // It's the perfect time to display a ""Content is cached for offline use."" message. + console.log(`Content is now available offline!`) + emitter.emit(`sw:installed`) + } + break + + case `redundant`: + console.error(`The installing service worker became redundant.`) + break + } + }) + }) + }) + .catch(function(e) { + console.error(`Error during service worker registration:`, e) + }) +} +","import emitter from ""./emitter"" + +if (`serviceWorker` in navigator) { + navigator.serviceWorker + .register(`sw.js`) + .then(function(reg) { + reg.addEventListener(`updatefound`, () => { + // The updatefound event implies that reg.installing is set; see + // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event + const installingWorker = reg.installing + console.log(`installingWorker`, installingWorker) + installingWorker.addEventListener(`statechange`, () => { + switch (installingWorker.state) { + case `installed`: + if (navigator.serviceWorker.controller) { + // At this point, the old content will have been purged and the fresh content will + // have been added to the cache. + // We reload immediately so the user sees the new content. + // This could/should be made configurable in the future. + window.location.reload() + } else { + // At this point, everything has been precached. + // It's the perfect time to display a ""Content is cached for offline use."" message. + console.log(`Content is now available offline!`) + emitter.emit(`sw:installed`) + } + break + + case `redundant`: + console.error(`The installing service worker became redundant.`) + break + } + }) + }) + }) + .catch(function(e) { + console.error(`Error during service worker registration:`, e) + }) +} +" +[CON-3711] Add missing export status icon,"//{namespace name=backend/connect/view/main} + +//{block name=""backend/connect/view/export/tab_panel""} +Ext.define('Shopware.apps.Connect.view.export.TabPanel', { + extend: 'Ext.tab.Panel', + alias: 'widget.export-tab-panel', + + border: false, + layout: 'card', + snippets: { + products: ""{s name=export/tab/products}Products{/s}"", + streams: ""{s name=export/tab/streams}Product Streams{/s}"" + }, + + initComponent: function () { + var me = this; + + Ext.applyIf(me, { + items: [{ + xtype: 'connect-export', + title: me.snippets.products, + iconMapping: me.getStatusIconMapping(), + itemId: 'export' + }, { + xtype: 'connect-export-stream', + title: me.snippets.streams, + iconMapping: me.getStatusIconMapping(), + itemId: 'stream' + }] + }); + + me.callParent(arguments); + }, + + getStatusIconMapping: function() { + return { + 'insert': 'sprite-arrow-circle-135', + 'synced': 'sprite-tick-circle', + 'error': 'sprite-minus-circle-frame', + 'error-price': 'icon-creative-commons-noncommercial-eu icon-size', + 'inactive': 'sc-icon-inactive icon-size', + 'update': 'sprite-arrow-circle-135', + 'export': 'sprite-arrow-circle-135' + }; + } +}); +//{/block}","//{namespace name=backend/connect/view/main} + +//{block name=""backend/connect/view/export/tab_panel""} +Ext.define('Shopware.apps.Connect.view.export.TabPanel', { + extend: 'Ext.tab.Panel', + alias: 'widget.export-tab-panel', + + border: false, + layout: 'card', + snippets: { + products: ""{s name=export/tab/products}Products{/s}"", + streams: ""{s name=export/tab/streams}Product Streams{/s}"" + }, + + initComponent: function () { + var me = this; + + Ext.applyIf(me, { + items: [{ + xtype: 'connect-export', + title: me.snippets.products, + iconMapping: me.getStatusIconMapping(), + itemId: 'export' + }, { + xtype: 'connect-export-stream', + title: me.snippets.streams, + iconMapping: me.getStatusIconMapping(), + itemId: 'stream' + }] + }); + + me.callParent(arguments); + }, + + getStatusIconMapping: function() { + return { + 'insert': 'sprite-arrow-circle-135', + 'synced': 'sprite-tick-circle', + 'error': 'sprite-minus-circle-frame', + 'error-price': 'icon-creative-commons-noncommercial-eu icon-size', + 'inactive': 'sc-icon-inactive icon-size', + 'update': 'sprite-arrow-circle-135' + }; + } +}); +//{/block}" +Add process.env.PORT in webpack server config,"/* eslint-disable import/no-unresolved, global-require */ +import nodeExternals from 'webpack-node-externals'; +import webpack from 'webpack'; + +import common from './common'; + +const isProduction = process.env.NODE_ENV === 'production'; + +export default { + name: 'server', + entry: './server', + target: 'node', + node: { + __dirname: false, + }, + output: { + filename: 'server.js', + path: common.output.path, + publicPath: common.output.publicPath, + libraryTarget: 'commonjs2', + }, + module: { + rules: [ + ...common.module.rules, + { + exclude: /\.(js|json)$/, + use: [ + { + loader: 'url-loader', + options: { + emitFile: false, + limit: 10000, + name: `media/[name]${isProduction ? '.[hash:8]' : ''}.[ext]`, + }, + }, + ], + }, + ], + }, + plugins: [ + ...common.plugins, + new webpack.DefinePlugin({ + CLIENT_BUNDLE: JSON.stringify(isProduction ? require('../build/assets.json').client.js : '/js/client.js'), + VENDOR_BUNDLE: JSON.stringify(isProduction ? require('../build/assets.json').vendor.js : '/js/vendor.js'), + 'process.env': { + PORT: JSON.stringify(process.env.PORT), + }, + }), + ], + externals: [nodeExternals()], + bail: isProduction, +}; +","/* eslint-disable import/no-unresolved, global-require */ +import nodeExternals from 'webpack-node-externals'; +import webpack from 'webpack'; + +import common from './common'; + +const isProduction = process.env.NODE_ENV === 'production'; + +export default { + name: 'server', + entry: './server', + target: 'node', + node: { + __dirname: false, + }, + output: { + filename: 'server.js', + path: common.output.path, + publicPath: common.output.publicPath, + libraryTarget: 'commonjs2', + }, + module: { + rules: [ + ...common.module.rules, + { + exclude: /\.(js|json)$/, + use: [ + { + loader: 'url-loader', + options: { + emitFile: false, + limit: 10000, + name: `media/[name]${isProduction ? '.[hash:8]' : ''}.[ext]`, + }, + }, + ], + }, + ], + }, + plugins: [ + ...common.plugins, + new webpack.DefinePlugin({ + CLIENT_BUNDLE: JSON.stringify(isProduction ? require('../build/assets.json').client.js : '/js/client.js'), + VENDOR_BUNDLE: JSON.stringify(isProduction ? require('../build/assets.json').vendor.js : '/js/vendor.js'), + }), + ], + externals: [nodeExternals()], + bail: isProduction, +}; +" +Sort by title instead of id in `report:terms` [API-224],"argument('artistId'); + + $terms = Agent::findOrFail($artistId) + ->createdArtworks + ->pluck('terms') + ->collapse() + ->unique('lake_uid') + ->sortBy([ + ['subtype', 'asc'], + ['title', 'asc'], + ]) + ->values(); + + $csv = Writer::createFromString(''); + + $csv->insertOne([ + 'term_type', + 'term_id', + 'term_title', + 'aat_id', + ]); + + foreach ($terms as $term) { + $row = [ + 'term_type' => $term->getSubtypeDisplay(), + 'term_id' => $term->lake_uid, + 'term_title' => $term->title, + 'aat_id' => null, + ]; + + $this->info(json_encode(array_values($row))); + $csv->insertOne($row); + } + + Storage::put('terms-for-' . $artistId . '.csv', $csv->getContent()); + } +} +","argument('artistId'); + + $terms = Agent::findOrFail($artistId) + ->createdArtworks + ->pluck('terms') + ->collapse() + ->unique('lake_uid') + ->sortBy([ + ['subtype', 'asc'], + ['lake_uid', 'asc'], + ]) + ->values(); + + $csv = Writer::createFromString(''); + + $csv->insertOne([ + 'term_type', + 'term_id', + 'term_title', + 'aat_id', + ]); + + foreach ($terms as $term) { + $row = [ + 'term_type' => $term->getSubtypeDisplay(), + 'term_id' => $term->lake_uid, + 'term_title' => $term->title, + 'aat_id' => null, + ]; + + $this->info(json_encode(array_values($row))); + $csv->insertOne($row); + } + + Storage::put('terms-for-' . $artistId . '.csv', $csv->getContent()); + } +} +" +Use correct timestamp format in serialized JSON.,"package com.openxc.measurements.serializers; + +import java.io.IOException; +import java.io.StringWriter; + +import java.text.DecimalFormat; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; + +import android.util.Log; + +public class JsonSerializer implements MeasurementSerializer { + private static final String TAG = ""JsonSerializer""; + public static final String NAME_FIELD = ""name""; + public static final String VALUE_FIELD = ""value""; + public static final String EVENT_FIELD = ""event""; + public static final String TIMESTAMP_FIELD = ""timestamp""; + private static DecimalFormat sTimestampFormatter = + new DecimalFormat(""##########.000000""); + + public static String serialize(String name, Object value, Object event, + Double timestamp) { + StringWriter buffer = new StringWriter(64); + JsonFactory jsonFactory = new JsonFactory(); + try { + JsonGenerator gen = jsonFactory.createJsonGenerator(buffer); + + gen.writeStartObject(); + gen.writeStringField(NAME_FIELD, name); + + if(value != null) { + gen.writeObjectField(VALUE_FIELD, value); + } + + if(event != null) { + gen.writeObjectField(EVENT_FIELD, event); + } + + if(timestamp != null) { + gen.writeFieldName(TIMESTAMP_FIELD); + gen.writeRawValue(sTimestampFormatter.format(timestamp)); + } + + gen.writeEndObject(); + gen.close(); + } catch(IOException e) { + Log.w(TAG, ""Unable to encode all data to JSON -- "" + + ""message may be incomplete"", e); + } + return buffer.toString(); + } +} +","package com.openxc.measurements.serializers; + +import java.io.IOException; +import java.io.StringWriter; + +import java.text.DecimalFormat; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; + +import android.util.Log; + +public class JsonSerializer implements MeasurementSerializer { + private static final String TAG = ""JsonSerializer""; + public static final String NAME_FIELD = ""name""; + public static final String VALUE_FIELD = ""value""; + public static final String EVENT_FIELD = ""event""; + public static final String TIMESTAMP_FIELD = ""timestamp""; + private static DecimalFormat sTimestampFormatter = + new DecimalFormat(""##########.000000""); + + public static String serialize(String name, Object value, Object event, + Double timestamp) { + StringWriter buffer = new StringWriter(64); + JsonFactory jsonFactory = new JsonFactory(); + try { + JsonGenerator gen = jsonFactory.createJsonGenerator(buffer); + + gen.writeStartObject(); + gen.writeStringField(NAME_FIELD, name); + + if(value != null) { + gen.writeObjectField(VALUE_FIELD, value); + } + + if(event != null) { + gen.writeObjectField(EVENT_FIELD, event); + } + + if(timestamp != null) { + gen.writeNumberField(TIMESTAMP_FIELD, timestamp); + } + + gen.writeEndObject(); + gen.close(); + } catch(IOException e) { + Log.w(TAG, ""Unable to encode all data to JSON -- "" + + ""message may be incomplete"", e); + } + return buffer.toString(); + } +} +" +Use queryset in validate publicbodies command,"from io import StringIO +from contextlib import contextmanager + +from django.conf import settings +from django.core.management.base import BaseCommand +from django.utils import translation +from django.utils.translation import ugettext_lazy as _ + +from froide.helper.email_sending import send_mail + +from ...validators import PublicBodyValidator +from ...models import PublicBody + + +class Command(BaseCommand): + help = ""Validates public bodies"" + + def add_arguments(self, parser): + parser.add_argument('filename', type=str, nargs='?', default=None) + + @contextmanager + def get_stream(self, filename): + if filename is None: + stream = StringIO() + else: + if filename == '-': + stream = self.stdout + else: + stream = open(filename, 'w') + yield stream + if filename is not None and filename != '-': + stream.close() + + def handle(self, *args, **options): + translation.activate(settings.LANGUAGE_CODE) + filename = options['filename'] + + pbs = PublicBody.objects.all() + validator = PublicBodyValidator(pbs) + + with self.get_stream(filename) as stream: + validator.write_csv(stream) + + if filename is None and not validator.is_valid: + for name, email in settings.MANAGERS: + send_mail( + _('Public body validation results'), + _('Please find attached the results of the public body validation'), + email, + attachments=[ + ('validation_result.csv', stream.getvalue().encode('utf-8'), 'text/csv') + ] + ) +","from io import StringIO +from contextlib import contextmanager + +from django.conf import settings +from django.core.management.base import BaseCommand +from django.utils import translation +from django.utils.translation import ugettext_lazy as _ + +from froide.helper.email_sending import send_mail + +from ...validators import PublicBodyValidator +from ...models import PublicBody + + +class Command(BaseCommand): + help = ""Validates public bodies"" + + def add_arguments(self, parser): + parser.add_argument('filename', type=str, nargs='?', default=None) + + @contextmanager + def get_stream(self, filename): + if filename is None: + stream = StringIO() + else: + if filename == '-': + stream = self.stdout + else: + stream = open(filename, 'w') + yield stream + if filename is not None and filename != '-': + stream.close() + + def handle(self, *args, **options): + translation.activate(settings.LANGUAGE_CODE) + filename = options['filename'] + + pbs = PublicBody.objects.all().iterator() + validator = PublicBodyValidator(pbs) + + with self.get_stream(filename) as stream: + validator.write_csv(stream) + + if filename is None and not validator.is_valid: + for name, email in settings.MANAGERS: + send_mail( + _('Public body validation results'), + _('Please find attached the results of the public body validation'), + email, + attachments=[ + ('validation_result.csv', stream.getvalue().encode('utf-8'), 'text/csv') + ] + ) +" +Add some color to SVG key/values,"#import PIL +import cairosvg +from django.template import Template, Context + + + +def make_svg(context): + svg_tmpl = Template("""""" + + + + {{ name }} {{ text }} + + {% for k,v in data.items %} + {% if v.items %} + + {{ k }}: + + {% for kk, vv in v.items %} + + {{ kk }}: {{ vv }} + + {% endfor %} + {% else %} + + {{ k }}: {{ v }} + + {% endif %} + {% endfor %} + + + """""".strip()) + + svg = svg_tmpl.render(Context({'data': context})) + + return svg + + +def write_svg_to_png(svg_raw, outfile): + + cairosvg.svg2png(bytestring=svg_raw, write_to=outfile) + + return outfile +","#import PIL +import cairosvg +from django.template import Template, Context + + + +def make_svg(context): + svg_tmpl = Template("""""" + + + + {{ name }} {{ text }} + + {% for k,v in data.items %} + {% if v.items %} + + {{ k }}: + + {% for kk, vv in v.items %} + + {{ kk }}: {{ vv }} + + {% endfor %} + {% else %} + + {{ k }}: {{ v }} + + {% endif %} + {% endfor %} + + + """""".strip()) + + svg = svg_tmpl.render(Context({'data': context})) + + return svg + + +def write_svg_to_png(svg_raw, outfile): + + cairosvg.svg2png(bytestring=svg_raw, write_to=outfile) + + return outfile +" +Add the CRUD Of Projects Type & Project Status.,"add('name') + ->add('description') + ->add('createdAt') + ->add('orderTaskBy') + ->add('team', 'entity', [ + 'class' => 'AppBundle\Entity\User', + 'property' => 'username', + 'multiple' => true, + 'expanded' => true + ]) + ->add('projectStatus', 'entity', ['class' => 'AppBundle\Entity\ProjectStatus', 'property' => 'name']) + ->add('projectType', 'entity', ['class' => 'AppBundle\Entity\ProjectType', 'property' => 'name']) + ->add('createdBy') + ; + } + + /** + * @param OptionsResolverInterface $resolver + */ + public function setDefaultOptions(OptionsResolverInterface $resolver) + { + $resolver->setDefaults(array( + 'data_class' => 'AppBundle\Entity\Project' + )); + } + + /** + * @return string + */ + public function getName() + { + return 'appbundle_project'; + } +} +","add('name') + ->add('description') + ->add('createdAt') + ->add('orderTaskBy') + ->add('team') + ->add('projectStatus', 'entity', ['class' => 'AppBundle\Entity\ProjectStatus', 'property' => 'name']) + ->add('projectType', 'entity', ['class' => 'AppBundle\Entity\ProjectType', 'property' => 'name']) + ->add('createdBy') + ; + } + + /** + * @param OptionsResolverInterface $resolver + */ + public function setDefaultOptions(OptionsResolverInterface $resolver) + { + $resolver->setDefaults(array( + 'data_class' => 'AppBundle\Entity\Project' + )); + } + + /** + * @return string + */ + public function getName() + { + return 'appbundle_project'; + } +} +" +Change args order for report function,"const logger = require('./utils/logger'), + argsParser = require('./parsers/argsParser'), + styleParser = require('./parsers/styleParser'), + filesReader = require('./utils/filesReader'), + filesWriter = require('./utils/filesWriter'), + minificationReport = require('./utils/minificationReport'), + replacer = require('./replacer'); + +function unbemify () { + logger.log('Unbemify started ...'); + + const startTime = process.hrtime(), + options = argsParser(process.argv); + + + if (options.mistake) { + logger.error(options.mistake); + } + else { + const allPaths = [options.style.path] + .concat(options.files.map(file => file.path)), + readedFiles = filesReader(allPaths); + + Promise.all(readedFiles) + .then(resources => { + options.style.content = resources.splice(0, 1)[0]; + options.style.size = options.style.content.length; + resources.forEach((resource, index) => { + const file = options.files[index]; + + file.content = resource; + file.size = resource.length; + }); + + const selectors = styleParser(options.style.content); + + replacer(selectors, options); + + filesWriter(options) + .then(() => minificationReport(selectors, options, startTime)) + .catch(e => logger.error(e)); + }) + .catch(e => logger.error(e)); + } +} + +module.exports = unbemify;","const logger = require('./utils/logger'), + argsParser = require('./parsers/argsParser'), + styleParser = require('./parsers/styleParser'), + filesReader = require('./utils/filesReader'), + filesWriter = require('./utils/filesWriter'), + minificationReport = require('./utils/minificationReport'), + replacer = require('./replacer'); + +function unbemify () { + logger.log('Unbemify started ...'); + + const startTime = process.hrtime(), + options = argsParser(process.argv); + + + if (options.mistake) { + logger.error(options.mistake); + return null; + } + else { + const allPaths = [options.style.path] + .concat(options.files.map(file => file.path)), + readedFiles = filesReader(allPaths); + + Promise.all(readedFiles) + .then(resources => { + options.style.content = resources.splice(0, 1)[0]; + options.style.size = options.style.content.length; + resources.forEach((resource, index) => { + const file = options.files[index]; + + file.content = resource; + file.size = resource.length; + }); + + const selectors = styleParser(options.style.content); + + replacer(selectors, options); + + filesWriter(options) + .then(() => minificationReport(options, selectors, startTime)) + .catch(e => logger.error(e)); + }) + .catch(e => logger.error(e)); + } +} + +module.exports = unbemify;" +"spawn-1007006: Allow wider set of messages in exception tests + +If Task.spawn catches an exception message then it adds ""Error: "" onto +the front, so allow a slightly wider set of error messages when testing. + +Signed-off-by: Joe Walker <7a17872fbb32c7d760c9a16ee3076daead11efcf@mozilla.com>","/* + * Copyright 2012, Mozilla Foundation and contributors + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var helpers = require('./helpers'); + +exports.testBasic = function(options) { + return helpers.audit(options, [ + { + setup: 'tsfail reject', + exec: { + output: 'rejected promise', + type: 'error', + error: true + } + }, + { + setup: 'tsfail rejecttyped', + exec: { + output: '54', + type: 'number', + error: true + } + }, + { + setup: 'tsfail throwerror', + exec: { + output: /thrown error$/, + type: 'error', + error: true + } + }, + { + setup: 'tsfail throwstring', + exec: { + output: 'thrown string', + type: 'error', + error: true + } + }, + { + setup: 'tsfail noerror', + exec: { + output: 'no error', + type: 'string', + error: false + } + } + ]); +}; +","/* + * Copyright 2012, Mozilla Foundation and contributors + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var helpers = require('./helpers'); + +exports.testBasic = function(options) { + return helpers.audit(options, [ + { + setup: 'tsfail reject', + exec: { + output: 'rejected promise', + type: 'error', + error: true + } + }, + { + setup: 'tsfail rejecttyped', + exec: { + output: '54', + type: 'number', + error: true + } + }, + { + setup: 'tsfail throwerror', + exec: { + output: 'thrown error', + type: 'error', + error: true + } + }, + { + setup: 'tsfail throwstring', + exec: { + output: 'thrown string', + type: 'error', + error: true + } + }, + { + setup: 'tsfail noerror', + exec: { + output: 'no error', + type: 'string', + error: false + } + } + ]); +}; +" +Comment out some stub components,"import React from 'react'; +import { connect } from 'react-redux'; +import request from 'superagent'; + +import Header from '../components/header'; +import Footer from '../components/footer'; +import River from '../components/river_of_posts'; +import Followed from '../components/most_followed_people'; +import Tags from '../components/popular_tags'; +import Sidebar from '../components/sidebar' +import {API_HOST} from '../config'; +import {getStore, setPosts} from '../store'; + + +class Index extends React.Component { + async componentWillMount() { + let result = await request.get(`${API_HOST}/api/v1/posts`); + getStore().dispatch(setPosts(result.body)); + } + render() { + let current_user = this.props.current_user; + + return ( +
+
+
+
+ + +
+

This is a List-page!!!!!!!!

+ + {/* */} + {/**/} +
+
+
+
+
+ ) + } +} + +function select(state) { + return state.toJS(); +} + +export default connect(select)(Index); +","import React from 'react'; +import { connect } from 'react-redux'; +import request from 'superagent'; + +import Header from '../components/header'; +import Footer from '../components/footer'; +import River from '../components/river_of_posts'; +import Followed from '../components/most_followed_people'; +import Tags from '../components/popular_tags'; +import Sidebar from '../components/sidebar' +import {API_HOST} from '../config'; +import {getStore, setPosts} from '../store'; + + +class Index extends React.Component { + async componentWillMount() { + let result = await request.get(`${API_HOST}/api/v1/posts`); + getStore().dispatch(setPosts(result.body)); + } + render() { + let current_user = this.props.current_user; + + return ( +
+
+
+
+ + +
+

This is a List-page!!!!!!!!

+ + + +
+
+
+
+
+ ) + } +} + +function select(state) { + return state.toJS(); +} + +export default connect(select)(Index); +" +"REMOVE the animation, as it's very awkward","import window from 'global'; +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; + +// this component renders an iframe, which gets updates via post-messages +export class IFrame extends Component { + iframe = null; + + componentDidMount() { + const { id } = this.props; + this.iframe = window.document.getElementById(id); + } + + shouldComponentUpdate(nextProps) { + const { scale } = this.props; + return scale !== nextProps.scale; + } + + componentDidUpdate(prevProps) { + const { scale } = this.props; + if (scale !== prevProps.scale) { + this.setIframeBodyStyle({ + width: `${scale * 100}%`, + height: `${scale * 100}%`, + transform: `scale(${1 / scale})`, + transformOrigin: 'top left', + }); + } + } + + setIframeBodyStyle(style) { + return Object.assign(this.iframe.contentDocument.body.style, style); + } + + render() { + const { id, title, src, allowFullScreen, scale, ...rest } = this.props; + return ( + + """""" % (self.width, self.height, self.id, params) +","""""""Various display related classes. + +Authors : MinRK, dannystaple +"""""" +import urllib + +class YouTubeVideo(object): + """"""Class for embedding a YouTube Video in an IPython session, based on its video id. + + e.g. to embed the video on this page: + + http://www.youtube.com/watch?v=foo + + you would do: + + vid = YouTubeVideo(""foo"") + display(vid) + + To start from 30 seconds: + + vid = YouTubeVideo(""abc"", start=30) + display(vid) + + To calculate seconds from time as hours, minutes, seconds use: + start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) + + Other parameters can be provided as documented at + https://developers.google.com/youtube/player_parameters#parameter-subheader + """""" + + def __init__(self, id, width=400, height=300, **kwargs): + self.id = id + self.width = width + self.height = height + self.params = kwargs + + def _repr_html_(self): + """"""return YouTube embed iframe for this video id"""""" + if self.params: + params = ""?"" + urllib.urlencode(self.params) + else: + params = """" + return """""" + + """"""%(self.width, self.height, self.id, params)" +"Fix reference to strophe in tests + +Now that we use the production mode for webpack in the build +script, strophe is at dist/strophe.min.js","require.config({ + baseUrl: '../', + paths: { + ""strophe"": ""dist/strophe.min"", + + // Examples + ""basic"": ""examples/basic"", + + // Tests + ""jquery"": ""node_modules/jquery/dist/jquery"", + ""sinon"": ""node_modules/sinon/pkg/sinon"", + ""sinon-qunit"": ""node_modules/sinon-qunit/lib/sinon-qunit"", + ""tests"": ""tests/tests"" + }, + + shim: { + 'sinon-qunit': { deps: ['sinon']} + } +}); + +require([""tests"", ""strophe""], function (tests, Strophe) { + window.Strophe = Strophe; + + QUnit.done(function (details) { + console.log(""Total: ""+details.total+"" Failed: ""+details.failed+"" Passed: ""+details.passed+"" Runtime: ""+details.runtime); + console.log(""All tests completed!""); + }); + + QUnit.testDone(function (details) { + var result = { + ""Module name"": details.module, + ""Test name"": details.name, + ""Assertions"": { + ""Total"": details.total, + ""Passed"": details.passed, + ""Failed"": details.failed + }, + ""Skipped"": details.skipped, + ""Todo"": details.todo, + ""Runtime"": details.runtime + }; + console.log(JSON.stringify(result, null, 2)); + }); + + QUnit.start(); + QUnit.begin(function (details) { + tests.run(); + }); +}); +","require.config({ + baseUrl: '../', + paths: { + ""strophe"": ""dist/strophe"", + + // Examples + ""basic"": ""examples/basic"", + + // Tests + ""jquery"": ""node_modules/jquery/dist/jquery"", + ""sinon"": ""node_modules/sinon/pkg/sinon"", + ""sinon-qunit"": ""node_modules/sinon-qunit/lib/sinon-qunit"", + ""tests"": ""tests/tests"" + }, + + shim: { + 'sinon-qunit': { deps: ['sinon']} + } +}); + +require([""tests"", ""strophe""], function (tests, Strophe) { + window.Strophe = Strophe; + + QUnit.done(function (details) { + console.log(""Total: ""+details.total+"" Failed: ""+details.failed+"" Passed: ""+details.passed+"" Runtime: ""+details.runtime); + console.log(""All tests completed!""); + }); + + QUnit.testDone(function (details) { + var result = { + ""Module name"": details.module, + ""Test name"": details.name, + ""Assertions"": { + ""Total"": details.total, + ""Passed"": details.passed, + ""Failed"": details.failed + }, + ""Skipped"": details.skipped, + ""Todo"": details.todo, + ""Runtime"": details.runtime + }; + console.log(JSON.stringify(result, null, 2)); + }); + + QUnit.start(); + QUnit.begin(function (details) { + tests.run(); + }); +}); +" +Return `OrderItemTuple`s rather than order item database entities from service,""""""" +byceps.services.shop.order.ordered_articles_service +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:Copyright: 2006-2018 Jochen Kupperschmidt +:License: Modified BSD, see LICENSE for details. +"""""" + +from collections import Counter +from typing import Dict, Sequence + +from ....database import db + +from ..article.models.article import ArticleNumber + +from .models.order_item import OrderItem, OrderItemTuple +from .models.payment import PaymentState + + +def count_ordered_articles(article_number: ArticleNumber + ) -> Dict[PaymentState, int]: + """"""Count how often the article has been ordered, grouped by the + order's payment state. + """""" + order_items = OrderItem.query \ + .filter_by(article_number=article_number) \ + .options( + db.joinedload('order'), + db.joinedload('article'), + ) \ + .all() + + # Ensure every payment state is present in the resulting dictionary, + # even if no orders of the corresponding payment state exist for the + # article. + counter = Counter({state: 0 for state in PaymentState}) + + for order_item in order_items: + counter[order_item.order.payment_state] += order_item.quantity + + return dict(counter) + + +def get_order_items_for_article(article_number: ArticleNumber + ) -> Sequence[OrderItemTuple]: + """"""Return all order items for that article."""""" + order_items = OrderItem.query \ + .filter_by(article_number=article_number) \ + .all() + + return [item.to_tuple() for item in order_items] +",""""""" +byceps.services.shop.order.ordered_articles_service +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:Copyright: 2006-2018 Jochen Kupperschmidt +:License: Modified BSD, see LICENSE for details. +"""""" + +from collections import Counter +from typing import Dict, Sequence + +from ....database import db + +from ..article.models.article import ArticleNumber + +from .models.order_item import OrderItem +from .models.payment import PaymentState + + +def count_ordered_articles(article_number: ArticleNumber + ) -> Dict[PaymentState, int]: + """"""Count how often the article has been ordered, grouped by the + order's payment state. + """""" + order_items = OrderItem.query \ + .filter_by(article_number=article_number) \ + .options( + db.joinedload('order'), + db.joinedload('article'), + ) \ + .all() + + # Ensure every payment state is present in the resulting dictionary, + # even if no orders of the corresponding payment state exist for the + # article. + counter = Counter({state: 0 for state in PaymentState}) + + for order_item in order_items: + counter[order_item.order.payment_state] += order_item.quantity + + return dict(counter) + + +def get_order_items_for_article(article_number: ArticleNumber + ) -> Sequence[OrderItem]: + """"""Return all order items for that article."""""" + return OrderItem.query \ + .filter_by(article_number=article_number) \ + .all() +" +Remove meta from source class (belongs to issue not source),"from mythril.solidity.soliditycontract import SolidityContract +from mythril.ethereum.evmcontract import EVMContract + + +class Source: + def __init__( + self, source_type=None, source_format=None, source_list=None, meta=None + ): + self.source_type = source_type + self.source_format = source_format + self.source_list = [] + self.meta = meta + + def get_source_from_contracts_list(self, contracts): + if contracts is None or len(contracts) == 0: + return + if isinstance(contracts[0], SolidityContract): + self.source_type = ""solidity-file"" + self.source_format = ""text"" + for contract in contracts: + self.source_list += [file.filename for file in contract.solidity_files] + elif isinstance(contracts[0], EVMContract): + self.source_format = ""evm-byzantium-bytecode"" + self.source_type = ( + ""raw-bytecode"" if contracts[0].name == ""MAIN"" else ""ethereum-address"" + ) + for contract in contracts: + self.source_list.append(contract.bytecode_hash) + + else: + assert False # Fail hard +","from mythril.solidity.soliditycontract import SolidityContract +from mythril.ethereum.evmcontract import EVMContract + + +class Source: + def __init__( + self, source_type=None, source_format=None, source_list=None, meta=None + ): + self.source_type = source_type + self.source_format = source_format + self.source_list = [] + self.meta = meta + + def get_source_from_contracts_list(self, contracts): + if contracts is None or len(contracts) == 0: + return + if isinstance(contracts[0], SolidityContract): + self.source_type = ""solidity-file"" + self.source_format = ""text"" + for contract in contracts: + self.source_list += [file.filename for file in contract.solidity_files] + elif isinstance(contracts[0], EVMContract): + self.source_format = ""evm-byzantium-bytecode"" + self.source_type = ( + ""raw-bytecode"" if contracts[0].name == ""MAIN"" else ""ethereum-address"" + ) + for contract in contracts: + self.source_list.append(contract.bytecode_hash) + + else: + assert False # Fail hard + self.meta = """" +" +Remove trailing comma from gruntfile,"module.exports = function(grunt){ + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + jshint: { + all: ['Gruntfile.js', 'src/*.js'] + }, + uglify: { + options: { + banner: '/*! <%= pkg.name %> <%= grunt.template.today(""yyyy-mm-dd"") %> */\n' + }, + build: { + src: 'src/index.js', + dest: 'dist/<%= pkg.name %>.min.js' + } + }, + concat: { + option: { + separator: ';' + }, + dist: { + src: ['src/index.js'], + dest: 'dist/<%= pkg.name %>.js' + } + }, + watch: { + files: ['src/*.js'], + tasks: ['concat', 'uglify'], + options: { + spawn: false, + interrupt: true, + debounceDelay: 100 + } + } + }); + + grunt.loadNpmTasks('grunt-contrib-uglify'); + grunt.loadNpmTasks('grunt-contrib-jshint'); + grunt.loadNpmTasks('grunt-contrib-concat'); + grunt.loadNpmTasks('grunt-contrib-watch'); + + grunt.registerTask('test', ['jshint']); + grunt.registerTask('default', ['jshint', 'concat', 'uglify']); +}; +","module.exports = function(grunt){ + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + jshint: { + all: ['Gruntfile.js', 'src/*.js'] + }, + uglify: { + options: { + banner: '/*! <%= pkg.name %> <%= grunt.template.today(""yyyy-mm-dd"") %> */\n' + }, + build: { + src: 'src/index.js', + dest: 'dist/<%= pkg.name %>.min.js' + } + }, + concat: { + option: { + separator: ';', + }, + dist: { + src: ['src/index.js'], + dest: 'dist/<%= pkg.name %>.js' + } + }, + watch: { + files: ['src/*.js'], + tasks: ['concat', 'uglify'], + options: { + spawn: false, + interrupt: true, + debounceDelay: 100 + } + } + }); + + grunt.loadNpmTasks('grunt-contrib-uglify'); + grunt.loadNpmTasks('grunt-contrib-jshint'); + grunt.loadNpmTasks('grunt-contrib-concat'); + grunt.loadNpmTasks('grunt-contrib-watch'); + + grunt.registerTask('test', ['jshint']); + grunt.registerTask('default', ['jshint', 'concat', 'uglify']); +}; +" +Add method to check that padCharacter is not empty or null," new \Twig_Filter_Method($this, 'padStringFilter'), + ); + } + + /** + * Pads string on right or left with given padCharacter until string + * reaches maxLength + * + * @param string $value + * @param string $padCharacter + * @param int $maxLength + * @param string $padType + * + * @return string + * @throws \InvalidArgumentException + */ + public function padStringFilter($value, $padCharacter, $maxLength, $padType = 'STR_PAD_RIGHT') + { + if ($this->isNullOrEmptyString($padCharacter)) { + throw new \InvalidArgumentException('Pad String Filter cannot accept a null value or empty string as its first argument'); + } + if ( ! is_int($maxLength)) { + throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer'); + } + $diff = strlen($value) - mb_strlen($value); + $padType = constant($padType); + + return str_pad($value, $maxLength + $diff, $padCharacter, $padType); + } + + /** + * Make sure a padCharacter is provided + * + * @param $padCharacter + * @return bool + */ + protected function isNullOrEmptyString($padCharacter){ + return (!isset($padCharacter) || trim($padCharacter)==='' || is_null($padCharacter)); + } +} +"," new \Twig_Filter_Method($this, 'padStringFilter'), + ); + } + + /** + * Pads string on right or left with given padCharacter until string + * reaches maxLength + * + * @param string $value + * @param string $padCharacter + * @param int $maxLength + * @param string $padType + * + * @return string + * @throws \InvalidArgumentException + */ + public function padStringFilter($value, $padCharacter, $maxLength, $padType = 'STR_PAD_RIGHT') + { + if ( ! is_int($maxLength)) { + throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer'); + } + $diff = strlen($value) - mb_strlen($value); + $padType = constant($padType); + + return str_pad($value, $maxLength + $diff, $padCharacter, $padType); + } +} +" +Remove character in js click function,"//autocomplete for organism search + $(""#search_organism"").autocomplete({ + position: { + my: ""right top"", at: ""right bottom"" + }, + source: function (request, response) { + var $search = request.term; + $.ajax({ + url: WebRoot.concat(""/ajax/listing/Organisms""), + data: {term: request.term, limit: 500, search: $search}, + dataType: ""json"", + success: function (data) { + response(data); + } + }); + }, + minLength: 3 +}); + +$(""#search_organism"").data(""ui-autocomplete"")._renderItem = function (ul, item) { + var li = $(""
  • "") + .append("""" + item.scientific_name + """" + item.rank + """") + .appendTo(ul); + return li; +}; + + +$(""#btn_search_organism"").click(function(){ + $searchTerm = $(""#search_organism"").val(); + $.ajax({ + url: WebRoot.concat(""/ajax/listing/Organisms""), + data: {limit: 500, search: $searchTerm}, + dataType: ""json"", + success: function (data) { + console.log(data); + } + }); +}); + + +","//autocomplete for organism search + $(""#search_organism"").autocomplete({ + position: { + my: ""right top"", at: ""right bottom"" + }, + source: function (request, response) { + var $search = request.term; + $.ajax({ + url: WebRoot.concat(""/ajax/listing/Organisms""), + data: {term: request.term, limit: 500, search: $search}, + dataType: ""json"", + success: function (data) { + response(data); + } + }); + }, + minLength: 3 +}); + +$(""#search_organism"").data(""ui-autocomplete"")._renderItem = function (ul, item) { + var li = $(""
  • "") + .append("""" + item.scientific_name + """" + item.rank + """") + .appendTo(ul); + return li; +}; + + +$(""#btn_search_organism"").click(function(){ + $searchTerm = $(""#search_organism"").val(); + $.ajax({ + url: WebRoot.concat(""/ajax/listing/Organisms""), + data: {limit: 500, search: $searchTerm}, + dataType: ""json"", + success: function (data) { + console.log(data);e + } + }); +}); + + +" +Change jwt storage from session to local,"import fetch from 'isomorphic-fetch' + +export function signUpUser(register, history) { + return(dispatch) => { + + const options = { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + user: { + first_name: register.name, + email: register.email, + password: register.password, + password_confirmation: register.password, + } + }), + }; + + return fetch('api/v1/register', options) + .then(response => response.json()) + .then(token => { + localStorage.setItem('jwt', token.jwt); + history.push(""/""); + dispatch({ type: 'SIGN_UP_SUCCESS' }); + }); + } +} + +export function signInUser(credentials, history) { + return(dispatch) => { + + const options = { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + auth: { + email: credentials.email, + password: credentials.password, + } + }), + }; + + return fetch('api/v1/signin', options) + .then(response => response.json()) + .then(token => { + localStorage.setItem('jwt', token.jwt); + history.push(""/""); + dispatch({ type: 'SIGN_IN_SUCCESS' }); + }); + } +} + +export function signOutUser() { + localStorage.removeItem('jwt'); + + return(dispatch) => { + dispatch({ type: 'CLEAR_CURRENT_ROUTINE' }); + dispatch({ type: 'SIGN_OUT' }); + } +} +","import fetch from 'isomorphic-fetch' + +export function signUpUser(register, history) { + return(dispatch) => { + + const options = { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + user: { + first_name: register.name, + email: register.email, + password: register.password, + password_confirmation: register.password, + } + }), + }; + + return fetch('api/v1/register', options) + .then(response => response.json()) + .then(token => { + sessionStorage.setItem('jwt', token.jwt); + history.push(""/""); + dispatch({ type: 'SIGN_UP_SUCCESS' }); + }); + } +} + +export function signInUser(credentials, history) { + return(dispatch) => { + + const options = { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + auth: { + email: credentials.email, + password: credentials.password, + } + }), + }; + + return fetch('api/v1/signin', options) + .then(response => response.json()) + .then(token => { + sessionStorage.setItem('jwt', token.jwt); + history.push(""/""); + dispatch({ type: 'SIGN_IN_SUCCESS' }); + }); + } +} + +export function signOutUser() { + sessionStorage.removeItem('jwt'); + + return(dispatch) => { + dispatch({ type: 'CLEAR_CURRENT_ROUTINE' }); + dispatch({ type: 'SIGN_OUT' }); + } +} +" +Fix some things in evidence sources,"from util import pklload +from collections import defaultdict +import indra.tools.assemble_corpus as ac + + +if __name__ == '__main__': + # Load cached Statements just before going into the model + stmts = pklload('pysb_stmts') + + # Start a dictionary for source counts + sources_count = defaultdict(int) + # Count statements according to sources of evidence + for stmt in stmts: + sources = tuple(sorted(list(set([ev.source_api for ev in stmt.evidence])))) + sources_count[sources] += 1 + + # Statements from databases only + db_only = 0 + # Statements from reading only + reading_only = 0 + # Statements from databases and reading + mixture = 0 + # Database sources + dbs = set(['bel', 'biopax', 'phosphosite', 'signor']) + # Reader sources + readers = set(['reach', 'trips', 'sparser', 'r3']) + for k, v in sources_count.items(): + d = set(k).intersection(dbs) + r = set(k).intersection(readers) + if d and r: + mixture += v + if d and not r: + db_only += v + if r and not d: + reading_only += v + + for k, v in sorted(sources_count.items(), key=lambda x: (len(x[0]), ','.join(sorted(x[0])))): + sources_str = ','.join(k) + line_str = sources_str + '\t' + str(v) + print(line_str) +","from util import pklload +from collections import defaultdict +import indra.tools.assemble_corpus as ac + + +if __name__ == '__main__': + # Load cached Statements just before going into the model + stmts = pklload('pysb_stmts') + + # Start a dictionary for source counts + sources_count = defaultdict(int) + # Count statements according to sources of evidence + for stmt in stmts: + sources = tuple(sorted(list(set([ev.source_api for ev in stmt.evidence])))) + sources_count[sources] += 1 + + # Statements from databases only + db_only = 0 + # Statements from reading only + reading_only = 0 + # Statements from databases and reading + mixture = 0 + # Database sources + dbs = set(['bel', 'biopax', 'phosphosite', 'signor']) + # Reader sources + readers = set(['reach', 'trips', 'sparser', 'r3']) + for k, v in sources_count.items(): + d = set(k).intersection(dbs) + r = set(k).intersection(readers) + if d and r: + mixture += v + if d and not r: + db_only += v + if r and not d: + reading_only += v + + for k, v in sorted(sources_count.items(), key=lambda x: (len(x[1]), x[1])): + sources_str = ','.join(k) + line_str = sources_str + ',' + str(v) +" +Use Event-Dispatcher contracts Event class.,"registration = $registration; + $this->user = $user; + $this->keyName = $name; + } + + public function getRegistration(): Registration + { + return $this->registration; + } + + public function getUser(): TwoFactorInterface + { + return $this->user; + } + + public function setUser(TwoFactorInterface $user): self + { + $this->user = $user; + + return $this; + } + + public function getResponse(): Response + { + return $this->response; + } + + public function setResponse(Response $response): self + { + $this->response = $response; + + return $this; + } + + public function getKeyName(): string + { + return $this->keyName; + } + + public function setKeyName(string $keyName): self + { + $this->keyName = $keyName; + + return $this; + } +} +","registration = $registration; + $this->user = $user; + $this->keyName = $name; + } + + public function getRegistration(): Registration + { + return $this->registration; + } + + public function getUser(): TwoFactorInterface + { + return $this->user; + } + + public function setUser(TwoFactorInterface $user): self + { + $this->user = $user; + + return $this; + } + + public function getResponse(): Response + { + return $this->response; + } + + public function setResponse(Response $response): self + { + $this->response = $response; + + return $this; + } + + public function getKeyName(): string + { + return $this->keyName; + } + + public function setKeyName(string $keyName): self + { + $this->keyName = $keyName; + + return $this; + } +} +" +Modify publicPath so asset URLs resolve correctly,"var path = require('path') +var webpack = require('webpack') + +module.exports = { + entry: './src/index.js', + output: { + path: path.resolve(__dirname, './dist'), + publicPath: '/', + filename: 'build.js' + }, + resolveLoader: { + root: path.join(__dirname, 'node_modules'), + }, + module: { + loaders: [ + { + test: /\.vue$/, + loader: 'vue' + }, + { + test: /\.js$/, + loader: 'babel' + }, + { + test: /\.(png|jpg|gif|svg|ttf)$/, + loader: 'file', + query: { + name: '[hash:8].[ext]' + } + }, + { + test: /\.json$/, + loader: 'json' + } + ] + }, + babel: { + presets: ['es2015'] + }, + devServer: { + historyApiFallback: true, + noInfo: false + }, + devtool: '#eval-source-map' +} + +if (process.env.NODE_ENV === 'production') { + module.exports.devtool = '#source-map' + module.exports.plugins = (module.exports.plugins || []).concat([ + new webpack.DefinePlugin({ + 'process.env': { + NODE_ENV: '""production""' + } + }), + new webpack.optimize.UglifyJsPlugin({ + compress: { + warnings: false + } + }) + ]) +} +","var path = require('path') +var webpack = require('webpack') + +module.exports = { + entry: './src/index.js', + output: { + path: path.resolve(__dirname, './dist'), + publicPath: '/dist/', + filename: 'build.js' + }, + resolveLoader: { + root: path.join(__dirname, 'node_modules'), + }, + module: { + loaders: [ + { + test: /\.vue$/, + loader: 'vue' + }, + { + test: /\.js$/, + loader: 'babel' + }, + { + test: /\.(png|jpg|gif|svg|ttf)$/, + loader: 'file', + query: { + name: '[hash:8].[ext]' + } + }, + { + test: /\.json$/, + loader: 'json' + } + ] + }, + babel: { + presets: ['es2015'] + }, + devServer: { + historyApiFallback: true, + noInfo: false + }, + devtool: '#eval-source-map' +} + +if (process.env.NODE_ENV === 'production') { + module.exports.devtool = '#source-map' + module.exports.plugins = (module.exports.plugins || []).concat([ + new webpack.DefinePlugin({ + 'process.env': { + NODE_ENV: '""production""' + } + }), + new webpack.optimize.UglifyJsPlugin({ + compress: { + warnings: false + } + }) + ]) +} +" +Load and test for admin users.,"module.exports = function(access) { + 'use strict'; + + let _ = require('lodash'); + let projectAccessCache = {}; + let adminUsersCache = {}; + return { + find: find, + clear: clear, + validateAccess: validateAccess + }; + + // find looks up a given project in the project cache. + // If the projectAccessCache hasn't been loaded it loads the + // cache. + function *find(project_id) { + if (_.isEmpty(adminUsersCache)) { + let adminUsers = yield access.adminUsers(); + adminUsers.forEach(function(user) { + adminUsersCache[user.id] = user; + }); + } + + if (! _.isEmpty(projectAccessCache)) { + return projectAccessCache[project_id]; + } + + projectAccessCache = yield access.allByProject(); + return projectAccessCache[project_id]; + } + + // clear will clear the current project cache. This is useful + // when project permissions have been updated or a new project + // has been created. + function clear() { + projectAccessCache = {}; + } + + // validateAccess checks if the user has access to the + // given project. This method assumes that find was called + // first so that the projectAccessCache was preloaded. If the + // projectAccessCache is empty then it returns false (no access). + function validateAccess(project_id, user) { + if (user.id in adminUsersCache) { + return true; + } + + if (_.isEmpty(projectAccessCache)) { + return false; + } + + if (!(project_id in projectAccessCache)) { + return false; + } + let index = _.indexOf(projectAccessCache[project_id], function(a) { + return a.user_id == user.id; + }); + + // when index !== -1 we found the given user in the project. + return index !== -1; + } +}; +","module.exports = function(access) { + 'use strict'; + + let _ = require('lodash'); + let projectAccessCache = {}; + return { + find: find, + clear: clear, + validateAccess: validateAccess + }; + + // find looks up a given project in the project cache. + // If the projectAccessCache hasn't been loaded it loads the + // cache. + function *find(project_id) { + if (! _.isEmpty(projectAccessCache)) { + return projectAccessCache[project_id]; + } + + projectAccessCache = yield access.allByProject(); + return projectAccessCache[project_id]; + } + + // clear will clear the current project cache. This is useful + // when project permissions have been updated or a new project + // has been created. + function clear() { + projectAccessCache = {}; + } + + // validateAccess checks if the user has access to the + // given project. This method assumes that find was called + // first so that the projectAccessCache was preloaded. If the + // projectAccessCache is empty then it returns false (no access). + function validateAccess(project_id, user) { + if (_.isEmpty(projectAccessCache)) { + return false; + } + if (!(project_id in projectAccessCache)) { + return false; + } + let index = _.indexOf(projectAccessCache[project_id], function(a) { + return a.user_id == user.id; + }); + + // when index !== -1 we found the given user in the project. + return index !== -1; + } +}; +" +Replace reference to previously factored out variable,"import re +from urlparse import urlsplit + +from bs4 import BeautifulSoup +import requests +from urlparse import urldefrag, urljoin + +class PyPI(object): + def __init__(self, index=""http://pypi.python.org/simple""): + self._index = index + + def list_packages(self): + resp = requests.get(self._index) + + soup = BeautifulSoup(resp.content) + + for link in soup.find_all(""a""): + yield link.text + + def list_files(self, package): + package_uri = ""%s/%s/"" % (self._index, package) + resp = requests.get(package_uri) + + soup = BeautifulSoup(resp.content) + + for link in soup.find_all(""a""): + # filter out links to home and download pages + if ""rel"" in link.attrs: + continue + + filename = link.text + + # filter out links to other web pages + if urlsplit(filename).scheme: + continue + + file_uri, frag = urldefrag(link.attrs['href']) + file_uri = urljoin(package_uri, file_uri) + + mo = re.match(r""^md5=([a-fA-F0-9]{32})$"", frag) + md5 = mo.group(1) if mo else """" + + yield dict(filename=filename, + remote_uri=file_uri, + md5=md5) +","import re +from urlparse import urlsplit + +from bs4 import BeautifulSoup +import requests +from urlparse import urldefrag, urljoin + +class PyPI(object): + def __init__(self, index=""http://pypi.python.org/simple""): + self._index = index + + def list_packages(self): + resp = requests.get(self._index) + + soup = BeautifulSoup(package_list) + + for link in soup.find_all(""a""): + yield link.text + + def list_files(self, package): + package_uri = ""%s/%s/"" % (self._index, package) + resp = requests.get(package_uri) + + soup = BeautifulSoup(resp.content) + + for link in soup.find_all(""a""): + # filter out links to home and download pages + if ""rel"" in link.attrs: + continue + + filename = link.text + + # filter out links to other web pages + if urlsplit(filename).scheme: + continue + + file_uri, frag = urldefrag(link.attrs['href']) + file_uri = urljoin(package_uri, file_uri) + + mo = re.match(r""^md5=([a-fA-F0-9]{32})$"", frag) + md5 = mo.group(1) if mo else """" + + yield dict(filename=filename, + remote_uri=file_uri, + md5=md5) +" +Adjust /admin panel to changes in module manager class.," + */ +class ModuleLoader { + const all_modules = ':all:'; + + private $lpa; + private $lpa_count; + private $lpa_index = 0; + private $loaded_modules = array(); + private $initialized = false; + + private function init() { + if (!$this->initialized) { + $this->initialized = true; + $this->lpa = ModuleManager::get_load_priority_array(); + $this->lpa_count = count($this->lpa); + ModulesAutoloader::enable(); + } + } + + function load($modules) { + $this->init(); + + if (!is_array($modules)) + $modules = array($modules); + + foreach ($modules as $m) { + if (array_key_exists($m, ModuleManager::$modules)) + continue; + + while ($this->lpa_index < $this->lpa_count) { + $row = $this->lpa[$this->lpa_index++]; + $module = $row['name']; + $version = $row['version']; + ModuleManager :: include_common($module, $version); + ModuleManager :: register($module, $version, ModuleManager::$modules); + if ($m != self::all_modules && $module == $m) + break; + } + } + } + +} + +?> +"," + */ +class ModuleLoader { + const all_modules = ':all:'; + + private $lpa; + private $lpa_count; + private $lpa_index = 0; + private $loaded_modules = array(); + private $initialized = false; + + private function init() { + if (!$this->initialized) { + $this->initialized = true; + $this->lpa = ModuleManager::get_load_priority_array(); + $this->lpa_count = count($this->lpa); + ModuleManager::$not_loaded_modules = $this->lpa; + ModuleManager::$loaded_modules = array(); + ModulesAutoloader::enable(); + } + } + + function load($modules) { + $this->init(); + + if (!is_array($modules)) + $modules = array($modules); + + foreach ($modules as $m) { + if (array_key_exists($m, ModuleManager::$modules)) + continue; + + while ($this->lpa_index < $this->lpa_count) { + $row = $this->lpa[$this->lpa_index++]; + $module = $row['name']; + $version = $row['version']; + ModuleManager :: include_common($module, $version); + ModuleManager :: register($module, $version, ModuleManager::$modules); + if ($m != self::all_modules && $module == $m) + break; + } + } + } + +} + +?> +" +Fix config check to work with ngCloakAuth,"'use strict'; + +// Declare app level module which depends on filters, and services +angular.module('myApp', + ['myApp.config', 'myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'firebase', 'ngRoute', 'waitForAuth'] + ) + + // configure views; note the authRequired parameter for authenticated pages + .config(['$routeProvider', function($routeProvider) { + $routeProvider.when('/home', { + templateUrl: 'partials/home.html', + controller: 'HomeCtrl' + }); + + $routeProvider.when('/chat', { + templateUrl: 'partials/chat.html', + controller: 'ChatCtrl' + }); + + $routeProvider.when('/account', { + authRequired: true, // must authenticate before viewing this page + templateUrl: 'partials/account.html', + controller: 'AccountCtrl' + }); + + $routeProvider.when('/login', { + templateUrl: 'partials/login.html', + controller: 'LoginCtrl' + }); + + $routeProvider.otherwise({redirectTo: '/home'}); + }]) + + + // establish authentication + .run(['loginService', '$rootScope', 'FBURL', function(loginService, $rootScope, FBURL) { + if( FBURL === 'https://INSTANCE.firebaseio.com' ) { + // double-check that the app has been configured + angular.element(document.body).html('

    Please configure app/js/config.js before running!

    '); + setTimeout(function() { + angular.element(document.body).removeClass('hide'); + }, 250); + } + else { + $rootScope.auth = loginService.init('/login'); + $rootScope.FBURL = FBURL; + } + }]);","'use strict'; + +// Declare app level module which depends on filters, and services +angular.module('myApp', + ['myApp.config', 'myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'firebase', 'ngRoute', 'waitForAuth'] + ) + + // configure views; note the authRequired parameter for authenticated pages + .config(['$routeProvider', function($routeProvider) { + $routeProvider.when('/home', { + templateUrl: 'partials/home.html', + controller: 'HomeCtrl' + }); + + $routeProvider.when('/chat', { + templateUrl: 'partials/chat.html', + controller: 'ChatCtrl' + }); + + $routeProvider.when('/account', { + authRequired: true, // must authenticate before viewing this page + templateUrl: 'partials/account.html', + controller: 'AccountCtrl' + }); + + $routeProvider.when('/login', { + templateUrl: 'partials/login.html', + controller: 'LoginCtrl' + }); + + $routeProvider.otherwise({redirectTo: '/home'}); + }]) + + // double-check that the app has been configured + .run(['FBURL', function(FBURL) { + if( FBURL === 'https://INSTANCE.firebaseio.com' ) { + angular.element(document.body).html('

    Please configure app/js/config.js before running!

    '); + } + }]) + + // establish authentication + .run(['loginService', '$rootScope', 'FBURL', function(loginService, $rootScope, FBURL) { + $rootScope.auth = loginService.init('/login'); + $rootScope.FBURL = FBURL; + }]);" +Remove extraneous references to modal.,"PANDA.views.DatasetsResults = Backbone.View.extend({ + template: PANDA.templates.datasets_results, + pager_template: PANDA.templates.pager, + + initialize: function(options) { + _.bindAll(this, ""render""); + + this.search = options.search; + this.search.datasets.bind(""reset"", this.render); + }, + + render: function() { + context = this.search.datasets.meta; + context[""settings""] = PANDA.settings; + + context[""query""] = this.search.query; + context[""category""] = this.search.category; + + context[""datasets""] = this.search.datasets.results()[""datasets""]; + + this.el.html(this.template(context)); + + // Enable result sorting + $(""#datasets-results table"").tablesorter({ + cssHeader: ""no-sort-header"", + cssDesc: ""sort-desc-header"", + cssAsc: ""sort-asc-header"", + headers: { + 0: { sorter: ""text"" }, + 1: { sorter: false }, + 2: { sorter: ""text"" }, + 3: { sorter: false } + }, + textExtraction: function(node) { + return $(node).children("".sort-value"").text(); + } + }); + } +}); + + +","PANDA.views.DatasetsResults = Backbone.View.extend({ + template: PANDA.templates.datasets_results, + pager_template: PANDA.templates.pager, + + initialize: function(options) { + _.bindAll(this, ""render""); + + this.search = options.search; + this.search.datasets.bind(""reset"", this.render); + }, + + render: function() { + context = this.search.datasets.meta; + context[""settings""] = PANDA.settings; + + context[""query""] = this.search.query; + context[""category""] = this.search.category; + + context[""datasets""] = this.search.datasets.results()[""datasets""]; + + // Remove any lingering modal from previous usage + $(""#modal-dataset-search"").remove(); + + this.el.html(this.template(context)); + + // Enable result sorting + $(""#datasets-results table"").tablesorter({ + cssHeader: ""no-sort-header"", + cssDesc: ""sort-desc-header"", + cssAsc: ""sort-asc-header"", + headers: { + 0: { sorter: ""text"" }, + 1: { sorter: false }, + 2: { sorter: ""text"" }, + 3: { sorter: false } + }, + textExtraction: function(node) { + return $(node).children("".sort-value"").text(); + } + }); + + // Create new modal + $(""#modal-dataset-search"").modal({ + keyboard: true + }); + } +}); + + +" +Fix typo Nate caught in Galaxy.,"from __future__ import absolute_import +try: + from galaxy import eggs + eggs.require(""requests"") +except ImportError: + pass + +try: + import requests +except ImportError: + requests = None +requests_multipart_post_available = False +try: + import requests_toolbelt + requests_multipart_post_available = True +except ImportError: + requests_toolbelt = None + + +REQUESTS_UNAVAILABLE_MESSAGE = ""Pulsar configured to use requests module - but it is unavailable. Please install requests."" +REQUESTS_TOOLBELT_UNAVAILABLE_MESSAGE = ""Pulsar configured to use requests_toolbelt module - but it is unavailable. Please install requests_toolbelt."" + +import logging +log = logging.getLogger(__name__) + + +def post_file(url, path): + if requests_toolbelt is None: + raise ImportError(REQUESTS_TOOLBELT_UNAVAILABLE_MESSAGE) + + __ensure_requests() + m = requests_toolbelt.MultipartEncoder( + fields={'file': ('filename', open(path, 'rb'))} + ) + requests.post(url, data=m, headers={'Content-Type': m.content_type}) + + +def get_file(url, path): + __ensure_requests() + r = requests.get(url, stream=True) + with open(path, 'wb') as f: + for chunk in r.iter_content(chunk_size=1024): + if chunk: # filter out keep-alive new chunks + f.write(chunk) + f.flush() + + +def __ensure_requests(): + if requests is None: + raise ImportError(REQUESTS_UNAVAILABLE_MESSAGE) +","from __future__ import absolute_import +try: + from galaxy import eggs + eggs.require(""requets"") +except ImportError: + pass + +try: + import requests +except ImportError: + requests = None +requests_multipart_post_available = False +try: + import requests_toolbelt + requests_multipart_post_available = True +except ImportError: + requests_toolbelt = None + + +REQUESTS_UNAVAILABLE_MESSAGE = ""Pulsar configured to use requests module - but it is unavailable. Please install requests."" +REQUESTS_TOOLBELT_UNAVAILABLE_MESSAGE = ""Pulsar configured to use requests_toolbelt module - but it is unavailable. Please install requests_toolbelt."" + +import logging +log = logging.getLogger(__name__) + + +def post_file(url, path): + if requests_toolbelt is None: + raise ImportError(REQUESTS_TOOLBELT_UNAVAILABLE_MESSAGE) + + __ensure_requests() + m = requests_toolbelt.MultipartEncoder( + fields={'file': ('filename', open(path, 'rb'))} + ) + requests.post(url, data=m, headers={'Content-Type': m.content_type}) + + +def get_file(url, path): + __ensure_requests() + r = requests.get(url, stream=True) + with open(path, 'wb') as f: + for chunk in r.iter_content(chunk_size=1024): + if chunk: # filter out keep-alive new chunks + f.write(chunk) + f.flush() + + +def __ensure_requests(): + if requests is None: + raise ImportError(REQUESTS_UNAVAILABLE_MESSAGE) +" +Use different values between tests,"import React from 'react'; +import ReactDOM from 'react-dom'; +import { Simulate } from 'react-addons-test-utils'; +import { render } from '../../../helpers/rendering.js'; +import $ from 'jquery'; +import App, { TodoList } from './setup.js'; + +const ENTER = 13; + + +describe('App', function() { + describe('adding new todos', function() { + let $component; + + beforeEach(function() { + const component = render(); + + $component = $(ReactDOM.findDOMNode(component)); + }); + + it('should update the new todo input field when typing', function() { + const node = $component.find('.new-todo')[0]; + + Simulate.change(node, { target: { value: 'buy milk' } }); + + expect($(node).val()).to.equal('buy milk'); + }); + + it('should render a todo when pressing the enter key', function() { + addTodo($component, 'buy milk'); + + expect(TodoList).to.have.been.renderedWith({ + todos: [{ title: 'buy milk' }] + }); + }); + + it('should trim whitespace from new todos', function() { + addTodo($component, ' wash car '); + + expect(TodoList).to.have.been.renderedWith({ + todos: [{ title: 'wash car' }] + }); + }); + }); +}); + +function addTodo($component, todo) { + const node = $component.find('.new-todo')[0]; + + Simulate.change(node, { target: { value: todo } }); + Simulate.keyDown(node, { + keyCode: ENTER + }); +} +","import React from 'react'; +import ReactDOM from 'react-dom'; +import { Simulate } from 'react-addons-test-utils'; +import { render } from '../../../helpers/rendering.js'; +import $ from 'jquery'; +import App, { TodoList } from './setup.js'; + +const ENTER = 13; + + +describe('App', function() { + describe('adding new todos', function() { + let $component; + + beforeEach(function() { + const component = render(); + + $component = $(ReactDOM.findDOMNode(component)); + }); + + it('should update the new todo input field when typing', function() { + const node = $component.find('.new-todo')[0]; + + Simulate.change(node, { target: { value: 'buy milk' } }); + + expect($(node).val()).to.equal('buy milk'); + }); + + it('should render a todo when pressing the enter key', function() { + addTodo($component, 'buy milk'); + + expect(TodoList).to.have.been.renderedWith({ + todos: [{ title: 'buy milk' }] + }); + }); + + it('should trim whitespace from new todos', function() { + addTodo($component, ' buy milk '); + + expect(TodoList).to.have.been.renderedWith({ + todos: [{ title: 'buy milk' }] + }); + }); + }); +}); + +function addTodo($component, todo) { + const node = $component.find('.new-todo')[0]; + + Simulate.change(node, { target: { value: todo } }); + Simulate.keyDown(node, { + keyCode: ENTER + }); +} +" +Make harvesters dump in extensions before links,"module.exports = function (creep) { + var optimalStructureId; + + function isStructureAvailable(structure) { + if(structure.energy < structure.energyCapacity && (structure.pos.room.name > creep.pos.room.name ? false : (structure.pos.room.name < creep.pos.room.name)) ) { + optimalStructureId = structure.id; + return true; + } + } + + if(creep.memory.currentTarget) { + creep.memory.currentTarget = Game.getObjectById(creep.memory.currentTarget.id); + } + + // Aquire target + if(!creep.memory.currentTarget || !creep.memory.currentTarget.structureType || creep.memory.currentTarget.energy === creep.memory.currentTarget.energyCapacity) { + if(Object.keys(Game.spawns).some(function (spawnName) { + return isStructureAvailable(Game.spawns[spawnName]); + })) {} else if (Memory.extensionList.some(function (extensionId) { + return isStructureAvailable(Game.getObjectById(extensionId)); + })) {} else if (Memory.linkList.some(function (linkId) { + return isStructureAvailable(Game.getObjectById(linkId)); + })) {} + + creep.memory.currentTarget = optimalStructureId; + } + + // Execute on target + if(creep.memory.currentTarget) { + if(creep.pos.isNearTo(creep.memory.currentTarget.pos.x, creep.memory.currentTarget.pos.y)) { + creep.transferEnergy(Game.getObjectById(creep.memory.currentTarget.id)); + } else { + creep.advMove(creep.memory.currentTarget); + } + } +}; +","module.exports = function (creep) { + if(creep.memory.currentTarget) { + creep.memory.currentTarget = Game.getObjectById(creep.memory.currentTarget.id); + } + + // Aquire target + if(!creep.memory.currentTarget || !creep.memory.currentTarget.structureType || creep.memory.currentTarget.energy === creep.memory.currentTarget.energyCapacity) { + creep.memory.currentTarget = creep.pos.findClosest(FIND_MY_SPAWNS, { + filter: function(spawn) { + return (spawn.energy < spawn.energyCapacity); + }, + algorithm: ""astar"" + }); + + if(!creep.memory.currentTarget) { + creep.memory.currentTarget = creep.pos.findClosest(FIND_MY_STRUCTURES, { + filter: function(structure) { + return (structure.structureType === STRUCTURE_EXTENSION || structure.structureType === STRUCTURE_LINK) && (structure.energy < structure.energyCapacity); + }, + algorithm: ""astar"" + }); + } + } + + // Execute on target + if(creep.memory.currentTarget) { + if(creep.pos.isNearTo(creep.memory.currentTarget.pos.x, creep.memory.currentTarget.pos.y)) { + creep.transferEnergy(Game.getObjectById(creep.memory.currentTarget.id)); + } else { + creep.advMove(creep.memory.currentTarget); + } + } +}; +" +Include phones in default org object,"import React, { Component } from 'react' + +import { fetchOrganization } from '../../core/firebaseRestAPI' +import { authenticate } from '../../lib/session' +import { uuid } from '../../lib/uuid' + +import Layout from '../../components/Layout' +import Loading from '../../components/Loading' +import OrganizationEdit from '../../components/OrganizationEdit' + +const blankOrganization = () => ({ + id: uuid(), + longDescription: """", + name: """", + url: """", + phones: [] +}) + +class OrganizationAdminPage extends Component { + constructor(props) { + super(props) + this.state = { + organization: null, + } + } + + componentWillMount() { + authenticate() + } + + componentDidMount() { + const match = this.props.route.pattern.exec(window.location.pathname) + const organizationId = match[1] + + if (organizationId === 'new') { + this.setState({ organization: blankOrganization() }) + } else { + fetchOrganization(organizationId) + .then(organization => { + this.setState({ organization }) + }) + } + } + + componentDidUpdate() { + const { organization } = this.state + + if (organization && organization.name) { + document.title = organization.name + } else { + document.title = 'Create Organization' + } + } + + render() { + const { organization } = this.state + + return ( + + { organization ? + : + + } + + ) + } +} + +export default OrganizationAdminPage +","import React, { Component } from 'react' + +import { fetchOrganization } from '../../core/firebaseRestAPI' +import { authenticate } from '../../lib/session' +import { uuid } from '../../lib/uuid' + +import Layout from '../../components/Layout' +import Loading from '../../components/Loading' +import OrganizationEdit from '../../components/OrganizationEdit' + +const blankOrganization = () => ({ + id: uuid(), + longDescription: """", + name: """", + url: """" +}) + +class OrganizationAdminPage extends Component { + constructor(props) { + super(props) + this.state = { + organization: null, + } + } + + componentWillMount() { + authenticate() + } + + componentDidMount() { + const match = this.props.route.pattern.exec(window.location.pathname) + const organizationId = match[1] + + if (organizationId === 'new') { + this.setState({ organization: blankOrganization() }) + } else { + fetchOrganization(organizationId) + .then(organization => { + this.setState({ organization }) + }) + } + } + + componentDidUpdate() { + const { organization } = this.state + + if (organization && organization.name) { + document.title = organization.name + } else { + document.title = 'Create Organization' + } + } + + render() { + const { organization } = this.state + + return ( + + { organization ? + : + + } + + ) + } +} + +export default OrganizationAdminPage +" +"Fix editor in iFrame should be the code +This should be changed","/* eslint-disable no-undef, no-unused-vars, no-native-reassign */ +window.__$ = parent.$; +window.__$(function() { + var _ = parent._; + var Rx = parent.Rx; + var chai = parent.chai; + var assert = chai.assert; + var tests = parent.tests; + var common = parent.common; + var editor = common.editor.getValue(); + // grab the iframe body element + var body = document.getElementsByTagName('body'); + // change the context of $ so it uses the iFrame for testing + var $ = __$.proxy(__$.fn.find, __$(body)); + + common.runPreviewTests$ = + function runPreviewTests$({ tests = [], ...rest }) { + return Rx.Observable.from(tests) + .map(test => { + const userTest = {}; + try { + /* eslint-disable no-eval */ + eval(test); + /* eslint-enable no-eval */ + } catch (e) { + userTest.err = e.message.split(':').shift(); + } finally { + userTest.text = test + .split(',') + .pop() + .replace(/\'/g, '') + .replace(/\)/, ''); + } + return userTest; + }) + .toArray() + .map(tests => ({ ...rest, tests })); + }; + +}); +","/* eslint-disable no-undef, no-unused-vars, no-native-reassign */ +window.__$ = parent.$; +window.__$(function() { + var _ = parent._; + var Rx = parent.Rx; + var chai = parent.chai; + var assert = chai.assert; + var tests = parent.tests; + var common = parent.common; + var code = common.editor.getValue(); + var editor = common.editor; + // grab the iframe body element + var body = document.getElementsByTagName('body'); + // change the context of $ so it uses the iFrame for testing + var $ = __$.proxy(__$.fn.find, __$(body)); + + common.runPreviewTests$ = + function runPreviewTests$({ tests = [], ...rest }) { + return Rx.Observable.from(tests) + .map(test => { + const userTest = {}; + try { + /* eslint-disable no-eval */ + eval(test); + /* eslint-enable no-eval */ + } catch (e) { + userTest.err = e.message.split(':').shift(); + } finally { + userTest.text = test + .split(',') + .pop() + .replace(/\'/g, '') + .replace(/\)/, ''); + } + return userTest; + }) + .toArray() + .map(tests => ({ ...rest, tests })); + }; + +}); +" +"Make codemirror plugins depends on codemirror + +It is important codemirror is loaded before those as otherwise it will give +certain nasty errors.","require.config({ + paths: { + jquery: '../components/jquery/jquery', + + codemirror: '../components/codemirror/lib/codemirror', + matchbrackets: '../components/codemirror/addon/edit/matchbrackets', + continuecomment: '../components/codemirror/addon/edit/continuecomment', + javascripthint: '../components/codemirror/addon/hint/javascript-hint', + javascriptmode: '../components/codemirror/mode/javascript/javascript', + + threejs: '../vendor/three' + }, + shim: { + matchbrackets: ['codemirror'], + continuecomment: ['codemirror'], + javascripthint: ['codemirror'], + javascriptmode: ['codemirror'] + }, + urlArgs: 'buster=' + (new Date()).getTime() // for dev only! use rev otherwise +}); + +require(['jquery', './preview', './editor', './commands'], function($, preview, editor, commands) { + $(function() { + // TODO: figure out how to deal with this. hook up cb at command? + var previews = []; + previews.evaluate = function(ops) { + previews.forEach(function(p) { + p.evaluate(ops); + }); + }; + + $('.preview').each(function() { + previews.push(preview($(this))); + }); + $('.editor').each(function() { + var $e = $(this); + var $commands = $('
    ', {'class': 'commands'}).appendTo($e); + var $editArea = $('
    ', {'class': 'editArea'}).appendTo($e); + + commands($commands, editor($editArea), previews); + }); + }); +}); +","require.config({ + paths: { + jquery: '../components/jquery/jquery', + + codemirror: '../components/codemirror/lib/codemirror', + matchbrackets: '../components/codemirror/addon/edit/matchbrackets', + continuecomment: '../components/codemirror/addon/edit/continuecomment', + javascripthint: '../components/codemirror/addon/hint/javascript-hint', + javascriptmode: '../components/codemirror/mode/javascript/javascript', + + threejs: '../vendor/three' + }, + urlArgs: 'buster=' + (new Date()).getTime() // for dev only! use rev otherwise +}); + +require(['jquery', './preview', './editor', './commands'], function($, preview, editor, commands) { + $(function() { + // TODO: figure out how to deal with this. hook up cb at command? + var previews = []; + previews.evaluate = function(ops) { + previews.forEach(function(p) { + p.evaluate(ops); + }); + }; + + $('.preview').each(function() { + previews.push(preview($(this))); + }); + $('.editor').each(function() { + var $e = $(this); + var $commands = $('
    ', {'class': 'commands'}).appendTo($e); + var $editArea = $('
    ', {'class': 'editArea'}).appendTo($e); + + commands($commands, editor($editArea), previews); + }); + }); +}); +" +Fix Travis issue with Karma pt.3,"// const webpack = require('webpack'); + +module.exports = (config) => { + config.set({ + browsers: process.env.TRAVIS ? ['Chrome_travis_ci'] : ['Chrome'], // run in Chrome + singleRun: true, // just run once by default + frameworks: ['mocha', 'chai'], // use the mocha test framework + files: [ + 'tests.webpack.js', // just load this file + ], + preprocessors: { + 'tests.webpack.js': ['webpack', 'sourcemap'], // preprocess with webpack and our sourcemap loader + }, + reporters: ['progress', 'coverage', 'coveralls'], + webpack: { // kind of a copy of your webpack config + devtool: 'inline-source-map', // just do inline source maps instead of the default + module: { + loaders: [ + { test: /\.js$/, loader: 'babel-loader' }, + ], + }, + }, + coverageReporter: { + check: { + global: { + statements: 11, + branches: 0, + functions: 0, + lines: 11, + }, + }, + reporters: [ + { type: 'lcov', dir: 'coverage/', subdir: '.' }, + { type: 'json', dir: 'coverage/', subdir: '.' }, + { type: 'text-summary' }, + ], + }, + customLaunchers: { + Chrome_travis_ci: { + base: 'Chrome', + flags: ['--no-sandbox'], + }, + }, + webpackMiddleware: { noInfo: true }, + colors: true, + concurrency: Infinity, + logLevel: config.LOG_DEBUG, + }); +}; +","// const webpack = require('webpack'); + +module.exports = (config) => { + config.set({ + browsers: ['Chrome'], // run in Chrome + singleRun: true, // just run once by default + frameworks: ['mocha', 'chai'], // use the mocha test framework + files: [ + 'tests.webpack.js', // just load this file + ], + preprocessors: { + 'tests.webpack.js': ['webpack', 'sourcemap'], // preprocess with webpack and our sourcemap loader + }, + reporters: ['progress', 'coverage', 'coveralls'], + webpack: { // kind of a copy of your webpack config + devtool: 'inline-source-map', // just do inline source maps instead of the default + module: { + loaders: [ + { test: /\.js$/, loader: 'babel-loader' }, + ], + }, + }, + coverageReporter: { + check: { + global: { + statements: 11, + branches: 0, + functions: 0, + lines: 11, + }, + }, + reporters: [ + { type: 'lcov', dir: 'coverage/', subdir: '.' }, + { type: 'json', dir: 'coverage/', subdir: '.' }, + { type: 'text-summary' }, + ], + }, + webpackMiddleware: { noInfo: true }, + colors: true, + concurrency: Infinity, + logLevel: config.LOG_DEBUG, + }); +}; +" +"Update TestingRCBugs datasource to new API + +Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>","#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import unittest + +import os, sys +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from DebianChangesBot import Datasource +from DebianChangesBot.datasources import TestingRCBugs + +class TestDatasourceTestingRCBugs(unittest.TestCase): + + def setUp(self): + self.fixture = os.path.join(os.path.dirname(os.path.abspath(__file__)), \ + 'fixtures', 'testing_rc_bugs.html') + + self.datasource = TestingRCBugs() + + def testURL(self): + """""" + Check we have a sane URL. + """""" + self.assert_(len(self.datasource.URL) > 5) + self.assert_(self.datasource.URL.startswith('http')) + self.assert_('dist' in self.datasource.URL) + + def testInterval(self): + """""" + Check we have a sane update interval. + """""" + self.assert_(self.datasource.INTERVAL > 60) + + def testParse(self): + fileobj = open(self.fixture) + self.datasource.update(fileobj) + val = self.datasource.get_num_bugs() + + self.assert_(type(val) is int) + self.assertEqual(val, 538) + + def testParseEmpty(self): + fileobj = open('/dev/null') + self.assertRaises(Datasource.DataError, self.datasource.update, fileobj) + +if __name__ == ""__main__"": + unittest.main() +","#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import unittest + +import os, sys +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from DebianChangesBot import Datasource +from DebianChangesBot.datasources import TestingRCBugs + +class TestDatasourceTestingRCBugs(unittest.TestCase): + + def setUp(self): + self.fixture = os.path.join(os.path.dirname(os.path.abspath(__file__)), \ + 'fixtures', 'testing_rc_bugs.html') + + self.datasource = TestingRCBugs() + + def testURL(self): + """""" + Check we have a sane URL. + """""" + self.assert_(len(self.datasource.URL) > 5) + self.assert_(self.datasource.URL.startswith('http')) + self.assert_('dist' in self.datasource.URL) + + def testInterval(self): + """""" + Check we have a sane update interval. + """""" + self.assert_(self.datasource.INTERVAL > 60) + + def testParse(self): + fileobj = open(self.fixture) + val = self.datasource.parse(fileobj) + + self.assert_(type(val) is int) + self.assertEqual(val, 538) + + def testParseEmpty(self): + fileobj = open('/dev/null') + self.assertRaises(Datasource.DataError, self.datasource.parse, fileobj) + +if __name__ == ""__main__"": + unittest.main() +" +Fix line longer than 120 characters error,"package seedu.doit.logic; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.time.LocalDateTime; +import java.util.Optional; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import seedu.doit.logic.parser.DateTimeParser; + +/** + * Tests if DateTimeParser is parsing the date correctly + **/ + +public class DateTimeParserTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + private void assertSameDate(LocalDateTime time1, LocalDateTime time2) { + LocalDateTime diff = time1.minusHours(time2.getHour()).minusMinutes(time2.getMinute()) + .minusSeconds(time2.getSecond()); + assertEquals(time1, diff); + } + + @Test + public void check_ifDateParsedCorrectly() throws Exception { + Optional t = DateTimeParser.parseDateTime(""03/20/17""); + assertSameDate(t.get(), LocalDateTime.of(2017, 3, 20, 0, 0)); + } + + @Test + public void parseEmptyString() { + Optional dateParsed = DateTimeParser.parseDateTime(""""); + assertFalse(dateParsed.isPresent()); + } + + @Test + public void parseNullString() throws Exception { + thrown.expect(NullPointerException.class); + DateTimeParser.parseDateTime(null); + } + + @Test + public void parseRubbishString() { + Optional dateParsed = DateTimeParser.parseDateTime(""jsadf""); + assertFalse(dateParsed.isPresent()); + } + + + +} +","package seedu.doit.logic; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.time.LocalDateTime; +import java.util.Optional; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import seedu.doit.logic.parser.DateTimeParser; + +/** + * Tests if DateTimeParser is parsing the date correctly + **/ + +public class DateTimeParserTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + private void assertSameDate(LocalDateTime time1, LocalDateTime time2) { + LocalDateTime diff = time1.minusHours(time2.getHour()).minusMinutes(time2.getMinute()).minusSeconds(time2.getSecond()); + assertEquals(time1, diff); + } + + @Test + public void check_ifDateParsedCorrectly() throws Exception { + Optional t = DateTimeParser.parseDateTime(""03/20/17""); + assertSameDate(t.get(), LocalDateTime.of(2017, 3, 20, 0, 0)); + } + + @Test + public void parseEmptyString() { + Optional dateParsed = DateTimeParser.parseDateTime(""""); + assertFalse(dateParsed.isPresent()); + } + + @Test + public void parseNullString() throws Exception { + thrown.expect(NullPointerException.class); + DateTimeParser.parseDateTime(null); + } + + @Test + public void parseRubbishString() { + Optional dateParsed = DateTimeParser.parseDateTime(""jsadf""); + assertFalse(dateParsed.isPresent()); + } + + + +} +" +Prepare for replacing the first occurrence,"var replaceAll = function( occurrences ) { + var configs = this; + return { + from: function( target ) { + return { + to: function( replacement ) { + var template; + var index = -1; + if ( configs.ignoringCase ) { + template = occurrences.toLowerCase(); + while(( + index = target + .toLowerCase() + .indexOf( + template, + index === -1 ? 0 : index + replacement.length + ) + ) !== -1 ) { + target = target + .substring( 0, index ) + + replacement + + target.substring( index + replacement.length ); + } + return target; + } + return target.split( occurrences ).join( replacement ); + } + }; + }, + ignoringCase: function() { + return replaceAll.call({ + ignoringCase: true + }, occurrences ); + } + }; +}; + +var replace = new function() { + // TODO Replace the first occurrence +}; + +replace.all = replaceAll; + +module.exports = replace; +","var replaceAll = function( occurrences ) { + var configs = this; + return { + from: function( target ) { + return { + to: function( replacement ) { + var template; + var index = -1; + if ( configs.ignoringCase ) { + template = occurrences.toLowerCase(); + while(( + index = target + .toLowerCase() + .indexOf( + template, + index === -1 ? 0 : index + replacement.length + ) + ) !== -1 ) { + target = target + .substring( 0, index ) + + replacement + + target.substring( index + replacement.length ); + } + return target; + } + return target.split( occurrences ).join( replacement ); + } + }; + }, + ignoringCase: function() { + return replaceAll.call({ + ignoringCase: true + }, occurrences ); + } + }; +}; + +module.exports = { + all: replaceAll +}; +" +Fix ApolloClient tests in phantomjs,"/* eslint-disable prefer-arrow-callback, func-names */ +/* eslint-env mocha */ +import chai from 'chai'; +import gql from 'graphql-tag'; +import { Promise } from 'meteor/promise'; +import { ApolloClient } from 'apollo-client'; +import { InMemoryCache } from 'apollo-cache-inmemory'; +import { getDDPLink } from '../../lib/client/apollo-link-ddp'; +import { FOO_CHANGED_TOPIC } from '../data/resolvers'; + +describe('ApolloClient with DDP link', function () { + beforeEach(function () { + // The ApolloClient won't recognize Promise in package tests unless exported like this + global.Promise = Promise; + + this.client = new ApolloClient({ + link: getDDPLink(), + cache: new InMemoryCache(), + }); + }); + + describe('#query', function () { + it('returns query data', async function () { + const { data } = await this.client.query({ query: gql`query { foo }` }); + + chai.expect(data.foo).to.be.a('string'); + }); + + it('returns subscription data', function (done) { + const message = { fooSub: 'bar' }; + const observer = this.client.subscribe({ query: gql`subscription { fooSub }` }); + + const subscription = observer.subscribe({ + next: (data) => { + try { + chai.expect(data).to.deep.equal(message); + subscription.unsubscribe(); + done(); + } catch (e) { + done(e); + } + }, + }); + + Meteor.call('ddp-apollo/publish', FOO_CHANGED_TOPIC, message); + }); + }); +}); +","/* eslint-disable prefer-arrow-callback, func-names */ +/* eslint-env mocha */ +import chai from 'chai'; +import gql from 'graphql-tag'; +import { ApolloClient } from 'apollo-client'; +import { InMemoryCache } from 'apollo-cache-inmemory'; +import { getDDPLink } from '../../lib/client/apollo-link-ddp'; +import { FOO_CHANGED_TOPIC } from '../data/resolvers'; + +describe('ApolloClient with DDP link', function () { + beforeEach(function () { + this.client = new ApolloClient({ + link: getDDPLink(), + cache: new InMemoryCache(), + }); + }); + + describe('#query', function () { + it('returns query data', async function () { + const { data } = await this.client.query({ query: gql`query { foo }` }); + + chai.expect(data.foo).to.be.a('string'); + }); + + it('returns subscription data', function (done) { + const message = { fooSub: 'bar' }; + const observer = this.client.subscribe({ query: gql`subscription { fooSub }` }); + + const subscription = observer.subscribe({ + next: (data) => { + try { + chai.expect(data).to.deep.equal(message); + subscription.unsubscribe(); + done(); + } catch (e) { + done(e); + } + }, + }); + + Meteor.call('ddp-apollo/publish', FOO_CHANGED_TOPIC, message); + }); + }); +}); +" +Fix issue with the existence of the decorators array introduced by syntax changes,"export default function({ types }) { + return { + visitor: { + Function: function parseFunctionPath(path) { + (path.get('params') || []).reverse().forEach(function(param) { + let currentDecorator; + + (param.node.decorators || []).reverse() + .forEach(function(decorator) { + + /** + * TODO: Validate the name of the decorator is not + * the same as any of the passed params + */ + currentDecorator = types.callExpression( + decorator.expression, [ + currentDecorator || + types.Identifier(`_${param.node.name}`) + ] + ); + }); + + param.parentPath.get('body').unshiftContainer( + 'body', types.variableDeclaration('var', [ + types.variableDeclarator( + types.Identifier(param.node.name), + currentDecorator + ) + ]) + ); + + param.replaceWith( + types.Identifier(`_${param.node.name}`) + ); + }); + } + } + }; +}","export default function({ types }) { + return { + visitor: { + Function: function parseFunctionPath(path) { + (path.get('params') || []).reverse().forEach(function(param) { + const decorators = param.node.decorators.reverse(); + + if (param.node && Array.isArray(decorators)) { + let currentDecorator; + + decorators.forEach(function(decorator) { + + /** + * TODO: Validate the name of the decorator is not + * the same as any of the passed params + */ + const callNode = types.callExpression( + decorator.expression, [ + currentDecorator || + types.Identifier(`_${param.node.name}`) + ] + ); + + currentDecorator = callNode; + }); + + param.parentPath.get('body').unshiftContainer( + 'body', types.variableDeclaration('var', [ + types.variableDeclarator( + types.Identifier(param.node.name), + currentDecorator + ) + ]) + ); + + param.replaceWith( + types.Identifier(`_${param.node.name}`) + ); + } + }); + } + } + }; +}" +Remove ResponseListener to avoid headers replacement,"share(function (Application $app) { + return new HttpClient(); + }); + $values['controller.proxy'] = $this->share(function (Application $app) { + return new ProxyController($app['url_generator'], $app['http_client']); + }); + + parent::__construct($values); + + // Remove ResponseListener to avoid headers replacement + $this['dispatcher'] = $this->extend('dispatcher', $this->share(function (EventDispatcherInterface $dispatcher) { + $listeners = $dispatcher->getListeners(KernelEvents::RESPONSE); + foreach ($listeners as $listener) { + list($object, $method) = $listener; + if ($object instanceof ResponseListener) { + $dispatcher->removeListener(KernelEvents::RESPONSE, $listener); + } + } + + return $dispatcher; + })); + +// $this->register(new TwigServiceProvider(), [ +// 'twig.path' => __DIR__.'/../views', +// 'twig.options' => [ +// 'cache' => is_writable(__DIR__.'/..') ? __DIR__.'/../cache/twig' : false, +// ], +// ]); + $this->register(new UrlGeneratorServiceProvider()); + $this->register(new ServiceControllerServiceProvider()); + + $this + ->match('/{url}', 'controller.proxy:indexAction') + ->bind('index') + ->assert('url', '.*') + ; + } +} +","share(function (Application $app) { + return new HttpClient(); + }); + $values['controller.proxy'] = $this->share(function (Application $app) { + return new ProxyController($app['url_generator'], $app['http_client']); + }); + + parent::__construct($values); + +// $this->register(new TwigServiceProvider(), [ +// 'twig.path' => __DIR__.'/../views', +// 'twig.options' => [ +// 'cache' => is_writable(__DIR__.'/..') ? __DIR__.'/../cache/twig' : false, +// ], +// ]); + $this->register(new UrlGeneratorServiceProvider()); + $this->register(new ServiceControllerServiceProvider()); + + $this + ->match('/{url}', 'controller.proxy:indexAction') + ->bind('index') + ->assert('url', '.*') + ; + } +} +" +Add Support for boolean as to string into yaml extension," + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bridge\Twig\Extension; + +use Symfony\Component\Yaml\Dumper as YamlDumper; + +/** + * Provides integration of the Yaml component with Twig. + * + * @author Fabien Potencier + */ +class YamlExtension extends \Twig_Extension +{ + /** + * {@inheritdoc} + */ + public function getFilters() + { + return array( + 'yaml_encode' => new \Twig_Filter_Method($this, 'encode'), + 'yaml_dump' => new \Twig_Filter_Method($this, 'dump'), + ); + } + + public function encode($input, $inline = 0) + { + static $dumper; + + if (null === $dumper) { + $dumper = new YamlDumper(); + } + + return $dumper->dump($input, $inline); + } + + public function dump($value) + { + if (is_resource($value)) { + return '%Resource%'; + } + + if (is_array($value) || is_object($value)) { + return '%'.gettype($value).'% '.$this->encode($value); + } + + return $this->encode($value); + } + + /** + * Returns the name of the extension. + * + * @return string The extension name + */ + public function getName() + { + return 'yaml'; + } +} +"," + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bridge\Twig\Extension; + +use Symfony\Component\Yaml\Dumper as YamlDumper; + +/** + * Provides integration of the Yaml component with Twig. + * + * @author Fabien Potencier + */ +class YamlExtension extends \Twig_Extension +{ + /** + * {@inheritdoc} + */ + public function getFilters() + { + return array( + 'yaml_encode' => new \Twig_Filter_Method($this, 'encode'), + 'yaml_dump' => new \Twig_Filter_Method($this, 'dump'), + ); + } + + public function encode($input, $inline = 0) + { + static $dumper; + + if (null === $dumper) { + $dumper = new YamlDumper(); + } + + return $dumper->dump($input, $inline); + } + + public function dump($value) + { + if (is_resource($value)) { + return '%Resource%'; + } + + if (is_array($value) || is_object($value)) { + return '%'.gettype($value).'% '.$this->encode($value); + } + + return $value; + } + + /** + * Returns the name of the extension. + * + * @return string The extension name + */ + public function getName() + { + return 'yaml'; + } +} +" +Set correct time zone after loading datetime from database,"setTimezone(self::getUtc()); + } + + return parent::convertToDatabaseValue($dateTime, $platform); + } + + /** + * @param string $dateTimeString + * @param AbstractPlatform $platform + * + * @throws ConversionException + * + * @return DateTime|null + */ + public function convertToPHPValue($dateTimeString, AbstractPlatform $platform) + { + if (null === $dateTimeString || $dateTimeString instanceof DateTime) { + return $dateTimeString; + } + + $dateTime = DateTime::createFromFormat($platform->getDateTimeFormatString(), $dateTimeString, self::getUtc()); + + if (!$dateTime) { + throw ConversionException::conversionFailedFormat( + $dateTimeString, + $this->getName(), + $platform->getDateTimeFormatString() + ); + } + + // set time zone + $dateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); + + return $dateTime; + } + + /** + * @return DateTimeZone + */ + private static function getUtc() + { + return self::$utc ? self::$utc : self::$utc = new DateTimeZone('UTC'); + } +} +","setTimezone(self::getUtc()); + } + + return parent::convertToDatabaseValue($dateTime, $platform); + } + + /** + * @param string $dateTimeString + * @param AbstractPlatform $platform + * + * @throws ConversionException + * + * @return DateTime|null + */ + public function convertToPHPValue($dateTimeString, AbstractPlatform $platform) + { + if (null === $dateTimeString || $dateTimeString instanceof DateTime) { + return $dateTimeString; + } + + $dateTime = DateTime::createFromFormat($platform->getDateTimeFormatString(), $dateTimeString, self::getUtc()); + + if (!$dateTime) { + throw ConversionException::conversionFailedFormat( + $dateTimeString, + $this->getName(), + $platform->getDateTimeFormatString() + ); + } + + return $dateTime; + } + + /** + * @return DateTimeZone + */ + private static function getUtc() + { + return self::$utc ? self::$utc : self::$utc = new DateTimeZone('UTC'); + } +} +" +Adjust package metadata to reflect support for Django 3.2+.,"from setuptools import find_packages, setup + +import picklefield + +with open('README.rst') as file_: + long_description = file_.read() + +setup( + name='django-picklefield', + version=picklefield.__version__, + description='Pickled object field for Django', + long_description=long_description, + author='Simon Charette', + author_email='charette.s+django-picklefiel@gmail.com', + url='http://github.com/gintas/django-picklefield', + license='MIT', + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Web Environment', + 'Framework :: Django', + 'Framework :: Django :: 3.2', + 'Framework :: Django :: 4.0', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 3 :: Only', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Software Development :: Libraries :: Application Frameworks', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + keywords=['django pickle model field'], + packages=find_packages(exclude=['tests', 'tests.*']), + python_requires='>=3', + install_requires=['Django>=3.2'], + extras_require={ + 'tests': ['tox'], + }, +) +","from setuptools import find_packages, setup + +import picklefield + +with open('README.rst') as file_: + long_description = file_.read() + +setup( + name='django-picklefield', + version=picklefield.__version__, + description='Pickled object field for Django', + long_description=long_description, + author='Simon Charette', + author_email='charette.s+django-picklefiel@gmail.com', + url='http://github.com/gintas/django-picklefield', + license='MIT', + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Web Environment', + 'Framework :: Django', + 'Framework :: Django :: 2.2', + 'Framework :: Django :: 3.0', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 3 :: Only', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Software Development :: Libraries :: Application Frameworks', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + keywords=['django pickle model field'], + packages=find_packages(exclude=['tests', 'tests.*']), + python_requires='>=3', + install_requires=['Django>=2.2'], + extras_require={ + 'tests': ['tox'], + }, +) +" +"Remove the convenience functions, reorganize around the SQLAlchemy class","from __future__ import unicode_literals +import os +import pdb + +from sqlalchemy import create_engine, MetaData +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker, scoped_session + +class Model(object): + def __repr__(self): + cols = self.__mapper__.c.keys() + class_name = self.__class__.__name__ + items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col + in cols]) + return '%s(%s)' % (class_name, items) + + def attrs_dict(self): + keys = self.__mapper__.c.keys() + attrs = {} + for key in keys: + attrs[key] = getattr(self, key) + return attrs + +class SQLAlchemy(object): + def __init__(self): + self.session = self.create_session() + self.Model = self.make_declarative_base() + + @property + def engine(self): + dburl = os.environ['DATABASE_URL'] + return create_engine(dburl) + + def create_session(self): + session = scoped_session(sessionmaker()) + session.configure(bind=self.engine) + return session + + def make_declarative_base(self): + base = declarative_base(cls=Model) + base.query = self.session.query_property() + return base + +db = SQLAlchemy() + +all = [db] + +def rollback(*_): + db.session.rollback()","from __future__ import unicode_literals +import os + +from sqlalchemy import create_engine, MetaData +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker, scoped_session + +class SQLAlchemy(object): + def __init__(self): + self.session = self.create_session() + + @property + def engine(self): + dburl = os.environ['DATABASE_URL'] + return create_engine(dburl) + + def create_session(self): + session = scoped_session(sessionmaker()) + session.configure(bind=self.engine) + return session + +db = SQLAlchemy() + +class Model(object): + def __repr__(self): + cols = self.__mapper__.c.keys() + class_name = self.__class__.__name__ + items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col + in cols]) + return '%s(%s)' % (class_name, items) + + def attrs_dict(self): + keys = self.__mapper__.c.keys() + attrs = {} + for key in keys: + attrs[key] = getattr(self, key) + return attrs + + def save(self): + db.session.add(self) + db.session.commit() + + def delete(self): + db.session.delete(self) + db.session.commit() + +Base = declarative_base(cls=Model) +Base.metadata.bind = db.engine +Base.query = db.session.query_property() + +metadata = MetaData() +metadata.bind = db.engine + +all = [Base, db, metadata] + + +def rollback(*_): + db.session.rollback()" +Add $httpbackend test to test notesTabController,"/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + + + + +(function () { + 'use strict'; + + describe('Unit: NotesTabController', function () { + //Load the module with NotesTabController + beforeEach(module('trackerApp')); + + var ctrl, scope; + var $httpBackend, createController, authRequestHandler; + + // inject the $controller and $rootScope services + // in the beforeEach block\ + + beforeEach(inject(function ($controller, $rootScope, $injector,$http) { + // Set up the mock http service responses + $httpBackend = $injector.get('$httpBackend'); + + // backend definition common for all tests + authRequestHandler = $httpBackend.when('GET', 'exampleNotes') + .respond([{}]); + + + //Create a new scope that's a child of the $rootScope + scope = $rootScope.$new(); + + //Create the controller + ctrl = $controller('NotesTabController', {$scope: scope,$http: $http}); + + })); + + it('Should define $scope.notesTabText', + function () { + expect(scope.notesTabText).toBeDefined(); + scope.clearNotesTab(); + expect(scope.notesTabText).toEqual(""""); + $httpBackend.flush(); + + } + + ); + + + it('should fetch notes.json', function () { + $httpBackend.expectGET('exampleNotes'); + var controller = ctrl; + $httpBackend.flush(); + }); + +it(""should have 1 object"", function () { + $httpBackend.flush(); + expect(scope.notesTabText.length).toBe(1); + }); + + afterEach(function () { + $httpBackend.verifyNoOutstandingExpectation(); + $httpBackend.verifyNoOutstandingRequest(); + }) + + + }); + +})();","/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + + + + +(function () { + 'use strict'; + + describe('Unit: NotesTabController', function () { + //Load the module with NotesTabController + beforeEach(module('trackerApp')); + + var ctrl, scope; + var $httpBackend, createController, authRequestHandler; + + // inject the $controller and $rootScope services + // in the beforeEach block\ + + beforeEach(inject(function ($controller, $rootScope, $injector) { + // Set up the mock http service responses + $httpBackend = $injector.get('$httpBackend'); + + // backend definition common for all tests + authRequestHandler = $httpBackend.when('GET', 'exampleNotes') + .respond(); + + + //Create a new scope that's a child of the $rootScope + scope = $rootScope.$new(); + + //Create the controller + ctrl = $controller('NotesTabController', {$scope: scope}); + + })); + + it('Should define $scope.notesTabText', + function () { + expect(scope.notesTabText).toBeDefined(); + scope.clearNotesTab(); + expect(scope.notesTabText).toEqual(""""); + $httpBackend.flush(); + + } + + ); + + + it('should fetch notes.json', function () { + $httpBackend.expectGET('exampleNotes'); + var controller = ctrl; + $httpBackend.flush(); + }); + + + afterEach(function () { + $httpBackend.verifyNoOutstandingExpectation(); + $httpBackend.verifyNoOutstandingRequest(); + }) + + + }); + +})();" +Make sure the latest pygments is used,"try: + from setuptools import setup, find_packages +except ImportError: + from ez_setup import use_setuptools + use_setuptools() + from setuptools import setup, find_packages + +setup( + name='kai', + version='0.1', + description='', + author='Ben Bangert', + author_email='ben@groovie.org', + install_requires=[ + ""Pylons>=0.9.7rc4"", ""CouchDB>=0.4"", ""python-openid>=2.2.1"", + ""pytz>=2008i"", ""Babel>=0.9.4"", ""tw.forms==0.9.2"", ""docutils>=0.5"", + ""PyXML>=0.8.4"", ""cssutils>=0.9.6a0"", ""Pygments>=1.0"", + ], + setup_requires=[""PasteScript>=1.6.3""], + packages=find_packages(exclude=['ez_setup']), + include_package_data=True, + test_suite='nose.collector', + package_data={'kai': ['i18n/*/LC_MESSAGES/*.mo']}, + message_extractors = {'kai': [ + ('**.py', 'python', None), + ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}), + ('public/**', 'ignore', None)]}, + zip_safe=False, + paster_plugins=['PasteScript', 'Pylons'], + entry_points="""""" + [paste.app_factory] + main = kai.config.middleware:make_app + + [paste.app_install] + main = pylons.util:PylonsInstaller + """""", +) +","try: + from setuptools import setup, find_packages +except ImportError: + from ez_setup import use_setuptools + use_setuptools() + from setuptools import setup, find_packages + +setup( + name='kai', + version='0.1', + description='', + author='Ben Bangert', + author_email='ben@groovie.org', + install_requires=[ + ""Pylons>=0.9.7rc4"", ""CouchDB>=0.4"", ""python-openid>=2.2.1"", + ""pytz>=2008i"", ""Babel>=0.9.4"", ""tw.forms==0.9.2"", ""docutils>=0.5"", + ""PyXML>=0.8.4"", ""cssutils>=0.9.6a0"", + ], + setup_requires=[""PasteScript>=1.6.3""], + packages=find_packages(exclude=['ez_setup']), + include_package_data=True, + test_suite='nose.collector', + package_data={'kai': ['i18n/*/LC_MESSAGES/*.mo']}, + message_extractors = {'kai': [ + ('**.py', 'python', None), + ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}), + ('public/**', 'ignore', None)]}, + zip_safe=False, + paster_plugins=['PasteScript', 'Pylons'], + entry_points="""""" + [paste.app_factory] + main = kai.config.middleware:make_app + + [paste.app_install] + main = pylons.util:PylonsInstaller + """""", +) +" +Add a warning about being in early demo stage,"import React, { Component, PropTypes } from 'react'; +import Relay from 'react-relay'; +import { Link } from 'react-router'; +import FontAwesome from 'react-fontawesome'; +import TeamRoute from '../../relay/TeamRoute'; +import teamFragment from '../../relay/teamFragment'; + +class TeamHeaderComponent extends Component { + render() { + const team = this.props.team; + + return ( + + ); + } +} + +const TeamHeaderContainer = Relay.createContainer(TeamHeaderComponent, { + fragments: { + team: () => teamFragment + } +}); + +class TeamHeader extends Component { + render() { + var route = new TeamRoute({ teamId: Checkdesk.context.team.dbid }); + return (); + } +} + +export default TeamHeader; +","import React, { Component, PropTypes } from 'react'; +import Relay from 'react-relay'; +import { Link } from 'react-router'; +import FontAwesome from 'react-fontawesome'; +import TeamRoute from '../../relay/TeamRoute'; +import teamFragment from '../../relay/teamFragment'; + +class TeamHeaderComponent extends Component { + render() { + const team = this.props.team; + + return ( + + ); + } +} + +const TeamHeaderContainer = Relay.createContainer(TeamHeaderComponent, { + fragments: { + team: () => teamFragment + } +}); + +class TeamHeader extends Component { + render() { + var route = new TeamRoute({ teamId: Checkdesk.context.team.dbid }); + return (); + } +} + +export default TeamHeader; +" +"Use Email facade instead of Notification since we aren't notifying a Notifiable, just some addresses","addHours($hours); + Notification::send($chunk, (new GeneralInterestNotification())->delay($when)); + $hours++; + }); + return response()->json(['status' => 'success']); + } + + public function sendNotificationManual(Request $request) + { + if (!$request->has('emails')) { + return response()->json(['status' => 'error', 'error' => ""Missing parameter 'emails'""], 400); + } + + $hours = 0; + $emails = $request->input('emails'); + $chunks = array_chunk($emails, 30); + foreach ($chunks as $chunk) { + $when = Carbon::now()->addHours($hours); + foreach ($chunk as $address) { + Mail::to($address)->later($when, new GeneralInterestNotification()); + } + $hours++; + } + return response()->json(['status' => 'success', 'count' => count($emails)]); + } +} +","addHours($hours); + Notification::send($chunk, (new GeneralInterestNotification())->delay($when)); + $hours++; + }); + return response()->json(['status' => 'success']); + } + + public function sendNotificationManual(Request $request) + { + if (!$request->has('emails')) { + return response()->json(['status' => 'error', 'error' => ""Missing parameter 'emails'""], 400); + } + + $hours = 0; + $emails = $request->input('emails'); + $chunks = array_chunk($emails, 30); + foreach ($chunks as $chunk) { + $when = Carbon::now()->addHours($hours); + Notification::send($chunk, (new GeneralInterestNotification())->delay($when)); + $hours++; + } + return response()->json(['status' => 'success', 'count' => count($emails)]); + } +} +" +Fix init of local recognizer,"import unittest + +import os +from speech_recognition import WavFile + +from mycroft.client.speech.listener import RecognizerLoop + +__author__ = 'seanfitz' + +DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), ""data"") + + +class LocalRecognizerTest(unittest.TestCase): + def setUp(self): + rl = RecognizerLoop() + self.recognizer = RecognizerLoop.create_mycroft_recognizer(rl, + 16000, + ""en-us"") + + def testRecognizerWrapper(self): + source = WavFile(os.path.join(DATA_DIR, ""hey_mycroft.wav"")) + with source as audio: + hyp = self.recognizer.transcribe(audio.stream.read()) + assert self.recognizer.key_phrase in hyp.hypstr.lower() + source = WavFile(os.path.join(DATA_DIR, ""mycroft.wav"")) + with source as audio: + hyp = self.recognizer.transcribe(audio.stream.read()) + assert self.recognizer.key_phrase in hyp.hypstr.lower() + + def testRecognitionInLongerUtterance(self): + source = WavFile(os.path.join(DATA_DIR, ""weather_mycroft.wav"")) + with source as audio: + hyp = self.recognizer.transcribe(audio.stream.read()) + assert self.recognizer.key_phrase in hyp.hypstr.lower() +","import unittest + +import os +from speech_recognition import WavFile + +from mycroft.client.speech.listener import RecognizerLoop + +__author__ = 'seanfitz' + +DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), ""data"") + + +class LocalRecognizerTest(unittest.TestCase): + def setUp(self): + self.recognizer = RecognizerLoop.create_mycroft_recognizer(16000, + ""en-us"") + + def testRecognizerWrapper(self): + source = WavFile(os.path.join(DATA_DIR, ""hey_mycroft.wav"")) + with source as audio: + hyp = self.recognizer.transcribe(audio.stream.read()) + assert self.recognizer.key_phrase in hyp.hypstr.lower() + source = WavFile(os.path.join(DATA_DIR, ""mycroft.wav"")) + with source as audio: + hyp = self.recognizer.transcribe(audio.stream.read()) + assert self.recognizer.key_phrase in hyp.hypstr.lower() + + def testRecognitionInLongerUtterance(self): + source = WavFile(os.path.join(DATA_DIR, ""weather_mycroft.wav"")) + with source as audio: + hyp = self.recognizer.transcribe(audio.stream.read()) + assert self.recognizer.key_phrase in hyp.hypstr.lower() +" +Add title to page + notice about storage/processing,"""use strict""; + +var React = require('react') + , h = require('react-hyperscript') + +module.exports = React.createClass({ + displayName: 'Main', + + getInitialState() { + return { + mboxStream: null + } + }, + + handleClickUpload() { + this.refs.upload.dispatchEvent(new MouseEvent('click')); + }, + + handleUploadFile(e) { + var fileReaderStream = require('filereader-stream') + , file = e.target.files[0] + + this.setState({ mboxStream: fileReaderStream(file) }); + }, + + render() { + var Stream = require('./stream') + , { mboxStream } = this.state + + return ( + h('div', [ + mboxStream + ? h(Stream, { mboxStream }) + : h('div', [ + h('h1', 'maelstrom'), + + h('p', [ + h('button .btn .btn-primary', { + onClick: this.handleClickUpload + }, 'choose mail archive') + ]), + + h('p', ` + All processing of mail files is done on your own computer. + No files will be uploaded to a remote server. + `), + + h('input .absolute', { + type: 'file', + ref: 'upload', + onChange: this.handleUploadFile, + style: { top: -1000 } + }) + ]) + ]) + ) + }, +}); +","""use strict""; + +var React = require('react') + , h = require('react-hyperscript') + +module.exports = React.createClass({ + displayName: 'Main', + + getInitialState() { + return { + mboxStream: null + } + }, + + handleClickUpload() { + this.refs.upload.dispatchEvent(new MouseEvent('click')); + }, + + handleUploadFile(e) { + var fileReaderStream = require('filereader-stream') + , file = e.target.files[0] + + this.setState({ mboxStream: fileReaderStream(file) }); + }, + + render() { + var Stream = require('./stream') + , { mboxStream } = this.state + + return ( + h('div', [ + mboxStream + ? h(Stream, { mboxStream }) + : h('div', [ + h('p', [ + h('button .btn .btn-primary', { + onClick: this.handleClickUpload + }, 'choose mail archive') + ]), + + h('input .absolute', { + type: 'file', + ref: 'upload', + onChange: this.handleUploadFile, + style: { top: -1000 } + }) + ]) + ]) + ) + }, +}); +" +Allow image_uri to be part of the public API,"import BlogPost from '../database/models/blog-post'; +import log from '../log'; + +const PUBLIC_API_ATTRIBUTES = [ + 'id', + 'title', + 'link', + 'image_uri', + 'description', + 'date_updated', + 'date_published', + 'author_id' +]; + +const DEFAULT_ORDER = [ + ['date_published', 'DESC'] +]; + +export function getAll() { + return new Promise((resolve, reject) => { + BlogPost.findAll({ + attributes: PUBLIC_API_ATTRIBUTES, + order: DEFAULT_ORDER, + raw: true + }) + .then(resolve) + .catch(error => { + log.error({ error }, 'Error getting list of all posts'); + reject(error); + }); + }); +} + +export function getById(id) { + return new Promise((resolve, reject) => { + BlogPost.findOne({ + attributes: PUBLIC_API_ATTRIBUTES, + where: { id }, + raw: true + }) + .then(resolve) + .catch(error => { + log.error({ error }, 'Error getting blog post by id'); + reject(error); + }); + }); +} + +export function getPage(pageNumber, pageSize) { + return new Promise((resolve, reject) => { + BlogPost.findAll({ + attributes: PUBLIC_API_ATTRIBUTES, + order: DEFAULT_ORDER, + offset: pageNumber * pageSize, + limit: pageSize, + raw: true + }) + .then(resolve) + .catch(error => { + log.error({ error }, 'Error getting page of posts'); + reject(error); + }); + }); +} +","import BlogPost from '../database/models/blog-post'; +import log from '../log'; + +const PUBLIC_API_ATTRIBUTES = [ + 'id', + 'title', + 'link', + 'description', + 'date_updated', + 'date_published', + 'author_id' +]; + +const DEFAULT_ORDER = [ + ['date_published', 'DESC'] +]; + +export function getAll() { + return new Promise((resolve, reject) => { + BlogPost.findAll({ + attributes: PUBLIC_API_ATTRIBUTES, + order: DEFAULT_ORDER, + raw: true + }) + .then(resolve) + .catch(error => { + log.error({ error }, 'Error getting list of all posts'); + reject(error); + }); + }); +} + +export function getById(id) { + return new Promise((resolve, reject) => { + BlogPost.findOne({ + attributes: PUBLIC_API_ATTRIBUTES, + where: { id }, + raw: true + }) + .then(resolve) + .catch(error => { + log.error({ error }, 'Error getting blog post by id'); + reject(error); + }); + }); +} + +export function getPage(pageNumber, pageSize) { + return new Promise((resolve, reject) => { + BlogPost.findAll({ + attributes: PUBLIC_API_ATTRIBUTES, + order: DEFAULT_ORDER, + offset: pageNumber * pageSize, + limit: pageSize, + raw: true + }) + .then(resolve) + .catch(error => { + log.error({ error }, 'Error getting page of posts'); + reject(error); + }); + }); +} +" +Use empty dict instead of True for remote resource queryset,"from collections import OrderedDict +import json +import six + +from rest_framework.relations import * +from rest_framework_json_api.relations import ResourceRelatedField + +from zc_common.remote_resource.models import * + + +class RemoteResourceField(ResourceRelatedField): + def __init__(self, *args, **kwargs): + if 'model' not in kwargs: + kwargs['model'] = RemoteResource + if not kwargs.get('read_only', None): + # The queryset is required to be not None, but not used + # due to the overriding of the methods below. + kwargs['queryset'] = {} + super(RemoteResourceField, self).__init__(*args, **kwargs) + + def to_internal_value(self, data): + if isinstance(data, six.text_type): + try: + data = json.loads(data) + except ValueError: + self.fail('incorrect_type', data_type=type(data).__name__) + if not isinstance(data, dict): + self.fail('incorrect_type', data_type=type(data).__name__) + + if 'type' not in data: + self.fail('missing_type') + + if 'id' not in data: + self.fail('missing_id') + + return RemoteResource(data['type'], data['id']) + + def to_representation(self, value): + return OrderedDict([('type', value.type), ('id', str(value.id))]) +","from collections import OrderedDict +import json +import six + +from rest_framework.relations import * +from rest_framework_json_api.relations import ResourceRelatedField + +from zc_common.remote_resource.models import * + + +class RemoteResourceField(ResourceRelatedField): + def __init__(self, *args, **kwargs): + if 'model' not in kwargs: + kwargs['model'] = RemoteResource + if not kwargs.get('read_only', None): + # The queryset is required to be not None, but not used + # due to the overriding of the methods below. + kwargs['queryset'] = True + super(RemoteResourceField, self).__init__(*args, **kwargs) + + def to_internal_value(self, data): + if isinstance(data, six.text_type): + try: + data = json.loads(data) + except ValueError: + self.fail('incorrect_type', data_type=type(data).__name__) + if not isinstance(data, dict): + self.fail('incorrect_type', data_type=type(data).__name__) + + if 'type' not in data: + self.fail('missing_type') + + if 'id' not in data: + self.fail('missing_id') + + return RemoteResource(data['type'], data['id']) + + def to_representation(self, value): + return OrderedDict([('type', value.type), ('id', str(value.id))]) +" +Remove cache dir before command execute,"baseDirectory = $baseDirectory; + $this->bundles = $bundles; + $this->fileSystem = new Filesystem(); + } + + /** + * Prepare migration directory to use. + * + * @return void + */ + public function prepare() + { + $migrationDirectory = $this->baseDirectory; + if ($this->fileSystem->exists($migrationDirectory)) { + $this->fileSystem->remove(array($migrationDirectory)); + } + $this->fileSystem->mkdir($migrationDirectory); + + foreach ($this->bundles as $bundle) { + $bundleMigrationDirectory = $bundle->getPath() . '/Resources/migrations'; + if (file_exists($bundleMigrationDirectory)) { + $finder = new Finder(); + $finder->files('*.php')->in($bundleMigrationDirectory); + foreach ($finder as $file) { + $this->fileSystem->copy($file->getRealpath(), $migrationDirectory . '/' . $file->getFilename(), true); + } + } + } + } +} +","baseDirectory = $baseDirectory; + $this->bundles = $bundles; + $this->fileSystem = new Filesystem(); + } + + /** + * Prepare migration directory to use. + * + * @return void + */ + public function prepare() + { + $migrationDirectory = $this->baseDirectory; + $this->fileSystem->mkdir($migrationDirectory); + + foreach ($this->bundles as $bundle) { + $bundleMigrationDirectory = $bundle->getPath() . '/Resources/migrations'; + if (file_exists($bundleMigrationDirectory)) { + $finder = new Finder(); + $finder->files('*.php')->in($bundleMigrationDirectory); + foreach ($finder as $file) { + $this->fileSystem->copy($file->getRealpath(), $migrationDirectory . '/' . $file->getFilename(), true); + } + } + } + } +} +" +Fix 'call stack size exceeded' error when parsing props with React components as values,"'use_strict'; +import _ from 'lodash'; +import ReactNativePropRegistry from 'react/lib/ReactNativePropRegistry'; +// For compatibility with RN 0.25 +// import ReactNativePropRegistry from ""react-native/Libraries/ReactNative/ReactNativePropRegistry""; +module.exports = function(incomingProps, defaultProps) { + // External props has a higher precedence + var computedProps = {}; + + incomingProps = _.clone(incomingProps); + delete incomingProps.children; + + var incomingPropsStyle = incomingProps.style; + delete incomingProps.style; + + // console.log(defaultProps, incomingProps); + if(incomingProps) { + try { + _.merge(computedProps, defaultProps, incomingProps); + } catch (exception) { + console.log('Warning: Call stack size exceeded when merging props, falling back to shallow merge.'); + _.assign(computedProps, defaultProps, incomingProps); + } + } else + computedProps = defaultProps; + // Pass the merged Style Object instead + if(incomingPropsStyle) { + + var computedPropsStyle = {}; + computedProps.style = {}; + if (Array.isArray(incomingPropsStyle)) { + _.forEach(incomingPropsStyle, (style)=>{ + if(typeof style == 'number') { + _.merge(computedPropsStyle, ReactNativePropRegistry.getByID(style)); + } else { + _.merge(computedPropsStyle, style); + } + }) + + } + else { + if(typeof incomingPropsStyle == 'number') { + computedPropsStyle = ReactNativePropRegistry.getByID(incomingPropsStyle); + } else { + computedPropsStyle = incomingPropsStyle; + } + } + + _.merge(computedProps.style, defaultProps.style, computedPropsStyle); + + + } + // console.log(""computedProps "", computedProps); + return computedProps; +} +","'use_strict'; +import _ from 'lodash'; +import ReactNativePropRegistry from 'react/lib/ReactNativePropRegistry'; +// For compatibility with RN 0.25 +// import ReactNativePropRegistry from ""react-native/Libraries/ReactNative/ReactNativePropRegistry""; +module.exports = function(incomingProps, defaultProps) { + // External props has a higher precedence + var computedProps = {}; + + incomingProps = _.clone(incomingProps); + delete incomingProps.children; + + var incomingPropsStyle = incomingProps.style; + delete incomingProps.style; + + // console.log(defaultProps, incomingProps); + if(incomingProps) + _.merge(computedProps, defaultProps, incomingProps); + else + computedProps = defaultProps; + // Pass the merged Style Object instead + if(incomingPropsStyle) { + + var computedPropsStyle = {}; + computedProps.style = {}; + if (Array.isArray(incomingPropsStyle)) { + _.forEach(incomingPropsStyle, (style)=>{ + if(typeof style == 'number') { + _.merge(computedPropsStyle, ReactNativePropRegistry.getByID(style)); + } else { + _.merge(computedPropsStyle, style); + } + }) + + } + else { + if(typeof incomingPropsStyle == 'number') { + computedPropsStyle = ReactNativePropRegistry.getByID(incomingPropsStyle); + } else { + computedPropsStyle = incomingPropsStyle; + } + } + + _.merge(computedProps.style, defaultProps.style, computedPropsStyle); + + + } + // console.log(""computedProps "", computedProps); + return computedProps; +}" +"Fix for empty errorMessages, moved length check to main logic for deciding which error +message to use and added check for 'errors' in the response.","import json + + +class JIRAError(Exception): + """"""General error raised for all problems in operation of the client."""""" + def __init__(self, status_code=None, text=None, url=None): + self.status_code = status_code + self.text = text + self.url = url + + def __str__(self): + if self.text: + return 'HTTP {0}: ""{1}""\n{2}'.format(self.status_code, self.text, self.url) + else: + return 'HTTP {0}: {1}'.format(self.status_code, self.url) + + +def raise_on_error(r): + if r.status_code >= 400: + error = '' + if r.text: + try: + response = json.loads(r.text) + if 'message' in response: + # JIRA 5.1 errors + error = response['message'] + elif 'errorMessages' in response and len(response['errorMessages']) > 0: + # JIRA 5.0.x error messages sometimes come wrapped in this array + # Sometimes this is present but empty + errorMessages = response['errorMessages'] + if isinstance(errorMessages, (list, tuple)): + error = errorMessages[0] + else: + error = errorMessages + elif 'errors' in response and len(response['errors']) > 0: + # JIRA 6.x error messages are found in this array. + error = response['errors'] + else: + error = r.text + except ValueError: + error = r.text + raise JIRAError(r.status_code, error, r.url) +","import json + + +class JIRAError(Exception): + """"""General error raised for all problems in operation of the client."""""" + def __init__(self, status_code=None, text=None, url=None): + self.status_code = status_code + self.text = text + self.url = url + + def __str__(self): + if self.text: + return 'HTTP {0}: ""{1}""\n{2}'.format(self.status_code, self.text, self.url) + else: + return 'HTTP {0}: {1}'.format(self.status_code, self.url) + + +def raise_on_error(r): + if r.status_code >= 400: + error = '' + if r.text: + try: + response = json.loads(r.text) + if 'message' in response: + # JIRA 5.1 errors + error = response['message'] + elif 'errorMessages' in response: + # JIRA 5.0.x error messages sometimes come wrapped in this array + errorMessages = response['errorMessages'] + if isinstance(errorMessages, (list, tuple)) and len(errorMessages) > 0: + error = errorMessages[0] + else: + error = errorMessages + else: + error = r.text + except ValueError: + error = r.text + raise JIRAError(r.status_code, error, r.url) +" +Fix if with the grunt/package.json if there is a white-space in the ExtensionName,"/*global define,require,window,console,_ */ +/*jslint devel:true, + white: true + */ +define([ + 'jquery', + 'underscore', + './<%= extensionNameSafe.toLowerCase() %>-properties', + './<%= extensionNameSafe.toLowerCase() %>-initialproperties', + 'text!./lib/css/style.css' +], +function ($, _, props, initProps, cssContent) { + 'use strict'; + + $(""