text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Reset another ruby environment variable.
'use strict'; var _ = require('lodash'), path = require('path'); _.extend(exports, { envOverrides: {}, supervisordConfigPath: function() { var config = require('api-umbrella-config').global(); return path.join(config.get('etc_dir'), 'supervisord.conf'); }, env: function() { return _.merge({ 'PATH': [ path.resolve(__dirname, '../bin'), path.resolve(__dirname, '../node_modules/.bin'), '/opt/api-umbrella/embedded/elasticsearch/bin', '/opt/api-umbrella/embedded/sbin', '/opt/api-umbrella/embedded/bin', '/opt/api-umbrella/embedded/jre/bin', '/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', ].join(':'), // Reset Ruby related environment variables. This is in case the system // being installed onto has something like rvm/rbenv/chruby in place. // This ensures that we're using our API Umbrella bundled version of Ruby // on PATH rather than another version. 'GEM_HOME': '', 'GEM_PATH': '', 'GEM_ROOT': '', 'RUBYLIB': '', 'RUBYOPT': '', 'RUBY_ENGINE': '', 'RUBY_ROOT': '', 'RUBY_VERSION': '', }, this.envOverrides); }, overrideEnv: function(overrides) { this.envOverrides = overrides; }, });
'use strict'; var _ = require('lodash'), path = require('path'); _.extend(exports, { envOverrides: {}, supervisordConfigPath: function() { var config = require('api-umbrella-config').global(); return path.join(config.get('etc_dir'), 'supervisord.conf'); }, env: function() { return _.merge({ 'PATH': [ path.resolve(__dirname, '../bin'), path.resolve(__dirname, '../node_modules/.bin'), '/opt/api-umbrella/embedded/elasticsearch/bin', '/opt/api-umbrella/embedded/sbin', '/opt/api-umbrella/embedded/bin', '/opt/api-umbrella/embedded/jre/bin', '/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', ].join(':'), // Reset Ruby related environment variables. This is in case the system // being installed onto has something like rvm/rbenv/chruby in place. // This ensures that we're using our API Umbrella bundled version of Ruby // on PATH rather than another version. 'GEM_HOME': '', 'GEM_PATH': '', 'GEM_ROOT': '', 'RUBYOPT': '', 'RUBY_ENGINE': '', 'RUBY_ROOT': '', 'RUBY_VERSION': '', }, this.envOverrides); }, overrideEnv: function(overrides) { this.envOverrides = overrides; }, });
Add stub methods for map handling
"""This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES (%s)" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin,)) cursor.execute(id_sql) insert_data = cursor.fetchone() mysql.connection.commit() cursor.close() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) @app.route('/maps', methods=['POST']) def upload_new_map(): """Method for uploading new map""" return jsonify({ 'code' : 'dummy' }) @app.route('/maps/<string:map_code>', methods=['GET']) def download_map(map_code): """Method for downloading a map""" return jsonify({ 'code' : map_code, 'data' : 'dummy' })
"""This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" try: cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES (%s)" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin,)) cursor.execute(id_sql) insert_data = cursor.fetchone() mysql.connection.commit() cursor.close() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) except Exception as er_msg: return make_response(jsonify({ 'error' : str(er_msg) }), 500)
Add accessor to unmodifiable copy of scoresMap
package com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers; import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer; import java.util.Collections; import java.util.Map; /** * Created by beng on 17/12/2015. */ public abstract class MapScorer<T> extends Scorer<T> { Map<T, Integer> scoresMap; public Map<T, Integer> getScoresMap() { return Collections.unmodifiableMap(scoresMap); } protected MapScorer(String scoreLabel, Map<T, Integer> scoresMap) { super(scoreLabel); if(scoresMap == null){ throw new NullPointerException( "The scores map can not be null" ); } if(scoresMap.isEmpty()){ throw new IllegalArgumentException( "The scores map cannot be empty" ); } this.scoresMap = scoresMap; } @Override public int score(T input){ validateScoreInput(input); boolean containsKey = scoresMap.containsKey(input); if (containsKey) return scoresMap.get(input); else return 0; } private void validateScoreInput(T input) { if(input == null){ throw new NullPointerException( "Input cannot be null" ); } } }
package com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers; import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer; import java.util.Map; /** * Created by beng on 17/12/2015. */ public abstract class MapScorer<T> extends Scorer<T> { Map<T, Integer> scoresMap; protected MapScorer(String scoreLabel, Map<T, Integer> scoresMap) { super(scoreLabel); if(scoresMap == null){ throw new NullPointerException( "The scores map can not be null" ); } if(scoresMap.isEmpty()){ throw new IllegalArgumentException( "The scores map cannot be empty" ); } this.scoresMap = scoresMap; } @Override public int score(T input){ validateScoreInput(input); boolean containsKey = scoresMap.containsKey(input); if (containsKey) return scoresMap.get(input); else return 0; } private void validateScoreInput(T input) { if(input == null){ throw new NullPointerException( "Input cannot be null" ); } } }
Fix yet another stupid mistake
import re from django.core.exceptions import ValidationError default_validator = lambda x: x != '' # FIXME: Do we need this? def validate_list(value, validator=default_validator, separator=',', strip_whitespace=True, min_length=0, die=False): """Validate a "list" of things separator: the char that separates list items (None means whitespace) allow_whitespace: whether to strip whitespace around separators before validating (unnecessary if separator is None) Returns whether validator returned True for every item in value. Note that this is not terribly useful. """ items = value.split(separator) length = len(items) all_valid = all([validator(x.strip() if strip_whitespace else x) for x in items]) if not all_valid: if die: raise ValidationError("One or more list items are invalid") else: return False elif length < min_length: if die: raise ValidationError("List must contain at least {0} items" .format(length)) else: return False else: return True def is_hex_byte(value): return bool(re.match(r'^[0-9a-fA-F]{2}$', value)) def is_hex_byte_sequence(value): return validate_list(value, is_hex_byte, separator=':', strip_whitespace=False) def strip_and_get_base(value): if value.startswith('0x'): value = value[len('0x'):] base = 16 else: base = 10 return (value, base)
import re from django.core.exceptions import ValidationError default_validator = lambda x: x != '' # FIXME: Do we need this? def validate_list(value, validator=default_validator, separator=',', strip_whitespace=True, min_length=0, die=False): """Validate a "list" of things separator: the char that separates list items (None means whitespace) allow_whitespace: whether to strip whitespace around separators before validating (unnecessary if separator is None) Returns whether validator returned True for every item in value. Note that this is not terribly useful. """ items = value.split(separator) length = len(items) all_valid = all([validator(x.strip() if strip_whitespace else x) for x in items]) if not all_valid: if die: raise ValidationError("One or more list items are invalid") else: return False elif length < min_length: if die: raise ValidationError("List must contain at least {0} items" .format(length)) else: return False else: return True def is_hex_byte(value): return bool(re.match(r'^[0-9a-fA-F]{2}$', value)) def is_hex_byte_sequence(value): return validate_list(value, _hex_byte, separator=':', strip_whitespace=False) def strip_and_get_base(value): if value.startswith('0x'): value = value[len('0x'):] base = 16 else: base = 10 return (value, base)
Change __name__ for label (Django 1.9)
from django.db.models.signals import post_migrate def mk_permissions(permissions, appname, verbosity): """ Make permission at app level - hack with empty ContentType. Adapted code from http://djangosnippets.org/snippets/334/ """ from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType # create a content type for the app ct, created = ContentType.objects.get_or_create(model='', app_label=appname, defaults={'name': appname}) if created and verbosity >= 2: print("Adding custom content type '%s'" % ct) # create permissions for codename, name in permissions: p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ct.id, defaults={'name': name, 'content_type': ct}) if created and verbosity >= 2: print("Adding custom permission '%s'" % p) def handler(sender, **kwargs): from dbsettings.loading import get_app_settings app_label = sender.label are_global_settings = any(not s.class_name for s in get_app_settings(app_label)) if are_global_settings: permission = ( 'can_edit__settings', 'Can edit %s non-model settings' % app_label, ) mk_permissions([permission], app_label, 0) post_migrate.connect(handler)
from django.db.models.signals import post_migrate def mk_permissions(permissions, appname, verbosity): """ Make permission at app level - hack with empty ContentType. Adapted code from http://djangosnippets.org/snippets/334/ """ from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType # create a content type for the app ct, created = ContentType.objects.get_or_create(model='', app_label=appname, defaults={'name': appname}) if created and verbosity >= 2: print("Adding custom content type '%s'" % ct) # create permissions for codename, name in permissions: p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ct.id, defaults={'name': name, 'content_type': ct}) if created and verbosity >= 2: print("Adding custom permission '%s'" % p) def handler(sender, **kwargs): from dbsettings.loading import get_app_settings app_label = sender.__name__.split('.')[-2] are_global_settings = any(not s.class_name for s in get_app_settings(app_label)) if are_global_settings: permission = ( 'can_edit__settings', 'Can edit %s non-model settings' % app_label, ) mk_permissions([permission], app_label, 0) post_migrate.connect(handler)
Add facebook error handler in view. This assumes that there is no other backend which can authenticate user with facebook credentials.
import logging from django.contrib.auth import authenticate from django.contrib.auth import login from django import http from django.views import generic import facepy from facebook_auth import urls logger = logging.getLogger(__name__) class Handler(generic.View): def get(self, request): try: self.next_url = urls.Next().decode(request.GET['next']) except urls.InvalidNextUrl: logger.warning('Invalid facebook handler next.', extra={'request': request}) return http.HttpResponseBadRequest() if 'code' in request.GET: try: self.login() except facepy.FacepyError as e: return self.handle_facebook_error(e) response = http.HttpResponseRedirect(self.next_url['next']) response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi' ' IVDi CONi HIS OUR IND CNT"') else: response = http.HttpResponseRedirect(self.next_url['close']) return response def login(self): user = authenticate( code=self.request.GET['code'], redirect_uri=urls.redirect_uri(self.next_url['next'], self.next_url['close'])) if user: login(self.request, user) def handle_facebook_error(self, e): return http.HttpResponseRedirect(self.next_url['next']) handler = Handler.as_view()
import logging from django.contrib.auth import authenticate from django.contrib.auth import login from django import http from django.views import generic from facebook_auth import urls logger = logging.getLogger(__name__) class Handler(generic.View): def get(self, request): try: next_url = urls.Next().decode(request.GET['next']) except urls.InvalidNextUrl: logger.warning('Invalid facebook handler next.', extra={'request': request}) return http.HttpResponseBadRequest() if 'code' in request.GET: self.login(next_url) response = http.HttpResponseRedirect(next_url['next']) response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi' ' IVDi CONi HIS OUR IND CNT"') else: response = http.HttpResponseRedirect(next_url['close']) return response def login(self, next_url): user = authenticate( code=self.request.GET['code'], redirect_uri=urls.redirect_uri(next_url['next'], next_url['close'])) if user: login(self.request, user) handler = Handler.as_view()
Fix up the manual register URL in the worker and fix the initial log tail.
import os import json import socket import requests from flask import request, jsonify, Response, abort from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POST']) def register_with_master(): register(app.config['HOST'], app.config['PORT']) return jsonify({'message': 'ok'}) def register(host, port): sess = requests.Session() if 'USERNAME' in app.config and 'PASSWORD' in app.config: sess.auth = (app.config['USERNAME'], app.config['PASSWORD']) sess.headers = {'content-type': 'application/json'} try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ 'host': app.config.get('HOSTNAME', socket.getfqdn()), 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e) @app.route('/logs/<path:path>', methods=['GET']) def tail_log(path): path = '/' + path if os.path.exists(path) and path.startswith('/tmp/'): return Response(open(path), content_type='text/plain') abort(404)
import os import json import socket import requests from flask import request, jsonify, Response, abort from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POST']) def register_with_master(): register(app) return jsonify({'message': 'ok'}) def register(host, port): sess = requests.Session() if 'USERNAME' in app.config and 'PASSWORD' in app.config: sess.auth = (app.config['USERNAME'], app.config['PASSWORD']) sess.headers = {'content-type': 'application/json'} try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ 'host': app.config.get('HOSTNAME', socket.getfqdn()), 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e) @app.route('/logs/<path>', methods=['GET']) def tail_log(path): if os.path.exists(path) and path.startswith('/tmp/'): return Response(open(path), content_type='text/plain') abort(404)
Fix minor error with HKID verification
Meteor.methods({ checkHKID: function (hkid) { var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/; // HKID format = 1 or 2 letters followed by 6 numbers and 1 checksum digit. var matchArray = hkid.match(hkidPat); if(matchArray == null){idError()} var checkSum = 0; var charPart = matchArray[1]; var numPart = matchArray[2]; var checkDigit = matchArray[3]; if (charPart.length == 2) { checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55); checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55); } else { checkSum += 8 * (charPart.charCodeAt(0)-55); checkSum += 324; } for (var i = 0, j = 7; i < numPart.length; i++, j--){ checkSum += j * numPart.charAt(i); } var remaining = checkSum % 11; var checkNumber = 11 - remaining; if(checkDigit == checkNumber) {return("valid")} else {idError()} function idError () { throw new Meteor.Error('invalid', 'The HKID entered is invalid') } } });
Meteor.methods({ checkHKID: function (hkid) { var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/; // HKID format = 1 or 2 letters followed by 6 numbers and 1 checksum digit. var matchArray = hkid.match(hkidPat); if(matchArray == null){idError()} var checkSum = 0; var charPart = matchArray[1]; var numPart = matchArray[2]; var checkDigit = matchArray[3]; if (charPart.length == 2) { checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55); checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55); } else { checkSum += 8 * (charPart.charCodeAt(0)-55); checkSum += 324; } for (var i = 0, j = 7; i < numPart.length; i++, j--){ checkSum += j * numPart.charAt(i); } var remaining = checkSum % 11; var checkNumber = 11 - remaining; if(checkDigit == checkNumber) {return("valid")} function idError () { throw new Meteor.Error('invalid', 'The HKID entered is invalid') } } });
Enable console logs in karma tests
var webpackConfig = require('./webpack.config.js'); webpackConfig.devtool = 'inline-source-map'; webpackConfig.module.rules.push({ test: /\.ts$/, enforce: 'post', loader: 'istanbul-instrumenter-loader', exclude: [ 'node_modules', /\.test\.ts$/ ] }); module.exports = function(config) { config.set({ browsers: [ 'PhantomJS' ], files: [ { pattern: 'test/**/*.test.js', watched: false } ], frameworks: ['mocha'], preprocessors: { 'test/**/*.test.js': ['webpack'] }, reporters: ['mocha', 'coverage'], webpack: webpackConfig, webpackMiddleware: { quiet: true, stats: { colors: true } }, coverageReporter: { type : 'json', dir : 'coverage/', subdir: '.', file: 'coverage.json' }, browserConsoleLogOptions: { level: 'log', format: '%b %T: %m', terminal: true } }); };
var webpackConfig = require('./webpack.config.js'); webpackConfig.devtool = 'inline-source-map'; webpackConfig.module.rules.push({ test: /\.ts$/, enforce: 'post', loader: 'istanbul-instrumenter-loader', exclude: [ 'node_modules', /\.test\.ts$/ ] }); module.exports = function(config) { config.set({ browsers: [ 'PhantomJS' ], files: [ { pattern: 'test/**/*.test.js', watched: false } ], frameworks: ['mocha'], preprocessors: { 'test/**/*.test.js': ['webpack'] }, reporters: ['mocha', 'coverage'], webpack: webpackConfig, webpackMiddleware: { quiet: true, stats: { colors: true } }, coverageReporter: { type : 'json', dir : 'coverage/', subdir: '.', file: 'coverage.json' } }); };
Fix - remove Year and Agenda view in General settings
import React from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import { SETTINGS_VIEW } from '../../constants'; const { DAY, WEEK, MONTH, YEAR, PLANNING } = SETTINGS_VIEW; const ViewPreferenceSelector = ({ className = 'pm-field w100', loading = false, disabled = false, view, onChange, ...rest }) => { const options = [ { text: c('Calendar view').t`Day`, value: DAY }, { text: c('Calendar view').t`Week`, value: WEEK }, { text: c('Calendar view').t`Month`, value: MONTH } // not activated for beta //{ text: c('Calendar view').t`Year`, value: YEAR }, //{ text: c('Calendar view').t`Agenda`, value: PLANNING }, ].filter(Boolean); return ( <select disabled={loading || disabled} className={className} title={c('Action').t`Select calendar view`} value={view} onChange={({ target }) => onChange(+target.value)} {...rest} > {options.map(({ text, value }) => { return ( <option key={value} value={value}> {text} </option> ); })} </select> ); }; ViewPreferenceSelector.propTypes = { disabled: PropTypes.bool, loading: PropTypes.bool, className: PropTypes.string, view: PropTypes.oneOf([DAY, WEEK, MONTH, YEAR, PLANNING]), onChange: PropTypes.func }; export default ViewPreferenceSelector;
import React from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import { SETTINGS_VIEW } from '../../constants'; const { DAY, WEEK, MONTH, YEAR, PLANNING } = SETTINGS_VIEW; const ViewPreferenceSelector = ({ className = 'pm-field w100', loading = false, disabled = false, view, onChange, ...rest }) => { const options = [ { text: c('Calendar view').t`Day`, value: DAY }, { text: c('Calendar view').t`Week`, value: WEEK }, { text: c('Calendar view').t`Month`, value: MONTH }, { text: c('Calendar view').t`Year`, value: YEAR }, { text: c('Calendar view').t`Agenda`, value: PLANNING }, ].filter(Boolean); return ( <select disabled={loading || disabled} className={className} title={c('Action').t`Select calendar view`} value={view} onChange={({ target }) => onChange(+target.value)} {...rest} > {options.map(({ text, value }) => { return ( <option key={value} value={value}> {text} </option> ); })} </select> ); }; ViewPreferenceSelector.propTypes = { disabled: PropTypes.bool, loading: PropTypes.bool, className: PropTypes.string, view: PropTypes.oneOf([DAY, WEEK, MONTH, YEAR, PLANNING]), onChange: PropTypes.func }; export default ViewPreferenceSelector;
Fix spacing for linting purposes
'use strict'; const express = require('express'); const router = express.Router(); const bodyParser = require('body-parser'); const request = require('request'); const models = require('../../db/models'); module.exports.getAll = (req, res) => { models.User.where({ email: req.user.email }).fetch() .then((result) => { models.Stats.where({ city: result.attributes.destination }).fetch() .then(data => { if (!data) { request .get(`https://api.teleport.org/api/urban_areas/slug:${result.attributes.destination}/scores/`, (error, response, stats) => { if (error) { console.error(err); } models.Stats.forge({ city: result.attributes.destination, city_stats: stats }) .save() .then(data => { res.status(201).send(data.attributes.city_stats); }) .catch(err => { res.status(500).send(err); }); }) .on('error', (err) => { res.status(500).send(err); }); } else { res.status(200).send(data.attributes.city_stats); } }) .catch(err => { console.log(1, err); res.status(503).send(err); }); }) .catch(err => { console.log(2, err); res.status(503).send(err); }); };
'use strict'; const express = require('express'); const router = express.Router(); const bodyParser = require('body-parser'); const request = require('request'); const models = require('../../db/models'); module.exports.getAll = (req, res) => { models.User.where({ email: req.user.email}).fetch() .then((result) => { models.Stats.where({city: result.attributes.destination}).fetch() .then(data => { if (!data) { request .get(`https://api.teleport.org/api/urban_areas/slug:${result.attributes.destination}/scores/`, (error, response, stats) => { if (error) { console.error(err); } models.Stats.forge({ city: result.attributes.destination, city_stats: stats }) .save() .then(data => { res.status(201).send(data.attributes.city_stats); }) .catch(err => { res.status(500).send(err); }); }) .on('error', (err) => { res.status(500).send(err); }); } else { res.status(200).send(data.attributes.city_stats); } }) .catch(err => { console.log(1, err); res.status(503).send(err); }); }) .catch(err => { console.log(2, err); res.status(503).send(err); }); };
Remove schedule from admin too
from django.contrib import admin from django.forms import model_to_dict from django.utils.timezone import now from main.models import Lan, Event class EventInline(admin.TabularInline): model = Event show_change_link = True fields = ('name', 'url', 'start', 'end') @admin.register(Lan) class LanAdmin(admin.ModelAdmin): list_display = ('name', 'start', 'seats_count', 'is_open') fieldsets = ( ('Tider', { 'fields': (('start', 'end'), 'open', 'show_calendar') }), ('Pladser', { 'fields': ('seats',) }), ('Tekst', { 'fields': ('name', 'blurb') }), ('Betaling', { 'fields': ('paytypes', 'price', 'payphone') }), ('Madbestilling', { 'fields': ('food_open', 'food_phone') }), ) inlines = [ EventInline ] def get_changeform_initial_data(self, request): try: prev_lan = Lan.objects.filter(start__lt=now()).order_by("-start")[0] return model_to_dict(prev_lan, ['blurb', 'seats', 'schedule']) except (Lan.DoesNotExist, AttributeError, IndexError): return {}
from django.contrib import admin from django.forms import model_to_dict from django.utils.timezone import now from main.models import Lan, Event class EventInline(admin.TabularInline): model = Event show_change_link = True fields = ('name', 'url', 'start', 'end') @admin.register(Lan) class LanAdmin(admin.ModelAdmin): list_display = ('name', 'start', 'seats_count', 'is_open') fieldsets = ( ('Tider', { 'fields': (('start', 'end'), 'open', 'show_calendar') }), ('Pladser', { 'fields': ('seats',) }), ('Tekst', { 'fields': ('name', 'schedule', 'blurb') }), ('Betaling', { 'fields': ('paytypes', 'price', 'payphone') }), ('Madbestilling', { 'fields': ('food_open', 'food_phone') }), ) inlines = [ EventInline ] def get_changeform_initial_data(self, request): try: prev_lan = Lan.objects.filter(start__lt=now()).order_by("-start")[0] return model_to_dict(prev_lan, ['blurb', 'seats', 'schedule']) except (Lan.DoesNotExist, AttributeError, IndexError): return {}
Remove last comma if no primary key is set
package me.mrten.mysqlapi.queries; import java.util.ArrayList; import java.util.List; public class CreateTableQuery { private String table; private boolean ifNotExists = false; private List<String> columns = new ArrayList<String>(); private String primaryKey; public CreateTableQuery(String table) { this.table = table; } public CreateTableQuery ifNotExists() { this.ifNotExists = true; return this; } public CreateTableQuery column(String column, String settings) { columns.add(column + " " + settings); return this; } public CreateTableQuery primaryKey(String column) { this.primaryKey = column; return this; } public String build() { StringBuilder builder = new StringBuilder(); builder.append("CREATE TABLE "); if (ifNotExists) { builder.append("IF NOT EXISTS "); } builder.append(table); builder.append(" ("); for (String column : columns) { builder.append(column + ","); } if (columns.size() > 0) { builder.deleteCharAt(builder.length() - 1); } if (primaryKey != null) { builder.append(",PRIMARY KEY("); builder.append(primaryKey); builder.append(")"); } builder.append(")"); return builder.toString(); } }
package me.mrten.mysqlapi.queries; import java.util.ArrayList; import java.util.List; public class CreateTableQuery { private String table; private boolean ifNotExists = false; private List<String> columns = new ArrayList<String>(); private String primaryKey; public CreateTableQuery(String table) { this.table = table; } public CreateTableQuery ifNotExists() { this.ifNotExists = true; return this; } public CreateTableQuery column(String column, String settings) { columns.add(column + " " + settings); return this; } public CreateTableQuery primaryKey(String column) { this.primaryKey = column; return this; } public String build() { StringBuilder builder = new StringBuilder(); builder.append("CREATE TABLE "); if (ifNotExists) { builder.append("IF NOT EXISTS "); } builder.append(table); builder.append(" ("); for (String column : columns) { builder.append(column + ", "); } if (primaryKey != null) { builder.append("PRIMARY KEY("); builder.append(primaryKey); builder.append(")"); } builder.append(")"); return builder.toString(); } }
Make test get correct url
"""Functional tests for the xml api part of aniauth project. This is a temporary app as EVE Online's xml api is deprecated and will be disabled March 2018. """ from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test import tag from django.shortcuts import reverse from selenium import webdriver from selenium.webdriver.common.keys import Keys MAX_WAIT = 10 @tag('functional') class SubmissionTest(StaticLiveServerTestCase): """Tests for users who are submitting xml api key. """ @classmethod def setUpClass(cls): super(SubmissionTest, cls).setUpClass() cls.browser = webdriver.Chrome() cls.browser.maximize_window() cls.browser.implicitly_wait(MAX_WAIT) super(SubmissionTest, cls).setUpClass() @classmethod def tearDownClass(cls): cls.browser.refresh() cls.browser.quit() super(SubmissionTest, cls).tearDownClass() def tearDown(self): self.browser.refresh() def test_user_can_see_apikey_form(self): """A user should be able to see the form for submitting api keys. """ # They browse to the eve api keys page. url = self.live_server_url + reverse('eveapi_add') self.browser.get(url) # They see input boxes for keyID and vCode. keyid_input = self.browser.find_element_by_name('keyID') vcode_input = self.browser.find_element_by_name('vCode')
"""Functional tests for the xml api part of aniauth project. This is a temporary app as EVE Online's xml api is deprecated and will be disabled March 2018. """ from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test import tag from django.shortcuts import reverse from selenium import webdriver from selenium.webdriver.common.keys import Keys MAX_WAIT = 10 @tag('functional') class SubmissionTest(StaticLiveServerTestCase): """Tests for users who are submitting xml api key. """ @classmethod def setUpClass(cls): super(SubmissionTest, cls).setUpClass() cls.browser = webdriver.Chrome() cls.browser.maximize_window() cls.browser.implicitly_wait(MAX_WAIT) super(SubmissionTest, cls).setUpClass() @classmethod def tearDownClass(cls): cls.browser.refresh() cls.browser.quit() super(SubmissionTest, cls).tearDownClass() def tearDown(self): self.browser.refresh() def test_user_can_see_apikey_form(self): """A user should be able to see the form for submitting api keys. """ # They browse to the eve api keys page. url = self.live_server_url + reverse('eveapi_submit') self.browser.get(self.live_server_url) # They see input boxes for keyID and vCode. keyid_input = self.browser.find_element_by_name('keyID') vcode_input = self.browser.find_element_by_name('vCode')
Add missing not-equal comparison for wbtypes Bug: T158848 Change-Id: Ib6e992b7ed1c5b4b8feac205758bdbaebda2b09c
# -*- coding: utf-8 -*- """Wikibase data type classes.""" # # (C) Pywikibot team, 2013-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import json from pywikibot.tools import StringTypes class WbRepresentation(object): """Abstract class for Wikibase representations.""" def __init__(self): """Constructor.""" raise NotImplementedError def toWikibase(self): """Convert representation to JSON for the Wikibase API.""" raise NotImplementedError @classmethod def fromWikibase(cls, json): """Create a representation object based on JSON from Wikibase API.""" raise NotImplementedError def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __repr__(self): assert isinstance(self._items, tuple) assert all(isinstance(item, StringTypes) for item in self._items) values = ((attr, getattr(self, attr)) for attr in self._items) attrs = ', '.join('{0}={1}'.format(attr, value) for attr, value in values) return '{0}({1})'.format(self.__class__.__name__, attrs) def __eq__(self, other): return self.__dict__ == other.__dict__ def __ne__(self, other): return not self.__eq__(other)
# -*- coding: utf-8 -*- """Wikibase data type classes.""" # # (C) Pywikibot team, 2013-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import json from pywikibot.tools import StringTypes class WbRepresentation(object): """Abstract class for Wikibase representations.""" def __init__(self): """Constructor.""" raise NotImplementedError def toWikibase(self): """Convert representation to JSON for the Wikibase API.""" raise NotImplementedError @classmethod def fromWikibase(cls, json): """Create a representation object based on JSON from Wikibase API.""" raise NotImplementedError def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __repr__(self): assert isinstance(self._items, tuple) assert all(isinstance(item, StringTypes) for item in self._items) values = ((attr, getattr(self, attr)) for attr in self._items) attrs = ', '.join('{0}={1}'.format(attr, value) for attr, value in values) return '{0}({1})'.format(self.__class__.__name__, attrs) def __eq__(self, other): return self.__dict__ == other.__dict__
Modify jwt token expiration time
import bcrypt from 'bcrypt'; import jwt from 'jsonwebtoken'; module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { fullName: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, validate: { isEmail: true, } }, role: { type: DataTypes.STRING, allowNull: true, }, password: { type: DataTypes.STRING, allowNull: false, validate: { notEmpty: true } } }); User.prototype.generateHash = (password) => { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; User.prototype.validatePassword = (password, savedPassword) => { return bcrypt.compareSync(password, savedPassword); }; User.prototype.generateJWT = (id, role) => { return jwt.sign({ id, role, }, process.env.JWT_SECRET, { expiresIn: '72h' }); }; User.associate = (models) => { User.hasMany(models.Document, { foreignKey: 'userId', as: 'myDocuments', }); User.belongsTo(models.Role, { foreignKey: 'role', onDelete: 'CASCADE', }); }; return User; };
import bcrypt from 'bcrypt'; import jwt from 'jsonwebtoken'; module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { fullName: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, validate: { isEmail: true, } }, role: { type: DataTypes.STRING, allowNull: true, }, password: { type: DataTypes.STRING, allowNull: false, validate: { notEmpty: true } } }); User.prototype.generateHash = (password) => { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; User.prototype.validatePassword = (password, savedPassword) => { return bcrypt.compareSync(password, savedPassword); }; User.prototype.generateJWT = (id, role) => { return jwt.sign({ id, role, }, process.env.JWT_SECRET, { expiresIn: '24h' }); }; User.associate = (models) => { User.hasMany(models.Document, { foreignKey: 'userId', as: 'myDocuments', }); User.belongsTo(models.Role, { foreignKey: 'role', onDelete: 'CASCADE', }); }; return User; };
Make URLField compatible with Django 1.4 and remove verify_exists attribute
from django import forms from django.utils.translation import ugettext_lazy as _ from tagging.forms import TagField from bookmarks.models import Bookmark, BookmarkInstance class BookmarkInstanceForm(forms.ModelForm): url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40})) description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40})) redirect = forms.BooleanField(label="Redirect", required=False) tags = TagField(label="Tags", required=False) def __init__(self, user=None, *args, **kwargs): self.user = user super(BookmarkInstanceForm, self).__init__(*args, **kwargs) # hack to order fields self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect'] def clean(self): if 'url' not in self.cleaned_data: return if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0: raise forms.ValidationError(_("You have already bookmarked this link.")) return self.cleaned_data def should_redirect(self): if self.cleaned_data["redirect"]: return True else: return False def save(self, commit=True): self.instance.url = self.cleaned_data['url'] return super(BookmarkInstanceForm, self).save(commit) class Meta: model = BookmarkInstance #fields = ('url', 'description', 'note', 'redirect')
from django import forms from django.utils.translation import ugettext_lazy as _ from tagging.forms import TagField from bookmarks.models import Bookmark, BookmarkInstance class BookmarkInstanceForm(forms.ModelForm): url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40})) description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40})) redirect = forms.BooleanField(label="Redirect", required=False) tags = TagField(label="Tags", required=False) def __init__(self, user=None, *args, **kwargs): self.user = user super(BookmarkInstanceForm, self).__init__(*args, **kwargs) # hack to order fields self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect'] def clean(self): if 'url' not in self.cleaned_data: return if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0: raise forms.ValidationError(_("You have already bookmarked this link.")) return self.cleaned_data def should_redirect(self): if self.cleaned_data["redirect"]: return True else: return False def save(self, commit=True): self.instance.url = self.cleaned_data['url'] return super(BookmarkInstanceForm, self).save(commit) class Meta: model = BookmarkInstance #fields = ('url', 'description', 'note', 'redirect')
Add tests to ensure DataPackage uses base schema by default
import pytest import datapackage class TestDataPackage(object): def test_init_uses_base_schema_by_default(self): dp = datapackage.DataPackage() assert dp.schema.title == 'DataPackage' def test_schema(self): descriptor = {} schema = {'foo': 'bar'} dp = datapackage.DataPackage(descriptor, schema=schema) assert dp.schema.to_dict() == schema def test_datapackage_attributes(self): dp = datapackage.DataPackage() dp.foo = 'bar' dp.bar = 'baz' assert dp.attributes == {'foo': 'bar', 'bar': 'baz'} def test_validate(self): descriptor = { 'name': 'foo', } schema = { 'properties': { 'name': {}, }, 'required': ['name'], } dp = datapackage.DataPackage(descriptor, schema) dp.validate() def test_validate_raises_validation_error_if_invalid(self): schema = { 'properties': { 'name': {}, }, 'required': ['name'], } dp = datapackage.DataPackage(schema=schema) with pytest.raises(datapackage.exceptions.ValidationError): dp.validate()
import pytest import datapackage class TestDataPackage(object): def test_schema(self): descriptor = {} schema = {'foo': 'bar'} dp = datapackage.DataPackage(descriptor, schema=schema) assert dp.schema.to_dict() == schema def test_datapackage_attributes(self): dp = datapackage.DataPackage() dp.foo = 'bar' dp.bar = 'baz' assert dp.attributes == {'foo': 'bar', 'bar': 'baz'} def test_validate(self): descriptor = { 'name': 'foo', } schema = { 'properties': { 'name': {}, }, 'required': ['name'], } dp = datapackage.DataPackage(descriptor, schema) dp.validate() def test_validate_raises_validation_error_if_invalid(self): schema = { 'properties': { 'name': {}, }, 'required': ['name'], } dp = datapackage.DataPackage(schema=schema) with pytest.raises(datapackage.exceptions.ValidationError): dp.validate()
Fix non informative exception text Error always throw `Stash\Driver\AbstractDriver is not available` insead of point what dirver not allowed.
<?php /* * This file is part of the Stash package. * * (c) Robert Hafner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Stash\Driver; use Stash\Interfaces\DriverInterface; use Stash\Exception\RuntimeException; /** * Abstract base class for all drivers to use. * * @package Stash * @author Robert Hafner <[email protected]> */ abstract class AbstractDriver implements DriverInterface { /** * Initializes the driver. * * @param array $options * An additional array of options to pass through to setOptions(). * * @throws RuntimeException */ public function __construct(array $options = array()) { if (!static::isAvailable()) { throw new RuntimeException(get_class($this) . ' is not available.'); } $this->setOptions($options); } /** * @return array */ public function getDefaultOptions() { return array(); } /** * {@inheritdoc} */ public function setOptions(array $options = array()) { // empty } /** * {@inheritdoc} */ public static function isAvailable() { return true; } /** * {@inheritdoc} */ public function isPersistent() { return false; } }
<?php /* * This file is part of the Stash package. * * (c) Robert Hafner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Stash\Driver; use Stash\Interfaces\DriverInterface; use Stash\Exception\RuntimeException; /** * Abstract base class for all drivers to use. * * @package Stash * @author Robert Hafner <[email protected]> */ abstract class AbstractDriver implements DriverInterface { /** * Initializes the driver. * * @param array $options * An additional array of options to pass through to setOptions(). * * @throws RuntimeException */ public function __construct(array $options = array()) { if (!static::isAvailable()) { throw new RuntimeException(__CLASS__ . ' is not available.'); } $this->setOptions($options); } /** * @return array */ public function getDefaultOptions() { return array(); } /** * {@inheritdoc} */ public function setOptions(array $options = array()) { // empty } /** * {@inheritdoc} */ public static function isAvailable() { return true; } /** * {@inheritdoc} */ public function isPersistent() { return false; } }
Fix redirect after password change
<?php namespace Mschlueter\Backend\Controllers\Auth; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Mschlueter\Backend\Controllers\Controller; class ChangePasswordController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Show the form for editing the specified resource. * * @return \Illuminate\Http\Response */ public function editAction() { $user = Auth::user(); return view('backend::auth.passwords.edit', compact('user')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function updateAction(Request $request) { $user = Auth::user(); $validation = [ 'old-password' => 'required|old_password', 'new-password' => 'required|confirmed|min:6', ]; $this->validate($request, $validation, trans('backend::validation'), trans('backend::validation.attributes')); $user->password = Hash::make($request->input('new-password')); $user->save(); return redirect() ->route('backend.user.edit', $user) ->with('message', trans('backend::auth.passwords.change.messages.success')); } }
<?php namespace Mschlueter\Backend\Controllers\Auth; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Mschlueter\Backend\Controllers\Controller; class ChangePasswordController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Show the form for editing the specified resource. * * @return \Illuminate\Http\Response */ public function editAction() { $user = Auth::user(); return view('backend::auth.passwords.edit', compact('user')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function updateAction(Request $request) { $user = Auth::user(); $validation = [ 'old-password' => 'required|old_password', 'new-password' => 'required|confirmed|min:6', ]; $this->validate($request, $validation, trans('backend::validation'), trans('backend::validation.attributes')); $user->password = Hash::make($request->input('new-password')); $user->save(); return redirect()->route('backend.user')->with('message', trans('backend::auth.passwords.change.messages.success')); } }
Normalize type before switching on it
package tours.compiler; import tours.grammar.ToursParser; public class Type { public static final Type BOOLEAN = new Type(ToursParser.BOOLEAN); public static final Type CHARACTER = new Type(ToursParser.CHARACTER); public static final Type INTEGER = new Type(ToursParser.INTEGER); public static final Type STRING = new Type(ToursParser.STRING); private final int type; public Type(int type) { this.type = type; } public Type(String type) { type = type.toLowerCase(); switch (type) { case "boolean" : this.type = BOOLEAN.getType(); break; case "character" : this.type = CHARACTER.getType(); break; case "integer" : this.type = INTEGER.getType(); break; case "string" : this.type = STRING.getType(); break; default : throw new UnsupportedOperationException("Type: " + type + " was undefined"); } } public int getType() { return type; } @Override public boolean equals(Object object) { if (object instanceof Type) { return this.getType() == ((Type) object).getType(); } return false; } }
package tours.compiler; import tours.grammar.ToursParser; public class Type { public static final Type BOOLEAN = new Type(ToursParser.BOOLEAN); public static final Type CHARACTER = new Type(ToursParser.CHARACTER); public static final Type INTEGER = new Type(ToursParser.INTEGER); public static final Type STRING = new Type(ToursParser.STRING); private final int type; public Type(int type) { this.type = type; } public Type(String type) { switch (type) { case "boolean" : this.type = BOOLEAN.getType(); break; case "character" : this.type = CHARACTER.getType(); break; case "integer" : this.type = INTEGER.getType(); break; case "string" : this.type = STRING.getType(); break; default : throw new UnsupportedOperationException("Type: " + type + " was undefined"); } } public int getType() { return type; } @Override public boolean equals(Object object) { if (object instanceof Type) { return this.getType() == ((Type) object).getType(); } return false; } }
Set a initial $scope.model.value for true/false
function booleanEditorController($scope, $rootScope, assetsService) { function setupViewModel() { $scope.renderModel = { value: false }; if ($scope.model.config && $scope.model.config.default && $scope.model.config.default.toString() === "1" && $scope.model && !$scope.model.value) { $scope.renderModel.value = true; } if ($scope.model && $scope.model.value && ($scope.model.value.toString() === "1" || angular.lowercase($scope.model.value) === "true")) { $scope.renderModel.value = true; } } setupViewModel(); if( $scope.model && !$scope.model.value ) { $scope.model.value = ($scope.renderModel.value === true) ? '1' : '0'; } //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server setupViewModel(); }; // Update the value when the toggle is clicked $scope.toggle = function(){ if($scope.renderModel.value){ $scope.model.value = "0"; setupViewModel(); return; } $scope.model.value = "1"; setupViewModel(); }; } angular.module("umbraco").controller("Umbraco.PropertyEditors.BooleanController", booleanEditorController);
function booleanEditorController($scope, $rootScope, assetsService) { function setupViewModel() { $scope.renderModel = { value: false }; if ($scope.model.config && $scope.model.config.default && $scope.model.config.default.toString() === "1" && $scope.model && !$scope.model.value) { $scope.renderModel.value = true; } if ($scope.model && $scope.model.value && ($scope.model.value.toString() === "1" || angular.lowercase($scope.model.value) === "true")) { $scope.renderModel.value = true; } } setupViewModel(); //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server setupViewModel(); }; // Update the value when the toggle is clicked $scope.toggle = function(){ if($scope.renderModel.value){ $scope.model.value = "0"; setupViewModel(); return; } $scope.model.value = "1"; setupViewModel(); }; } angular.module("umbraco").controller("Umbraco.PropertyEditors.BooleanController", booleanEditorController);
Fix uncaught error when the click is on the HTML element
// This code is injected into every page (function () { 'use strict'; /*jslint browser: true */ /*global chrome, console */ var parents; // Get the position of a element in the list of its siblings function getElementPosition(element, siblings) { var position = 0, i = 0; for (i = 0; i < siblings.length; i += 1) { if (element === siblings[i]) { position = i; break; } } return position; } // Get the list of parents and position of the clicked element function getParents(clicked) { var el = clicked, parents = [], position = 0; if (!el.parentElement) { return []; } while (el.parentElement.nodeName !== 'HTML') { position = getElementPosition(el, el.parentElement.children); el = el.parentElement; parents.push(position); } return parents; } // Click handler document.onmousedown = function (evt) { parents = getParents(evt.target); }; // Return the list of node positions function getSource() { var message = { method: "returnSource", parents: parents }; return message; } // Add listener to send the data when requested chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request.method === "sendSource") { sendResponse(getSource()); } }); }());
// This code is injected into every page (function () { 'use strict'; /*jslint browser: true */ /*global chrome, console */ var parents; // Get the position of a element in the list of its siblings function getElementPosition(element, siblings) { var position = 0, i = 0; for (i = 0; i < siblings.length; i += 1) { if (element === siblings[i]) { position = i; break; } } return position; } // Get the list of parents and position of the clicked element function getParents(clicked) { var el = clicked, parents = [], position = 0; while (el.parentElement.nodeName !== 'HTML') { position = getElementPosition(el, el.parentElement.children); el = el.parentElement; parents.push(position); } return parents; } // Click handler document.onmousedown = function (evt) { parents = getParents(evt.target); }; // Return the list of node positions function getSource() { var message = { method: "returnSource", parents: parents }; return message; } // Add listener to send the data when requested chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request.method === "sendSource") { sendResponse(getSource()); } }); }());
Remove Meta-class change for AtmosphereUser Fixed in solitary-snipe, so not needed anymore.
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-09-29 19:29 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0064_remove_ssh_keys_toggle'), ] operations = [ migrations.AlterField( model_name='machinerequest', name='new_application_description', field=models.TextField(default=b'Description Missing'), ), migrations.AlterField( model_name='machinerequest', name='new_application_name', field=models.CharField(default='No Name Provided', max_length=256), preserve_default=False, ), migrations.AlterField( model_name='machinerequest', name='new_application_visibility', field=models.CharField(default=b'private', max_length=256), ), migrations.AlterField( model_name='machinerequest', name='new_version_change_log', field=models.TextField(default=b'Changelog Missing'), ), migrations.AlterField( model_name='machinerequest', name='new_version_name', field=models.CharField(default=b'1.0', max_length=256), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-09-29 19:29 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0064_remove_ssh_keys_toggle'), ] operations = [ migrations.AlterModelOptions( name='atmosphereuser', options={'verbose_name': 'user', 'verbose_name_plural': 'users'}, ), migrations.AlterField( model_name='machinerequest', name='new_application_description', field=models.TextField(default=b'Description Missing'), ), migrations.AlterField( model_name='machinerequest', name='new_application_name', field=models.CharField(default='No Name Provided', max_length=256), preserve_default=False, ), migrations.AlterField( model_name='machinerequest', name='new_application_visibility', field=models.CharField(default=b'private', max_length=256), ), migrations.AlterField( model_name='machinerequest', name='new_version_change_log', field=models.TextField(default=b'Changelog Missing'), ), migrations.AlterField( model_name='machinerequest', name='new_version_name', field=models.CharField(default=b'1.0', max_length=256), ), ]
Adjust log prefix in tests for Python 2.4
import unittest import logging from yaml_server.YamlReader import YamlReader from yaml_server.YamlServerException import YamlServerException class Test(unittest.TestCase): data1_data = { 'data1': 'test1', 'data2': [ { 'test3': 'data4', 'test5': 'data5' }, { 'test6': 'data6' } ] } def setUp(self): unittest.TestCase.setUp(self) self.logger = logging.getLogger() self.loghandler = logging.StreamHandler() self.loghandler.setFormatter(logging.Formatter('yaml_server[%(filename)s:%(lineno)d]: %(levelname)s: %(message)s')) self.logger.addHandler(self.loghandler) self.logger.setLevel(logging.DEBUG) def test_should_correctly_merge_yaml_files(self): self.assertEqual(YamlReader("testdata/data1").get(), self.data1_data) def test_should_fail_on_invalid_yaml_dir(self): self.assertRaises(YamlServerException, YamlReader,"/dev/null") if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
import unittest import logging from yaml_server.YamlReader import YamlReader from yaml_server.YamlServerException import YamlServerException class Test(unittest.TestCase): data1_data = { 'data1': 'test1', 'data2': [ { 'test3': 'data4', 'test5': 'data5' }, { 'test6': 'data6' } ] } def setUp(self): unittest.TestCase.setUp(self) self.logger = logging.getLogger() self.loghandler = logging.StreamHandler() self.loghandler.setFormatter(logging.Formatter('yaml_server[%(module)s %(funcName)s]: %(levelname)s: %(message)s')) self.logger.addHandler(self.loghandler) self.logger.setLevel(logging.DEBUG) def test_should_correctly_merge_yaml_files(self): self.assertEqual(YamlReader("testdata/data1").get(), self.data1_data) def test_should_fail_on_invalid_yaml_dir(self): self.assertRaises(YamlServerException, YamlReader,"/dev/null") if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
Put the colon next to the name, moron
/** * Module Name: imgur * Description: Various imgur functionality */ var _ = require('underscore')._, request = require('request'); var imgur = function(dbot) { this.api = { 'getRandomImage': function(callback) { var random = function(len) { var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; return len ? chars.charAt(~~(Math.random()*chars.length)) + random(len-1) : ""; }; var testUrl = 'http://i.imgur.com/' + random(5) + '.png'; var image = request(testUrl, function(error, response, body) { // 492 is body.length of a removed image if(!error && response.statusCode == 200 && body.length != 492) { callback(testUrl); } else { this.api.getRandomImage(callback); } }.bind(this)); } }; this.commands = { '~ri': function(event) { this.api.getRandomImage(function(link) { event.reply(event.user + ': (' + dbot.t('nsfw') + ') ' + link); }); } } }; exports.fetch = function(dbot) { return new imgur(dbot); }
/** * Module Name: imgur * Description: Various imgur functionality */ var _ = require('underscore')._, request = require('request'); var imgur = function(dbot) { this.api = { 'getRandomImage': function(callback) { var random = function(len) { var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; return len ? chars.charAt(~~(Math.random()*chars.length)) + random(len-1) : ""; }; var testUrl = 'http://i.imgur.com/' + random(5) + '.png'; var image = request(testUrl, function(error, response, body) { // 492 is body.length of a removed image if(!error && response.statusCode == 200 && body.length != 492) { callback(testUrl); } else { this.api.getRandomImage(callback); } }.bind(this)); } }; this.commands = { '~ri': function(event) { this.api.getRandomImage(function(link) { event.reply(event.user + ' (' + dbot.t('nsfw') + '): ' + link); }); } } }; exports.fetch = function(dbot) { return new imgur(dbot); }
Set back Fresco logger to verbose
package chat.rocket.android.widget; import android.content.Context; import chat.rocket.android.widget.fresco.CustomImageFormatConfigurator; import com.facebook.common.logging.FLog; import com.facebook.drawee.backends.pipeline.DraweeConfig; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.imagepipeline.listener.RequestLoggingListener; import java.util.HashSet; import java.util.Set; import okhttp3.OkHttpClient; public class RocketChatWidgets { public static void initialize(Context context, OkHttpClient okHttpClient) { FLog.setMinimumLoggingLevel(FLog.VERBOSE); Set<RequestListener> listeners = new HashSet<>(); listeners.add(new RequestLoggingListener()); ImagePipelineConfig imagePipelineConfig = OkHttpImagePipelineConfigFactory .newBuilder(context, okHttpClient) .setRequestListeners(listeners) .setImageDecoderConfig(CustomImageFormatConfigurator.createImageDecoderConfig()) .setDownsampleEnabled(true) .experiment().setBitmapPrepareToDraw(true) .experiment().setPartialImageCachingEnabled(true) .build(); DraweeConfig.Builder draweeConfigBuilder = DraweeConfig.newBuilder(); CustomImageFormatConfigurator.addCustomDrawableFactories(draweeConfigBuilder); Fresco.initialize(context, imagePipelineConfig, draweeConfigBuilder.build()); } }
package chat.rocket.android.widget; import android.content.Context; import chat.rocket.android.widget.fresco.CustomImageFormatConfigurator; import com.facebook.common.logging.FLog; import com.facebook.drawee.backends.pipeline.DraweeConfig; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.imagepipeline.listener.RequestLoggingListener; import java.util.HashSet; import java.util.Set; import okhttp3.OkHttpClient; public class RocketChatWidgets { public static void initialize(Context context, OkHttpClient okHttpClient) { FLog.setMinimumLoggingLevel(FLog.VERBOSE); Set<RequestListener> listeners = new HashSet<>(); listeners.add(new RequestLoggingListener()); ImagePipelineConfig imagePipelineConfig = OkHttpImagePipelineConfigFactory .newBuilder(context, okHttpClient) .setRequestListeners(listeners) .setImageDecoderConfig(CustomImageFormatConfigurator.createImageDecoderConfig()) .setDownsampleEnabled(true) .experiment().setBitmapPrepareToDraw(true) .experiment().setPartialImageCachingEnabled(true) .build(); DraweeConfig.Builder draweeConfigBuilder = DraweeConfig.newBuilder(); CustomImageFormatConfigurator.addCustomDrawableFactories(draweeConfigBuilder); Fresco.initialize(context, imagePipelineConfig, draweeConfigBuilder.build()); FLog.setMinimumLoggingLevel(FLog.ERROR); } }
Use Input instead of request
<?php namespace App\Http\Middleware; use App\User; use Auth; use Closure; use Illuminate\Contracts\Auth\Guard; use Input; class Api { /** * The Guard implementation. * * @var Guard */ protected $auth; /** * Create a new filter instance. * * @param Guard $auth * @return void */ public function __construct(Guard $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!Input::has('key')) { return response()->json(["message" => "Missing API key", 'code' => 401]); } $apikey = Input::get('key'); $user = User::where('apikey', $apikey)->first(); if (!$user) { return response()->json(["message" => "Invalid API key", 'code' => 401]); } if (!$user->enabled) { return response()->json(["message" => "Your account has not been approved by an admin", 'code' => 401]); } if ($user->banned) { return response()->json(["message" => "You are banned", 'code' => 401]); } Auth::onceUsingId($user->id); return $next($request); } }
<?php namespace App\Http\Middleware; use App\User; use Auth; use Closure; use Illuminate\Contracts\Auth\Guard; class Api { /** * The Guard implementation. * * @var Guard */ protected $auth; /** * Create a new filter instance. * * @param Guard $auth * @return void */ public function __construct(Guard $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $apikey = $request->get('key'); if (!$apikey) { return response()->json(["message" => "Missing API key", 'code' => 401]); } $user = User::where('apikey', $apikey)->first(); if (!$user) { return response()->json(["message" => "Invalid API key", 'code' => 401]); } if (!$user->enabled) { return response()->json(["message" => "Your account has not been approved by an admin", 'code' => 401]); } if ($user->banned) { return response()->json(["message" => "You are banned", 'code' => 401]); } Auth::onceUsingId($user->id); return $next($request); } }
Add additional error detail to cover other circumstances that intend to throw 401
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ from rest_framework.views import exception_handler response = exception_handler(exc, context) # Title removed to avoid clash with node "title" errors acceptable_members = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response is not None: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in acceptable_members: errors.append({key: value}) else: errors.append({'detail': {key: value}}) elif isinstance(message, list): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} # Return 401 instead of 403 during unauthorized requests without having user log in with Basic Auth error_message = response.data['errors'][0].get('detail') errors_401 = ["Authentication credentials were not provided.", 'Incorrect authentication credentials.'] if response is not None and error_message in errors_401: response.status_code = 401 return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.')
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ from rest_framework.views import exception_handler response = exception_handler(exc, context) # Title removed to avoid clash with node "title" errors acceptable_members = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response is not None: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in acceptable_members: errors.append({key: value}) else: errors.append({'detail': {key: value}}) elif isinstance(message, list): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} # Return 401 instead of 403 during unauthorized requests without having user log in with Basic Auth if response is not None and response.data['errors'][0].get('detail') == "Authentication credentials were not provided.": response.status_code = 401 return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.')
Include registeredPlayerIds and confirmedPlayerIds fields when creating a new section object.
angular.module('chessRank') .controller('sectionEditDetailsCtrl', function (_, $scope, $state, tournament, section, lookups, sectionEditHelper, baseTypeConverter) { $scope.action = 'Edit'; var converter = new baseTypeConverter(); $scope.section = angular.copy(section); $scope.section.timeControls = angular.toJson($scope.section.timeControls); $scope.section.startDate = converter.bsonDateToJs($scope.section.startDate); $scope.section.endDate = converter.bsonDateToJs($scope.section.endDate); $scope.section.registrationStartDate = converter.bsonDateToJs($scope.section.registrationStartDate); $scope.section.registrationEndDate = converter.bsonDateToJs($scope.section.registrationEndDate); _.each($scope.section.roundData, function (rd) { rd.startTime = converter.bsonDateToJs(rd.startTime); }); var helper = new sectionEditHelper(); helper.attach($scope, tournament, lookups); }) .controller('sectionAddCtrl', function (_, $scope, $state, tournament, lookups, sectionEditHelper) { $scope.action = 'Create'; $scope.section = { tournamentId: tournament._id || tournament.fakeId, fakeId: new Date().getTime(), invitationOnly: false, rounds: 3, roundData: [], registrationManuallyClosed: null, registeredPlayerIds: [], confirmedPlayerIds: [] }; var helper = new sectionEditHelper(); helper.attach($scope, tournament, lookups); });
angular.module('chessRank') .controller('sectionEditDetailsCtrl', function (_, $scope, $state, tournament, section, lookups, sectionEditHelper, baseTypeConverter) { $scope.action = 'Edit'; var converter = new baseTypeConverter(); $scope.section = angular.copy(section); $scope.section.timeControls = angular.toJson($scope.section.timeControls); $scope.section.startDate = converter.bsonDateToJs($scope.section.startDate); $scope.section.endDate = converter.bsonDateToJs($scope.section.endDate); $scope.section.registrationStartDate = converter.bsonDateToJs($scope.section.registrationStartDate); $scope.section.registrationEndDate = converter.bsonDateToJs($scope.section.registrationEndDate); _.each($scope.section.roundData, function (rd) { rd.startTime = converter.bsonDateToJs(rd.startTime); }); var helper = new sectionEditHelper(); helper.attach($scope, tournament, lookups); }) .controller('sectionAddCtrl', function (_, $scope, $state, tournament, lookups, sectionEditHelper) { $scope.action = 'Create'; $scope.section = { tournamentId: tournament._id || tournament.fakeId, fakeId: new Date().getTime(), invitationOnly: false, rounds: 3, roundData: [], registrationManuallyClosed: null }; var helper = new sectionEditHelper(); helper.attach($scope, tournament, lookups); });
Make sure not to set auth header to null
import { router } from '../../main'; import URLS from '../../urls'; export default { user: { authenticated: false }, getProfile: localStorage.getItem('profile'), login(context, creds, redirect) { context.$http.post(URLS.LOGIN_URL, creds).then((data) => { localStorage.setItem('token', data.body.token); localStorage.setItem('profile', JSON.stringify(data.body.profile)); this.user.authenticated = true; if(redirect) { router.go(redirect); } }, (err) => { context.error = err.body.message; }); }, signup(context, creds, redirect) { context.$http.post(URLS.SIGNUP_URL, creds).then((data) => { localStorage.setItem('token', data.body.token); localStorage.setItem('profile', JSON.stringify(data.body.profile)); this.user.authenticated = true; if(redirect) { router.go(redirect); } }, (err) => { context.error = err.body.message; }); }, logout() { localStorage.removeItem('token'); localStorage.removeItem('profile'); this.user.authenticated = false; }, checkAuth() { var jwt = localStorage.getItem('token'); if(jwt) { this.user.authenticated = true; } else { this.user.authenticated = false; } }, getAuthHeader() { return localStorage.getItem('token') || ''; } };
import { router } from '../../main'; import URLS from '../../urls'; export default { user: { authenticated: false }, getProfile: localStorage.getItem('profile'), login(context, creds, redirect) { context.$http.post(URLS.LOGIN_URL, creds).then((data) => { localStorage.setItem('token', data.body.token); localStorage.setItem('profile', JSON.stringify(data.body.profile)); this.user.authenticated = true; if(redirect) { router.go(redirect); } }, (err) => { context.error = err.body.message; }); }, signup(context, creds, redirect) { context.$http.post(URLS.SIGNUP_URL, creds).then((data) => { localStorage.setItem('token', data.body.token); localStorage.setItem('profile', JSON.stringify(data.body.profile)); this.user.authenticated = true; if(redirect) { router.go(redirect); } }, (err) => { context.error = err.body.message; }); }, logout() { localStorage.removeItem('token'); localStorage.removeItem('profile'); this.user.authenticated = false; }, checkAuth() { var jwt = localStorage.getItem('token'); if(jwt) { this.user.authenticated = true; } else { this.user.authenticated = false; } }, getAuthHeader() { return localStorage.getItem('token') } };
Read mail settings from config.
import os import sys import web import yaml from . import default_settings def load_default_config(): # take all vars defined in default_config config = dict((k, v) for k, v in default_settings.__dict__.items() if not k.startswith("_")) web.config.update(config) def load_config_from_env(): keys = [ 'SITE_TITLE', 'GITHUB_CLIENT_ID', 'GITHUB_CLIENT_SECRET', 'SECRET_KEY', 'DATABASE_URL', 'ADMIN_USER', 'MAIL_SERVER', 'MAIL_USERNAME', 'MAIL_PASSWORD', 'MAIL_TLS', 'FROM_ADDRESS', ] for k in keys: if k in os.environ: web.config[k.lower()] = os.environ[k] load_default_config() load_config_from_env() from . import webapp application = webapp.app.wsgifunc() # Heroku doesn't handle static files, use StaticMiddleware. application = web.httpserver.StaticMiddleware(application) def load_config_from_file(configfile): web.config.update(yaml.load(open(configfile))) def main(): if "--config" in sys.argv: index = sys.argv.index("--config") configfile = sys.argv[index+1] sys.argv = sys.argv[:index] + sys.argv[index+2:] load_config_from_file(configfile) webapp.app.run() if __name__ == '__main__': main()
import os import sys import web import yaml from . import default_settings def load_default_config(): # take all vars defined in default_config config = dict((k, v) for k, v in default_settings.__dict__.items() if not k.startswith("_")) web.config.update(config) def load_config_from_env(): keys = [ 'SITE_TITLE', 'GITHUB_CLIENT_ID', 'GITHUB_CLIENT_SECRET', 'SECRET_KEY', 'DATABASE_URL', 'ADMIN_USER', ] for k in keys: if k in os.environ: web.config[k.lower()] = os.environ[k] load_default_config() load_config_from_env() from . import webapp application = webapp.app.wsgifunc() # Heroku doesn't handle static files, use StaticMiddleware. application = web.httpserver.StaticMiddleware(application) def load_config_from_file(configfile): web.config.update(yaml.load(open(configfile))) def main(): if "--config" in sys.argv: index = sys.argv.index("--config") configfile = sys.argv[index+1] sys.argv = sys.argv[:index] + sys.argv[index+2:] load_config_from_file(configfile) webapp.app.run() if __name__ == '__main__': main()
Update compiled JS for password block.
(function() { 'use strict'; var supported; supported = void 0; jQuery.prototype.tamiaPassword = function() { if (supported === void 0) { supported = (((jQuery('<b>')).html('<!--[if lte IE 8]><i></i><![endif]-->')).find('i')).length !== 1; } if (!supported) { return this; } return this.each(function() { var container, field, locked, lockedType, toggle, unlockedClass, unlockedType; container = jQuery(this); unlockedClass = 'is-unlocked'; lockedType = 'password'; unlockedType = 'text'; toggle = container.find('.password__toggle'); field = container.find('.password__field'); locked = !container.hasClass(unlockedClass); container.addClass('is-ok'); return toggle.mousedown(function() { var fieldType, focused; focused = document.activeElement === field[0]; locked = !locked; fieldType = field.attr('type'); container.toggleClass(unlockedClass, !locked); if (fieldType === lockedType && !locked) { field.attr('type', unlockedType); } else if (fieldType === unlockedType && locked) { field.attr('type', lockedType); } if (focused) { return setTimeout((function() { return field.focus(); }), 0); } }); }); }; utils.initComponents({ password: { tamiaPassword: void 0 } }); }).call(this);
// Generated by CoffeeScript 1.6.2 (function() { 'use strict'; var supported; supported = void 0; jQuery.prototype.tamiaPassword = function() { if (supported === void 0) { supported = (((jQuery('<b>')).html('<!--[if lte IE 8]><i></i><![endif]-->')).find('i')).length !== 1; } if (!supported) { return this; } return this.each(function() { var container, field, locked, lockedType, toggle, unlockedClass, unlockedType; container = jQuery(this); unlockedClass = 'is-unlocked'; lockedType = 'password'; unlockedType = 'text'; toggle = container.find('.password__toggle'); field = container.find('.password__field'); locked = !container.hasClass(unlockedClass); container.addClass('is-ok'); return toggle.mousedown(function() { var fieldType, focused; focused = document.activeElement === field[0]; locked = !locked; fieldType = field.attr('type'); if (fieldType === lockedType && !locked) { field.attr('type', unlockedType); } else if (fieldType === unlockedType && locked) { field.attr('type', lockedType); } if (focused) { return setTimeout((function() { return field.focus(); }), 0); } }); }); }; utils.initComponents({ password: { tamiaPassword: void 0 } }); }).call(this);
Make context a defaultdict so unknown values yield empty string
from collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx)
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) return self.template()(context)
Update user table seeder to assign roles
<?php use Illuminate\Database\Seeder; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Passwords\CanResetPassword; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker\Factory::create(); for ($i=0; $i<5; $i++) { $firstName = $faker->firstName; $lastName = $faker->lastName; $newUser = App\User::create( [ 'name_first' => $firstName, 'name_last' => $lastName, "affiliation_id"=> $faker->numberBetween(1,57), "email" => $faker->email, 'password' => 'admin' ] ); $this->command->info("Seeded user {$firstName} {$lastName}"); $role_id = $faker->numberBetween(1, 5); $role = \App\Role::find($role_id); $newUser->attachRole($role); } // Add dev account until we enable registration $newUser = App\User::create( [ 'name_first' => "Developer", 'name_last' => "lastName", "affiliation_id"=> 1, "email" => "[email protected]", 'password' => 'admin' ] ); $role = \App\Role::find(1); $newUser->attachRole($role); } }
<?php use Illuminate\Database\Seeder; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Passwords\CanResetPassword; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker\Factory::create(); for ($i=0; $i<5; $i++) { $firstName = $faker->firstName; $lastName = $faker->lastName; App\User::create( [ 'name_first' => $firstName, 'name_last' => $lastName, "affiliation_id"=> $faker->numberBetween(1,57), "email" => $faker->email, 'password' => 'admin' ] ); $this->command->info("Seeded user {$firstName} {$lastName}"); } // Add dev account until we enable registration App\User::create( [ 'name_first' => "Developer", 'name_last' => "lastName", "affiliation_id"=> 1, "email" => "[email protected]", 'password' => 'admin' ] ); } }
Make unleash record user from gatekeeper header. Signed-off-by: Elliot Murphy <014ce8fab4ab9f8a957bfe9f974379093994de97@users.noreply.github.com>
'use strict'; const fs = require("fs"); const express = require("express"); const unleash = require('unleash-server'); let options = {}; options.adminAuthentication = 'custom'; function gatekeeperAuthentication(app) { app.use('/api/admin/', (req, res, next) => { const email = req.get('X-Auth-Email'); if (email) { // TODO: need to do some verification of credentials here, probably // validate X-Auth-Token signature const user = new unleash.User({ email: `${email}` }); req.user = user; next(); } else { return res .status('401') .end('access denied'); } }); app.use((req, res, next) => { // Updates active sessions every hour req.session.nowInHours = Math.floor(Date.now() / 3600e3); next(); }); }; options.preRouterHook = gatekeeperAuthentication; function serveFrontend(app) { app.use('/', express.static('/frontend')); } options.preHook = serveFrontend; if (process.env.DATABASE_URL_FILE) { options.databaseUrl = fs.readFileSync(process.env.DATABASE_URL_FILE); } unleash .start(options) .then(server => { console.log( `Unleash API started on http://localhost:${server.app.get('port')}` ); });
'use strict'; const fs = require("fs"); const express = require("express"); const unleash = require('unleash-server'); let options = {}; options.adminAuthentication = 'custom'; function gatekeeperAuthentication(app) { app.use('/api/admin/', (req, res, next) => { const email = req.get('X-Auth-Email'); if (email) { // TODO: need to do some verification of credentials here, probably // validate X-Auth-Token signature const user = new unleash.User({ email: `${email}` }); req.user = user; next(); } else { return res .status('401') .end('access denied'); } }); app.use((req, res, next) => { // Updates active sessions every hour req.session.nowInHours = Math.floor(Date.now() / 3600e3); next(); }); }; options.preRouterHook = gatekeeperAuthentication; function serveFrontend(app) { app.use('/', express.static('/frontend')); } options.preHook = serveFrontend; if (process.env.DATABASE_URL_FILE) { options.databaseUrl = fs.readFileSync(process.env.DATABASE_URL_FILE); } unleash .start(options) .then(server => { console.log( `Unleash API started on http://localhost:${server.app.get('port')}` ); });
Add minified and non-minified umd build
const path = require('path'); const webpack = require('webpack'); const BabiliPlugin = require('babili-webpack-plugin'); const isProd = process.env.NODE_ENV === 'PRODUCTION'; const outputFilename = isProd ? 'react-layout-transition.min.js' : 'react-layout-transition.js'; module.exports = { devtool: !isProd ? 'source-map' : '', entry: path.resolve(__dirname, 'src/index.ts'), output: { path: path.resolve(__dirname, 'dist'), filename: outputFilename, library: 'ReactLayoutTransition', libraryTarget: 'umd', }, externals: { 'react': { commonjs: 'react', commonjs2: 'react', root: 'React', }, }, module: { rules: [ { test: /\.tsx|ts?$/, loader: 'awesome-typescript-loader', exclude: path.resolve(__dirname, 'node_modules'), }, ], }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], }, plugins: isProd ? [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), }), new BabiliPlugin({}, { removeComments: true, }), ] : [], };
const path = require('path'); const webpack = require('webpack'); const BabiliPlugin = require('babili-webpack-plugin'); module.exports = { entry: path.resolve(__dirname, 'src/index.ts'), output: { path: path.resolve(__dirname, 'dist'), filename: 'react-layout-transition.js', library: 'ReactLayoutTransition', libraryTarget: 'umd', }, externals: { 'react': { commonjs: 'react', commonjs2: 'react', root: 'React', }, }, module: { rules: [ { test: /\.tsx|ts?$/, loader: 'awesome-typescript-loader', exclude: path.resolve(__dirname, 'node_modules'), }, ], }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), }), new BabiliPlugin({}, { removeComments: true, }), ], };
Tweak the code to avoid fabbot false positives
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Intl\Data\Bundle\Reader; use Symfony\Component\Intl\Exception\ResourceBundleNotFoundException; use Symfony\Component\Intl\Exception\RuntimeException; /** * Reads .json resource bundles. * * @author Bernhard Schussek <[email protected]> * * @internal */ class JsonBundleReader implements BundleReaderInterface { /** * {@inheritdoc} */ public function read($path, $locale) { $fileName = $path.'/'.$locale.'.json'; // prevent directory traversal attacks if (\dirname($fileName) !== $path) { throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName)); } if (!file_exists($fileName)) { throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName)); } if (!is_file($fileName)) { throw new RuntimeException(sprintf('The resource bundle "%s" is not a file.', $fileName)); } $data = json_decode(file_get_contents($fileName), true); if (null === $data) { throw new RuntimeException(sprintf('The resource bundle "%s" contains invalid JSON: '.json_last_error_msg(), $fileName)); } return $data; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Intl\Data\Bundle\Reader; use Symfony\Component\Intl\Exception\ResourceBundleNotFoundException; use Symfony\Component\Intl\Exception\RuntimeException; /** * Reads .json resource bundles. * * @author Bernhard Schussek <[email protected]> * * @internal */ class JsonBundleReader implements BundleReaderInterface { /** * {@inheritdoc} */ public function read($path, $locale) { $fileName = $path.'/'.$locale.'.json'; // prevent directory traversal attacks if (\dirname($fileName) !== $path) { throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName)); } if (!file_exists($fileName)) { throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName)); } if (!is_file($fileName)) { throw new RuntimeException(sprintf('The resource bundle "%s" is not a file.', $fileName)); } $data = json_decode(file_get_contents($fileName), true); if (null === $data) { throw new RuntimeException(sprintf('The resource bundle "%s" contains invalid JSON: %s.', $fileName, json_last_error_msg())); } return $data; } }
Fix a bug when you try to add a geo tag to an object that does not have already one
from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from geotagging.models import Point def add_edit_point(request, content_type_id, object_id, template=None, form_class=None): model_class = ContentType.objects.get(id=content_type_id).model_class() object = model_class.objects.get(id=object_id) object_content_type = ContentType.objects.get_for_model(object) try: geotag = Point.objects.get(content_type__pk=object_content_type.id, object_id=object.id) except ObjectDoesNotExist: geotag = None if request.method == "POST": form = form_class(request.POST, instance=geotag) if form.is_valid(): new_object = form.save(commit=False) new_object.object = object new_object.save() return HttpResponseRedirect("/admin/%s/%s/%s/" %(object_content_type.app_label, object_content_type.model, object.id)) form = form_class(instance=geotag) #import ipdb; ipdb.set_trace() context = RequestContext(request, { 'form': form, 'object' : object, 'object_content_type' : object_content_type, 'geotag' : geotag, }) return render_to_response(template, context_instance=context )
from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.contenttypes.models import ContentType from geotagging.models import Point def add_edit_point(request, content_type_id, object_id, template=None, form_class=None): model_class = ContentType.objects.get(id=content_type_id).model_class() object = model_class.objects.get(id=object_id) object_content_type = ContentType.objects.get_for_model(object) geotag = Point.objects.get(content_type__pk=object_content_type.id, object_id=object.id) if request.method == "POST": form = form_class(request.POST, instance=geotag) if form.is_valid(): new_object = form.save(commit=False) new_object.object = object new_object.save() return HttpResponseRedirect("/admin/%s/%s/%s/" %(object_content_type.app_label, object_content_type.model, object.id)) form = form_class(instance=geotag) #import ipdb; ipdb.set_trace() context = RequestContext(request, { 'form': form, 'object' : object, 'object_content_type' : object_content_type, 'geotag' : geotag, }) return render_to_response(template, context_instance=context )
Remove flex helper from fromt page callouts
<?php $i = 0; $callouts = get_field("callouts"); ?> <?php if ($callouts): ?> <?php while (have_rows("callouts")): ?> <?php the_row(); ?> <?php $title = get_sub_field("title"); $content = get_sub_field("content"); ?> <?php if ($title || $content): ?> <?php $i++; ?> <?php if ($i === 1 || ($i - 1) % 3 === 0): ?> <div class="row -padded"> <?php endif; ?> <div class="col-tablet-6of12 col-notebook-4of12 col-desktop-4of12 -grow"> <div class="widget"> <?php if ($title): ?> <h6 class="widget_title title"><?php echo $title; ?></h6> <?php endif; ?> <?php if ($content): ?> <div class="widget_content user-content"><?php echo $content; ?></div> <?php endif;?> </div><!--/.widget--> </div><!--/.col-tablet-4of12._flex--> <?php if ($i === count($callouts) || $i % 3 === 0): ?> </div><!--/.row.-padded--> <?php endif;?> <?php endif; // if ($titile || $content) ?> <?php endwhile; // while (have_rows("callouts")) ?> <?php endif; // if ($callouts) ?>
<?php $i = 0; $callouts = get_field("callouts"); ?> <?php if ($callouts): ?> <?php while (have_rows("callouts")): ?> <?php the_row(); ?> <?php $title = get_sub_field("title"); $content = get_sub_field("content"); ?> <?php if ($title || $content): ?> <?php $i++; ?> <?php if ($i === 1 || ($i - 1) % 3 === 0): ?> <div class="row -padded"> <?php endif; ?> <div class="col-tablet-6of12 col-notebook-4of12 col-desktop-4of12 -grow _flex"> <div class="widget" style="min-height:100%;"> <?php if ($title): ?> <h6 class="widget_title title"><?php echo $title; ?></h6> <?php endif; ?> <?php if ($content): ?> <div class="widget_content user-content"><?php echo $content; ?></div> <?php endif;?> </div><!--/.widget--> </div><!--/.col-tablet-4of12._flex--> <?php if ($i === count($callouts) || $i % 3 === 0): ?> </div><!--/.row.-padded--> <?php endif;?> <?php endif; // if ($titile || $content) ?> <?php endwhile; // while (have_rows("callouts")) ?> <?php endif; // if ($callouts) ?>
Add function for get all files. Deleted anonymous function.
<?php //---------------------------------------------------------------------------------------------------------------------- /** * Unit Tests for testing optimize_css Task. */ class OptimizeCssTest extends PHPUnit_Framework_TestCase { //-------------------------------------------------------------------------------------------------------------------- /** * Get all files from directory and subdirectories. * * @param $theFolder string Expected or build folder * * @return array */ private function getFilesById($theFolder) { $rootpath = getcwd().'/'.$theFolder; $array = []; $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootpath)); foreach ($files as $fullpath => $file) { if ($file->isFile()) { $content = file_get_contents($fullpath); if ($content===false) print_r("\nUnable to read file '%s'.\n", $fullpath); if (preg_match('/(\/\*\s?)(ID:\s?)([^\s].+)(\s?\*\/)/', $content, $match)) { $array[$match[3]] = $fullpath; } } } return $array; } //-------------------------------------------------------------------------------------------------------------------- /** * Optimizing all files inside folder test01 and then compare files. */ public function testOptimizeCss() { chdir(__DIR__."/test01"); exec('../../bin/phing optimize_css'); $build = $this->getFilesById('build'); $expected = $this->getFilesById('expected'); foreach ($expected as $key => $b) { if (isset($build[$key]) && isset($expected[$key])) { $this->assertFileEquals($expected[$key], $build[$key]); } } } //-------------------------------------------------------------------------------------------------------------------- } //----------------------------------------------------------------------------------------------------------------------
<?php //---------------------------------------------------------------------------------------------------------------------- /** * Unit Tests for testing optimize_css Task. */ class OptimizeCssTest extends PHPUnit_Framework_TestCase { //-------------------------------------------------------------------------------------------------------------------- /** * Optimizing all files inside folder test01 and then compare files. */ public function testOptimizeCss() { chdir(__DIR__."/test01"); exec('../../bin/phing optimize_css'); $get_array = function ($folder) { $rootpath = getcwd().'/'.$folder; $array = []; $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootpath)); foreach ($files as $fullpath => $file) { if ($file->isFile()) { if (preg_match('/(\/\*\s?)(ID:\s?)([^\s].+)(\s?\*\/)/', file_get_contents($fullpath), $match)) { $array[$match[3]] = $fullpath; } } } return $array; }; $build = $get_array('build'); $expected = $get_array('expected'); foreach ($expected as $key => $b) { if (isset($build[$key]) && isset($expected[$key])) { $this->assertFileEquals($expected[$key], $build[$key]); } } } //-------------------------------------------------------------------------------------------------------------------- } //----------------------------------------------------------------------------------------------------------------------
Add ability to publish rc versions
var vow = require('vow'), vowNode = require('vow-node'), childProcess = require('child_process'), fs = require('fs'), exec = vowNode.promisify(childProcess.exec), readFile = vowNode.promisify(fs.readFile), writeFile = vowNode.promisify(fs.writeFile); version = process.argv.slice(2)[0] || 'patch'; exec('git pull') .then(() => exec('npm i')) .then(() => exec('npm run build')) .then(() => exec(`npm version ${version}`)) .then(() => vow.all([ readFile('package.json', 'utf8'), readFile(__dirname + '/distHeaderTmpl.txt', 'utf8'), readFile('dist/vidom.js'), readFile('dist/vidom.min.js') ])) .spread((packageContent, distHeaderTmpl, distContent, distMinContent) => { version = JSON.parse(packageContent).version; var distHeader = distHeaderTmpl.replace('${VERSION}', version); return vow.all([ writeFile('dist/vidom.js', distHeader + distContent), writeFile('dist/vidom.min.js', distHeader + distMinContent) ]); }) .then(() => exec('git push --follow-tags')) .then(() => exec('npm publish' + (version.includes('rc')? ' --tag next' : ''))) .then(() => { console.log(`version ${version} has just been released`); }) .done();
var vow = require('vow'), vowNode = require('vow-node'), childProcess = require('child_process'), fs = require('fs'), exec = vowNode.promisify(childProcess.exec), readFile = vowNode.promisify(fs.readFile), writeFile = vowNode.promisify(fs.writeFile); version = process.argv.slice(2)[0] || 'patch'; exec('git pull') .then(() => exec('npm i')) .then(() => exec('npm run build')) .then(() => exec('npm version ' + version)) .then(() => vow.all([ readFile('package.json', 'utf8'), readFile(__dirname + '/distHeaderTmpl.txt', 'utf8'), readFile('dist/vidom.js'), readFile('dist/vidom.min.js') ])) .spread((packageContent, distHeaderTmpl, distContent, distMinContent) => { version = JSON.parse(packageContent).version; var distHeader = distHeaderTmpl.replace('${VERSION}', version); return vow.all([ writeFile('dist/vidom.js', distHeader + distContent), writeFile('dist/vidom.min.js', distHeader + distMinContent) ]); }) .then(() => exec('git push --follow-tags')) .then(() => exec('npm publish')) .then(() => { console.log(`version ${version} has just been released`); }) .done();
Make function return false or true.
""" This file is part of Lisa. Lisa is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lisa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Lisa. If not, see <http://www.gnu.org/licenses/>. """ class MessageHandler: """ A general class to handle messages """ def __init__(self): """ Init of MessageHandler class """ def confirmation(self, stract): """ Show confirmation dialog """ answer = \ raw_input( 'Are you sure you want to %s? [y|n] ' % stract \ ).strip().lower() if answer != 'y': print('Aborted.') return False elif answer == 'y': return True def print_action(self, stract, dictstr): """ Print message about straction for each item in the lstObj list """ for s in dictstr.keys(): print('{0} {1}.'.format(stract, s)) class ErrorHandler(MessageHandler): """ A class to handle error messages, it inherits from MessageHandler """ def __init__(self): """ Init of ErrorHandler class """ print('ErrorHandling loaded...')
""" This file is part of Lisa. Lisa is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lisa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Lisa. If not, see <http://www.gnu.org/licenses/>. """ class MessageHandler: """ A general class to handle messages """ def __init__(self): """ Init of MessageHandler class """ def confirmation(self, stract): """ Show confirmation dialog """ answer = \ raw_input( 'Are you sure you want to %s? [y|n] ' % stract \ ).strip().lower() if answer != 'y': print('Aborted.') return -1 elif answer == 'y': return 0 def print_action(self, stract, dictstr): """ Print message about straction for each item in the lstObj list """ for s in dictstr.keys(): print('{0} {1}.'.format(stract, s)) class ErrorHandler(MessageHandler): """ A class to handle error messages, it inherits from MessageHandler """ def __init__(self): """ Init of ErrorHandler class """ print('ErrorHandling loaded...')
Add failsafe mongo calls [ci skip]
from datetime import datetime import logging from motor.motor_asyncio import AsyncIOMotorClient from pymongo.errors import AutoReconnect log = logging.getLogger(__name__) class MongoBackend(object): def __init__(self, name): self.name = name self.host = None self._collection = None async def init(self, host, ttl=60): self.host = host # Get collection for this nyuki client = AsyncIOMotorClient(host) db = client['bus_persistence'] self._collection = db[self.name] # Set a TTL to the documents in this collection try: await self._collection.create_index( 'created_at', expireAfterSeconds=ttl*60 ) except AutoReconnect: log.error("Could not reach mongo at address '%s'", self.host) async def store(self, topic, message): try: await self._collection.insert({ 'created_at': datetime.utcnow(), 'topic': str(topic), 'message': message }) except AutoReconnect: log.error("Could not reach mongo at address '%s'", self.host) async def retrieve(self, since=None): if since: cursor = self._collection.find({'created_at': {'$gte': since}}) else: cursor = self._collection.find() cursor.sort('created_at') try: return await cursor.to_list(None) except AutoReconnect: log.error("Could not reach mongo at address '%s'", self.host)
from datetime import datetime import logging from motor.motor_asyncio import AsyncIOMotorClient from pymongo.errors import AutoReconnect log = logging.getLogger(__name__) class MongoBackend(object): def __init__(self, name): self.name = name self.host = None self._collection = None async def init(self, host, ttl=60): self.host = host # Get collection for this nyuki client = AsyncIOMotorClient(host) db = client['bus_persistence'] self._collection = db[self.name] # Set a TTL to the documents in this collection try: await self._collection.create_index( 'created_at', expireAfterSeconds=ttl*60 ) except AutoReconnect: log.error("Could not reach mongo at address '%s'", self.host) async def store(self, topic, message): await self._collection.insert({ 'created_at': datetime.utcnow(), 'topic': str(topic), 'message': message }) async def retrieve(self, since=None): if since: cursor = self._collection.find({'created_at': {'$gte': since}}) else: cursor = self._collection.find() cursor.sort('created_at') return await cursor.to_list(None)
Refactor Random Color as Flag Method
import random class Flag: def __init__(self, **kwargs): self.mode = kwargs.get('mode', self.random_mode()) self.bg = kwargs.get('bg', self.random_color()) if self.mode == 'plain': pass elif self.mode == 'quarters': self.quarterpanels = kwargs.get('quarterpanels', None) if self.quarterpanels == None: self.quarterpanels = [Flag() for i in range(4)] elif self.mode == 'canton': self.canton = kwargs.get('canton', None) if not self.canton: self.canton = Flag() elif self.mode == 'cross': self.cross = kwargs.get('cross', self.random_color()) else: raise ValueError('invalid mode') def random_color(self): colors = ['white', 'black', '#cc0033', #red '#ffcc00', #yellow '#009933', #green '#003399', #blue ] return random.choice(colors) def random_mode(self): modes = [(5, 'plain'), (1, 'quarters'), (1, 'canton'), (5, 'cross')] total = sum([i[0] for i in modes]) choice = random.randint(1, total) for weight, mode in modes: if choice <= weight: return mode else: choice -= weight
import random def random_color(): colors = ['white', 'black', '#cc0033', #red '#ffcc00', #yellow '#009933', #green '#003399', #blue ] return random.choice(colors) class Flag: def __init__(self, **kwargs): self.mode = kwargs.get('mode', self.random_mode()) self.bg = kwargs.get('bg', random_color()) if self.mode == 'plain': pass elif self.mode == 'quarters': self.quarterpanels = kwargs.get('quarterpanels', None) if self.quarterpanels == None: self.quarterpanels = [Flag() for i in range(4)] elif self.mode == 'canton': self.canton = kwargs.get('canton', None) if not self.canton: self.canton = Flag() elif self.mode == 'cross': self.cross = kwargs.get('cross', random_color()) else: raise ValueError('invalid mode') def random_mode(self): modes = [(5, 'plain'), (1, 'quarters'), (1, 'canton'), (5, 'cross')] total = sum([i[0] for i in modes]) choice = random.randint(1, total) for weight, mode in modes: if choice <= weight: return mode else: choice -= weight
Remove unused call for classes
<?php namespace Grav\Plugin; use \Grav\Common\Plugin; class PreCachePlugin extends Plugin { /** @var Config $config */ protected $config; /** * @return array */ public static function getSubscribedEvents() { return [ 'onPluginsInitialized' => ['onPluginsInitialized', 0] ]; } /** * Initialize configuration */ public function onPluginsInitialized() { $config = $this->grav['config']->get('plugins.precache'); if (!$config['enabled_admin'] || $this->isAdmin()) { $this->active = false; return; } $this->enable([ 'onShutdown' => ['onShutdown', 0] ]); } public function onShutdown() { /** @var Cache $cache */ $cache = $this->grav['cache']; $cache_id = md5('preacache'.$cache->getKey()); $precached = $cache->fetch($cache_id); if (!$precached) { /** @var Pages $pages */ $pages = $this->grav['pages']; $routes = $pages->routes(); foreach ($routes as $route => $path) { try { $page = $pages->get($path); // call the content to load/cache it $page->content(); } catch (\Exception $e) { // do nothing on error } } $cache->save($cache_id, true); } } }
<?php namespace Grav\Plugin; use \Grav\Common\Plugin; use \Grav\Common\Grav; use \Grav\Common\Cache; use \Grav\Common\Config\Config; use \Grav\Common\Page\Page; use \Grav\Common\Page\Pages; class PreCachePlugin extends Plugin { /** @var Config $config */ protected $config; /** * @return array */ public static function getSubscribedEvents() { return [ 'onPluginsInitialized' => ['onPluginsInitialized', 0] ]; } /** * Initialize configuration */ public function onPluginsInitialized() { $config = $this->grav['config']->get('plugins.precache'); if (!$config['enabled_admin'] || $this->isAdmin()) { $this->active = false; return; } $this->enable([ 'onShutdown' => ['onShutdown', 0] ]); } public function onShutdown() { /** @var Cache $cache */ $cache = $this->grav['cache']; $cache_id = md5('preacache'.$cache->getKey()); $precached = $cache->fetch($cache_id); if (!$precached) { /** @var Pages $pages */ $pages = $this->grav['pages']; $routes = $pages->routes(); foreach ($routes as $route => $path) { try { $page = $pages->get($path); // call the content to load/cache it $page->content(); } catch (\Exception $e) { // do nothing on error } } $cache->save($cache_id, true); } } }
Add "all" to the queryset in DepartmentForm
from django import forms from .models import Department, Province, District class DepartmentForm(forms.Form): department = forms.ModelChoiceField( queryset=Department.objects.all() ) class ProvinceForm(DepartmentForm): province = forms.ModelChoiceField( queryset=Province.objects.none() ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_bound: department = self._get_field_value('department') if department: self.fields['province'].queryset = Province.objects.filter( parent=department ) def _get_field_value(self, name): field = self.fields[name] value = field.widget.value_from_datadict( self.data, self.files, self.add_prefix(name) ) try: return field.clean(value) except: return None class DistrictForm(ProvinceForm): district = forms.ModelChoiceField( queryset=District.objects.none() ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_bound: province = self._get_field_value('province') if province: self.fields['district'].queryset = District.objects.filter( parent=province ) UbigeoForm = DistrictForm
from django import forms from .models import Department, Province, District class DepartmentForm(forms.Form): department = forms.ModelChoiceField( queryset=Department.objects ) class ProvinceForm(DepartmentForm): province = forms.ModelChoiceField( queryset=Province.objects.none() ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_bound: department = self._get_field_value('department') if department: self.fields['province'].queryset = Province.objects.filter( parent=department ) def _get_field_value(self, name): field = self.fields[name] value = field.widget.value_from_datadict( self.data, self.files, self.add_prefix(name) ) try: return field.clean(value) except: return None class DistrictForm(ProvinceForm): district = forms.ModelChoiceField( queryset=District.objects.none() ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_bound: province = self._get_field_value('province') if province: self.fields['district'].queryset = District.objects.filter( parent=province ) UbigeoForm = DistrictForm
Fix test_writable_stream failing in Python 3.3 and 3.4
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import io import os import unittest import tempfile try: from unittest import mock except ImportError: import mock from fs.archive import _utils class TestUtils(unittest.TestCase): @unittest.skipUnless(os.name == 'posix', 'POSIX platform needed') def test_writable_path(self): self.assertFalse(_utils.writable_path('/')) self.assertFalse(_utils.writable_path('/root_location')) self.assertTrue(_utils.writable_path(__file__)) def test_writable_stream(self): with tempfile.NamedTemporaryFile(mode='wb+') as tmp: self.assertTrue(_utils.writable_stream(tmp)) with open(tmp.name, 'rb') as tmp2: self.assertFalse(_utils.writable_stream(tmp2)) buff = io.BytesIO() self.assertTrue(_utils.writable_stream(buff)) buff = io.BufferedReader(buff) self.assertFalse(_utils.writable_stream(buff)) buff = mock.MagicMock() buff.write = mock.MagicMock(side_effect=IOError("not writable")) self.assertFalse(_utils.writable_stream(buff)) def test_import_from_names(self): imp = _utils.import_from_names self.assertIs(imp('os'), os) self.assertIs(imp('akjhkjhsk', 'os'), os) self.assertIs(imp('akeskjhk'), None)
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import io import os import unittest import tempfile try: from unittest import mock except ImportError: import mock from fs.archive import _utils class TestUtils(unittest.TestCase): @unittest.skipUnless(os.name == 'posix', 'POSIX platform needed') def test_writable_path(self): self.assertFalse(_utils.writable_path('/')) self.assertFalse(_utils.writable_path('/root_location')) self.assertTrue(_utils.writable_path(__file__)) def test_writable_stream(self): with tempfile.NamedTemporaryFile() as tmp: self.assertTrue(_utils.writable_stream(tmp)) with open(tmp.name) as tmp2: self.assertFalse(_utils.writable_stream(tmp2)) buff = io.BytesIO() self.assertTrue(_utils.writable_stream(buff)) buff = io.BufferedReader(buff) self.assertFalse(_utils.writable_stream(buff)) buff = mock.MagicMock() buff.write = mock.MagicMock(side_effect=IOError("not writable")) self.assertFalse(_utils.writable_stream(buff)) def test_import_from_names(self): imp = _utils.import_from_names self.assertIs(imp('os'), os) self.assertIs(imp('akjhkjhsk', 'os'), os) self.assertIs(imp('akeskjhk'), None)
Add option for a cc in email
<?php namespace SynchWeb; class Email { private $vars = array(); private $html = true; function __construct($template, $subject) { $this->template = $template.'.html'; $this->subject = $subject; } public function __get($name) { return $this->vars[$name]; } public function __set($name, $value) { $this->vars[$name] = $value; } public function send($recepients, $cc) { global $email_from; ob_start(); $path = dirname(__FILE__).'/../assets/emails/'.($this->html ? 'html/' : ''); if (file_exists($path.$this->template)) { extract($this->vars); if ($this->html) include($path.'email-header.html'); include($path.$this->template); if ($this->html) include($path.'email-footer.html'); } $content = ob_get_contents(); ob_end_clean(); $headers = "From: ".$email_from."\r\n"; $headers .= "Reply-To: ".$email_from."\r\n"; if ($this->html) { $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; } if ($cc) $headers .= "Cc: " . $cc; $result = mail($recepients, $this->subject, $content, $headers); return $result; } }
<?php namespace SynchWeb; class Email { private $vars = array(); private $html = true; function __construct($template, $subject) { $this->template = $template.'.html'; $this->subject = $subject; } public function __get($name) { return $this->vars[$name]; } public function __set($name, $value) { $this->vars[$name] = $value; } public function send($recepients) { global $email_from; ob_start(); $path = dirname(__FILE__).'/../assets/emails/'.($this->html ? 'html/' : ''); if (file_exists($path.$this->template)) { extract($this->vars); if ($this->html) include($path.'email-header.html'); include($path.$this->template); if ($this->html) include($path.'email-footer.html'); } $content = ob_get_contents(); ob_end_clean(); $headers = "From: ".$email_from."\r\n"; $headers .= "Reply-To: ".$email_from."\r\n"; if ($this->html) { $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; } mail($recepients, $this->subject, $content, $headers); } }
Add failing spec for package deserialization
/** @babel */ describe('About', () => { let workspaceElement beforeEach(() => { workspaceElement = atom.views.getView(atom.workspace) waitsForPromise(() => { return atom.packages.activatePackage('about') }) }) it('deserializes correctly', () => { let deserializedAboutView = atom.deserializers.deserialize({ deserializer: 'AboutView', uri: 'atom://about' }) expect(deserializedAboutView).toBeTruthy() }) describe('when the about:about-atom command is triggered', () => { it('shows the About Atom view', () => { // Attaching the workspaceElement to the DOM is required to allow the // `toBeVisible()` matchers to work. Anything testing visibility or focus // requires that the workspaceElement is on the DOM. Tests that attach the // workspaceElement to the DOM are generally slower than those off DOM. jasmine.attachToDOM(workspaceElement) expect(workspaceElement.querySelector('.about')).not.toExist() atom.workspace.open('atom://about') waitsFor(() => { return atom.workspace.getActivePaneItem() }) runs(() => { let aboutElement = workspaceElement.querySelector('.about') expect(aboutElement).toBeVisible() }) }) }) describe('when the version number is clicked', () => { it('copies the version number to the clipboard', () => { atom.workspace.open('atom://about') waitsFor(() => { return atom.workspace.getActivePaneItem() }) runs(() => { let aboutElement = workspaceElement.querySelector('.about') let versionContainer = aboutElement.querySelector('.about-version-container') versionContainer.click() expect(atom.clipboard.read()).toBe(atom.getVersion()) }) }) }) })
/** @babel */ describe('About', () => { let workspaceElement beforeEach(() => { workspaceElement = atom.views.getView(atom.workspace) waitsForPromise(() => { return atom.packages.activatePackage('about') }) }) describe('when the about:about-atom command is triggered', () => { it('shows the About Atom view', () => { // Attaching the workspaceElement to the DOM is required to allow the // `toBeVisible()` matchers to work. Anything testing visibility or focus // requires that the workspaceElement is on the DOM. Tests that attach the // workspaceElement to the DOM are generally slower than those off DOM. jasmine.attachToDOM(workspaceElement) expect(workspaceElement.querySelector('.about')).not.toExist() atom.workspace.open('atom://about') waitsFor(() => { return atom.workspace.getActivePaneItem() }) runs(() => { let aboutElement = workspaceElement.querySelector('.about') expect(aboutElement).toBeVisible() }) }) }) describe('when the version number is clicked', () => { it('copies the version number to the clipboard', () => { atom.workspace.open('atom://about') waitsFor(() => { return atom.workspace.getActivePaneItem() }) runs(() => { let aboutElement = workspaceElement.querySelector('.about') let versionContainer = aboutElement.querySelector('.about-version-container') versionContainer.click() expect(atom.clipboard.read()).toBe(atom.getVersion()) }) }) }) })
Fix issue in anonymous filters in aggregations
<?php namespace Elastica\Aggregation; use Elastica\Filter\AbstractFilter; /** * Class Filters. * * @link http://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filters-aggregation.html */ class Filters extends AbstractAggregation { /** * Add a filter. * * If a name is given, it will be added as a key, otherwise considered as an anonymous filter * * @param AbstractFilter $filter * @param string $name * * @return $this */ public function addFilter(AbstractFilter $filter, $name = '') { $filterArray = array(); if (is_string($name)) { $filterArray[$name] = $filter; } else { $filterArray[] = $filter; } return $this->addParam('filters', $filterArray); } /** * @return array */ public function toArray() { $array = array(); $filters = $this->getParam('filters'); foreach ($filters as $filter) { // Detect between anonymous filters and named ones $key = key($filter); if (is_string($key) && !empty($key)) { $array['filters']['filters'][$key] = current($filter)->toArray(); } else { $array['filters']['filters'][] = current($filter)->toArray(); } } if ($this->_aggs) { $array['aggs'] = $this->_convertArrayable($this->_aggs); } return $array; } }
<?php namespace Elastica\Aggregation; use Elastica\Filter\AbstractFilter; /** * Class Filters. * * @link http://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filters-aggregation.html */ class Filters extends AbstractAggregation { /** * Add a filter. * * If a name is given, it will be added as a key, otherwise considered as an anonymous filter * * @param AbstractFilter $filter * @param string $name * * @return $this */ public function addFilter(AbstractFilter $filter, $name = '') { $filterArray = array(); if (is_string($name)) { $filterArray[$name] = $filter; } else { $filterArray[] = $filter; } return $this->addParam('filters', $filterArray); } /** * @return array */ public function toArray() { $array = array(); $filters = $this->getParam('filters'); foreach ($filters as $filter) { // Detect between anonymous filters and named ones $key = key($filter); if (is_string($key)) { $array['filters']['filters'][$key] = current($filter)->toArray(); } else { $array['filters']['filters'][] = current($filter)->toArray(); } } if ($this->_aggs) { $array['aggs'] = $this->_convertArrayable($this->_aggs); } return $array; } }
Replace undefined/null with something human-readable
function restore() { var nurls = 0; for (var k in localStorage) { if (k.match(/^http:/)) { nurls++; var tr = document.createElement('tr'); var info = JSON.parse(localStorage[k]); tr.innerHTML = '<td>' + k + '</td><td><a href="' + info['long-url'] + '">' + (info.title ? info.title : info['long-url'].split('/').pop()) + '</a></td>'; document.getElementById('urldetail').appendChild(tr); } } document.getElementById('nurls').innerHTML = nurls; if (localStorage['services']) { var services = JSON.parse(localStorage['services']); var nsvcs = 0; for (var k in services) { nsvcs++; var tr = document.createElement('tr'); tr.innerHTML = '<td>' + services[k].domain + '</td><td>' + (services[k].regex ? services[k].regex : '') + '</td>'; document.getElementById('svcdetail').appendChild(tr); } document.getElementById('nsvcs').innerHTML = nsvcs; } var exp = localStorage['servicesExpire']; document.getElementById('svcstatus').innerHTML = exp ? 'cached until ' + new Date(+exp) : 'not cached'; }
function restore() { var nurls = 0; for (var k in localStorage) { if (k.match(/^http:/)) { nurls++; var tr = document.createElement('tr'); var info = JSON.parse(localStorage[k]); tr.innerHTML = '<td>' + k + '</td><td><a href="' + info['long-url'] + '">' + info.title + '</a></td>'; document.getElementById('urldetail').appendChild(tr); } } document.getElementById('nurls').innerHTML = nurls; if (localStorage['services']) { var services = JSON.parse(localStorage['services']); var nsvcs = 0; for (var k in services) { nsvcs++; var tr = document.createElement('tr'); tr.innerHTML = '<td>' + services[k].domain + '</td><td>' + services[k].regex + '</td>'; document.getElementById('svcdetail').appendChild(tr); } document.getElementById('nsvcs').innerHTML = nsvcs; } var exp = localStorage['servicesExpire']; document.getElementById('svcstatus').innerHTML = exp ? 'cached until ' + new Date(+exp) : 'not cached'; }
Set default LOG_LEVEL to logging.DEBUG
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Debug tools. Can be configured by changing values of those variable. DEBUG = False Enable this variable to activate debug features (like defined_at parameters). It can slow down Rebulk LOG_LEVEL = 0 Default log level of generated rebulk logs. """ import inspect import logging import os from collections import namedtuple DEBUG = False LOG_LEVEL = logging.DEBUG class Frame(namedtuple('Frame', ['lineno', 'package', 'name', 'filename'])): """ Stack frame representation. """ __slots__ = () def __repr__(self): return "%s#L%s" % (os.path.basename(self.filename), self.lineno) def defined_at(): """ Get definition location of a pattern or a match (outside of rebulk package). :return: :rtype: """ if DEBUG: frame = inspect.currentframe() while frame: try: if frame.f_globals['__package__'] != __package__: break except KeyError: # pragma:no cover # If package is missing, consider we are in. Workaround for python 3.3. break frame = frame.f_back ret = Frame(frame.f_lineno, frame.f_globals.get('__package__'), frame.f_globals.get('__name__'), frame.f_code.co_filename) del frame return ret
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Debug tools. Can be configured by changing values of those variable. DEBUG = False Enable this variable to activate debug features (like defined_at parameters). It can slow down Rebulk LOG_LEVEL = 0 Default log level of generated rebulk logs. """ import inspect import os from collections import namedtuple DEBUG = False LOG_LEVEL = 0 class Frame(namedtuple('Frame', ['lineno', 'package', 'name', 'filename'])): """ Stack frame representation. """ __slots__ = () def __repr__(self): return "%s#L%s" % (os.path.basename(self.filename), self.lineno) def defined_at(): """ Get definition location of a pattern or a match (outside of rebulk package). :return: :rtype: """ if DEBUG: frame = inspect.currentframe() while frame: try: if frame.f_globals['__package__'] != __package__: break except KeyError: # pragma:no cover # If package is missing, consider we are in. Workaround for python 3.3. break frame = frame.f_back ret = Frame(frame.f_lineno, frame.f_globals.get('__package__'), frame.f_globals.get('__name__'), frame.f_code.co_filename) del frame return ret
Remove the ending slash for handle ipn url
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn$', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn/', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
Fix test to use /google instead of /google2
import unittest import http.client import time class TestStringMethods(unittest.TestCase): def test_404NoConfig(self): connRouter = http.client.HTTPConnection("localhost", 8666) connConfig = http.client.HTTPConnection("localhost", 8888) connRouter.request("GET", "/google") response = connRouter.getresponse() connRouter.close() self.assertEqual(response.status, 404) def test_200WithConfig(self): connConfig = http.client.HTTPConnection("localhost", 8888) connConfig.request("GET","/configure?location=/google&upstream=http://www.google.com/&ttl=10") response = connConfig.getresponse() data = response.read() connConfig.close() self.assertEqual(response.status, 200) connRouter = http.client.HTTPConnection("localhost", 8666) connRouter.request("GET", "/google") response = connRouter.getresponse() data = response.read() self.assertEqual(response.status, 302) connRouter.close() connConfig2 = http.client.HTTPConnection("localhost", 8888) connConfig2.request("DELETE","/configure?location=/google") response2 = connConfig2.getresponse() data = response2.read() self.assertEqual(response2.status, 200) connConfig2.close() time.sleep(20) if __name__ == '__main__': unittest.main()
import unittest import http.client import time class TestStringMethods(unittest.TestCase): def test_404NoConfig(self): connRouter = http.client.HTTPConnection("localhost", 8666) connConfig = http.client.HTTPConnection("localhost", 8888) connRouter.request("GET", "/google2") response = connRouter.getresponse() connRouter.close() self.assertEqual(response.status, 404) def test_200WithConfig(self): connConfig = http.client.HTTPConnection("localhost", 8888) connConfig.request("GET","/configure?location=/google&upstream=http://www.google.com/&ttl=10") response = connConfig.getresponse() data = response.read() connConfig.close() self.assertEqual(response.status, 200) connRouter = http.client.HTTPConnection("localhost", 8666) connRouter.request("GET", "/google") response = connRouter.getresponse() data = response.read() self.assertEqual(response.status, 302) connRouter.close() connConfig2 = http.client.HTTPConnection("localhost", 8888) connConfig2.request("DELETE","/configure?location=/google") response2 = connConfig2.getresponse() data = response2.read() self.assertEqual(response2.status, 200) connConfig2.close() time.sleep(20) if __name__ == '__main__': unittest.main()
Add a huge hack to treat Decimals like floats This commit provided to you by highly trained professional stuntmen, do not try to reproduce any of this at home!
from decimal import Decimal from django.http import HttpResponse from django.utils import simplejson def decimal_format(value, min_decimal_places=0): decimal_tuple = value.as_tuple() have_decimal_places = -decimal_tuple.exponent digits = list(decimal_tuple.digits) while have_decimal_places < min_decimal_places: digits.append(0) have_decimal_places += 1 while have_decimal_places > min_decimal_places and not digits[-1]: if len(digits) > 1: digits = digits[:-1] have_decimal_places -= 1 return Decimal((decimal_tuple.sign, digits, -have_decimal_places)) class JSONResponse(HttpResponse): class UndercoverDecimal(float): ''' A horrible hack that lets us encode Decimals as numbers. Do not do this at home. ''' def __init__(self, value): self.value = value def __repr__(self): return str(self.value) def handle_decimal(self, o): if isinstance(o, Decimal): return self.UndercoverDecimal(o) raise TypeError() def __init__(self, content='', mimetype=None, status=None, content_type='application/json'): content = simplejson.dumps(content, default=self.handle_decimal) return super(JSONResponse, self).__init__(content=content, mimetype=mimetype, status=status, content_type=content_type)
from decimal import Decimal from django.http import HttpResponse from django.utils import simplejson def decimal_format(value, min_decimal_places=0): decimal_tuple = value.as_tuple() have_decimal_places = -decimal_tuple.exponent digits = list(decimal_tuple.digits) while have_decimal_places < min_decimal_places: digits.append(0) have_decimal_places += 1 while have_decimal_places > min_decimal_places and not digits[-1]: if len(digits) > 1: digits = digits[:-1] have_decimal_places -= 1 return Decimal((decimal_tuple.sign, digits, -have_decimal_places)) class JSONResponse(HttpResponse): def handle_decimal(self, o): if isinstance(o, Decimal): return float(o) raise TypeError() def __init__(self, content='', mimetype=None, status=None, content_type='application/json'): content = simplejson.dumps(content, default=self.handle_decimal) return super(JSONResponse, self).__init__(content=content, mimetype=mimetype, status=status, content_type=content_type)
Remove version number for snowballstemmer
from __future__ import with_statement import os from setuptools import setup this_dir = os.path.dirname(__file__) with open(os.path.join(this_dir, 'src', 'pydocstyle', 'utils.py')) as f: for line in f: if line.startswith('__version__'): version = eval(line.split('=')[-1]) setup( name='pydocstyle', version=version, description="Python docstring style checker", long_description=open('README.rst').read(), license='MIT', author='Amir Rachum', author_email='[email protected]', url='https://github.com/PyCQA/pydocstyle/', classifiers=[ 'Intended Audience :: Developers', 'Environment :: Console', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ], keywords='pydocstyle, PEP 257, pep257, PEP 8, pep8, docstrings', packages=('pydocstyle',), package_dir={'': 'src'}, package_data={'pydocstyle': ['data/*.txt']}, install_requires=[ 'snowballstemmer', ], entry_points={ 'console_scripts': [ 'pydocstyle = pydocstyle.cli:main', ], }, )
from __future__ import with_statement import os from setuptools import setup this_dir = os.path.dirname(__file__) with open(os.path.join(this_dir, 'src', 'pydocstyle', 'utils.py')) as f: for line in f: if line.startswith('__version__'): version = eval(line.split('=')[-1]) setup( name='pydocstyle', version=version, description="Python docstring style checker", long_description=open('README.rst').read(), license='MIT', author='Amir Rachum', author_email='[email protected]', url='https://github.com/PyCQA/pydocstyle/', classifiers=[ 'Intended Audience :: Developers', 'Environment :: Console', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ], keywords='pydocstyle, PEP 257, pep257, PEP 8, pep8, docstrings', packages=('pydocstyle',), package_dir={'': 'src'}, package_data={'pydocstyle': ['data/*.txt']}, install_requires=[ 'snowballstemmer==1.2.1', ], entry_points={ 'console_scripts': [ 'pydocstyle = pydocstyle.cli:main', ], }, )
Fix bug to display all branches when there is only 1 repo
from __future__ import absolute_import import os import logging from workspace.commands import AbstractCommand from workspace.commands.helpers import ProductPager from workspace.scm import stat_repo, repos, product_name, all_branches, is_repo log = logging.getLogger(__name__) class Status(AbstractCommand): """ Show status on current product or all products in workspace """ alias = 'st' def run(self): try: scm_repos = repos() in_repo = is_repo(os.getcwd()) optional = len(scm_repos) == 1 pager = ProductPager(optional=optional) for repo in scm_repos: stat_path = os.getcwd() if in_repo else repo output = stat_repo(stat_path, True) nothing_to_commit = 'nothing to commit' in output and 'Your branch is ahead of' not in output branches = all_branches(repo) child_branches = [b for b in branches if '@' in b] if len(child_branches) > 1 or len(scm_repos) == 1: if nothing_to_commit: output = '# Branches: %s' % ' '.join(branches) nothing_to_commit = False elif len(branches) > 1: output = '# Branches: %s\n#\n%s' % (' '.join(branches), output) if output and not nothing_to_commit: pager.write(product_name(repo), output) finally: pager.close_and_wait()
from __future__ import absolute_import import os import logging from workspace.commands import AbstractCommand from workspace.commands.helpers import ProductPager from workspace.scm import stat_repo, repos, product_name, all_branches, is_repo log = logging.getLogger(__name__) class Status(AbstractCommand): """ Show status on current product or all products in workspace """ alias = 'st' def run(self): try: scm_repos = repos() in_repo = is_repo(os.getcwd()) optional = len(scm_repos) == 1 pager = ProductPager(optional=optional) for repo in scm_repos: stat_path = os.getcwd() if in_repo else repo output = stat_repo(stat_path, True) nothing_to_commit = 'nothing to commit' in output and 'Your branch is ahead of' not in output branches = all_branches(repo) child_branches = [b for b in branches if '@' in b] if len(child_branches) > 1: if nothing_to_commit: output = '# Branches: %s' % ' '.join(branches) nothing_to_commit = False elif len(branches) > 1: output = '# Branches: %s\n#\n%s' % (' '.join(branches), output) if output and not nothing_to_commit: pager.write(product_name(repo), output) finally: pager.close_and_wait()
Fix bug that caused HTML comments to halt all additional parsing
import Bit from '../components/Bit' import { createElement } from 'react' const COMMENT_TAG = '--' const DEFAULT_TAG = Bit // eslint-disable-next-line max-params function parse (buffer, doc, options, key) { switch (doc.type) { case 'text': return [...buffer, doc.content] case 'tag': { let children = reactify(doc.children, options, key) if (!children.length) { children = null } if (doc.name.startsWith(COMMENT_TAG)) { return [...buffer, ...children] } const tag = options.mappings[doc.name] || DEFAULT_TAG if (tag.fromMarkup) { doc.attrs = tag.fromMarkup(doc.attrs) } if (tag === DEFAULT_TAG && !doc.attrs.as) { doc.attrs.as = doc.name } if (doc.attrs.class) { // Rename class to className for React compatibility doc.attrs.className = doc.attrs.class delete doc.attrs.class } return [...buffer, createElement(tag, { key, ...doc.attrs }, children)] } default: return buffer } } export default function reactify (doc, options, keyPrefix = '$') { return doc.reduce( (collection, rootEl, key) => [ ...collection, ...parse([], rootEl, options, `${keyPrefix}.${key}`) ], [] ) }
import Bit from '../components/Bit' import { createElement } from 'react' const COMMENT_TAG = '--' const DEFAULT_TAG = Bit // eslint-disable-next-line max-params function parse (buffer, doc, options, key) { switch (doc.type) { case 'text': return [...buffer, doc.content] case 'tag': { if (doc.name.startsWith(COMMENT_TAG)) { return buffer } const tag = options.mappings[doc.name] || DEFAULT_TAG let children = reactify(doc.children, options, key) if (!children.length) { children = null } if (tag.fromMarkup) { doc.attrs = tag.fromMarkup(doc.attrs) } if (tag === DEFAULT_TAG && !doc.attrs.as) { doc.attrs.as = doc.name } if (doc.attrs.class) { // Rename class to className for React compatibility doc.attrs.className = doc.attrs.class delete doc.attrs.class } return [...buffer, createElement(tag, { key, ...doc.attrs }, children)] } default: return buffer } } export default function reactify (doc, options, keyPrefix = '$') { return doc.reduce( (collection, rootEl, key) => [ ...collection, ...parse([], rootEl, options, `${keyPrefix}.${key}`) ], [] ) }
Set startConnect: false and tunnelIdentifier Reference: https://github.com/karma-runner/karma-sauce-launcher/issues/73
module.exports = function(config) { require("./karma.conf")(config); config.set({ customLaunchers: { SL_Chrome: { base: 'SauceLabs', browserName: 'chrome', version: '35' }, SL_Firefox: { base: 'SauceLabs', browserName: 'firefox', version: '30' }, SL_Safari: { base: 'SauceLabs', browserName: 'safari', version: '9' }, SL_IE8: { base: 'SauceLabs', browserName: 'internet explorer', version: '8', platform: 'Windows XP' }, SL_IE9: { base: 'SauceLabs', browserName: 'internet explorer', version: '9', platform: 'Windows 7' }, SL_IE10: { base: 'SauceLabs', browserName: 'internet explorer', version: '10', platform: 'Windows 8' }, SL_IE11: { base: 'SauceLabs', browserName: 'internet explorer', version: '11', platform: 'Windows 10' } }, browsers: [ 'SL_IE8', 'SL_IE9', 'SL_IE10', 'SL_IE11' ], sauceLabs: { testName: 'Script Loader Tests', tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER, startConnect: false, recordVideo: false }, captureTimeout: 120000, browserNoActivityTimeout: 300000 }); };
module.exports = function(config) { require("./karma.conf")(config); config.set({ customLaunchers: { SL_Chrome: { base: 'SauceLabs', browserName: 'chrome', version: '35' }, SL_Firefox: { base: 'SauceLabs', browserName: 'firefox', version: '30' }, SL_Safari: { base: 'SauceLabs', browserName: 'safari', version: '9' }, SL_IE8: { base: 'SauceLabs', browserName: 'internet explorer', version: '8', platform: 'Windows XP' }, SL_IE9: { base: 'SauceLabs', browserName: 'internet explorer', version: '9', platform: 'Windows 7' }, SL_IE10: { base: 'SauceLabs', browserName: 'internet explorer', version: '10', platform: 'Windows 8' }, SL_IE11: { base: 'SauceLabs', browserName: 'internet explorer', version: '11', platform: 'Windows 10' } }, browsers: [ 'SL_IE8', 'SL_IE9', 'SL_IE10', 'SL_IE11' ], sauceLabs: { recordVideo: false }, captureTimeout: 120000, browserNoActivityTimeout: 300000 }); };
Make sure `output` variable is in scope no matter what.
import requests from collections import defaultdict from requests.exceptions import RequestException from django.conf import settings from django.utils.dateparse import parse_datetime import sal.plugin import server.utils as utils class CryptStatus(sal.plugin.DetailPlugin): description = 'FileVault Escrow Status' supported_os_families = [sal.plugin.OSFamilies.darwin] def get_context(self, machine, **kwargs): context = defaultdict(str) context['title'] = self.description crypt_url = utils.get_setting('crypt_url', None) machine_url = crypt_url if crypt_url: crypt_url = crypt_url.rstrip() if crypt_url: try: verify = settings.ROOT_CA except AttributeError: verify = True request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial) output = None machine_url = crypt_url try: response = requests.get(request_url, verify=verify) if response.status_code == requests.codes.ok: output = response.json() # Have template link to machine info page rather # than Crypt root. machine_url = '{}/info/{}'.format(crypt_url, machine.serial) except RequestException: # Either there was an error or the machine hasn't been # seen. pass if output: context['escrowed'] = output['escrowed'] if output['escrowed']: context['date_escrowed'] = parse_datetime(output['date_escrowed']) context['crypt_url'] = machine_url return context
import requests from collections import defaultdict from requests.exceptions import RequestException from django.conf import settings from django.utils.dateparse import parse_datetime import sal.plugin import server.utils as utils class CryptStatus(sal.plugin.DetailPlugin): description = 'FileVault Escrow Status' supported_os_families = [sal.plugin.OSFamilies.darwin] def get_context(self, machine, **kwargs): context = defaultdict(str) context['title'] = self.description crypt_url = utils.get_setting('crypt_url', None) machine_url = crypt_url if crypt_url: crypt_url = crypt_url.rstrip() if crypt_url: try: verify = settings.ROOT_CA except AttributeError: verify = True request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial) try: response = requests.get(request_url, verify=verify) if response.status_code == requests.codes.ok: output = response.json() # Have template link to machine info page rather # than Crypt root. machine_url = '{}/info/{}'.format(crypt_url, machine.serial) except RequestException: # Either there was an error or the machine hasn't been # seen. output = None machine_url = crypt_url if output: context['escrowed'] = output['escrowed'] if output['escrowed']: context['date_escrowed'] = parse_datetime(output['date_escrowed']) context['crypt_url'] = machine_url return context
Py3: Exit with non-0 status if there are failed tests or errors.
# -*- coding: utf-8 -*- """ Unit tests for pytils """ __all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"] import unittest import sys def get_django_suite(): try: import django except ImportError: return unittest.TestSuite() import pytils.test.templatetags return pytils.test.templatetags.get_suite() def get_suite(): """Return TestSuite for all unit-test of pytils""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test."+module_name, globals(), locals(), ["pytils.test"]) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) suite.addTest(get_django_suite()) return suite def run_tests_from_module(module, verbosity=1): """Run unit-tests for single module""" suite = unittest.TestSuite() loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=verbosity).run(suite) def run(verbosity=1): """Run all unit-test of pytils""" suite = get_suite() res = unittest.TextTestRunner(verbosity=verbosity).run(suite) if res.errors or res.failures: sys.exit(1) if __name__ == '__main__': run(2)
# -*- coding: utf-8 -*- """ Unit tests for pytils """ __all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"] import unittest def get_django_suite(): try: import django except ImportError: return unittest.TestSuite() import pytils.test.templatetags return pytils.test.templatetags.get_suite() def get_suite(): """Return TestSuite for all unit-test of pytils""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test."+module_name, globals(), locals(), ["pytils.test"]) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) suite.addTest(get_django_suite()) return suite def run_tests_from_module(module, verbosity=1): """Run unit-tests for single module""" suite = unittest.TestSuite() loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=verbosity).run(suite) def run(verbosity=1): """Run all unit-test of pytils""" suite = get_suite() unittest.TextTestRunner(verbosity=verbosity).run(suite) if __name__ == '__main__': run(2)
Add temporary fix for problem where selected model on hover does not exist
define([ 'extensions/views/single_stat' ], function (SingleStatView) { var NumberView = SingleStatView.extend({ changeOnSelected: true, labelPrefix: '', formatValue: function(value) { return this.formatNumericLabel(value); }, getValue: function () { return this.formatValue(this.collection.at(0).get(this.valueAttr)); }, getLabel: function () { var periodLabel = this.model.get('period') || "week"; var events = this.collection.at(0).get("weeks"), unavailableEvents = events.total - events.available, label = [ this.labelPrefix, 'last', events.total, this.pluralise(periodLabel, events.total) ]; if (unavailableEvents > 0) { label = label.concat([ "<span class='unavailable'>(" + unavailableEvents, this.pluralise(periodLabel, unavailableEvents), "unavailable)</span>" ]); } return label.join(' '); }, getValueSelected: function (selection) { var val; if (selection.selectedGroupIndex !== null) { val = selection.selectedModel.get(this.selectionValueAttr); } else { val = null; } return this.formatValue(val); }, getLabelSelected: function (selection) { var val; if (selection.selectedGroupIndex !== null) { return this.formatPeriod(selection.selectedModel, 'week'); } else { return ''; } } }); return NumberView; });
define([ 'extensions/views/single_stat' ], function (SingleStatView) { var NumberView = SingleStatView.extend({ changeOnSelected: true, labelPrefix: '', formatValue: function(value) { return this.formatNumericLabel(value); }, getValue: function () { return this.formatValue(this.collection.at(0).get(this.valueAttr)); }, getLabel: function () { var periodLabel = this.model.get('period') || "week"; var events = this.collection.at(0).get("weeks"), unavailableEvents = events.total - events.available, label = [ this.labelPrefix, 'last', events.total, this.pluralise(periodLabel, events.total) ]; if (unavailableEvents > 0) { label = label.concat([ "<span class='unavailable'>(" + unavailableEvents, this.pluralise(periodLabel, unavailableEvents), "unavailable)</span>" ]); } return label.join(' '); }, getValueSelected: function (selection) { return this.formatValue(selection.selectedModel.get(this.selectionValueAttr)); }, getLabelSelected: function (selection) { return this.formatPeriod(selection.selectedModel, 'week'); } }); return NumberView; });
Implement empty metadata a little differently
import copy import json from py4j.java_gateway import java_import from pymrgeo.instance import is_instance_of as iio class RasterMapOp(object): mapop = None gateway = None context = None job = None def __init__(self, gateway=None, context=None, mapop=None, job=None): self.gateway = gateway self.context = context self.mapop = mapop self.job = job @staticmethod def nan(): return float('nan') def clone(self): return copy.copy(self) def is_instance_of(self, java_object, java_class): return iio(self.gateway, java_object, java_class) def metadata(self): if self.mapop is None: return None jvm = self.gateway.jvm java_import(jvm, "org.mrgeo.mapalgebra.raster.RasterMapOp") java_import(jvm, "org.mrgeo.image.MrsPyramidMetadata") if self.mapop.metadata().isEmpty(): return None meta = self.mapop.metadata().get() java_import(jvm, "com.fasterxml.jackson.databind.ObjectMapper") mapper = jvm.com.fasterxml.jackson.databind.ObjectMapper() jsonstr = mapper.writeValueAsString(meta) # print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(meta)) return json.loads(jsonstr)
import copy import json from py4j.java_gateway import JavaClass, java_import from pymrgeo.instance import is_instance_of as iio class RasterMapOp(object): mapop = None gateway = None context = None job = None def __init__(self, gateway=None, context=None, mapop=None, job=None): self.gateway = gateway self.context = context self.mapop = mapop self.job = job @staticmethod def nan(): return float('nan') def clone(self): return copy.copy(self) def is_instance_of(self, java_object, java_class): return iio(self.gateway, java_object, java_class) def metadata(self): if self.mapop is None: return None jvm = self.gateway.jvm java_import(jvm, "org.mrgeo.mapalgebra.raster.RasterMapOp") java_import(jvm, "org.mrgeo.image.MrsPyramidMetadata") meta = self.mapop.metadata().getOrElse(None) if meta is None: return None java_import(jvm, "com.fasterxml.jackson.databind.ObjectMapper") mapper = jvm.com.fasterxml.jackson.databind.ObjectMapper() jsonstr = mapper.writeValueAsString(meta) # print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(meta)) return json.loads(jsonstr)
Add yearless date as an acceptable format for moment parsing Closes #2331
/* global moment */ var parseDateFormats = ['DD MMM YY @ HH:mm', 'DD MMM YY HH:mm', 'DD MMM YYYY @ HH:mm', 'DD MMM YYYY HH:mm', 'DD/MM/YY @ HH:mm', 'DD/MM/YY HH:mm', 'DD/MM/YYYY @ HH:mm', 'DD/MM/YYYY HH:mm', 'DD-MM-YY @ HH:mm', 'DD-MM-YY HH:mm', 'DD-MM-YYYY @ HH:mm', 'DD-MM-YYYY HH:mm', 'YYYY-MM-DD @ HH:mm', 'YYYY-MM-DD HH:mm', 'DD MMM @ HH:mm', 'DD MMM HH:mm'], displayDateFormat = 'DD MMM YY @ HH:mm'; /** * Add missing timestamps */ var verifyTimeStamp = function (dateString) { if (dateString && !dateString.slice(-5).match(/\d+:\d\d/)) { dateString += ' 12:00'; } return dateString; }; //Parses a string to a Moment var parseDateString = function (value) { return value ? moment(verifyTimeStamp(value), parseDateFormats, true) : undefined; }; //Formats a Date or Moment var formatDate = function (value) { return verifyTimeStamp(value ? moment(value).format(displayDateFormat) : ''); }; export {parseDateString, formatDate};
/* global moment */ var parseDateFormats = ['DD MMM YY @ HH:mm', 'DD MMM YY HH:mm', 'DD MMM YYYY @ HH:mm', 'DD MMM YYYY HH:mm', 'DD/MM/YY @ HH:mm', 'DD/MM/YY HH:mm', 'DD/MM/YYYY @ HH:mm', 'DD/MM/YYYY HH:mm', 'DD-MM-YY @ HH:mm', 'DD-MM-YY HH:mm', 'DD-MM-YYYY @ HH:mm', 'DD-MM-YYYY HH:mm', 'YYYY-MM-DD @ HH:mm', 'YYYY-MM-DD HH:mm'], displayDateFormat = 'DD MMM YY @ HH:mm'; /** * Add missing timestamps */ var verifyTimeStamp = function (dateString) { if (dateString && !dateString.slice(-5).match(/\d+:\d\d/)) { dateString += ' 12:00'; } return dateString; }; //Parses a string to a Moment var parseDateString = function (value) { return value ? moment(verifyTimeStamp(value), parseDateFormats, true) : undefined; }; //Formats a Date or Moment var formatDate = function (value) { return verifyTimeStamp(value ? moment(value).format(displayDateFormat) : ''); }; export {parseDateString, formatDate};
Fix demo. And *actually* test new Django versions
import os from setuptools import setup, find_packages def read_relative_file(filename): """Returns contents of the given file, which path is supposed relative to this module.""" with open(os.path.join(os.path.dirname(__file__), filename)) as f: return f.read() NAME = 'django-genericfilters-demo' README = read_relative_file('README') VERSION = '0.1' PACKAGES = find_packages() REQUIRES = [ 'django-generic-filters', 'mock', 'Django', 'coverage', ] setup(name=NAME, version=VERSION, description='Demo project for django-generic-filters.', long_description=README, classifiers=['Development Status :: 1 - Planning', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3', 'Framework :: Django', ], keywords='class-based view, generic view, filters', author='Novapost', author_email='[email protected]', url='https://github.com/novapost/django-generic-filters', license='BSD', packages=PACKAGES, include_package_data=True, zip_safe=False, install_requires=REQUIRES, entry_points={ 'console_scripts': [ 'demo = demoproject.manage:main', ] }, )
import os from setuptools import setup def read_relative_file(filename): """Returns contents of the given file, which path is supposed relative to this module.""" with open(os.path.join(os.path.dirname(__file__), filename)) as f: return f.read() NAME = 'django-genericfilters-demo' README = read_relative_file('README') VERSION = '0.1' PACKAGES = ['demoproject'] REQUIRES = [ 'django-generic-filters', 'mock', 'Django>=1.8,<1.12', 'coverage', ] setup(name=NAME, version=VERSION, description='Demo project for django-generic-filters.', long_description=README, classifiers=['Development Status :: 1 - Planning', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3', 'Framework :: Django', ], keywords='class-based view, generic view, filters', author='Novapost', author_email='[email protected]', url='https://github.com/novapost/django-generic-filters', license='BSD', packages=PACKAGES, include_package_data=True, zip_safe=False, install_requires=REQUIRES, entry_points={ 'console_scripts': [ 'demo = demoproject.manage:main', ] }, )
Increment version in preperation for release of version 1.2.0
try: # Try using ez_setup to install setuptools if not already installed. from ez_setup import use_setuptools use_setuptools() except ImportError: # Ignore import error and assume Python 3 which already has setuptools. pass from setuptools import setup DESC = ('This Python library for Raspberry Pi makes it easy to leverage the ' 'complex functionality of the Texas Instruments INA219 ' 'sensor to measure voltage, current and power.') classifiers = ['Development Status :: 4 - Beta', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: System :: Hardware :: Hardware Drivers'] # Define required packages. requires = ['Adafruit_GPIO', 'mock'] def read_long_description(): try: import pypandoc return pypandoc.convert('README.md', 'rst') except(IOError, ImportError): return "" setup(name='pi-ina219', version='1.2.0', author='Chris Borrill', author_email='[email protected]', description=DESC, long_description=read_long_description(), license='MIT', url='https://github.com/chrisb2/pi_ina219/', classifiers=classifiers, keywords='ina219 raspberrypi', install_requires=requires, test_suite='tests', py_modules=['ina219'])
try: # Try using ez_setup to install setuptools if not already installed. from ez_setup import use_setuptools use_setuptools() except ImportError: # Ignore import error and assume Python 3 which already has setuptools. pass from setuptools import setup DESC = ('This Python library for Raspberry Pi makes it easy to leverage the ' 'complex functionality of the Texas Instruments INA219 ' 'sensor to measure voltage, current and power.') classifiers = ['Development Status :: 4 - Beta', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: System :: Hardware :: Hardware Drivers'] # Define required packages. requires = ['Adafruit_GPIO', 'mock'] def read_long_description(): try: import pypandoc return pypandoc.convert('README.md', 'rst') except(IOError, ImportError): return "" setup(name='pi-ina219', version='1.1.0', author='Chris Borrill', author_email='[email protected]', description=DESC, long_description=read_long_description(), license='MIT', url='https://github.com/chrisb2/pi_ina219/', classifiers=classifiers, keywords='ina219 raspberrypi', install_requires=requires, test_suite='tests', py_modules=['ina219'])
Fix ascii blink regex to match non blink command
'use strict'; var figlet = require('figlet'); var util = require('../../utilities'); var random_font = function() { var fonts = [ 'Basic', 'Big', 'JS Stick Letters', 'Kban', 'Slant', 'Soft' ]; return fonts[Math.floor(Math.random() * fonts.length)]; }; if (process.env.IRC_ENV != 'production') { random_font = function() { return 'Soft'; }; } function messageListener(db, from, channel, message, reply) { var img_regex = /^@ascii +https?:\/\//; var ascii_regex = /^@ascii +[^ ]/; if (ascii_regex.test(message) && !img_regex.test(message)) { var cmd = message.match(/^@ascii +(blink *)?([^ ].*)$/); var formatLine = cmd[1] ? util.blink_text : function(s) { return s; }; var text = cmd[2]; var ascii = figlet.textSync(text, { font: random_font(), horizontalLayout: 'default', verticalLayout: 'default' }); ascii.split("\n").forEach(function (line) { reply({ to: channel, message: formatLine(line) }); }); } } module.exports = messageListener; module.exports.help = [{ cmd:'@ascii', syntax: '@ascii [blink] <text>', output: {success: ['Multiple line ascii representation of the text.'], failure: []} }];
'use strict'; var figlet = require('figlet'); var util = require('../../utilities'); var random_font = function() { var fonts = [ 'Basic', 'Big', 'JS Stick Letters', 'Kban', 'Slant', 'Soft' ]; return fonts[Math.floor(Math.random() * fonts.length)]; }; if (process.env.IRC_ENV != 'production') { random_font = function() { return 'Soft'; }; } function messageListener(db, from, channel, message, reply) { var img_regex = /^@ascii +https?:\/\//; var ascii_regex = /^@ascii +[^ ]/; if (ascii_regex.test(message) && !img_regex.test(message)) { var cmd = message.match(/^@ascii +(blink)? +([^ ].*)$/); var formatLine = cmd[1] ? util.blink_text : function(s) { return s; }; var text = cmd[2]; var ascii = figlet.textSync(text, { font: random_font(), horizontalLayout: 'default', verticalLayout: 'default' }); ascii.split("\n").forEach(function (line) { reply({ to: channel, message: formatLine(line) }); }); } } module.exports = messageListener; module.exports.help = [{ cmd:'@ascii', syntax: '@ascii [blink] <text>', output: {success: ['Multiple line ascii representation of the text.'], failure: []} }];
Fix test of ArrayAccessProvider to avoid using Pimple
<?php namespace Knp\Menu\Tests\Renderer; use Knp\Menu\Renderer\ArrayAccessProvider; use PHPUnit\Framework\TestCase; class ArrayAccessProviderTest extends TestCase { public function testHas() { $provider = new ArrayAccessProvider(new \ArrayObject(), 'first', array('first' => 'first', 'second' => 'dummy')); $this->assertTrue($provider->has('first')); $this->assertTrue($provider->has('second')); $this->assertFalse($provider->has('third')); } public function testGetExistentRenderer() { $registry = new \ArrayObject(); $renderer = $this->getMockBuilder('Knp\Menu\Renderer\RendererInterface')->getMock(); $registry['renderer'] = $renderer; $provider = new ArrayAccessProvider($registry, 'default', array('default' => 'renderer')); $this->assertSame($renderer, $provider->get('default')); } public function testGetDefaultRenderer() { $registry = new \ArrayObject(); $renderer = $this->getMockBuilder('Knp\Menu\Renderer\RendererInterface')->getMock(); $registry['renderer'] = $renderer; $provider = new ArrayAccessProvider($registry, 'default', array('default' => 'renderer')); $this->assertSame($renderer, $provider->get()); } /** * @expectedException \InvalidArgumentException */ public function testGetNonExistentRenderer() { $provider = new ArrayAccessProvider(new \ArrayObject(), 'default', array()); $provider->get('non-existent'); } }
<?php namespace Knp\Menu\Tests\Renderer; use Knp\Menu\Renderer\ArrayAccessProvider; use PHPUnit\Framework\TestCase; class ArrayAccessProviderTest extends TestCase { public function testHas() { $provider = new ArrayAccessProvider(new \ArrayObject(), 'first', array('first' => 'first', 'second' => 'dummy')); $this->assertTrue($provider->has('first')); $this->assertTrue($provider->has('second')); $this->assertFalse($provider->has('third')); } public function testGetExistentRenderer() { $registry = new \Pimple(); $renderer = $this->getMockBuilder('Knp\Menu\Renderer\RendererInterface')->getMock(); $registry['renderer'] = $renderer; $provider = new ArrayAccessProvider($registry, 'default', array('default' => 'renderer')); $this->assertSame($renderer, $provider->get('default')); } public function testGetDefaultRenderer() { $registry = new \ArrayObject(); $renderer = $this->getMockBuilder('Knp\Menu\Renderer\RendererInterface')->getMock(); $registry['renderer'] = $renderer; $provider = new ArrayAccessProvider($registry, 'default', array('default' => 'renderer')); $this->assertSame($renderer, $provider->get()); } /** * @expectedException \InvalidArgumentException */ public function testGetNonExistentRenderer() { $provider = new ArrayAccessProvider(new \ArrayObject(), 'default', array()); $provider->get('non-existent'); } }
Use Stream::limit instead of List::subList
package uk.ac.ebi.atlas.solr.query; import org.apache.solr.client.solrj.SolrQuery; import uk.ac.ebi.atlas.search.SemanticQueryTerm; import uk.ac.ebi.atlas.species.Species; import javax.inject.Inject; import javax.inject.Named; import java.util.List; import java.util.stream.Collectors; @Named public class SolrBioentitiesSuggesterService { private final BioentitiesSolrClient solrClient; @Inject public SolrBioentitiesSuggesterService(BioentitiesSolrClient solrClient) { this.solrClient = solrClient; } public List<SemanticQueryTerm> fetchSuggestions(String query, Species species, int numberOfSuggestions) { SolrQuery solrQuery = new SolrQuery(); solrQuery.setRequestHandler("/suggest") .setParam("suggest.dictionary", "propertySuggester") .setParam("suggest.q", query) .setParam("suggest.cfq", species.getEnsemblName().toLowerCase()); return solrClient.query(solrQuery).getSuggesterResponse().getSuggestions().values().stream() .flatMap(List::stream) .distinct() .limit(numberOfSuggestions) .map(suggestion -> SemanticQueryTerm.create(suggestion.getTerm(), suggestion.getPayload())) .collect(Collectors.toList()); } }
package uk.ac.ebi.atlas.solr.query; import org.apache.solr.client.solrj.SolrQuery; import uk.ac.ebi.atlas.search.SemanticQueryTerm; import uk.ac.ebi.atlas.species.Species; import javax.inject.Inject; import javax.inject.Named; import java.util.List; import java.util.stream.Collectors; @Named public class SolrBioentitiesSuggesterService { private final BioentitiesSolrClient solrClient; @Inject public SolrBioentitiesSuggesterService(BioentitiesSolrClient solrClient) { this.solrClient = solrClient; } public List<SemanticQueryTerm> fetchSuggestions(String query, Species species, int numberOfSuggestions) { SolrQuery solrQuery = new SolrQuery(); solrQuery.setRequestHandler("/suggest") .setParam("suggest.dictionary", "propertySuggester") .setParam("suggest.q", query) .setParam("suggest.cfq", species.getEnsemblName().toLowerCase()); return solrClient.query(solrQuery).getSuggesterResponse().getSuggestions().values().stream() .flatMap(List::stream) .distinct() .map(suggestion -> SemanticQueryTerm.create(suggestion.getTerm(), suggestion.getPayload())) .collect(Collectors.toList()) .subList(0, numberOfSuggestions); } }
Remove the extra dispatcher that snuck in
<?php namespace LastCall\Crawler; use LastCall\Crawler\Command\ClearCommand; use LastCall\Crawler\Command\CrawlCommand; use LastCall\Crawler\Command\SetupCommand; use LastCall\Crawler\Command\SetupTeardownCommand; use LastCall\Crawler\Command\TeardownCommand; use LastCall\Crawler\Helper\CrawlerHelper; use Symfony\Component\Console\Application as BaseApplication; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Crawler application */ class Application extends BaseApplication { public function __construct($name = 'LCM Crawler', $version = '1.0') { parent::__construct($name, $version); } /** * Get the default helper set. * * @return HelperSet */ public function getDefaultHelperSet() { $helpers = parent::getDefaultHelperSet(); $helpers->set(new CrawlerHelper()); return $helpers; } /** * Get the default commands. * * @return Command[] */ public function getDefaultCommands() { return array_merge(parent::getDefaultCommands(), array( new CrawlCommand(), SetupTeardownCommand::setup(), SetupTeardownCommand::teardown(), SetupTeardownCommand::reset(), )); } }
<?php namespace LastCall\Crawler; use LastCall\Crawler\Command\ClearCommand; use LastCall\Crawler\Command\CrawlCommand; use LastCall\Crawler\Command\SetupCommand; use LastCall\Crawler\Command\SetupTeardownCommand; use LastCall\Crawler\Command\TeardownCommand; use LastCall\Crawler\Helper\CrawlerHelper; use Symfony\Component\Console\Application as BaseApplication; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Crawler application */ class Application extends BaseApplication { /** * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface * $dispatcher */ private $dispatcher; public function __construct($name = 'LCM Crawler', $version = '1.0') { parent::__construct($name, $version); } /** * Get the default helper set. * * @return HelperSet */ public function getDefaultHelperSet() { $helpers = parent::getDefaultHelperSet(); $helpers->set(new CrawlerHelper()); return $helpers; } /** * Get the default commands. * * @return Command[] */ public function getDefaultCommands() { return array_merge(parent::getDefaultCommands(), array( new CrawlCommand(), SetupTeardownCommand::setup(), SetupTeardownCommand::teardown(), SetupTeardownCommand::reset(), )); } }
Remove formatting issues with CI.
<?php namespace League\HTMLToMarkdown\Converter; use League\HTMLToMarkdown\Configuration; use League\HTMLToMarkdown\ConfigurationAwareInterface; use League\HTMLToMarkdown\ElementInterface; class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface { /** * @var Configuration */ protected $config; /** * @param Configuration $config */ public function setConfig(Configuration $config) { $this->config = $config; } /** * @param ElementInterface $element * * @return string */ public function convert(ElementInterface $element) { $tag = $element->getTagName(); $value = $element->getValue(); if (!trim($value)) { return ''; } if ($tag === 'i' || $tag === 'em') { $style = $this->config->getOption('italic_style'); } else { $style = $this->config->getOption('bold_style'); } $prefix = ltrim($value) !== $value ? ' ' : ''; $suffix = rtrim($value) !== $value ? ' ' : ''; return $prefix . $style . trim($value) . $style . $suffix; } /** * @return string[] */ public function getSupportedTags() { return array('em', 'i', 'strong', 'b'); } }
<?php namespace League\HTMLToMarkdown\Converter; use League\HTMLToMarkdown\Configuration; use League\HTMLToMarkdown\ConfigurationAwareInterface; use League\HTMLToMarkdown\ElementInterface; class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface { /** * @var Configuration */ protected $config; /** * @param Configuration $config */ public function setConfig(Configuration $config) { $this->config = $config; } /** * @param ElementInterface $element * * @return string */ public function convert(ElementInterface $element) { $tag = $element->getTagName(); $value = $element->getValue(); if (!trim($value)) { return ''; } if ($tag === 'i' || $tag === 'em') { $style = $this->config->getOption('italic_style'); } else { $style = $this->config->getOption('bold_style'); } $prefix = ltrim($value) !== $value ? ' ' : ''; $suffix = rtrim($value) !== $value ? ' ' : ''; return $prefix . $style . trim($value) . $style . $suffix; } /** * @return string[] */ public function getSupportedTags() { return array('em', 'i', 'strong', 'b'); } }
Use beta version of Firefox (supports vertical writing-mode) in tests on Sauce Labs
module.exports = function(config) { var commonConfig = (require("./karma-common.conf"))(config); var customLaunchers = { sl_chrome: { base: "SauceLabs", browserName: "chrome", platform: "Windows 8.1" }, sl_firefox: { base: "SauceLabs", browserName: "firefox", platform: "Windows 8.1", version: "beta" }, sl_safari: { base: "SauceLabs", browserName: "safari", platform: "OS X 10.10" }, sl_ie_11: { base: "SauceLabs", browserName: "internet explorer", platform: "Windows 8.1" } }; var options = { reporters: ["verbose", "saucelabs"], sauceLabs: { testName: "Vivliostyle.js", recordScreenshots: false, startConnect: false, // Sauce Connect is started by Travis CI tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, captureTimeout: 120000, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), singleRun: true }; for (var key in commonConfig) { if (commonConfig.hasOwnProperty(key)) { options[key] = commonConfig[key]; } } config.set(options); };
module.exports = function(config) { var commonConfig = (require("./karma-common.conf"))(config); var customLaunchers = { sl_chrome: { base: "SauceLabs", browserName: "chrome", platform: "Windows 8.1" }, sl_firefox: { base: "SauceLabs", browserName: "firefox", platform: "Windows 8.1" }, sl_safari: { base: "SauceLabs", browserName: "safari", platform: "OS X 10.10" }, sl_ie_11: { base: "SauceLabs", browserName: "internet explorer", platform: "Windows 8.1" } }; var options = { reporters: ["verbose", "saucelabs"], sauceLabs: { testName: "Vivliostyle.js", recordScreenshots: false, startConnect: false, // Sauce Connect is started by Travis CI tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, captureTimeout: 120000, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), singleRun: true }; for (var key in commonConfig) { if (commonConfig.hasOwnProperty(key)) { options[key] = commonConfig[key]; } } config.set(options); };
Fix bug in sentiment calculation Signed-off-by: Itai Koren <[email protected]>
// Include The 'require.async' Module require("require.async")(require); /** * Tokenizes an input string. * * @param {String} Input * * @return {Array} */ function tokenize (input) { return input .replace(/[^a-zA-Z ]+/g, "") .replace("/ {2,}/", " ") .toLowerCase() .split(" "); } /** * Performs sentiment analysis on the provided input "term". * * @param {String} Input term * * @return {Object} */ module.exports = function (term, callback) { // Include the AFINN Dictionary JSON asynchronously require.async("./AFINN.json", function(afinn) { // Split line term to letters only words array var words = tokenize(term || ""); var score = 0; var rate; var i = 0; function calculate(word) { // Get the word rate from the AFINN dictionary rate = afinn[word]; if (rate) { // Add current word rate to the final calculated sentiment score score += rate; } // Defer next turn execution (Etheration) setImmediate(function() { // Use callback for completion if (i === (words.length - 1)) { callback(null, score); } else { // Invoke next turn calculate(words[++i]); } }); } // Start calculating calculate(words[i]); }); };
// Include The 'require.async' Module require("require.async")(require); /** * Tokenizes an input string. * * @param {String} Input * * @return {Array} */ function tokenize (input) { return input .replace(/[^a-zA-Z ]+/g, "") .replace("/ {2,}/", " ") .toLowerCase() .split(" "); } /** * Performs sentiment analysis on the provided input "term". * * @param {String} Input term * * @return {Object} */ module.exports = function (term, callback) { // Include the AFINN Dictionary JSON asynchronously require.async("./AFINN.json", function(afinn) { // Split line term to letters only words array var words = tokenize(term || ""); var score = 0; var rate; var i = 0; function calculate(word) { // Get the word rate from the AFINN dictionary rate = afinn[word]; if (rate) { // Add current word rate to the final calculated sentiment score score += rate; } // Defer next turn execution (Etheration) setImmediate(function() { // Use callback for completion if (i === (words.length - 1)) { callback(null, score); } else { // Invoke next turn calculate(words[++i]); } }); } // Start calculating calculate(i); }); };
Fix error in the apikey import task
from celery.decorators import task from eve_api.api_puller.accounts import import_eve_account from eve_api.app_defines import * from sso.tasks import update_user_access @task() def import_apikey(api_userid, api_key, user=None, force_cache=False): acc = import_eve_account(api_key, api_userid, force_cache=force_cache) donecorps = [] if acc and acc.api_status == API_STATUS_OK: if user and not acc.user: acc.user = user if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count(): donecorps = [] for char in acc.characters.filter(director=1): if not char.corporation.id in donecorps: #pull_corp_members(acc.api_key, acc.api_user_id, char.id) char.corporation.query_and_update_corp() donecorps.append(char.corporation.id) for char in acc.characters.all(): try: if char.corporation.id not in donecorps: char.corporation.query_and_update_corp() donecorps.append(char.corporation.id) except: continue acc.save() if acc.user: update_user_access.delay(user=acc.user) return acc
from celery.decorators import task from eve_api.api_puller.accounts import import_eve_account from eve_api.app_defines import * from sso.tasks import update_user_access @task() def import_apikey(api_userid, api_key, user=None, force_cache=False): log = import_apikey.get_logger() l.info("Importing %s/%s" % (api_userid, api_key)) acc = import_eve_account(api_key, api_userid, force_cache=force_cache) donecorps = [] if acc and acc.api_status == API_STATUS_OK: if user and not acc.user: acc.user = user if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count(): donecorps = [] for char in acc.characters.filter(director=1): if not char.corporation.id in donecorps: #pull_corp_members(acc.api_key, acc.api_user_id, char.id) char.corporation.query_and_update_corp() donecorps.append(char.corporation.id) for char in acc.characters.all(): try: if char.corporation.id not in donecorps: char.corporation.query_and_update_corp() donecorps.append(char.corporation.id) except: continue acc.save() if acc.user: update_user_access.delay(user=acc.user) return acc
Make library dependencies python-debian a bit more sane
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='debexpo', version="", #description='', #author='', #author_email='', #url='', install_requires=[ "Pylons>=1.0", "SQLAlchemy>=0.6", "Webhelpers>=0.6.1", "Babel>=0.9.6", "ZSI", "python-debian>=0.1.16", "soaplib==0.8.1"], packages=find_packages(exclude=['ez_setup']), include_package_data=True, test_suite='nose.collector', package_data={'debexpo': ['i18n/*/LC_MESSAGES/*.mo']}, message_extractors = {'debexpo': [ ('**.py', 'python', None), ('templates/**.mako', 'mako', None), ('public/**', 'ignore', None)]}, entry_points=""" [paste.app_factory] main = debexpo.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller [console_scripts] debexpo-importer = debexpo.scripts.debexpo_importer:main debexpo-user-importer = debexpo.scripts.user_importer:main """, )
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='debexpo', version="", #description='', #author='', #author_email='', #url='', install_requires=[ "Pylons>=1.0", "SQLAlchemy>=0.6", "Webhelpers>=0.6.1", "Babel>=0.9.6", "ZSI", "python-debian==0.1.16", "soaplib==0.8.1"], packages=find_packages(exclude=['ez_setup']), include_package_data=True, test_suite='nose.collector', package_data={'debexpo': ['i18n/*/LC_MESSAGES/*.mo']}, message_extractors = {'debexpo': [ ('**.py', 'python', None), ('templates/**.mako', 'mako', None), ('public/**', 'ignore', None)]}, entry_points=""" [paste.app_factory] main = debexpo.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller [console_scripts] debexpo-importer = debexpo.scripts.debexpo_importer:main debexpo-user-importer = debexpo.scripts.user_importer:main """, )
Use nifty filter widget for selecting questions for an assignment.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): filter_horizontal = ['questions']
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Main image or video'), {'fields': ['primary_image', 'primary_video_url']}), (_('Secondary image or video'), { 'fields': ['secondary_image', 'secondary_video_url'], 'classes': ['collapse'], 'description': _( 'Choose either a video or image to include on the first page of the question, ' 'where students select concept tags. This is only used if you want the question ' 'to be hidden when students select concept tags; instead, a preliminary video or ' 'image can be displayed. The main question image will be displayed on all ' 'subsequent pages.' ), }), (_('Answers'), {'fields': [ 'answer_style', 'answer_num_choices', 'correct_answer', 'second_best_answer' ]}), (None, {'fields': ['example_rationale']}), ] @admin.register(models.Assignment) class AssignmentAdmin(admin.ModelAdmin): pass
Add the package template data to the egg This adds some extra files that are needed at run time to the packaged egg.
from setuptools import setup, find_packages import codecs import os.path as path # buildout build system # http://www.buildout.org/en/latest/docs/tutorial.html # setup() documentation: # http://python-packaging-user-guide.readthedocs.org/en/latest/distributing/#setup-py cwd = path.dirname(__file__) longdesc = codecs.open(path.join(cwd, 'README.md'), 'r', 'ascii').read() name = 'son' setup( name=name, license='To be determined', version='0.0.1', url='https://github.com/sonata-nfv/son-cli', author_email='[email protected]', long_description=longdesc, package_dir={'': 'src'}, packages=find_packages('src'), # dependency resolution namespace_packages=['son',], include_package_data=True, package_data= { 'son': ['package/templates/*', 'workspace/samples/*'] }, install_requires=['setuptools', 'pyaml', 'jsonschema', 'validators', 'requests'], zip_safe=False, entry_points={ 'console_scripts': [ 'son-workspace=son.workspace.workspace:main', 'son-package=son.package.package:main', 'son-push=son.push.push:main' ], }, test_suite='son' #test_suite='son.workspace.tests.TestSample.main' )
from setuptools import setup, find_packages import codecs import os.path as path # buildout build system # http://www.buildout.org/en/latest/docs/tutorial.html # setup() documentation: # http://python-packaging-user-guide.readthedocs.org/en/latest/distributing/#setup-py cwd = path.dirname(__file__) longdesc = codecs.open(path.join(cwd, 'README.md'), 'r', 'ascii').read() name = 'son' setup( name=name, license='To be determined', version='0.0.1', url='https://github.com/sonata-nfv/son-cli', author_email='[email protected]', long_description=longdesc, package_dir={'': 'src'}, packages=find_packages('src'), # dependency resolution namespace_packages=['son',], include_package_data=True, package_data= { 'son': ['workspace/samples/*'] }, install_requires=['setuptools', 'pyaml', 'jsonschema', 'validators', 'requests'], zip_safe=False, entry_points={ 'console_scripts': [ 'son-workspace=son.workspace.workspace:main', 'son-package=son.package.package:main', 'son-push=son.push.push:main' ], }, test_suite='son' #test_suite='son.workspace.tests.TestSample.main' )
Remove side effect when booting middleware stack See #64
package com.vtence.molecule; import com.vtence.molecule.middlewares.NotFound; import com.vtence.molecule.middlewares.URLMap; import java.util.function.Consumer; public class MiddlewareStack { private Middleware pipeline = Middleware.identity(); private URLMap map; private Application runner; private Consumer<Application> warmup; public MiddlewareStack use(Middleware middleware) { if (map != null) { pipeline = pipeline.andThen(map); map = null; } pipeline = pipeline.andThen(middleware); return this; } public MiddlewareStack mount(String path, Application app) { if (map == null) { map = new URLMap(); } map.mount(path, app); return this; } public MiddlewareStack warmup(Consumer<Application> warmup) { this.warmup = warmup; return this; } public MiddlewareStack run(Application runner) { this.runner = runner; return this; } public Application boot() { if (map == null && runner == null) { throw new IllegalStateException("No app or mount points defined"); } Middleware chain = map != null ? pipeline.andThen(map) : pipeline; Application app = chain.then(runner != null ? runner : new NotFound()); if (warmup != null) warmup.accept(app); return app; } }
package com.vtence.molecule; import com.vtence.molecule.middlewares.NotFound; import com.vtence.molecule.middlewares.URLMap; import java.util.function.Consumer; public class MiddlewareStack { private Middleware pipeline = Middleware.identity(); private URLMap map; private Application runner; private Consumer<Application> warmup; public MiddlewareStack use(Middleware middleware) { if (map != null) { pipeline = pipeline.andThen(map); map = null; } pipeline = pipeline.andThen(middleware); return this; } public MiddlewareStack mount(String path, Application app) { if (map == null) { map = new URLMap(); } map.mount(path, app); return this; } public MiddlewareStack warmup(Consumer<Application> warmup) { this.warmup = warmup; return this; } public MiddlewareStack run(Application runner) { this.runner = runner; return this; } public Application boot() { if (map == null && runner == null) { throw new IllegalStateException("No app or mount points defined"); } if (map != null) { pipeline = pipeline.andThen(map); } Application app = pipeline.then(runner != null ? runner : new NotFound()); if (warmup != null) warmup.accept(app); return app; } }
Update to rawurlencode / rawurldecode Due to [this](https://github.com/paypal/ipn-code-samples/issues/51), the listener will *always* return INVALID unless `raw` methods are used for encoding / decoding.
<?php namespace Mdb\PayPal\Ipn; class Message { /** * @var array */ private $data; /** * @param array|string $data */ public function __construct($data) { if (!is_array($data)) { $data = $this->extractDataFromRawPostDataString($data); } $this->data = $data; } /** * @param string $key * * @return string */ public function get($key) { $value = ''; if (isset($this->data[$key])) { $value = $this->data[$key]; } return $value; } /** * @return array */ public function getAll() { return $this->data; } /** * @return string */ public function __toString() { $str = ''; foreach ($this->data as $k => $v) { $str .= sprintf('%s=%s&', $k, rawurlencode($v)); } return rtrim($str, '&'); } /** * @param string $rawPostDataString * * @return array */ private function extractDataFromRawPostDataString($rawPostDataString) { $data = array(); $keyValuePairs = preg_split('/&/', $rawPostDataString, null, PREG_SPLIT_NO_EMPTY); foreach ($keyValuePairs as $keyValuePair) { list($k, $v) = explode('=', $keyValuePair); $data[$k] = rawurldecode($v); } return $data; } }
<?php namespace Mdb\PayPal\Ipn; class Message { /** * @var array */ private $data; /** * @param array|string $data */ public function __construct($data) { if (!is_array($data)) { $data = $this->extractDataFromRawPostDataString($data); } $this->data = $data; } /** * @param string $key * * @return string */ public function get($key) { $value = ''; if (isset($this->data[$key])) { $value = $this->data[$key]; } return $value; } /** * @return array */ public function getAll() { return $this->data; } /** * @return string */ public function __toString() { $str = ''; foreach ($this->data as $k => $v) { $str .= sprintf('%s=%s&', $k, urlencode($v)); } return rtrim($str, '&'); } /** * @param string $rawPostDataString * * @return array */ private function extractDataFromRawPostDataString($rawPostDataString) { $data = array(); $keyValuePairs = preg_split('/&/', $rawPostDataString, null, PREG_SPLIT_NO_EMPTY); foreach ($keyValuePairs as $keyValuePair) { list($k, $v) = explode('=', $keyValuePair); $data[$k] = urldecode($v); } return $data; } }
Store --keep-publish value in options['publish'] (duh)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ import logging from django.core.management import call_command from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand logger = logging.getLogger(__name__) class Command(updatecommand): """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages' def add_arguments(self, parser): """ Adds custom arguments specific to this command. """ super(Command, self).add_arguments(parser) parser.add_argument( "--publish", action="store_true", dest="publish", default=False, help="Publish baked content" ) def handle(self, *args, **options): """ Make it happen. """ super(Command, self).handle(*args, **options) self.header('Creating latest file links') call_command('createlatestlinks') self.header('Baking downloads-website content') call_command('build') if options['publish']: self.header('Publishing baked content to S3 bucket.') call_command('publish') self.success("Done!")
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ import logging from django.core.management import call_command from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand logger = logging.getLogger(__name__) class Command(updatecommand): """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages' def add_arguments(self, parser): """ Adds custom arguments specific to this command. """ super(Command, self).add_arguments(parser) parser.add_argument( "--publish", action="store_true", dest="keep_files", default=False, help="Publish baked content" ) def handle(self, *args, **options): """ Make it happen. """ super(Command, self).handle(*args, **options) self.header('Creating latest file links') call_command('createlatestlinks') self.header('Baking downloads-website content') call_command('build') if options['publish']: self.header('Publishing baked content to S3 bucket.') call_command('publish') self.success("Done!")
Rename the WebBridge payload property: date -> time
package plugins.webbridge.api; import logbook.api.APIListenerSpi; import logbook.proxy.RequestMetaData; import logbook.proxy.ResponseMetaData; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import plugins.webbridge.bean.WebBridgeConfig; import javax.json.Json; import javax.json.JsonObject; import java.util.Date; public class WebBridgeListener implements APIListenerSpi { private static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); private OkHttpClient client = new OkHttpClient(); @Override public void accept(JsonObject jsonObject, RequestMetaData requestMetaData, ResponseMetaData responseMetaData) { WebBridgeConfig config = WebBridgeConfig.get(); if (!config.isBridgeEnabled()) { return; } String url = "http://" + config.getBridgeHost() + ":" + config.getBridgePort() + "/pub"; RequestBody body = RequestBody.create(Json.createObjectBuilder() .add("uri", requestMetaData.getRequestURI()) .add("time", new Date().getTime()) .add("body", jsonObject) .build().toString(), JSON); Request request = new Request.Builder() .url(url) .post(body) .build(); try { this.client.newCall(request).execute(); } catch (Exception e) { e.printStackTrace(); } } }
package plugins.webbridge.api; import logbook.api.APIListenerSpi; import logbook.proxy.RequestMetaData; import logbook.proxy.ResponseMetaData; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import plugins.webbridge.bean.WebBridgeConfig; import javax.json.Json; import javax.json.JsonObject; import java.util.Date; public class WebBridgeListener implements APIListenerSpi { private static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); private OkHttpClient client = new OkHttpClient(); @Override public void accept(JsonObject jsonObject, RequestMetaData requestMetaData, ResponseMetaData responseMetaData) { WebBridgeConfig config = WebBridgeConfig.get(); if (!config.isBridgeEnabled()) { return; } RequestBody body = RequestBody.create(Json.createObjectBuilder() .add("uri", requestMetaData.getRequestURI()) .add("date", new Date().getTime()) .add("body", jsonObject) .build().toString(), JSON); String url = "http://" + config.getBridgeHost() + ":" + config.getBridgePort() + "/pub"; Request request = new Request.Builder() .url(url) .post(body) .build(); try { this.client.newCall(request).execute(); } catch (Exception e) { e.printStackTrace(); } } }
Remove hard coded socket provider class.
/* * Copyright: 2012, V. Glenn Tarcea * MIT License Applies */ angular.module('AngularStomp', []). factory('ngstomp', function($rootScope) { var stompClient = {}; function NGStomp(url) { this.stompClient = Stomp.client(url); } NGStomp.prototype.subscribe = function(queue, callback) { this.stompClient.subscribe(queue, function() { var args = arguments; $rootScope.$apply(function() { callback(args[0]); }) }) } NGStomp.prototype.send = function(queue, headers, data) { this.stompClient.send(queue, headers, data); } NGStomp.prototype.connect = function(user, password, on_connect, on_error, vhost) { this.stompClient.connect(user, password, function(frame) { $rootScope.$apply(function() { on_connect.apply(stompClient, frame); }) }, function(frame) { $rootScope.$apply(function() { on_error.apply(stompClient, frame); }) }, vhost); } NGStomp.prototype.disconnect = function(callback) { this.stompClient.disconnect(function() { var args = arguments; $rootScope.$apply(function() { callback.apply(args); }) }) } return function(url) { return new NGStomp(url); } });
/* * Copyright: 2012, V. Glenn Tarcea * MIT License Applies */ angular.module('AngularStomp', []). factory('ngstomp', function($rootScope) { Stomp.WebSocketClass = SockJS; var stompClient = {}; function NGStomp(url) { this.stompClient = Stomp.client(url); } NGStomp.prototype.subscribe = function(queue, callback) { this.stompClient.subscribe(queue, function() { var args = arguments; $rootScope.$apply(function() { callback(args[0]); }) }) } NGStomp.prototype.send = function(queue, headers, data) { this.stompClient.send(queue, headers, data); } NGStomp.prototype.connect = function(user, password, on_connect, on_error, vhost) { this.stompClient.connect(user, password, function(frame) { $rootScope.$apply(function() { on_connect.apply(stompClient, frame); }) }, function(frame) { $rootScope.$apply(function() { on_error.apply(stompClient, frame); }) }, vhost); } NGStomp.prototype.disconnect = function(callback) { this.stompClient.disconnect(function() { var args = arguments; $rootScope.$apply(function() { callback.apply(args); }) }) } return function(url) { return new NGStomp(url); } });
Fix potential NPE with command context
package top.quantic.sentry.discord.core; import joptsimple.OptionSet; import sx.blah.discord.handle.obj.IMessage; public class CommandContext { private IMessage message; private String prefix; private Command command; private String[] args; private OptionSet optionSet; public IMessage getMessage() { return message; } public void setMessage(IMessage message) { this.message = message; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public Command getCommand() { return command; } public void setCommand(Command command) { this.command = command; } public String[] getArgs() { return args; } public void setArgs(String[] args) { this.args = args; } public OptionSet getOptionSet() { return optionSet; } public void setOptionSet(OptionSet optionSet) { this.optionSet = optionSet; } public String getContentAfterPrefix() { if (message == null || prefix == null) { return null; } String content = message.getContent(); if (!content.contains(prefix)) { return content; } return content.substring(prefix.length()); } public String getContentAfterCommand() { String withCommand = getContentAfterPrefix(); if (withCommand == null) { return ""; } return withCommand.contains(" ") ? withCommand.split(" ", 2)[1] : ""; } }
package top.quantic.sentry.discord.core; import joptsimple.OptionSet; import sx.blah.discord.handle.obj.IMessage; public class CommandContext { private IMessage message; private String prefix; private Command command; private String[] args; private OptionSet optionSet; public IMessage getMessage() { return message; } public void setMessage(IMessage message) { this.message = message; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public Command getCommand() { return command; } public void setCommand(Command command) { this.command = command; } public String[] getArgs() { return args; } public void setArgs(String[] args) { this.args = args; } public OptionSet getOptionSet() { return optionSet; } public void setOptionSet(OptionSet optionSet) { this.optionSet = optionSet; } public String getContentAfterPrefix() { if (message == null || prefix == null) { return null; } String content = message.getContent(); if (!content.contains(prefix)) { return content; } return content.substring(prefix.length()); } public String getContentAfterCommand() { String withCommand = getContentAfterPrefix(); return withCommand.contains(" ") ? withCommand.split(" ", 2)[1] : ""; } }
Handle situation if timer is already running.
#!/usr/bin/env python from Axon.Component import component from threading import Timer class TimerMixIn(object): def __init__(self, *argl, **argd): super(TimerMixIn,self).__init__(*argl,**argd) self.timer = None self.timerSuccess = True def startTimer(self, secs): if self.timer is not None: self.cancelTimer() self.timer = Timer(secs, self.__handleTimerDone) self.timerSuccess = False self.timer.start() def cancelTimer(self): if self.timer is not None and self.timer: self.timer.cancel() self.timer = None self.timerSuccess = False def timerRunning(self): return self.timer is not None def timerWasCancelled(self): return not self.timerSuccess def __handleTimerDone(self): self.scheduler.wakeThread(self) self.timer = None self.timerSuccess = True if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleEchoer class TestComponent(TimerMixIn,component): def __init__(self): super(TestComponent,self).__init__() def main(self): count = 0 while True: self.startTimer(0.5) while self.timerRunning(): self.pause() yield 1 self.send(count, "outbox") count=count+1 Pipeline(TestComponent(),ConsoleEchoer()).run()
#!/usr/bin/env python from Axon.Component import component from threading import Timer class TimerMixIn(object): def __init__(self, *argl, **argd): super(TimerMixIn,self).__init__(*argl,**argd) self.timer = None self.timerSuccess = True def startTimer(self, secs): self.timer = Timer(secs, self.__handleTimerDone) self.timerSuccess = False self.timer.start() def cancelTimer(self): if self.timer is not None and self.timer: self.timer.cancel() self.timer = None self.timerSuccess = False def timerRunning(self): return self.timer is not None def timerWasCancelled(self): return not self.timerSuccess def __handleTimerDone(self): self.scheduler.wakeThread(self) self.timer = None self.timerSuccess = True if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Console import ConsoleEchoer class TestComponent(TimerMixIn,component): def __init__(self): super(TestComponent,self).__init__() def main(self): count = 0 while True: self.startTimer(0.5) while self.timerRunning(): self.pause() yield 1 self.send(count, "outbox") count=count+1 Pipeline(TestComponent(),ConsoleEchoer()).run()
Add alias for the extension path
import path from 'path'; import webpack from 'webpack'; const srcPath = path.join(__dirname, '../src/browser/'); const baseConfig = ({input, output = {}, globals = {}, plugins, loaders, entry = []}) => ({ entry: input || { background: [ `${srcPath}extension/background/index`, ...entry ], window: [ `${srcPath}window/index`, ...entry ], popup: [ `${srcPath}extension/popup/index`, ...entry ], inject: [ `${srcPath}extension/inject/index`, ...entry ] }, output: { filename: '[name].bundle.js', chunkFilename: '[id].chunk.js', ...output }, plugins: [ new webpack.DefinePlugin(globals), ...(plugins ? plugins : [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ comments: false, compressor: { warnings: false } }) ]) ], resolve: { alias: { app: path.join(__dirname, '../src/app'), extension: path.join(__dirname, '../src/browser/extension') }, extensions: ['', '.js'] }, module: { loaders: [ ...(loaders ? loaders : [{ test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ }]), { test: /\.css?$/, loaders: ['style', 'raw'] } ] } }); export default baseConfig;
import path from 'path'; import webpack from 'webpack'; const srcPath = path.join(__dirname, '../src/browser/'); const baseConfig = ({input, output = {}, globals = {}, plugins, loaders, entry = []}) => ({ entry: input || { background: [ `${srcPath}extension/background/index`, ...entry ], window: [ `${srcPath}window/index`, ...entry ], popup: [ `${srcPath}extension/popup/index`, ...entry ], inject: [ `${srcPath}extension/inject/index`, ...entry ] }, output: { filename: '[name].bundle.js', chunkFilename: '[id].chunk.js', ...output }, plugins: [ new webpack.DefinePlugin(globals), ...(plugins ? plugins : [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ comments: false, compressor: { warnings: false } }) ]) ], resolve: { alias: {app: path.join(__dirname, '../src/app')}, extensions: ['', '.js'] }, module: { loaders: [ ...(loaders ? loaders : [{ test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ }]), { test: /\.css?$/, loaders: ['style', 'raw'] } ] } }); export default baseConfig;
Fix for case when something is deleted in the left side and it is also deleted in the right side without refresh
(function() { "use strict"; angular .module('awesome-app.search') .controller('SearchCtrl', SearchCtrl); SearchCtrl.$inject = ['$scope', 'SearchService']; function SearchCtrl($scope, SearchService) { $scope.$on('chosenTeamMember', function(event, worker) { $scope.teamMembers = angular.copy($scope.teamMembers); $scope.teamMembers.push( { name: worker.name, age: worker.age, job: worker.job, id: worker.id, grade: worker.grade } ); $scope.worker = ''; }); $scope.$on('removeTeamMember', function(event, members) { $scope.teamMembers = members; }); $scope.refreshTeamList = function() { $scope.$emit('saveTeamMembers', $scope.teamMembers); }; $scope.getTypeaheadData = function() { SearchService.getTypeaheadData('staff.json').then(function(data) { $scope.items = data; }); }; $scope.removeTeamMember = function(index) { $scope.teamMembers = angular.copy($scope.teamMembers); $scope.teamMembers.splice(index, 1); }; $scope.getTypeaheadData(); } })();
(function() { "use strict"; angular .module('awesome-app.search') .controller('SearchCtrl', SearchCtrl); SearchCtrl.$inject = ['$scope', 'SearchService']; function SearchCtrl($scope, SearchService) { $scope.$on('chosenTeamMember', function(event, worker) { $scope.teamMembers = angular.copy($scope.teamMembers); $scope.teamMembers.push( { name: worker.name, age: worker.age, job: worker.job, id: worker.id, grade: worker.grade } ); $scope.worker = ''; }); $scope.$on('removeTeamMember', function(event, members) { $scope.teamMembers = members; }); $scope.refreshTeamList = function() { $scope.$emit('saveTeamMembers', $scope.teamMembers); }; $scope.getTypeaheadData = function() { SearchService.getTypeaheadData('staff.json').then(function(data) { $scope.items = data; }); }; $scope.removeTeamMember = function(index) { $scope.teamMembers.splice(index, 1); }; $scope.getTypeaheadData(); } })();
Remove upper-bound on required Sphinx version
#!/usr/bin/env python from setuptools import setup # Version info -- read without importing _locals = {} with open('releases/_version.py') as fp: exec(fp.read(), None, _locals) version = _locals['__version__'] setup( name='releases', version=version, description='A Sphinx extension for changelog manipulation', author='Jeff Forcier', author_email='[email protected]', url='https://github.com/bitprophet/releases', packages=['releases'], install_requires=['semantic_version<3.0', 'sphinx>=1.3'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Unix', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development', 'Topic :: Software Development :: Documentation', 'Topic :: Documentation', 'Topic :: Documentation :: Sphinx', ], )
#!/usr/bin/env python from setuptools import setup # Version info -- read without importing _locals = {} with open('releases/_version.py') as fp: exec(fp.read(), None, _locals) version = _locals['__version__'] setup( name='releases', version=version, description='A Sphinx extension for changelog manipulation', author='Jeff Forcier', author_email='[email protected]', url='https://github.com/bitprophet/releases', packages=['releases'], install_requires=['semantic_version<3.0', 'sphinx>=1.3,<1.5'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Unix', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development', 'Topic :: Software Development :: Documentation', 'Topic :: Documentation', 'Topic :: Documentation :: Sphinx', ], )
Remove shell requirement to avoid escaping
import sublime_plugin from ..libs.global_vars import * from ..libs import cli class TypescriptBuildCommand(sublime_plugin.WindowCommand): def run(self): if get_node_path() is None: print("Cannot found node. Build cancelled.") return file_name = self.window.active_view().file_name() project_info = cli.service.project_info(file_name) if project_info["success"]: if "configFileName" in project_info["body"]: tsconfig_dir = dirname(project_info["body"]["configFileName"]) self.window.run_command("exec", { "cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir], "file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$" }) else: sublime.active_window().show_input_panel( "Build parameters: ", "", # initial text self.compile_inferred_project, None, # on change None # on cancel ) def compile_inferred_project(self, params=""): file_name = self.window.active_view().file_name() cmd = [get_node_path(), TSC_PATH, file_name] print(cmd) if params != "": cmd.extend(params.split(' ')) self.window.run_command("exec", { "cmd": cmd, "file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$" })
import sublime_plugin from ..libs.global_vars import * from ..libs import cli class TypescriptBuildCommand(sublime_plugin.WindowCommand): def run(self): if get_node_path() is None: print("Cannot found node. Build cancelled.") return file_name = self.window.active_view().file_name() project_info = cli.service.project_info(file_name) if project_info["success"]: if "configFileName" in project_info["body"]: tsconfig_dir = dirname(project_info["body"]["configFileName"]) self.window.run_command("exec", { "cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir], "file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$", "shell": True }) else: sublime.active_window().show_input_panel( "Build parameters: ", "", # initial text self.compile_inferred_project, None, # on change None # on cancel ) def compile_inferred_project(self, params=""): file_name = self.window.active_view().file_name() cmd = [get_node_path(), TSC_PATH, file_name] if params != "": cmd.extend(params.split(' ')) self.window.run_command("exec", { "cmd": cmd, "file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$", "shell": True })
Throw an exception if no response in http tuple
<?php declare(strict_types=1); namespace Behapi\HttpHistory; use IteratorAggregate; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Http\Client\Common\Plugin\Journal; use Http\Client\Exception; use Http\Client\Exception\HttpException; use function end; use function reset; use function count; final class History implements Journal, IteratorAggregate { /** @var Tuple[] */ private $tuples = []; /** {@inheritDoc} */ public function addSuccess(RequestInterface $request, ResponseInterface $response) { $this->tuples[] = new Tuple($request, $response); } /** {@inheritDoc} */ public function addFailure(RequestInterface $request, Exception $exception) { $response = $exception instanceof HttpException ? $exception->getResponse() : null; $this->tuples[] = new Tuple($request, $response); } public function getLastResponse(): ResponseInterface { if (1 > count($this->tuples)) { throw new NoResponse; } /** @var Tuple $tuple */ $tuple = end($this->tuples); reset($this->tuples); $response = $tuple->getResponse(); if (null === $response) { throw new NoResponse; } return $response; } /** @return iterable<Tuple> */ public function getIterator(): iterable { yield from $this->tuples; return count($this->tuples); } public function reset(): void { $this->tuples = []; } }
<?php declare(strict_types=1); namespace Behapi\HttpHistory; use IteratorAggregate; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Http\Client\Common\Plugin\Journal; use Http\Client\Exception; use Http\Client\Exception\HttpException; use function end; use function reset; use function count; final class History implements Journal, IteratorAggregate { /** @var Tuple[] */ private $tuples = []; /** {@inheritDoc} */ public function addSuccess(RequestInterface $request, ResponseInterface $response) { $this->tuples[] = new Tuple($request, $response); } /** {@inheritDoc} */ public function addFailure(RequestInterface $request, Exception $exception) { $response = $exception instanceof HttpException ? $exception->getResponse() : null; $this->tuples[] = new Tuple($request, $response); } public function getLastResponse(): ResponseInterface { if (1 > count($this->tuples)) { throw new NoResponse; } /** @var Tuple $tuple */ $tuple = end($this->tuples); reset($this->tuples); return $tuple->getResponse(); } /** @return iterable<Tuple> */ public function getIterator(): iterable { yield from $this->tuples; return count($this->tuples); } public function reset(): void { $this->tuples = []; } }
Increment version to trigger auto build
"""Config for PyPI.""" from setuptools import find_packages from setuptools import setup setup( author='Kyle P. Johnson', author_email='[email protected]', classifiers=[ 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: Chinese (Traditional)', 'Natural Language :: English', 'Natural Language :: Greek', 'Natural Language :: Latin', 'Operating System :: POSIX', 'Programming Language :: Python :: 3.6', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Text Processing', 'Topic :: Text Processing :: General', 'Topic :: Text Processing :: Linguistic', ], description='NLP for the ancient world', install_requires=['gitpython', 'nltk', 'python-crfsuite', 'pyuca', 'pyyaml', 'regex', 'whoosh'], keywords=['nlp', 'nltk', 'greek', 'latin', 'chinese', 'sanskrit', 'pali', 'tibetan'], license='MIT', long_description='The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.', # pylint: disable=C0301, name='cltk', packages=find_packages(), url='https://github.com/cltk/cltk', version='0.1.65', zip_safe=True, test_suite='cltk.tests.test_cltk', )
"""Config for PyPI.""" from setuptools import find_packages from setuptools import setup setup( author='Kyle P. Johnson', author_email='[email protected]', classifiers=[ 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: Chinese (Traditional)', 'Natural Language :: English', 'Natural Language :: Greek', 'Natural Language :: Latin', 'Operating System :: POSIX', 'Programming Language :: Python :: 3.6', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Text Processing', 'Topic :: Text Processing :: General', 'Topic :: Text Processing :: Linguistic', ], description='NLP for the ancient world', install_requires=['gitpython', 'nltk', 'python-crfsuite', 'pyuca', 'pyyaml', 'regex', 'whoosh'], keywords=['nlp', 'nltk', 'greek', 'latin', 'chinese', 'sanskrit', 'pali', 'tibetan'], license='MIT', long_description='The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.', # pylint: disable=C0301, name='cltk', packages=find_packages(), url='https://github.com/cltk/cltk', version='0.1.64', zip_safe=True, test_suite='cltk.tests.test_cltk', )
Use StringBuilder to constructo the longcat body, as it can be very loooooooooong
package longcat; public class Longcat { // Source: http://encyclopediadramatica.com/Longcat public static final String HEAD_ROW = "" + " /\\___/\\ \n" + " / \\ \n" + " | # # | \n" + " \\ @ | \n" + " \\ _|_ / \n" + " / \\______ \n" + " / _______ ___ \\ \n" + " |_____ \\ \\__/ \n" + " | \\__/ \n"; public static final String BODY_ROW = "" + " | | \n"; public static final String FEET_ROW = "" + " / \\ \n" + " / ____ \\ \n" + " | / \\ | \n" + " | | | | \n" + " / | | \\ \n" + " \\__/ \\__/ \n"; private final int bodySize; public Longcat(int bodySize) { this.bodySize = bodySize; } public String getBody() { StringBuilder body = new StringBuilder(); for (int i = 0; i < bodySize; i++) { body.append(BODY_ROW); } return body.toString(); } public String toString() { return HEAD_ROW + getBody() + FEET_ROW; } }
package longcat; public class Longcat { // Source: http://encyclopediadramatica.com/Longcat public static final String HEAD_ROW = "" + " /\\___/\\ \n" + " / \\ \n" + " | # # | \n" + " \\ @ | \n" + " \\ _|_ / \n" + " / \\______ \n" + " / _______ ___ \\ \n" + " |_____ \\ \\__/ \n" + " | \\__/ \n"; public static final String BODY_ROW = "" + " | | \n"; public static final String FEET_ROW = "" + " / \\ \n" + " / ____ \\ \n" + " | / \\ | \n" + " | | | | \n" + " / | | \\ \n" + " \\__/ \\__/ \n"; private final int bodySize; public Longcat(int bodySize) { this.bodySize = bodySize; } public String getBody() { String body = ""; for (int i = 0; i < bodySize; i++) { body += BODY_ROW; } return body; } public String toString() { return HEAD_ROW + getBody() + FEET_ROW; } }
Add ability to iterate over all currently loaded ports. This function provides a snapshot of ports and does not provide support to query ports that are still loading.
"""FreeBSD Ports.""" from __future__ import absolute_import __all__ = ["get_port", "get_ports", "ports"] class PortCache(object): """Caches created ports.""" def __init__(self): """Initialise port cache.""" self._ports = {} self._waiters = {} def __len__(self): return len(self._ports) def get_port(self, origin): """Get a port and callback with it.""" if origin in self._ports: from ..event import post_event from ..signal import Signal signal = Signal() post_event(signal.emit, self._ports[origin]) return signal else: if origin in self._waiters: return self._waiters[origin] else: from .mk import attr from ..signal import Signal signal = Signal() self._waiters[origin] = signal attr(origin).connect(self._attr) return signal def __iter__(self): return self._ports.values() def _attr(self, origin, attr): """Use attr to create a port.""" from .port import Port signal = self._waiters.pop(origin) if attr is None: port = origin else: port = Port(origin, attr) self._ports[origin] = port signal.emit(port) _cache = PortCache() ports = _cache.__len__ get_port = _cache.get_port get_ports = _cache.__iter__
"""FreeBSD Ports.""" from __future__ import absolute_import __all__ = ["get_port"] class PortCache(object): """Caches created ports.""" def __init__(self): """Initialise port cache.""" self._ports = {} self._waiters = {} def __len__(self): return len(self._ports) def get_port(self, origin): """Get a port and callback with it.""" if origin in self._ports: from ..event import post_event from ..signal import Signal signal = Signal() post_event(signal.emit, self._ports[origin]) return signal else: if origin in self._waiters: return self._waiters[origin] else: from .mk import attr from ..signal import Signal signal = Signal() self._waiters[origin] = signal attr(origin).connect(self._attr) return signal def _attr(self, origin, attr): """Use attr to create a port.""" from .port import Port signal = self._waiters.pop(origin) if attr is None: port = origin else: port = Port(origin, attr) self._ports[origin] = port signal.emit(port) _cache = PortCache() ports = _cache.__len__ get_port = _cache.get_port
Remove the expectedFailure decorator. The test has been passing for some time now. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@138452 91177308-0d34-0410-b5e6-96231b3b80d8
""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 @unittest2.expectedFailure def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
Fix placeholder text in mithril example
var app = app || {}; (function () { 'use strict'; app.watchInput = function (ontype, onenter, onescape) { return function (e) { ontype(e) if (e.keyCode == app.ENTER_KEY) onenter() if (e.keyCode == app.ESC_KEY) onescape() } }; app.view = function (ctrl) { return [ m('header.header', [ m('h1', 'todos'), m('input.new-todo[placeholder="Need something done?"]', { onkeypress: app.watchInput( m.withAttr('value', ctrl.title), ctrl.add.bind(ctrl, ctrl.title), ctrl.clearTitle.bind(ctrl) ), value: ctrl.title() }) ]), m('section.main', [ m('input.toggle-all[type=checkbox]'), m('ul.todo-list', [ ctrl.list.filter(ctrl.isVisible.bind(ctrl)).map(function (task, index) { return m('li', { class: task.completed() ? 'completed' : '' }, [ m('.view', [ m('input.toggle[type=checkbox]', { onclick: m.withAttr('checked', task.completed), checked: task.completed() }), m('label', task.title()), m('button.destroy', { onclick: ctrl.remove.bind(ctrl, index) }) ]), m('input.edit') ]) }) ]) ]), ctrl.list.length == 0 ? '' : app.footer(ctrl) ]; }; })();
var app = app || {}; (function () { 'use strict'; app.watchInput = function (ontype, onenter, onescape) { return function (e) { ontype(e) if (e.keyCode == app.ENTER_KEY) onenter() if (e.keyCode == app.ESC_KEY) onescape() } }; app.view = function (ctrl) { return [ m('header.header', [ m('h1', 'todos'), m('input.new-todo[placeholder="Get something done? needs to be done?"]', { onkeypress: app.watchInput( m.withAttr('value', ctrl.title), ctrl.add.bind(ctrl, ctrl.title), ctrl.clearTitle.bind(ctrl) ), value: ctrl.title() }) ]), m('section.main', [ m('input.toggle-all[type=checkbox]'), m('ul.todo-list', [ ctrl.list.filter(ctrl.isVisible.bind(ctrl)).map(function (task, index) { return m('li', { class: task.completed() ? 'completed' : '' }, [ m('.view', [ m('input.toggle[type=checkbox]', { onclick: m.withAttr('checked', task.completed), checked: task.completed() }), m('label', task.title()), m('button.destroy', { onclick: ctrl.remove.bind(ctrl, index) }) ]), m('input.edit') ]) }) ]) ]), ctrl.list.length == 0 ? '' : app.footer(ctrl) ]; }; })();
Use the correct UMD pattern
(function (root, factory) { if (typeof define === 'function' && define.amd) define([], factory); else if (typeof exports === 'object') module.exports = factory(); else root.Inverse = factory(); })(this, function () { 'use strict'; var Inverse = function() { this._boundCallbacks = {}; this._singletonCallbacks = {}; this._instantiatedSingletons = {}; this._registeredObjects = {}; }; var proto = Inverse.prototype; proto.make = function(name) { if (this._registeredObjects.hasOwnProperty(name)) { return this._registeredObjects[name]; } if (this._singletonCallbacks.hasOwnProperty(name)) { if (!this._instantiatedSingletons.hasOwnProperty(name)) { this._instantiatedSingletons[name] = this._singletonCallbacks[name](this); } return this._instantiatedSingletons[name]; } if (this._boundCallbacks.hasOwnProperty(name)) { return this._boundCallbacks[name](this); } return null; }; proto.bind = function(name, callback) { this._boundCallbacks[name] = callback; }; proto.singleton = function(name, callback) { this._singletonCallbacks[name] = callback; }; proto.register = function(name, object) { this._registeredObjects[name] = object; }; return Inverse; });
(function (root, factory) { if (typeof define === 'function' && define.amd) define(['exports'], factory); else if (typeof exports === 'object') factory(exports); else factory(root.Inverse = {}); })(this, function (exports) { 'use strict'; var Inverse = function() { this._boundCallbacks = {}; this._singletonCallbacks = {}; this._instantiatedSingletons = {}; this._registeredObjects = {}; }; var proto = Inverse.prototype; proto.make = function(name) { if (this._registeredObjects.hasOwnProperty(name)) { return this._registeredObjects[name]; } if (this._singletonCallbacks.hasOwnProperty(name)) { if (!this._instantiatedSingletons.hasOwnProperty(name)) { this._instantiatedSingletons[name] = this._singletonCallbacks[name](this); } return this._instantiatedSingletons[name]; } if (this._boundCallbacks.hasOwnProperty(name)) { return this._boundCallbacks[name](this); } return null; }; proto.bind = function(name, callback) { this._boundCallbacks[name] = callback; }; proto.singleton = function(name, callback) { this._singletonCallbacks[name] = callback; }; proto.register = function(name, object) { this._registeredObjects[name] = object; }; });
Update the hour list if the day start, end or interval changes
'use strict'; var angular = require('angular'); angular .module('mwl.calendar') .controller('MwlCalendarHourListCtrl', function($scope, moment, calendarConfig, calendarHelper) { var vm = this; var dayViewStart, dayViewEnd; function updateDays() { dayViewStart = moment($scope.dayViewStart || '00:00', 'HH:mm'); dayViewEnd = moment($scope.dayViewEnd || '23:00', 'HH:mm'); vm.dayViewSplit = parseInt($scope.dayViewSplit); vm.hours = []; var dayCounter = moment(dayViewStart); for (var i = 0; i <= dayViewEnd.diff(dayViewStart, 'hours'); i++) { vm.hours.push({ label: calendarHelper.formatDate(dayCounter, calendarConfig.dateFormats.hour) }); dayCounter.add(1, 'hour'); } } var originalLocale = moment.locale(); $scope.$on('calendar.refreshView', function() { if (originalLocale !== moment.locale()) { originalLocale = moment.locale(); updateDays(); } }); $scope.$watch(function() { return $scope.dayViewStart + $scope.dayViewEnd + $scope.dayViewSplit; }, function() { updateDays(); }); updateDays(); }) .directive('mwlCalendarHourList', function() { return { restrict: 'EA', template: require('./../templates/calendarHourList.html'), controller: 'MwlCalendarHourListCtrl as vm', scope: { dayViewStart: '=', dayViewEnd: '=', dayViewSplit: '=' } }; });
'use strict'; var angular = require('angular'); angular .module('mwl.calendar') .controller('MwlCalendarHourListCtrl', function($scope, moment, calendarConfig, calendarHelper) { var vm = this; var dayViewStart, dayViewEnd; function updateDays() { dayViewStart = moment($scope.dayViewStart || '00:00', 'HH:mm'); dayViewEnd = moment($scope.dayViewEnd || '23:00', 'HH:mm'); vm.dayViewSplit = parseInt($scope.dayViewSplit); vm.hours = []; var dayCounter = moment(dayViewStart); for (var i = 0; i <= dayViewEnd.diff(dayViewStart, 'hours'); i++) { vm.hours.push({ label: calendarHelper.formatDate(dayCounter, calendarConfig.dateFormats.hour) }); dayCounter.add(1, 'hour'); } } var originalLocale = moment.locale(); $scope.$on('calendar.refreshView', function() { if (originalLocale !== moment.locale()) { originalLocale = moment.locale(); updateDays(); } }); updateDays(); }) .directive('mwlCalendarHourList', function() { return { restrict: 'EA', template: require('./../templates/calendarHourList.html'), controller: 'MwlCalendarHourListCtrl as vm', scope: { dayViewStart: '=', dayViewEnd: '=', dayViewSplit: '=' } }; });
Replace hardcoded indicator key with keySize dependent
import CSVReader from 'readers/csv/csv'; import { isNumber } from 'base/utils'; const CSVTimeInColumnsReader = CSVReader.extend({ _name: 'csv-time_in_columns', init(readerInfo) { this._super(readerInfo); }, load() { return this._super() .then((data) => { const [firstRow] = data; const [indicatorKey] = Object.keys(firstRow) .filter((key) => Number(key) != key) .slice(this.keySize, this.keySize + 1); const concepts = data.reduce((result, row) => { Object.keys(row).forEach((concept) => { concept = concept === indicatorKey ? row[indicatorKey] : concept; if (Number(concept) != concept && !result.includes(concept)) { result.push(concept); } }); return result; }, []).concat('time'); const indicators = concepts.slice(1, -1); const [entityDomain] = concepts; return data.reduce((result, row) => { Object.keys(row).forEach((key) => { if (![entityDomain, indicatorKey].includes(key)) { result.push( Object.assign({ [entityDomain]: row[entityDomain], time: key, }, indicators.reduce((result, indicator) => { result[indicator] = row[indicatorKey] === indicator ? row[key] : null; return result; }, {}) ) ); } }); return result; }, []); }); } }); export default CSVTimeInColumnsReader;
import CSVReader from 'readers/csv/csv'; import { isNumber } from 'base/utils'; const CSVTimeInColumnsReader = CSVReader.extend({ _name: 'csv-time_in_columns', init(readerInfo) { this._super(readerInfo); }, load() { return this._super() .then((data) => { const concepts = data.reduce((result, row) => { Object.keys(row).forEach(concept => { concept = concept === 'indicator' ? row.indicator : concept; if (Number(concept) != concept && !result.includes(concept)) { result.push(concept); } }); return result; }, []).concat('time'); const indicators = concepts.slice(1, -1); const [entityDomain] = concepts; return data.reduce((result, row) => { Object.keys(row).forEach((key) => { if (![entityDomain, 'indicator'].includes(key)) { result.push( Object.assign({ [entityDomain]: row[entityDomain], time: key, }, indicators.reduce((result, indicator) => { result[indicator] = row.indicator === indicator ? row[key] : null; return result; }, {}) ) ); } }); return result; }, []); }); } }); export default CSVTimeInColumnsReader;
Set Cython language_level to 3 when compiling for python3
#!/usr/bin/env python """ Setup script. Created on Oct 10, 2011 @author: tmetsch """ from distutils.core import setup from distutils.extension import Extension import sys try: from Cython.Build import build_ext, cythonize BUILD_EXTENSION = {'build_ext': build_ext} EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd", "dtrace_cython/consumer.pyx"], libraries=["dtrace"])], language_level=sys.version_info.major) except ImportError: BUILD_EXTENSION = {} EXT_MODULES = None print('WARNING: Cython seems not to be present. Currently you will only' ' be able to use the ctypes wrapper. Or you can install cython and' ' try again.') setup(name='python-dtrace', version='0.0.10', description='DTrace consumer for Python based on libdtrace. Use Python' + ' as DTrace Consumer and Provider! See the homepage for' + ' more information.', license='MIT', keywords='DTrace', url='http://tmetsch.github.com/python-dtrace/', packages=['dtrace_ctypes'], cmdclass=BUILD_EXTENSION, ext_modules=EXT_MODULES, classifiers=["Development Status :: 2 - Pre-Alpha", "Operating System :: OS Independent", "Programming Language :: Python" ])
#!/usr/bin/env python """ Setup script. Created on Oct 10, 2011 @author: tmetsch """ from distutils.core import setup from distutils.extension import Extension try: from Cython.Build import build_ext, cythonize BUILD_EXTENSION = {'build_ext': build_ext} EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd", "dtrace_cython/consumer.pyx"], libraries=["dtrace"])], language_level=2) except ImportError: BUILD_EXTENSION = {} EXT_MODULES = None print('WARNING: Cython seems not to be present. Currently you will only' ' be able to use the ctypes wrapper. Or you can install cython and' ' try again.') setup(name='python-dtrace', version='0.0.10', description='DTrace consumer for Python based on libdtrace. Use Python' + ' as DTrace Consumer and Provider! See the homepage for' + ' more information.', license='MIT', keywords='DTrace', url='http://tmetsch.github.com/python-dtrace/', packages=['dtrace_ctypes'], cmdclass=BUILD_EXTENSION, ext_modules=EXT_MODULES, classifiers=["Development Status :: 2 - Pre-Alpha", "Operating System :: OS Independent", "Programming Language :: Python" ])
Remove last slash from file path
from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] def record(self, measure: Measurement): line = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) print(line, end='\n') class FileRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] self.container = config['container'] self.extension = config['extension'] def record(self, measure: Measurement): log_entry = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) file_path = self.container + measure.device_id.split('/')[-1] + self.extension f = open(file_path, 'w') f.writelines([log_entry])
from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] def record(self, measure: Measurement): line = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) print(line, end='\n') class FileRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] self.container = config['container'] self.extension = config['extension'] def record(self, measure: Measurement): log_entry = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) file_path = self.container + measure.device_id.split('/')[-1] + '/' + self.extension f = open(file_path, 'w') f.writelines([log_entry])