text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
[fp/43524][FIX] Fix to default to global if null git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@43566 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ function wikiplugin_userlink_info() { return array( 'name' => tra('User Link'), 'documentation' => 'PluginUserlink', 'description' => tra('Display a link to a user\'s information page'), 'prefs' => array('wikiplugin_userlink'), 'icon' => 'img/icons/user_go.png', 'params' => array( 'user' => array( 'required' => false, 'name' => tra('User Name'), 'description' => tra('User account name (which can be an email address)'), 'filter' => 'xss', 'default' => '' ), ), ); } function wikiplugin_userlink($data, $params) { global $smarty, $user; $path = 'lib/smarty_tiki/modifier.userlink.php'; include_once($path); $func = 'smarty_modifier_userlink'; $content = $func(isset($params['user']) ? $params['user'] : $user, '', '', $data); return '~np~'.$content.'~/np~'; }
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ function wikiplugin_userlink_info() { return array( 'name' => tra('User Link'), 'documentation' => 'PluginUserlink', 'description' => tra('Display a link to a user\'s information page'), 'prefs' => array('wikiplugin_userlink'), 'icon' => 'img/icons/user_go.png', 'params' => array( 'user' => array( 'required' => false, 'name' => tra('User Name'), 'description' => tra('User account name (which can be an email address)'), 'filter' => 'xss', 'default' => '' ), ), ); } function wikiplugin_userlink($data, $params) { global $smarty; $path = 'lib/smarty_tiki/modifier.userlink.php'; include_once($path); $func = 'smarty_modifier_userlink'; $content = $func($params['user'], '', '', $data); return '~np~'.$content.'~/np~'; }
Add **kwargs to ActionViewmixin.post() handler Details: #359
from django.contrib.auth import user_logged_in, user_logged_out, login, logout from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from djoser.conf import settings def encode_uid(pk): return urlsafe_base64_encode(force_bytes(pk)).decode() def decode_uid(pk): return force_text(urlsafe_base64_decode(pk)) def login_user(request, user): token, _ = settings.TOKEN_MODEL.objects.get_or_create(user=user) if settings.CREATE_SESSION_ON_LOGIN: login(request, user) user_logged_in.send(sender=user.__class__, request=request, user=user) return token def logout_user(request): if settings.TOKEN_MODEL: settings.TOKEN_MODEL.objects.filter(user=request.user).delete() user_logged_out.send( sender=request.user.__class__, request=request, user=request.user ) if settings.CREATE_SESSION_ON_LOGIN: logout(request) class ActionViewMixin(object): def post(self, request, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) return self._action(serializer)
from django.contrib.auth import user_logged_in, user_logged_out, login, logout from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from djoser.conf import settings def encode_uid(pk): return urlsafe_base64_encode(force_bytes(pk)).decode() def decode_uid(pk): return force_text(urlsafe_base64_decode(pk)) def login_user(request, user): token, _ = settings.TOKEN_MODEL.objects.get_or_create(user=user) if settings.CREATE_SESSION_ON_LOGIN: login(request, user) user_logged_in.send(sender=user.__class__, request=request, user=user) return token def logout_user(request): if settings.TOKEN_MODEL: settings.TOKEN_MODEL.objects.filter(user=request.user).delete() user_logged_out.send( sender=request.user.__class__, request=request, user=request.user ) if settings.CREATE_SESSION_ON_LOGIN: logout(request) class ActionViewMixin(object): def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) return self._action(serializer)
fab: Watch the docs/ dir for changes
from fabric.api import execute, local, settings, task @task def preprocess_header(): local('cpp -nostdinc spotify/api.h > spotify/api.processed.h || true') @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(): local('nosetests') @task def autotest(): auto(test) def auto(task): while True: local('clear') with settings(warn_only=True): execute(task) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ spotify/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
from fabric.api import execute, local, settings, task @task def preprocess_header(): local('cpp -nostdinc spotify/api.h > spotify/api.processed.h || true') @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(): local('nosetests') @task def autotest(): auto(test) def auto(task): while True: local('clear') with settings(warn_only=True): execute(task) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r spotify/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
Hide popovers when clicked outside
/*global $:true*/ import Ember from 'ember'; export default Ember.Controller.extend({ queryParams: ['editMode'], isAdmin: Ember.computed('node', function(){ return this.get('model.node.currentUserPermissions').includes('admin'); }), editMode: false, actions: { scrollToTop(){ $('body').animate({scrollTop:0}, '500'); }, toggleEditMode(){ this.toggleProperty('editMode'); }, undo(){ this.get('model.theme').undo(); }, redo(){ this.get('model.theme').redo(); } }, init(){ this._super(...arguments); $('body').on('click', function(e){ console.log('a'); if($(e.target).parents('.popover').length === 0){ $('.popover').hide(); } }) } });
/*global $:true*/ import Ember from 'ember'; export default Ember.Controller.extend({ queryParams: ['editMode'], isAdmin: Ember.computed('node', function(){ return this.get('model.node.currentUserPermissions').includes('admin'); }), editMode: false, actions: { scrollToTop(){ $('body').animate({scrollTop:0}, '500'); }, toggleEditMode(){ this.toggleProperty('editMode'); }, undo(){ this.get('model.theme').undo(); }, redo(){ this.get('model.theme').redo(); } } });
Fix a broken export test Former-commit-id: fea471180d544a95f3d0adf87a7a46f51c067324 [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759] [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759 [formerly e37e964bf9d2819c0234303d31ed2839c317be04]] Former-commit-id: 5b8a20fa99eab2f33c8f293a505a2dbadad36eee Former-commit-id: 17492956ea8b4ed8b5465f6a057b6e026c2d4a75
# Copyright (c) 2010-2014, GEM Foundation. # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake 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 Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. import os import unittest from openquake.commonlib import nrml def number_of(elem_name, tree): """ Given an element name (including the namespaces prefix, if applicable), return the number of occurrences of the element in a given XML document. """ expr = '//%s' % elem_name return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05})) class BaseExportTestCase(unittest.TestCase): def _test_exported_file(self, filename): self.assertTrue(os.path.exists(filename)) self.assertTrue(os.path.isabs(filename)) self.assertTrue(os.path.getsize(filename) > 0)
# Copyright (c) 2010-2014, GEM Foundation. # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake 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 Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. import os import unittest from openquake.commonlib import nrml def number_of(elem_name, tree): """ Given an element name (including the namespaces prefix, if applicable), return the number of occurrences of the element in a given XML document. """ expr = '//%s' % elem_name return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP)) class BaseExportTestCase(unittest.TestCase): def _test_exported_file(self, filename): self.assertTrue(os.path.exists(filename)) self.assertTrue(os.path.isabs(filename)) self.assertTrue(os.path.getsize(filename) > 0)
Return $http request from playerModel instead of deferred
export class PlayerModelService { constructor($log, $http, $localStorage, $q, _, playersApi) { 'ngInject'; this.$log = $log; this.$http = $http; this.$localStorage = $localStorage; this.$q = $q; this._ = _; this.playersApi = playersApi; this.model = { player: null }; this.numDrawCards = 7; } insert(data) { let pl = Object.assign({}, { isCurrent: true, cardsInHand: [] }, data ); this.$log.info('insert()', pl, this); this.model.player = pl; this.$localStorage.player = this.model.player; } discard(id) { let cards = this.model.player.cardsInHand; this.$log.info('discard()', id, cards, this); // Remove card from player this._.pull(cards, id); let plData = { cardsInHand: cards, totalCards: cards.length }; this.$log.info('playerModel:cards -> ', plData); return this.playersApi.update(plData, this.model.player.id); } update(data) { Object.assign(this.model.player, data); } }
export class PlayerModelService { constructor($log, $http, $localStorage, $q, _, playersApi) { 'ngInject'; this.$log = $log; this.$http = $http; this.$localStorage = $localStorage; this.$q = $q; this._ = _; this.playersApi = playersApi; this.model = { player: null }; this.numDrawCards = 7; } insert(data) { let pl = Object.assign({}, { isCurrent: true, cardsInHand: [] }, data ); this.$log.info('insert()', pl, this); this.model.player = pl; this.$localStorage.player = this.model.player; } discard(id) { let cards = this.model.player.cardsInHand, defer = this.$q.defer(), onSuccess = (res => { defer.resolve(res); }), onError = (err => { this.$log.error(err); defer.reject(err); }); this.$log.info('discard()', id, cards, this); // Remove card from player this._.pull(cards, id); this.$log.info('playerModel:cards -> ', cards); this.playersApi .update({ cardsInHand: cards, totalCards: cards.length }, this.model.player.id) .then(onSuccess, onError); return defer.promise; } update(data) { Object.assign(this.model.player, data); } }
Use ES6 let instead of var
// Define search and replace terms for image src link let search = /s[0-9]+/g; let replace = 's512'; function getProfileImageContainer() { // Get profile image containers return $('#channel-header-container'); } function getProfileImage(container) { // Get profile image tag return container.find('img'); } function wrapEnlargeLink() { // Get profile image link let imageContainer = getProfileImageContainer(); // No image? if (!imageContainer.length) { return; } // Get img tag nested within container let imageTag = getProfileImage(imageContainer); // No tag? if (!imageTag.length) { return; } // Get image src URL let src = imageTag.attr('src'); // Replace image pixel value in URL for a larger 512px image src = src.replace(search, replace); // Wrap image tag with a link that points to the larger image $( imageTag ).wrap( "<a href='" + src + "' target='_blank'></a>" ); } // One-time injection wrapEnlargeLink();
// Define search and replace terms for image src link var search = /s[0-9]+/g; var replace = 's512'; function getProfileImageContainer() { // Get profile image containers return $('#channel-header-container'); } function getProfileImage(container) { // Get profile image tag return container.find('img'); } function wrapEnlargeLink() { // Get profile image link var imageContainer = getProfileImageContainer(); // No image? if (!imageContainer.length) { return; } // Get img tag nested within container var imageTag = getProfileImage(imageContainer); // No tag? if (!imageTag.length) { return; } // Get image src URL var src = imageTag.attr('src'); // Replace image pixel value in URL for a larger 512px image src = src.replace(search, replace); // Wrap image tag with a link that points to the larger image $( imageTag ).wrap( "<a href='" + src + "' target='_blank'></a>" ); } // One-time injection wrapEnlargeLink();
Fix edit month in table cell
var _ = require('underscore'); var CoreView = require('backbone/core-view'); module.exports = CoreView.extend({ className: 'CDB-Box-modal Table-editor', initialize: function () { this.listenTo(this.model, 'change:show', this._onShowChange); this.listenTo(this.model, 'destroy', this._onDestroy); }, render: function () { this.clearSubViews(); var view = this.model.createContentView(); this.addView(view); view.render(); this.$el.append(view.el); this.$el.css(_.extend({ zIndex: 100 }, this.options.position)); return this; }, show: function () { this.model.show(); }, hide: function () { this.model.hide(); }, destroy: function () { this.model.destroy(); }, _onShowChange: function (m, show) { this.$el[show ? 'show' : 'hide'](); }, _onClose: function () { this.destroy(); }, _onDestroy: function () { this.hide(); this.clean(); } });
var CoreView = require('backbone/core-view'); module.exports = CoreView.extend({ className: 'CDB-Box-modal Table-editor', initialize: function () { this.listenTo(this.model, 'change:show', this._onShowChange); this.listenTo(this.model, 'destroy', this._onDestroy); }, render: function () { this.clearSubViews(); var view = this.model.createContentView(); this.addView(view); view.render(); this.$el.append(view.el); this.$el.css(this.options.position); return this; }, show: function () { this.model.show(); }, hide: function () { this.model.hide(); }, destroy: function () { this.model.destroy(); }, _onShowChange: function (m, show) { this.$el[show ? 'show' : 'hide'](); }, _onClose: function () { this.destroy(); }, _onDestroy: function () { this.hide(); this.clean(); } });
Fix download link , again
import copy from django import template from django.conf import settings from games import models register = template.Library() def get_links(user_agent): systems = ['ubuntu', 'fedora', 'linux'] downloads = copy.copy(settings.DOWNLOADS) main_download = None for system in systems: if system in user_agent: main_download = {system: downloads[system]} downloads.pop(system) break if main_download is None: main_download = {'linux': downloads.pop('linux')} return (main_download, downloads) @register.inclusion_tag('includes/download_links.html', takes_context=True) def download_links(context): request = context['request'] user_agent = request.META.get('HTTP_USER_AGENT', '').lower() context['main_download'], context['downloads'] = get_links(user_agent) return context @register.inclusion_tag('includes/featured_slider.html', takes_context=True) def featured_slider(context): context['featured_contents'] = models.Featured.objects.all() return context @register.inclusion_tag('includes/latest_games.html', takes_context=True) def latest_games(context): games = models.Game.objects.published().order_by('-created')[:5] context['latest_games'] = games return context
import copy from django import template from django.conf import settings from games import models register = template.Library() def get_links(user_agent): systems = ['ubuntu', 'fedora', 'linux'] downloads = copy.copy(settings.DOWNLOADS) main_download = None for system in systems: if system in user_agent: main_download = {system: downloads[system]} downloads.pop(system) if not main_download: main_download = {'linux': downloads.pop('linux')} return (main_download, downloads) @register.inclusion_tag('includes/download_links.html', takes_context=True) def download_links(context): request = context['request'] user_agent = request.META.get('HTTP_USER_AGENT', '').lower() context['main_download'], context['downloads'] = get_links(user_agent) return context @register.inclusion_tag('includes/featured_slider.html', takes_context=True) def featured_slider(context): context['featured_contents'] = models.Featured.objects.all() return context @register.inclusion_tag('includes/latest_games.html', takes_context=True) def latest_games(context): games = models.Game.objects.published().order_by('-created')[:5] context['latest_games'] = games return context
Maintain project release sort order
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import Release class ProjectReleasesEndpoint(ProjectEndpoint): doc_section = DocSection.RELEASES def get(self, request, project): """ List a project's releases Retrieve a list of releases for a given project. {method} {path} """ queryset = Release.objects.filter( project=project, ) return self.paginate( request=request, queryset=queryset, order_by='-id', on_results=lambda x: serialize(x, request.user), )
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import Release class ProjectReleasesEndpoint(ProjectEndpoint): doc_section = DocSection.RELEASES def get(self, request, project): """ List a project's releases Retrieve a list of releases for a given project. {method} {path} """ queryset = Release.objects.filter( project=project, ).order_by('-date_added') return self.paginate( request=request, queryset=queryset, # TODO(dcramer): we want to sort by date_added order_by='-id', on_results=lambda x: serialize(x, request.user), )
Mark util class as internal API Though it's already package private, but anyhow
package org.jctools.queues; import org.jctools.util.InternalAPI; import static org.jctools.util.UnsafeRefArrayAccess.REF_ARRAY_BASE; import static org.jctools.util.UnsafeRefArrayAccess.REF_ELEMENT_SHIFT; /** * This is used for method substitution in the LinkedArray classes code generation. */ @InternalAPI final class LinkedArrayQueueUtil { static int length(Object[] buf) { return buf.length; } /** * This method assumes index is actually (index << 1) because lower bit is * used for resize. This is compensated for by reducing the element shift. * The computation is constant folded, so there's no cost. */ static long modifiedCalcCircularRefElementOffset(long index, long mask) { return REF_ARRAY_BASE + ((index & mask) << (REF_ELEMENT_SHIFT - 1)); } static long nextArrayOffset(Object[] curr) { return REF_ARRAY_BASE + ((long) (length(curr) - 1) << REF_ELEMENT_SHIFT); } }
package org.jctools.queues; import static org.jctools.util.UnsafeRefArrayAccess.REF_ARRAY_BASE; import static org.jctools.util.UnsafeRefArrayAccess.REF_ELEMENT_SHIFT; /** * This is used for method substitution in the LinkedArray classes code generation. */ final class LinkedArrayQueueUtil { static int length(Object[] buf) { return buf.length; } /** * This method assumes index is actually (index << 1) because lower bit is * used for resize. This is compensated for by reducing the element shift. * The computation is constant folded, so there's no cost. */ static long modifiedCalcCircularRefElementOffset(long index, long mask) { return REF_ARRAY_BASE + ((index & mask) << (REF_ELEMENT_SHIFT - 1)); } static long nextArrayOffset(Object[] curr) { return REF_ARRAY_BASE + ((long) (length(curr) - 1) << REF_ELEMENT_SHIFT); } }
Increase rest client connection pool size to 50
from .base_settings import * import os INSTALLED_APPS += [ 'data_aggregator.apps.DataAggregatorConfig', 'webpack_loader', ] if os.getenv('ENV') == 'localdev': DEBUG = True DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group' DATA_AGGREGATOR_THREADING_ENABLED = False RESTCLIENTS_DAO_CACHE_CLASS = None DATA_AGGREGATOR_THREADING_ENABLED = False else: DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '') DATA_AGGREGATOR_THREADING_ENABLED = True WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'data_aggregator/bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'), } } RESTCLIENTS_CANVAS_POOL_SIZE = 50 ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
from .base_settings import * import os INSTALLED_APPS += [ 'data_aggregator.apps.DataAggregatorConfig', 'webpack_loader', ] if os.getenv('ENV') == 'localdev': DEBUG = True DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group' DATA_AGGREGATOR_THREADING_ENABLED = False RESTCLIENTS_DAO_CACHE_CLASS = None DATA_AGGREGATOR_THREADING_ENABLED = False else: DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '') DATA_AGGREGATOR_THREADING_ENABLED = True WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'data_aggregator/bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'), } } RESTCLIENTS_CANVAS_POOL_SIZE = 25 ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
Set auth cookie to be returned on all api calls
package auth import ( "encoding/json" "fmt" "github.com/gorilla/mux" "net/http" ) const ( tokenCookieName = "access_token" ) func AddRoutes(r *mux.Router, service Service) { // Explicitly only serve login over https. r.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) req := LoginRequest{} err := decoder.Decode(&req) if err != nil { http.Error(w, fmt.Sprintf("failed to decode login request from request body: %v", err), 400) return } token, err := service.Login(req) if err != nil { // Explicitly do not pass up the reason for login failure. http.Error(w, "Invalid username or password.", 403) } signedString, err := service.Sign(token) if err != nil { http.Error(w, fmt.Sprintf("failed to issue token: %v", err), 503) } // Return token as a cookie. w.Header().Add("Set-Cookie", fmt.Sprintf("%v=%v; Path=/api; Secure; HttpOnly;", tokenCookieName, signedString)) w.WriteHeader(http.StatusNoContent) }).Methods("POST").Schemes("https") }
package auth import ( "encoding/json" "fmt" "github.com/gorilla/mux" "net/http" ) const ( tokenCookieName = "access_token" ) func AddRoutes(r *mux.Router, service Service) { // Explicitly only serve login over https. r.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) req := LoginRequest{} err := decoder.Decode(&req) if err != nil { http.Error(w, fmt.Sprintf("failed to decode login request from request body: %v", err), 400) return } token, err := service.Login(req) if err != nil { // Explicitly do not pass up the reason for login failure. http.Error(w, "Invalid username or password.", 403) } signedString, err := service.Sign(token) if err != nil { http.Error(w, fmt.Sprintf("failed to issue token: %v", err), 503) } // Return token as a cookie. w.Header().Add("Set-Cookie", fmt.Sprintf("%v=%v; Secure; HttpOnly;", tokenCookieName, signedString)) w.WriteHeader(http.StatusNoContent) }).Methods("POST").Schemes("https") }
Set a random session key if none is configured
import os from flask import current_app from flask import Flask from flask import g from flask import jsonify from flask import redirect from flask import url_for from relengapi import celery from relengapi import db import pkg_resources def create_app(cmdline=False): app = Flask('relengapi') app.config.from_envvar('RELENG_API_SETTINGS') # get blueprints from pkg_resources for ep in pkg_resources.iter_entry_points('relengapi_blueprints'): if cmdline: print " * registering blueprint", ep.name app.register_blueprint(ep.load(), url_prefix='/%s' % ep.name) # set up a random session key if none is specified if not app.config.get('SECRET_KEY'): print " * WARNING: setting per-process session key" app.secret_key = os.urandom(24) # add the necessary components to the app app.db = db.make_db(app) app.celery = celery.make_celery(app) @app.before_request def add_db(): g.db = app.db @app.route('/') def root(): return redirect(url_for('docs.root')) @app.route('/meta') def meta(): "API: Metadata about this RelengAPI instance" meta = {} meta['blueprints'] = current_app.blueprints.keys() return jsonify(meta) return app
from flask import current_app from flask import Flask from flask import g from flask import jsonify from flask import redirect from flask import url_for from relengapi import celery from relengapi import db import pkg_resources def create_app(cmdline=False): app = Flask('relengapi') app.config.from_envvar('RELENG_API_SETTINGS') # get blueprints from pkg_resources for ep in pkg_resources.iter_entry_points('relengapi_blueprints'): if cmdline: print " * registering blueprint", ep.name app.register_blueprint(ep.load(), url_prefix='/%s' % ep.name) # add the necessary components to the app app.db = db.make_db(app) app.celery = celery.make_celery(app) @app.before_request def add_db(): g.db = app.db @app.route('/') def root(): return redirect(url_for('docs.root')) @app.route('/meta') def meta(): "API: Metadata about this RelengAPI instance" meta = {} meta['blueprints'] = current_app.blueprints.keys() return jsonify(meta) return app
Fix multiple JavaScript functions not working in Safari. Things such as adding attendees and agendums weren't working in Safari. It seems that I was missing a closing brace in a query selector, which Safari was strict on, causing Ajax requests to fail because the CSRF token wasn't beening submitted. Although the following link is for jQuery specifically, it lead me in the right direction: https://stackoverflow.com/a/43209100
var md5 = require('md5'); /* * JavaScript utilities. */ export default class Utils { /* * Formats a Date() object into a string. */ static formatDateTime(date) { return moment(date).format('LLLL'); } /* * Returns a Date() object from a string in the same format * as formatDateTime(); */ static dateFromString(dateTimeString) { if (typeof dateTimeString === 'object') { // Assume that dateTimeString is a Date() object // and reurn that. return dateTimeString; } return new Date(dateTimeString.replace(' ', 'T').replace('Z', '')); } /* * Get the Rails authenticity token. */ static getAuthenticityToken() { return document.querySelector('meta[name=csrf-token]') .getAttribute('content'); } static getGravatarUrl(email) { var hashedEmail = md5(email.trim().toLowerCase()); return `https://www.gravatar.com/avatar/${hashedEmail}.jpg?s=32&d=mm`; } }
var md5 = require('md5'); /* * JavaScript utilities. */ export default class Utils { /* * Formats a Date() object into a string. */ static formatDateTime(date) { return moment(date).format('LLLL'); } /* * Returns a Date() object from a string in the same format * as formatDateTime(); */ static dateFromString(dateTimeString) { if (typeof dateTimeString === 'object') { // Assume that dateTimeString is a Date() object // and reurn that. return dateTimeString; } return new Date(dateTimeString.replace(' ', 'T').replace('Z', '')); } /* * Get the Rails authenticity token. */ static getAuthenticityToken() { return document.querySelector('meta[name=csrf-token').getAttribute('content'); } static getGravatarUrl(email) { var hashedEmail = md5(email.trim().toLowerCase()); return `https://www.gravatar.com/avatar/${hashedEmail}.jpg?s=32&d=mm`; } }
Use the modern files/assets APIs
Package.describe({ name: 'quark:electron', summary: "Electron", version: "0.1.3", git: "https://github.com/rissem/meteor-electron" }); Npm.depends({ connect: '2.11.0', "electron-packager": "5.0.2", "is-running": "1.0.5", "mkdirp": "0.5.1", "tar":"2.2.1", "fstream":"1.0.8", "serve-static": "1.1.0" }); Package.on_use(function (api, where) { api.use(["mongo-livedata", "webapp", "ejson", "underscore"], "server"); api.use(["iron:router"], {weak: true}); api.addFiles(['server.js'], 'server'); api.addAssets([ "app/package.json", "app/main.js" ], "server"); api.addFiles(['client.js'], "client"); api.export("Electron", ["client", "server"]); });
Package.describe({ name: 'quark:electron', summary: "Electron", version: "0.1.3", git: "https://github.com/rissem/meteor-electron" }); Npm.depends({ connect: '2.11.0', "electron-packager": "5.0.2", "is-running": "1.0.5", "mkdirp": "0.5.1", "tar":"2.2.1", "fstream":"1.0.8", "serve-static": "1.1.0" }); Package.on_use(function (api, where) { api.use(["mongo-livedata", "webapp", "ejson", "underscore"], "server"); api.use(["iron:router"], {weak: true}); api.add_files(['server.js'], 'server') api.add_files([ "app/package.json", "app/main.js" ], "server", {isAsset: true}); api.add_files(['client.js'], "client"); api.export("Electron", ["client", "server"]); });
Make search.elastic.version an int not a string Summary: Puppet is not budging in allowing me to use an int so let's just make it a int. This fixes prod for when we want to change versions too. Change-Id: I348d674762953433bd77c6ff8efb4246d5d68b73 Reviewers: mmodell, Dzahn Subscribers: jenkins Differential Revision: https://phabricator.wikimedia.org/D562
<?php final class PhabricatorSearchConfigOptions extends PhabricatorApplicationConfigOptions { public function getName() { return pht('Search'); } public function getDescription() { return pht('Options relating to Search.'); } public function getIcon() { return 'fa-search'; } public function getGroup() { return 'apps'; } public function getOptions() { return array( $this->newOption('search.elastic.host', 'string', null) ->setLocked(true) ->setDescription(pht('Elastic Search host.')) ->addExample('http://elastic.example.com:9200/', pht('Valid Setting')), $this->newOption('search.elastic.namespace', 'string', 'phabricator') ->setLocked(true) ->setDescription(pht('Elastic Search index.')) ->addExample('phabricator2', pht('Valid Setting')), $this->newOption('search.elastic.version', 'int', null) ->setLocked(true) ->setDescription(pht('Elastic Version, used for functions that work for a specific elastic version.')), $this->newOption('search.elastic.enabled', 'bool', false) ->setDescription(pht('Enable the elasticsearch backend.')) ->setBoolOptions(array(pht('Enable: Use elasticsearch'), pht('Disable: Use MySQL'))) ); } }
<?php final class PhabricatorSearchConfigOptions extends PhabricatorApplicationConfigOptions { public function getName() { return pht('Search'); } public function getDescription() { return pht('Options relating to Search.'); } public function getIcon() { return 'fa-search'; } public function getGroup() { return 'apps'; } public function getOptions() { return array( $this->newOption('search.elastic.host', 'string', null) ->setLocked(true) ->setDescription(pht('Elastic Search host.')) ->addExample('http://elastic.example.com:9200/', pht('Valid Setting')), $this->newOption('search.elastic.namespace', 'string', 'phabricator') ->setLocked(true) ->setDescription(pht('Elastic Search index.')) ->addExample('phabricator2', pht('Valid Setting')), $this->newOption('search.elastic.version', 'string', null) ->setLocked(true) ->setDescription(pht('Elastic Version, used for functions that work for a specific elastic version.')), $this->newOption('search.elastic.enabled', 'bool', false) ->setDescription(pht('Enable the elasticsearch backend.')) ->setBoolOptions(array(pht('Enable: Use elasticsearch'), pht('Disable: Use MySQL'))) ); } }
Remove duplicated code for getDisplayName
import React from 'react'; import getWindowDimensions from './utils/getWindowDimensions.js'; import { getDisplayName } from './ui/diagram/Utils.js'; export default function Resize(WrappedComponent) { class Resizer extends React.Component { constructor(props) { super(props); this.state = props.getDimensions(); this.handleResize = this.handleResize.bind(this); } handleResize() { this.setState(this.props.getDimensions()); } componentDidMount() { window.addEventListener('resize', this.handleResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); } render() { const {getDimensions, ...childProps} = this.props; const props = { ...childProps, ...this.state }; return ( <WrappedComponent {...props} /> ); } } Resizer.propTypes = { getDimensions: React.PropTypes.func }; Resizer.defaultProps = { getDimensions: getWindowDimensions }; Resizer.displayName = `Resize(${getDisplayName(WrappedComponent)})`; return Resizer; }
import React from 'react'; import getWindowDimensions from './utils/getWindowDimensions.js'; function getDisplayName(Component) { return Component.displayName || Component.name || 'Component'; } export default function Resize(WrappedComponent) { class Resizer extends React.Component { constructor(props) { super(props); this.state = props.getDimensions(); this.handleResize = this.handleResize.bind(this); } handleResize() { this.setState(this.props.getDimensions()); } componentDidMount() { window.addEventListener('resize', this.handleResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); } render() { const {getDimensions, ...childProps} = this.props; const props = { ...childProps, ...this.state }; return ( <WrappedComponent {...props} /> ); } } Resizer.propTypes = { getDimensions: React.PropTypes.func }; Resizer.defaultProps = { getDimensions: getWindowDimensions }; Resizer.displayName = `Resize(${getDisplayName(WrappedComponent)})`; return Resizer; }
Raise read-only fs on touch
from errno import EROFS from fuse import FuseOSError from gitfs import FuseMethodNotImplemented from .view import View class ReadOnlyView(View): def getxattr(self, path, fh): raise FuseMethodNotImplemented def open(self, path, flags): return 0 def create(self, path, fh): raise FuseOSError(EROFS) def write(self, path, fh): raise FuseOSError(EROFS) def opendir(self, path): return 0 def releasedir(self, path, fi): return 0 def flush(self, path, fh): return 0 def release(self, path, fh): return 0 def access(self, path, amode): return 0 def mkdir(self, path, mode): raise FuseOSError(EROFS) def utimens(self, path, times=None): raise FuseOSError(EROFS)
import os from errno import EROFS from fuse import FuseOSError from gitfs import FuseMethodNotImplemented from .view import View class ReadOnlyView(View): def getxattr(self, path, fh): raise FuseMethodNotImplemented def open(self, path, flags): return 0 def create(self, path, fh): raise FuseOSError(EROFS) def write(self, path, fh): raise FuseOSError(EROFS) def opendir(self, path): return 0 def releasedir(self, path, fi): return 0 def flush(self, path, fh): return 0 def release(self, path, fh): return 0 def access(self, path, amode): return 0 def mkdir(self, path, mode): raise FuseOSError(EROFS)
Update progress bar as authentication pages load
package uk.co.sftrabbit.stackanswers; import android.os.Bundle; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import uk.co.sftrabbit.stackanswers.app.DrawerActivity; public class AuthenticationActivity extends DrawerActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_authentication); setDrawerIndicatorEnabled(false); final ProgressBar progressBar = (ProgressBar) findViewById(R.id.authentication_progress); WebView webView = (WebView) findViewById(R.id.authentication_web_view); webView.setWebViewClient(new WebViewClient()); webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView webview, int newProgress) { progressBar.setProgress(newProgress); } }); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.loadUrl( "https://stackexchange.com/oauth/dialog?" + "client_id=2265&" + "scope=read_inbox,write_access,private_info&" + "redirect_uri=https://stackexchange.com/oauth/login_success" ); } }
package uk.co.sftrabbit.stackanswers; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import uk.co.sftrabbit.stackanswers.app.DrawerActivity; public class AuthenticationActivity extends DrawerActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_authentication); setDrawerIndicatorEnabled(false); WebView webView = (WebView) findViewById(R.id.authentication_web_view); webView.setWebViewClient(new WebViewClient()); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.loadUrl( "https://stackexchange.com/oauth/dialog?" + "client_id=2265&" + "scope=read_inbox,write_access,private_info&" + "redirect_uri=https://stackexchange.com/oauth/login_success" ); } }
Use VueMoment as Vue plugin
import Vue from "vue"; import VueRouter from "vue-router"; import VueMoment from 'vue-moment'; import {createProvider} from './apollo'; import {store} from "./store"; import App from "./app.vue"; import Login from "./login.vue"; import UserList from "./user/list.vue"; import UserProfile from "./user/profile.vue"; import UserEdit from "./user/edit.vue"; import Pulls from "./pulls/pulls.vue"; import Issues from "./issues/issues.vue"; import Repository from './repository/repository.vue'; Vue.use(VueRouter); Vue.use(VueMoment); const router = new VueRouter({ mode: 'history', routes: [ {path: "/", component: UserList}, {path: "/login", component: Login}, {path: '/pulls', component: Pulls}, {path: '/issues', component: Issues}, {path: "/:username", component: UserProfile}, {path: "/:username/edit", component: UserEdit}, {path: '/:owner/:repository', component: Repository}, ], }); new Vue({ el: '#app', store: store, router: router, apolloProvider: createProvider(), render: h => h(App) });
import Vue from "vue"; import VueRouter from "vue-router"; import {createProvider} from './apollo'; import {store} from "./store"; import App from "./app.vue"; import Login from "./login.vue"; import UserList from "./user/list.vue"; import UserProfile from "./user/profile.vue"; import UserEdit from "./user/edit.vue"; import Pulls from "./pulls/pulls.vue"; import Issues from "./issues/issues.vue"; import Repository from './repository/repository.vue'; Vue.use(VueRouter); const router = new VueRouter({ mode: 'history', routes: [ {path: "/", component: UserList}, {path: "/login", component: Login}, {path: '/pulls', component: Pulls}, {path: '/issues', component: Issues}, {path: "/:username", component: UserProfile}, {path: "/:username/edit", component: UserEdit}, {path: '/:owner/:repository', component: Repository}, ], }); new Vue({ el: '#app', store: store, router: router, apolloProvider: createProvider(), render: h => h(App) });
Handle env vars in volumes
from string import Template from collections import defaultdict import os import yaml def load_defaults(): skipper_conf = 'skipper.yaml' defaults = {} if os.path.exists(skipper_conf): with open(skipper_conf) as confile: config = yaml.load(confile) containers = config.pop('containers', None) _normalize_config(config, defaults) if containers is not None: defaults['containers'] = containers return defaults def _normalize_config(config, normalized_config): for key, value in config.iteritems(): if isinstance(value, dict): normalized_config[key] = {} _normalize_config(value, normalized_config[key]) elif isinstance(value, list): normalized_config[key] = [_interpolate_env_vars(x) for x in value] else: normalized_key = key.replace('-', '_') normalized_config[normalized_key] = _interpolate_env_vars(value) def _interpolate_env_vars(key): return Template(key).substitute(defaultdict(lambda: "", os.environ))
from string import Template from collections import defaultdict import os import yaml def load_defaults(): skipper_conf = 'skipper.yaml' defaults = {} if os.path.exists(skipper_conf): with open(skipper_conf) as confile: config = yaml.load(confile) containers = config.pop('containers', None) _normalize_config(config, defaults) if containers is not None: defaults['containers'] = containers return defaults def _normalize_config(config, normalized_config): for key, value in config.iteritems(): if isinstance(value, dict): normalized_config[key] = {} _normalize_config(value, normalized_config[key]) elif isinstance(value, list): normalized_config[key] = value else: normalized_key = key.replace('-', '_') normalized_config[normalized_key] = _interpolate_env_vars(value) def _interpolate_env_vars(key): return Template(key).substitute(defaultdict(lambda: "", os.environ))
Update default output path for bin/
#!/usr/bin/env node /* * Module dependencies. */ var fs = require('fs'); var path = require('path'); var program = require('commander'); var web2splash = require('./../lib/web2splash'); /* * Load package.json */ var packageJSON = JSON.parse(fs.readFileSync(path.join(__dirname,'..','package.json'), 'utf8')); /* * Command-line usage */ program .version(packageJSON.version) .usage('[options] <input html>') .option('-o, --output [path]', 'set output path for images', './'); /* * Command-line help */ program.on('--help', function(){ console.log(' Examples:'); console.log(''); console.log(' $', program.name, '/path/to/splash.html'); console.log(''); }); /* * Parse the command-line */ program.parse(process.argv); program.input = program.args[0]; if (!program.input) { console.log(''); console.log('Error: <input html> must be provided.'); console.log(''); return false; } /* * Render an HTML document to a set of splash screen images */ web2splash.onRenderImage = function(image) { console.log(' rendered: %s (%d x %dpx)', image.name, image.width, image.height); }; web2splash.render(program.input, program.output, function(e, images) { // complete });
#!/usr/bin/env node /* * Module dependencies. */ var fs = require('fs'); var path = require('path'); var program = require('commander'); var web2splash = require('./../lib/web2splash'); /* * Load package.json */ var packageJSON = JSON.parse(fs.readFileSync(path.join(__dirname,'..','package.json'), 'utf8')); /* * Command-line usage */ program .version(packageJSON.version) .usage('[options] <input html>') .option('-o, --output [path]', 'set output path for images', './output/'); /* * Command-line help */ program.on('--help', function(){ console.log(' Examples:'); console.log(''); console.log(' $', program.name, '/path/to/splash.html'); console.log(''); }); /* * Parse the command-line */ program.parse(process.argv); program.input = program.args[0]; if (!program.input) { console.log(''); console.log('Error: <input html> must be provided.'); console.log(''); return false; } /* * Render an HTML document to a set of splash screen images */ web2splash.onRenderImage = function(image) { console.log(' rendered: %s (%d x %dpx)', image.name, image.width, image.height); }; web2splash.render(program.input, program.output, function(e, images) { // complete });
Add limit clause to units relation
<?php namespace OpenDominion\Models; class Race extends AbstractModel { public function dominions() { return $this->hasMany(Dominion::class); } public function perks() { return $this->hasMany(RacePerk::class); } public function units() { return $this->hasMany(Unit::class)->orderBy('slot')->limit(4); } /** * Gets a Race's perk multiplier. * * @param string $key * @return float */ public function getPerkMultiplier($key) { $perk = $this->perks()->with('type')->whereHas('type', function ($q) use ($key) { $q->where('key', $key); })->first(); if ($perk === null) { return (float)0; } return (float)($perk->value / 100); } }
<?php namespace OpenDominion\Models; class Race extends AbstractModel { public function dominions() { return $this->hasMany(Dominion::class); } public function perks() { return $this->hasMany(RacePerk::class); } public function units() { return $this->hasMany(Unit::class)->orderBy('slot'); } /** * Gets a Race's perk multiplier. * * @param string $key * @return float */ public function getPerkMultiplier($key) { $perk = $this->perks()->with('type')->whereHas('type', function ($q) use ($key) { $q->where('key', $key); })->first(); if ($perk === null) { return (float)0; } return (float)($perk->value / 100); } }
Use body parser parsing request body
'use strict'; const bodyParser = require('body-parser'); const express = require('express'); const APP_CONST = require('../constant/app'); class Server { /** * Constructor * @param config */ constructor(config) { this.config = config || {}; this.core = express(); } /** * Initial middleware * @private */ _initMiddleware() { this.core.use(bodyParser.json()); } /** * Initial router * @private */ _initRouter() {} /** * Boot server * @private */ _boot() { this.core.listen(APP_CONST.PORT, console.log(`line bot server listened on ${APP_CONST.PORT}`)); } /** * Boot server */ boot() { this._initMiddleware(); this._initRouter(); this._boot(); } /** * Halt server * @private */ _halt() { process.exit(); } /** * Halt server */ halt() { this._halt(); } } module.exports = Server;
'use strict'; const express = require('express'); const APP_CONST = require('../constant/app'); class Server { /** * Constructor * @param config */ constructor(config) { this.config = config || {}; this.core = express(); } /** * Initial middleware * @private */ _initMiddleware() {} /** * Initial router * @private */ _initRouter() {} /** * Boot server * @private */ _boot() { this.core.listen(APP_CONST.PORT, console.log(`line bot server listened on ${APP_CONST.PORT}`)); } /** * Boot server */ boot() { this._initMiddleware(); this._initRouter(); this._boot(); } /** * Halt server * @private */ _halt() { process.exit(); } /** * Halt server */ halt() { this._halt(); } } module.exports = Server;
hugolib: Add a simple test for jsonify of Site Closes #5780
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) // Issue #1123 // Testing prevention of cyclic refs in JSON encoding // May be smart to run with: -timeout 4000ms func TestEncodePage(t *testing.T) { t.Parallel() templ := `Page: |{{ index .Site.RegularPages 0 | jsonify }}| Site: {{ site | jsonify }} ` b := newTestSitesBuilder(t) b.WithSimpleConfigFile().WithTemplatesAdded("index.html", templ) b.WithContent("page.md", `--- title: "Page" date: 2019-02-28 --- Content. `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `"Date":"2019-02-28T00:00:00Z"`) }
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugolib import ( "testing" ) // Issue #1123 // Testing prevention of cyclic refs in JSON encoding // May be smart to run with: -timeout 4000ms func TestEncodePage(t *testing.T) { t.Parallel() templ := `{{ index .Site.RegularPages 0 | jsonify }}` b := newTestSitesBuilder(t) b.WithSimpleConfigFile().WithTemplatesAdded("index.html", templ) b.WithContent("page.md", `--- title: "Page" date: 2019-02-28 --- Content. `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", `"Date":"2019-02-28T00:00:00Z"`) }
Undo changes to /discover page.
"use strict"; var PhotoStreamController = function($scope, $http, $log, $timeout, analytics, resourceCache) { $http({method: "GET", url: "/api/v1/hikes?fields=distance,locality,name,photo_facts,photo_preview,string_id", cache: resourceCache}). success(function(data, status, headers, config) { // Only show the hikes that have photo previews or facts photo, which is a backup option var hikes = jQuery.grep(data, function(hike){ return hike.photo_preview || hike.photo_facts; }); $scope.hikes = hikes; }). error(function(data, status, headers, config) { $log.error(config); }); $scope.hikes = []; $scope.htmlReady(); }; PhotoStreamController.$inject = ["$scope", "$http", "$log", "$timeout", "analytics", "resourceCache"];
"use strict"; var PhotoStreamController = function($scope, $http, $log, $timeout, analytics, resourceCache) { $http({method: "GET", url: "/api/v1/hikes?fields=distance,locality,name,photo_facts,photo_preview,string_id", cache: resourceCache}). success(function(data, status, headers, config) { var hikes = jQuery.grep(data, function(hike){ // Quick and dirty way of checking whether the entry is good enough to show on the /discover page, // Maybe want them to go through a curation process some day. return hike.photo_landscape && hike.photo_facts && hike.description && hike.description.length > 200; }); $scope.hikes = hikes; }). error(function(data, status, headers, config) { $log.error(config); }); $scope.hikes = []; $scope.htmlReady(); }; PhotoStreamController.$inject = ["$scope", "$http", "$log", "$timeout", "analytics", "resourceCache"];
Allow script to temporarily change directory mode to 777 and then return it to 644. Improves security of docs directory git-svn-id: e691eac7f4e7c267eb8bf668e75dc601c2a71df8@632 54a900ba-8191-11dd-a5c9-f1483cedc3eb
<?php session_start(); include 'db.php'; $folder_name = $_GET['folder_name']; $case_id = $_GET['case_id']; /* This to delete files off of server */ $unlink_query = mysql_query("SELECT * FROM `cm_documents` WHERE `folder` = '$folder_name' AND `case_id` = '$case_id' AND `url` != ''"); shell_exec('chmod 777 docs'); while ($r = mysql_fetch_array($unlink_query)) { $doc = $r['url']; unlink($doc); } shell_exec('chmod 644 docs'); /* This to delete document database entry */ $query = mysql_query("DELETE FROM `cm_documents` WHERE `folder` = '$folder_name' and `case_id` = '$case_id'"); echo "<br><br><a href=\"#\" onClick=\"killDroppables();createTargets('case_activity','case_activity');sendDataGet('cm_docs.php?id=$case_id');return false;\">OK</a> "; ?>
<?php session_start(); include 'db.php'; $folder_name = $_GET['folder_name']; $case_id = $_GET['case_id']; /* This to delete files off of server */ $unlink_query = mysql_query("SELECT * FROM `cm_documents` WHERE `folder` = '$folder_name' AND `case_id` = '$case_id' AND `url` != ''"); while ($r = mysql_fetch_array($unlink_query)) { $doc = $r['url']; unlink($doc); } /* This to delete document database entry */ $query = mysql_query("DELETE FROM `cm_documents` WHERE `folder` = '$folder_name' and `case_id` = '$case_id'"); echo "<br><br><a href=\"#\" onClick=\"killDroppables();createTargets('case_activity','case_activity');sendDataGet('cm_docs.php?id=$case_id');return false;\">OK</a> "; ?>
Change visiablity of exception to public
/* * Copyright 2017 Max Schafer, Ammar Mahdi, Riley Dixon, Steven Weikai Lu, Jiaxiong Yang * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.example.lit.userprofile; /** * Created by Riley Dixon on 01/12/2017. */ public class BitmapTooLargeException extends Exception { BitmapTooLargeException(){ super(); } BitmapTooLargeException(String msg){ super(msg); } }
/* * Copyright 2017 Max Schafer, Ammar Mahdi, Riley Dixon, Steven Weikai Lu, Jiaxiong Yang * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.example.lit.userprofile; /** * Created by Riley Dixon on 01/12/2017. */ class BitmapTooLargeException extends Exception { BitmapTooLargeException(){ super(); } BitmapTooLargeException(String msg){ super(msg); } }
Create an example firewall rule push with the antivirus enablement.
#!/usr/bin/python import logging import pprint from fortiosapi import FortiOSAPI formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') logger = logging.getLogger('fortiosapi') hdlr = logging.FileHandler('testfortiosapi.log') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) fgt = FortiOSAPI() def main(): # Login to the FGT ip fgt.debug('on') fgthost = '10.10.10.125' user = 'admin' passwd = 'toto' resp = fgt.login(fgthost, user, passwd) pp = pprint.PrettyPrinter(indent=4) resp = fgt.license() pp = pprint.PrettyPrinter(indent=4) pp.pprint(resp) if __name__ == '__main__': main()
#!/usr/bin/python from fortiosapi import FortiOSAPI import sys import os import pprint import json import pexpect import yaml import logging from packaging.version import Version formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') logger = logging.getLogger('fortiosapi') hdlr = logging.FileHandler('testfortiosapi.log') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) fgt = FortiOSAPI() def main(): # Login to the FGT ip fgt.debug('on') fgthost = '192.168.122.71' user = 'admin' passwd = '' resp = fgt.login(fgthost, user, passwd) pp = pprint.PrettyPrinter(indent=4) resp = fgt.license() pp = pprint.PrettyPrinter(indent=4) pp.pprint(resp) if __name__ == '__main__': main()
Fix incompatibilities with latest paho lib
#!/usr/bin/env python from hackeriet.mqtt import MQTT from hackeriet.door import Doors import threading, os, logging logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s') piface = False # Determine if piface is used on the Pi if "PIFACE" in os.environ: piface = True logging.info('Using piface configuration') # Be backwards compatible with old env variable name gpio_pin = int(os.getenv("DOOR_GPIO_PIN", os.getenv("DOOR_PIN", 0))) # How many seconds should the door lock remain open timeout = int(os.getenv("DOOR_TIMEOUT", 2)) door = Doors(piface=piface,pin=gpio_pin,timeout=timeout) def on_message(mosq, obj, msg): door.open() logging.info('Door opened: %s' % msg.payload door_name = os.getenv("DOOR_NAME", 'hackeriet') door_topic = "hackeriet/door/%s/open" % door_name mqtt = MQTT(on_message) mqtt.subscribe(door_topic, 0) # Block forever def main(): for t in threading.enumerate(): if t us threading.currentThread(): continue t.join() if __name__ == "__main__": main()
#!/usr/bin/env python from hackeriet.mqtt import MQTT from hackeriet.door import Doors import threading, os, logging logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s') piface = False # Determine if piface is used on the Pi if "PIFACE" in os.environ: piface = True logging.info('Using piface configuration') # Be backwards compatible with old env variable name gpio_pin = int(os.getenv("DOOR_GPIO_PIN", os.getenv("DOOR_PIN", 0))) # How many seconds should the door lock remain open timeout = int(os.getenv("DOOR_TIMEOUT", 2)) door = Doors(piface=piface,pin=gpio_pin,timeout=timeout) mqtt = MQTT() door_name = os.getenv("DOOR_NAME", 'hackeriet') door_topic = "hackeriet/door/%s/open" % door_name mqtt.subscribe(door_topic, 0) def on_message(mosq, obj, msg): door.open() logging('Door opened: %s' % msg.payload.decode()) mqtt.on_message = on_message # Block forever def main(): for t in threading.enumerate(): if t us threading.currentThread(): continue t.join() if __name__ == "__main__": main()
Correct return type in the docblock
<?php namespace React\Filesystem; use React\EventLoop\LoopInterface; use React\Filesystem\Node; class Filesystem { protected $filesystem; /** * @param LoopInterface $loop * @return Filesystem */ public static function create(LoopInterface $loop) { return new static(new EioAdapter($loop)); } /** * @param AdapterInterface $filesystem */ public function __construct(AdapterInterface $filesystem) { $this->filesystem = $filesystem; } /** * @param string $filename * @return Node\File */ public function file($filename) { return new Node\File($filename, $this->filesystem); } /** * @param string $path * @return Node\Directory */ public function dir($path) { return new Node\Directory($path, $this->filesystem); } /** * @param string $filename * @return \React\Promise\PromiseInterface */ public function getContents($filename) { return $this->file($filename)->getContents(); } }
<?php namespace React\Filesystem; use React\EventLoop\LoopInterface; use React\Filesystem\Node; class Filesystem { protected $filesystem; /** * @param LoopInterface $loop * @return AdapterInterface */ public static function create(LoopInterface $loop) { return new static(new EioAdapter($loop)); } /** * @param AdapterInterface $filesystem */ public function __construct(AdapterInterface $filesystem) { $this->filesystem = $filesystem; } /** * @param string $filename * @return Node\File */ public function file($filename) { return new Node\File($filename, $this->filesystem); } /** * @param string $path * @return Node\Directory */ public function dir($path) { return new Node\Directory($path, $this->filesystem); } /** * @param string $filename * @return \React\Promise\PromiseInterface */ public function getContents($filename) { return $this->file($filename)->getContents(); } }
Make rootURL: '' and location: 'hash' Closes #173
'use strict'; module.exports = function(environment) { let ENV = { modulePrefix: 'dummy', environment, rootURL: '', locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { // here you can enable a production-specific feature } return ENV; };
'use strict'; module.exports = function(environment) { let ENV = { modulePrefix: 'dummy', environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { // here you can enable a production-specific feature } return ENV; };
chore(cleanup): Make searchIntents be a stream of queries
import { Observable } from 'rxjs/Observable'; import { LOCATION_CHANGE } from 'react-router-redux'; import { ajax } from 'rxjs/observable/dom/ajax'; import * as ActionTypes from '../actionTypes'; export default function searchUsers(action$) { const searchIntents$ = action$.ofType(LOCATION_CHANGE) .filter(({ payload }) => payload.pathname === '/' && !!payload.query.q ) .map(action => action.payload.query.q); return Observable.merge( searchIntents$.map(() => ({ type: ActionTypes.SEARCHED_USERS })), searchIntents$ .switchMap(q => Observable.timer(800) // debouncing .takeUntil(action$.ofType(ActionTypes.CLEARED_RESULTS)) .mergeMapTo( ajax.getJSON(`https://api.github.com/search/users?q=${q}`) ) .map(res => ({ type: ActionTypes.RECEIVED_USERS, payload: { users: res.items } })) ) ); };
import { Observable } from 'rxjs/Observable'; import { LOCATION_CHANGE } from 'react-router-redux'; import { ajax } from 'rxjs/observable/dom/ajax'; import * as ActionTypes from '../actionTypes'; export default function searchUsers(action$) { const searchIntents$ = action$.ofType(LOCATION_CHANGE) .filter(({ payload }) => payload.pathname === '/' && !!payload.query.q ); return Observable.merge( searchIntents$.map(() => ({ type: ActionTypes.SEARCHED_USERS })), searchIntents$ .switchMap(({ payload: { query: { q } } }) => Observable.timer(800) // debouncing .takeUntil(action$.ofType(ActionTypes.CLEARED_RESULTS)) .mergeMapTo(ajax.getJSON(`https://api.github.com/search/users?q=${q}`)) .map(res => ({ type: ActionTypes.RECEIVED_USERS, payload: { users: res.items } })) ) ); };
Select local deployment when -l flag is present
const { LogUtils } = require('../shared/utils') const { ConfigurationFileNotExist } = require('../services/config') module.exports = exports = fileService => (modules, options) => { const localDeployment = options.local || false Promise.resolve() .then(scriptPath => LogUtils.log({ type: 'info', message: `Deployment (${modules.join(', ')}) start.` })) .then(() => fileService.deployModules(modules, !localDeployment)) .then(scriptPath => LogUtils.log({ type: 'success', message: `Deployment task is finished.` })) .catch(error => { if (error instanceof ConfigurationFileNotExist) { LogUtils.log({ type: 'error', message: 'No configuration file. You need to run the init command before.' }) return } LogUtils.log({ type: 'error', message: 'An error occured.', prefix: ' Fail ' }) }) }
const { LogUtils } = require('../shared/utils') const { ConfigurationFileNotExist } = require('../services/config') module.exports = exports = fileService => (modules, options) => { Promise.resolve() .then(scriptPath => LogUtils.log({ type: 'info', message: `Deployment (${modules.join(', ')}) start.` })) .then(() => fileService.deployModules(modules)) .then(scriptPath => LogUtils.log({ type: 'success', message: `Deployment task is finished.` })) .catch(error => { if (error instanceof ConfigurationFileNotExist) { LogUtils.log({ type: 'error', message: 'No configuration file. You need to run the init command before.' }) return } LogUtils.log({ type: 'error', message: 'An error occured.', prefix: ' Fail ' }) }) }
Fix for Blender version check
bl_info = { "name": "Booltron", "author": "Mikhail Rachinskiy (jewelcourses.com)", "version": (2000,), "blender": (2,74,0), "location": "3D View → Tool Shelf", "description": "Booltron—super add-on for super fast booleans.", "wiki_url": "https://github.com/mrachinskiy/blender-addon-booltron", "tracker_url": "https://github.com/mrachinskiy/blender-addon-booltron/issues", "category": "Object"} if "bpy" in locals(): from importlib import reload reload(utility) reload(operators) reload(ui) del reload else: import bpy from . import (operators, ui) classes = ( ui.ToolShelf, operators.UNION, operators.DIFFERENCE, operators.INTERSECT, operators.SLICE, operators.SUBTRACT, ) def register(): for cls in classes: bpy.utils.register_class(cls) def unregister(): for cls in classes: bpy.utils.unregister_class(cls) if __name__ == "__main__": register()
bl_info = { "name": "Booltron", "author": "Mikhail Rachinskiy (jewelcourses.com)", "version": (2000,), "blender": (2,7,4), "location": "3D View → Tool Shelf", "description": "Booltron—super add-on for super fast booleans.", "wiki_url": "https://github.com/mrachinskiy/blender-addon-booltron", "tracker_url": "https://github.com/mrachinskiy/blender-addon-booltron/issues", "category": "Mesh"} if "bpy" in locals(): from importlib import reload reload(utility) reload(operators) reload(ui) del reload else: import bpy from . import (operators, ui) classes = ( ui.ToolShelf, operators.UNION, operators.DIFFERENCE, operators.INTERSECT, operators.SLICE, operators.SUBTRACT, ) def register(): for cls in classes: bpy.utils.register_class(cls) def unregister(): for cls in classes: bpy.utils.unregister_class(cls) if __name__ == "__main__": register()
Fix type in creation of fasta_dir biobox entry
import os import yaml def generate(args): output = {"version" : "0.9.0", "arguments" : args} return yaml.safe_dump(output, default_flow_style = False) def parse(dir_): with open(os.path.join(dir_, 'biobox.yaml'), 'r') as f: return yaml.load(f.read()) def fastq_arguments(args): return files_values("fastq", args) def fasta_arguments(args): return files_values("fasta", args) def reference_argument(ref): return {"fasta_dir": [{"id" : 1, "type" : "reference", "value" : ref}]} def files_values(identifier, args): values = [entry(identifier + "_" + str(i), p_c, t) for (i, (p_c, t)) in enumerate(args)] return {identifier : values} def entry(id_, value, type_): return {"id" : id_, "value" : value, "type" : type_} def create_biobox_directory(content): import tempfile as tmp dir_ = tmp.mkdtemp() with open(os.path.join(dir_, "biobox.yaml"), "w") as f: f.write(content) return dir_
import os import yaml def generate(args): output = {"version" : "0.9.0", "arguments" : args} return yaml.safe_dump(output, default_flow_style = False) def parse(dir_): with open(os.path.join(dir_, 'biobox.yaml'), 'r') as f: return yaml.load(f.read()) def fastq_arguments(args): return files_values("fastq", args) def fasta_arguments(args): return files_values("fasta", args) def reference_argument(ref): return {"fasta_dir": [{"id" : 1, "type" : "reference", "value" : "ref"}]} def files_values(identifier, args): values = [entry(identifier + "_" + str(i), p_c, t) for (i, (p_c, t)) in enumerate(args)] return {identifier : values} def entry(id_, value, type_): return {"id" : id_, "value" : value, "type" : type_} def create_biobox_directory(content): import tempfile as tmp dir_ = tmp.mkdtemp() with open(os.path.join(dir_, "biobox.yaml"), "w") as f: f.write(content) return dir_
Remove old way of sorting This is redundant since the model layer has built-in sorting. It’s also not a good separation of concerns for something presentational (sort order) to be in the API client layer.
from app.notify_client import NotifyAdminAPIClient, cache class EmailBrandingClient(NotifyAdminAPIClient): @cache.set("email_branding-{branding_id}") def get_email_branding(self, branding_id): return self.get(url="/email-branding/{}".format(branding_id)) @cache.set("email_branding") def get_all_email_branding(self): return self.get(url="/email-branding")["email_branding"] @cache.delete("email_branding") def create_email_branding(self, logo, name, text, colour, brand_type): data = {"logo": logo, "name": name, "text": text, "colour": colour, "brand_type": brand_type} return self.post(url="/email-branding", data=data) @cache.delete("email_branding") @cache.delete("email_branding-{branding_id}") def update_email_branding(self, branding_id, logo, name, text, colour, brand_type): data = {"logo": logo, "name": name, "text": text, "colour": colour, "brand_type": brand_type} return self.post(url="/email-branding/{}".format(branding_id), data=data) email_branding_client = EmailBrandingClient()
from app.notify_client import NotifyAdminAPIClient, cache class EmailBrandingClient(NotifyAdminAPIClient): @cache.set("email_branding-{branding_id}") def get_email_branding(self, branding_id): return self.get(url="/email-branding/{}".format(branding_id)) @cache.set("email_branding") def get_all_email_branding(self, sort_key=None): brandings = self.get(url="/email-branding")["email_branding"] if sort_key and sort_key in brandings[0]: brandings.sort(key=lambda branding: branding[sort_key].lower()) return brandings @cache.delete("email_branding") def create_email_branding(self, logo, name, text, colour, brand_type): data = {"logo": logo, "name": name, "text": text, "colour": colour, "brand_type": brand_type} return self.post(url="/email-branding", data=data) @cache.delete("email_branding") @cache.delete("email_branding-{branding_id}") def update_email_branding(self, branding_id, logo, name, text, colour, brand_type): data = {"logo": logo, "name": name, "text": text, "colour": colour, "brand_type": brand_type} return self.post(url="/email-branding/{}".format(branding_id), data=data) email_branding_client = EmailBrandingClient()
:alien: Change Cache Provider Since Flask upgraded See: https://github.com/thadeusb/flask-cache/issues/188
# !/usr/bin/python3 # -*- coding: utf-8 -*- # Copyright (c) 2017-2020 Rhilip <rhilipruan@gmail.com> import pymysql from flask import Flask from flaskext.mysql import MySQL from flask_cors import CORS from flask_caching import Cache app = Flask(__name__, instance_relative_config=True) app.config.from_object('config') app.config.from_pyfile('config.py') class Database(MySQL): def exec(self, sql: str, args=None, r_dict: bool = False, fetch_all: bool = False, ret_row: bool = False): db = self.get_db() cursor = db.cursor(pymysql.cursors.DictCursor) if r_dict else db.cursor() # Cursor type row = cursor.execute(sql, args) data = cursor.fetchall() if fetch_all else cursor.fetchone() # The lines of return info (one or all) return (row, data) if ret_row else data mysql = Database(app=app, autocommit=True) cache = Cache(app) CORS(app)
# !/usr/bin/python3 # -*- coding: utf-8 -*- # Copyright (c) 2017-2020 Rhilip <rhilipruan@gmail.com> import pymysql from flask import Flask from flaskext.mysql import MySQL from flask_cors import CORS from flask_cache import Cache app = Flask(__name__, instance_relative_config=True) app.config.from_object('config') app.config.from_pyfile('config.py') class Database(MySQL): def exec(self, sql: str, args=None, r_dict: bool = False, fetch_all: bool = False, ret_row: bool = False): db = self.get_db() cursor = db.cursor(pymysql.cursors.DictCursor) if r_dict else db.cursor() # Cursor type row = cursor.execute(sql, args) data = cursor.fetchall() if fetch_all else cursor.fetchone() # The lines of return info (one or all) return (row, data) if ret_row else data mysql = Database(app=app, autocommit=True) cache = Cache(app) CORS(app)
Drop ThreadPool, use joblib instead
""" Example for parallel optimization with skopt. The points to evaluate in parallel are selected according to the "constant lie" approach. """ import numpy as np from sklearn.externals.joblib import Parallel, delayed from skopt.space import Real from skopt.learning import GaussianProcessRegressor from skopt import Optimizer optimizer = Optimizer( base_estimator=GaussianProcessRegressor(), dimensions=[Real(-3.0, 3.0) for i in range(10)] ) # objective function to minimze def objective(x): return np.sum(np.array(x) ** 2) # configure number of threads to be used in parallel, and overall # of computations n_points, n_steps, Y = 4, 20, [] for i in range(n_steps): x = optimizer.ask(n_points) # evaluate n_points in parallel y = Parallel()(delayed(objective)(v) for v in x) # tell points and corresponding objectives to the optimizer optimizer.tell(x, y) # keep objectives history Y.extend(y) print min(Y)
""" Example for parallel optimization with skopt. The points to evaluate in parallel are selected according to the "constant lie" approach. """ import numpy as np from multiprocessing.pool import ThreadPool from skopt.space import Real from skopt.learning import GaussianProcessRegressor from skopt import Optimizer # ThreadPool is used for parallel computations pool = ThreadPool() optimizer = Optimizer( base_estimator=GaussianProcessRegressor(), dimensions=[Real(-3.0, 3.0) for i in range(10)] ) # configure number of threads to be used in parallel, and overall # of computations n_points, n_steps, Y = 4, 20, [] for i in range(n_steps): x = optimizer.ask(n_points) # evaluate n_points in parallel y = pool.map(lambda x: np.sum(np.array(x) ** 2), x) # tell points and corresponding objectives to the optimizer optimizer.tell(x, y) # keep objectives history Y.extend(y) print min(Y)
Update manipulation class in context primary key
<?php namespace Rentgen\Schema; use Symfony\Component\DependencyInjection\ContainerInterface; use Rentgen\Rentgen; use Rentgen\Database\Table; use Rentgen\Database\ForeignKey; use Rentgen\Database\PrimaryKey; class Manipulation { private $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function createTable(Table $table, array $constraints = array()) { $command = $this->container ->get('create_table') ->setTable($table); foreach ($constraints as $constraint) { if($constraint instanceof PrimaryKey) { $command->setPrimaryKey($constraint); } } return $command->execute(); } public function dropTable(Table $table) { return $this->container ->get('drop_table') ->setTable($table) ->execute(); } public function addForeignKey(ForeignKey $foreignKey) { return $this->container ->get('add_foreign_key') ->setForeignKey($foreignKey) ->execute(); } public function dropForeignKey(ForeignKey $foreignKey) { return $this->container ->get('drop_constraint') ->setConstraint($foreignKey) ->execute(); } }
<?php namespace Rentgen\Schema; use Symfony\Component\DependencyInjection\ContainerInterface; use Rentgen\Rentgen; use Rentgen\Database\Table; use Rentgen\Database\ForeignKey; class Manipulation { private $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function createTable(Table $table) { return $this->container ->get('create_table') ->setTable($table) ->execute(); } public function dropTable(Table $table) { return $this->container ->get('drop_table') ->setTable($table) ->execute(); } public function addForeignKey(ForeignKey $foreignKey) { return $this->container ->get('add_foreign_key') ->setForeignKey($foreignKey) ->execute(); } public function dropForeignKey(ForeignKey $foreignKey) { return $this->container ->get('drop_constraint') ->setConstraint($foreignKey) ->execute(); } }
Add explicit JSON separators and append newline to end of JSON string.
"""Extension of flask.Response. """ from flask import Response as ResponseBase, json, current_app, request class Response(ResponseBase): """Extend flask.Response with support for list/dict conversion to JSON.""" def __init__(self, content=None, *args, **kargs): if isinstance(content, (list, dict)): kargs['mimetype'] = 'application/json' content = to_json(content) super(Response, self).__init__(content, *args, **kargs) @classmethod def force_type(cls, response, environ=None): """Override with support for list/dict.""" if isinstance(response, (list, dict)): return cls(response) else: return super(Response, cls).force_type(response, environ) def to_json(content): """Converts content to json while respecting config options.""" indent = None separators = (',', ':') if (current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr): indent = 2 separators = (', ', ': ') return (json.dumps(content, indent=indent, separators=separators), '\n')
"""Extension of flask.Response. """ from flask import Response as ResponseBase, json, current_app, request class Response(ResponseBase): """Extend flask.Response with support for list/dict conversion to JSON.""" def __init__(self, content=None, *args, **kargs): if isinstance(content, (list, dict)): kargs['mimetype'] = 'application/json' content = to_json(content) super(Response, self).__init__(content, *args, **kargs) @classmethod def force_type(cls, response, environ=None): """Override with support for list/dict.""" if isinstance(response, (list, dict)): return cls(response) else: return super(Response, cls).force_type(response, environ) def to_json(content): """Converts content to json while respecting config options.""" indent = None if (current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr): indent = 2 return json.dumps(content, indent=indent)
Load pagedown_custom.js a bit later so it can use translations
// The rest of the externals //= require_tree ./external //= require ./discourse/helpers/i18n_helpers //= require ./discourse //= require ./locales/date_locales.js // Pagedown customizations //= require ./pagedown_custom.js // Stuff we need to load first //= require_tree ./discourse/mixins //= require ./discourse/components/computed //= require ./discourse/views/view //= require ./discourse/components/debounce //= require ./discourse/models/model //= require ./discourse/models/user_action //= require ./discourse/controllers/controller //= require ./discourse/controllers/object_controller //= require ./discourse/views/modal/modal_body_view //= require ./discourse/views/combobox_view //= require ./discourse/views/buttons/button_view //= require ./discourse/views/buttons/dropdown_button_view //= require ./discourse/routes/discourse_route //= require ./discourse/routes/discourse_restricted_user_route //= require_tree ./discourse/controllers //= require_tree ./discourse/components //= require_tree ./discourse/models //= require_tree ./discourse/views //= require_tree ./discourse/helpers //= require_tree ./discourse/templates //= require_tree ./discourse/routes //= require ./external/browser-update.js
// Pagedown customizations //= require ./pagedown_custom.js // The rest of the externals //= require_tree ./external //= require ./discourse/helpers/i18n_helpers //= require ./discourse //= require ./locales/date_locales.js // Stuff we need to load first //= require_tree ./discourse/mixins //= require ./discourse/components/computed //= require ./discourse/views/view //= require ./discourse/components/debounce //= require ./discourse/models/model //= require ./discourse/models/user_action //= require ./discourse/controllers/controller //= require ./discourse/controllers/object_controller //= require ./discourse/views/modal/modal_body_view //= require ./discourse/views/combobox_view //= require ./discourse/views/buttons/button_view //= require ./discourse/views/buttons/dropdown_button_view //= require ./discourse/routes/discourse_route //= require ./discourse/routes/discourse_restricted_user_route //= require_tree ./discourse/controllers //= require_tree ./discourse/components //= require_tree ./discourse/models //= require_tree ./discourse/views //= require_tree ./discourse/helpers //= require_tree ./discourse/templates //= require_tree ./discourse/routes //= require ./external/browser-update.js
Use Karma 0.14 style programmatic calling Fixes https://github.com/olyckne/laravel-elixir-karma/issues/2
var gulp = require('gulp'); var elixir = require('laravel-elixir'); var KarmaServer = require('karma').Server; var _ = require('underscore'); var gutils = require('gulp-util'); var task = elixir.Task; function isTddOrWatchTask() { return gutils.env._.indexOf('watch') > -1 || gutils.env._.indexOf('tdd') > -1; } elixir.extend('karma', function(args) { if (! isTddOrWatchTask()) return; var defaults = { configFile: process.cwd() + '/karma.conf.js', jsDir: ['resources/assets/js/**/*.js', 'resources/assets/coffee/**/*.coffee'], autoWatch: true, singleRun: false }; var options = _.extend(defaults, args); var server; var isStarted = false; new task('karma', function() { if( ! isStarted) { server = new KarmaServer(options); server.start(); isStarted = true; } }).watch(options.jsDir, 'tdd'); });
var gulp = require('gulp'); var elixir = require('laravel-elixir'); var karma = require('karma').server; var _ = require('underscore'); var gutils = require('gulp-util'); var task = elixir.Task; function isTddOrWatchTask() { return gutils.env._.indexOf('watch') > -1 || gutils.env._.indexOf('tdd') > -1; } elixir.extend('karma', function(args) { if (! isTddOrWatchTask()) return; var defaults = { configFile: process.cwd()+'/karma.conf.js', jsDir: ['resources/assets/js/**/*.js', 'resources/assets/coffee/**/*.coffee'], autoWatch: true, singleRun: false }; var options = _.extend(defaults, args); var isStarted = false; new task('karma', function() { if( ! isStarted) { karma.start(options); isStarted = true; } }).watch(options.jsDir, 'tdd'); });
Use `nextTick` to avoid time shifting issues.
import { Promise } from 'rsvp'; import { nextTick } from './-utils'; export default function(callback, options = {}) { let timeout = 'timeout' in options ? options.timeout : 1000; let waitUntilTimedOut = new Error('waitUntil timed out'); return new Promise(function(resolve, reject) { // starting at -10 because the first invocation happens on 0 // but still increments the time... let time = -10; function tick() { time += 10; let value = callback(); if (value) { resolve(value); } else if (time < timeout) { // using `setTimeout` directly to allow fake timers // to intercept nextTick(tick, 10); } else { reject(waitUntilTimedOut); } } nextTick(tick); }); }
import { Promise } from 'rsvp'; import { nextTick } from './-utils'; export default function(callback, options = {}) { let timeout = 'timeout' in options ? options.timeout : 1000; let waitUntilTimedOut = new Error('waitUntil timed out'); return new Promise(function(resolve, reject) { // starting at -10 because the first invocation happens on 0 // but still increments the time... let time = -10; function tick() { time += 10; let value = callback(); if (value) { resolve(value); } else if (time < timeout) { // using `setTimeout` directly to allow fake timers // to intercept setTimeout(tick, 10); } else { reject(waitUntilTimedOut); } } nextTick(tick); }); }
Add fail case in API call
import fetch from 'isomorphic-fetch'; import API from 'utils/api'; import { set_loading } from './loading'; export const QUOTE_RECEIVED = 'quote_received'; export function get_quote() { return function(dispatch) { dispatch(set_loading(true)); return fetch(API.root + API.path.randomQuote) .then(response => response.json()) .then((json) => { dispatch(set_loading(false)); dispatch(quote_received(json)); }) .catch(() => { dispatch(set_loading(false)); }); } } export function quote_received(data) { return { type: QUOTE_RECEIVED, data } } export default function quote(state = {}, action) { switch(action.type) { case QUOTE_RECEIVED: return Object.assign({}, state, {value: action.data.quote, author: action.data.author}); default: return state; } }
import fetch from 'isomorphic-fetch'; import API from 'utils/api'; import { set_loading } from './loading'; export const QUOTE_RECEIVED = 'quote_received'; export function get_quote() { return function(dispatch) { dispatch(set_loading(true)); return fetch(API.root + API.path.randomQuote) .then(response => response.json()) .then((json) => { dispatch(set_loading(false)); dispatch(quote_received(json)); }); } } export function quote_received(data) { return { type: QUOTE_RECEIVED, data } } export default function quote(state = {}, action) { switch(action.type) { case QUOTE_RECEIVED: return Object.assign({}, state, {value: action.data.quote, author: action.data.author}); default: return state; } }
Make OIDC be default auth mechanism
const logger = require('../logging'); const passport = require('passport'); const { setupOIDC } = require('./oidc'); const getUserById = require('../models/user.accessors').getUserById; require('./providers/ow4.js'); module.exports = async (app) => { await setupOIDC(); passport.serializeUser((user, done) => { logger.silly('Serializing user', { userId: user.id }); done(null, user.id); }); passport.deserializeUser((id, done) => { logger.silly('Deserializing user', { userId: id }); done(null, () => getUserById(id)); }); app.use(passport.initialize()); app.use(passport.session()); app.get('/login', passport.authenticate('oidc')); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.get('/auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/openid-login' })); return app; };
const logger = require('../logging'); const passport = require('passport'); const { setupOIDC } = require('./oidc'); const getUserById = require('../models/user.accessors').getUserById; require('./providers/ow4.js'); module.exports = async (app) => { passport.serializeUser((user, done) => { logger.silly('Serializing user', { userId: user.id }); done(null, user.id); }); passport.deserializeUser((id, done) => { logger.silly('Deserializing user', { userId: id }); done(null, () => getUserById(id)); }); app.use(passport.initialize()); app.use(passport.session()); app.get('/login', passport.authenticate('oauth2', { successReturnToOrRedirect: '/' })); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.get('/auth', passport.authenticate('oauth2', { callback: true }), (req, res) => { res.redirect('/'); }); if (process.env.SDF_OIDC && process.env.SDF_OIDC.toLowerCase() === 'true') { const success = await setupOIDC(); if (success) { app.get('/openid-login', passport.authenticate('oidc')); app.get('/openid-auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/openid-login' })); } return app; } return app; };
Improve error message on DispatchError's
# -*- coding: utf-8 -*- import importlib from simpleflow.activity import Activity from .exceptions import DispatchError class Dispatcher(object): """ Dispatch by name, like simpleflow.swf.process.worker.dispatch.by_module.ModuleDispatcher but without a hierarchy. """ @staticmethod def dispatch_activity(name): """ :param name: :type name: str :return: :rtype: Activity :raise DispatchError: if doesn't exist or not an activity """ module_name, activity_name = name.rsplit('.', 1) module = importlib.import_module(module_name) activity = getattr(module, activity_name, None) if not isinstance(activity, Activity): raise DispatchError("dispatching '{}' resulted in: {}".format(name, activity)) return activity
# -*- coding: utf-8 -*- import importlib from simpleflow.activity import Activity from .exceptions import DispatchError class Dispatcher(object): """ Dispatch by name, like simpleflow.swf.process.worker.dispatch.by_module.ModuleDispatcher but without a hierarchy. """ @staticmethod def dispatch_activity(name): """ :param name: :type name: str :return: :rtype: Activity :raise DispatchError: if doesn't exist or not an activity """ module_name, activity_name = name.rsplit('.', 1) module = importlib.import_module(module_name) activity = getattr(module, activity_name, None) if not isinstance(activity, Activity): raise DispatchError() return activity
Use Whoops in debug mode, JSON API compliant errors otherwise
<?php use Flarum\Core; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Zend\Diactoros\Server; use Zend\Stratigility\MiddlewarePipe; // Instantiate the application, register providers etc. $app = require __DIR__.'/system/bootstrap.php'; // Set up everything we need for the API $app->instance('type', 'api'); $app->register('Flarum\Api\ApiServiceProvider'); $app->register('Flarum\Support\Extensions\ExtensionsServiceProvider'); // Build a middleware pipeline for the API $api = new MiddlewarePipe(); $api->pipe($app->make('Flarum\Api\Middleware\ReadJsonParameters')); $api->pipe($app->make('Flarum\Api\Middleware\LoginWithHeader')); $api->pipe('/api', $app->make('Flarum\Http\RouterMiddleware', ['routes' => $app->make('flarum.api.routes')])); if (Core::inDebugMode()) { $api->pipe(new \Franzl\Middleware\Whoops\Middleware()); } else { $api->pipe(new \Flarum\Api\Middleware\JsonApiErrors()); } $server = Server::createServer( $api, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES ); $server->listen();
<?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Zend\Diactoros\Server; use Zend\Stratigility\MiddlewarePipe; // Instantiate the application, register providers etc. $app = require __DIR__.'/system/bootstrap.php'; // Set up everything we need for the API $app->instance('type', 'api'); $app->register('Flarum\Api\ApiServiceProvider'); $app->register('Flarum\Support\Extensions\ExtensionsServiceProvider'); // Build a middleware pipeline for the API $api = new MiddlewarePipe(); $api->pipe($app->make('Flarum\Api\Middleware\ReadJsonParameters')); $api->pipe($app->make('Flarum\Api\Middleware\LoginWithHeader')); $api->pipe('/api', $app->make('Flarum\Http\RouterMiddleware', ['routes' => $app->make('flarum.api.routes')])); $api->pipe(new \Flarum\Api\Middleware\JsonApiErrors()); $server = Server::createServer( $api, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES ); $server->listen();
Fix test for Boolean value
package com.mpalourdio.hello.model; import com.mpalourdio.hello.AbstractTestRunner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import java.util.List; @DataJpaTest public class TaskRepositoryTest extends AbstractTestRunner { @Autowired private TestEntityManager entityManager; @Autowired private TaskRepository taskRepository; private Task task; @Before public void setUp() { task = new Task(); task.setTaskArchived(true); task.setTaskName("name"); task.setTaskDescription("description"); task.setTaskPriority("LOW"); task.setTaskStatus("ACTIVE"); } @Test public void testTableIsEmpty() { final List<Task> taskList = taskRepository.findAll(); Assert.assertEquals(0, taskList.size()); } @Test public void testAndPlayWithTheFakeentityManager() { final Task persistedTask = entityManager.persistFlushFind(task); Assert.assertEquals(persistedTask.getTaskDescription(), "description"); } }
package com.mpalourdio.hello.model; import com.mpalourdio.hello.AbstractTestRunner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import java.util.List; @DataJpaTest public class TaskRepositoryTest extends AbstractTestRunner { @Autowired private TestEntityManager entityManager; @Autowired private TaskRepository taskRepository; private Task task; @Before public void setUp() { task = new Task(); task.setTaskArchived(1); task.setTaskName("name"); task.setTaskDescription("description"); task.setTaskPriority("LOW"); task.setTaskStatus("ACTIVE"); } @Test public void testTableIsEmpty() { final List<Task> taskList = taskRepository.findAll(); Assert.assertEquals(0, taskList.size()); } @Test public void testAndPlayWithTheFakeentityManager() { final Task persistedTask = entityManager.persistFlushFind(task); Assert.assertEquals(persistedTask.getTaskDescription(), "description"); } }
Support for generic UI navigation
/* See license.txt for terms of usage */ "use strict"; define(function(require, exports, module) { // Dependencies const React = require("react"); const { Reps } = require("reps/reps"); const { A, SPAN } = Reps.DOM; /** * @template Generic link template. Used for all UI elements that * should behave as links and navigate the user thorough the UI. */ const ObjectLink = React.createClass( /** @lends ObjectLink */ { displayName: "ObjectLink", render: function() { var className = this.props.className; var objectClassName = className ? " objectLink-" + className : ""; var linkClassName = "objectLink" + objectClassName + " a11yFocus"; return ( SPAN({className: linkClassName, onClick: this.onClick}, this.props.children ) ) }, onClick: function(event) { if (!this.props.object) { return; } event.stopPropagation(); event.preventDefault(); // Fire generic event for UI navigation. E.g. clicking on // an element object navigates the user to the Inspector // panel. var customEvent = new CustomEvent("fbsdk:navigate", { detail: { repObject: this.props.object } }); var target = event.target; target.dispatchEvent(customEvent); } }); // Exports from this module exports.ObjectLink = React.createFactory(ObjectLink); });
/* See license.txt for terms of usage */ "use strict"; define(function(require, exports, module) { // Dependencies const React = require("react"); const { Reps } = require("reps/reps"); const { A, SPAN } = Reps.DOM; /** * @template TODO docs */ const ObjectLink = React.createClass({ displayName: "ObjectLink", render: function() { var className = this.props.className; var objectClassName = className ? " objectLink-" + className : ""; var linkClassName = "objectLink" + objectClassName + " a11yFocus"; return ( SPAN({className: linkClassName, _repObject: this.props.object}, this.props.children ) ) } }); // Exports from this module exports.ObjectLink = React.createFactory(ObjectLink); });
Fix hologram-ping to connect using TLS Fixes https://github.com/AdRoll/hologram/issues/70
package main import ( "flag" "fmt" "crypto/tls" "crypto/x509" "github.com/AdRoll/hologram/protocol" ) var host = flag.String("host", "localhost", "IP or hostname to ping") var port = flag.Int("port", 3100, "Port to connect to for ping") func main() { flag.Parse() connString := fmt.Sprintf("%s:%d", *host, *port) pool := x509.NewCertPool() tlsConf := &tls.Config{ RootCAs: pool, // Hologram only uses TLS to ensure the credentials that go across the wire are kept secret, and since go uses // ECDHE by default, we actually don't care about leaking keys or authenticating either end of the connection. InsecureSkipVerify: true, } conn, err := tls.Dial("tcp", connString, tlsConf) if err != nil { panic(err) } fmt.Printf("sending ping to %s...\n", connString) err = protocol.Write(conn, &protocol.Message{Ping: &protocol.Ping{}}) response, err := protocol.Read(conn) if err != nil { panic(err) } if response.GetPing() != nil { fmt.Println("Got pong!") } }
package main import ( "flag" "fmt" "net" "github.com/AdRoll/hologram/protocol" ) var host = flag.String("host", "localhost", "IP or hostname to ping") var port = flag.Int("port", 3100, "Port to connect to for ping") func main() { flag.Parse() connString := fmt.Sprintf("%s:%d", *host, *port) conn, err := net.Dial("tcp", connString) if err != nil { panic(err) } fmt.Printf("sending ping to %s...\n", connString) err = protocol.Write(conn, &protocol.Message{Ping: &protocol.Ping{}}) response, err := protocol.Read(conn) if err != nil { panic(err) } if response.GetPing() != nil { fmt.Println("Got pong!") } }
Remove default args for backwards compatibility
'use strict'; const path = require('path'); const fs = require('fs'); const tmp = require('tmp'); const _ = require('lodash'); const Util = require('../util'); const Deployment = require('../models/Deployment'); class Builder { constructor(deployment) { this.deployment = deployment; } get workdir() { return path.resolve(path.join(__dirname, '..', '..', 'nix')); } eval(args) { args = args || {}; const tmpFile = tmp.fileSync(); fs.write(tmpFile.fd, JSON.stringify(_.extend(this.deployment.args, args))); return Util.run( `nix-build --arg configuration ${this.deployment.file} --arg args ${tmpFile.name} --no-out-link ${this.workdir}/default.nix` ).then(result => { tmpFile.removeCallback(); // remove new lines from file const path = _.trimEnd(result); this.deployment.loadSpec(path); // construct new specs model return this.deployment; }); } } module.exports = Builder;
'use strict'; const path = require('path'); const fs = require('fs'); const tmp = require('tmp'); const _ = require('lodash'); const Util = require('../util'); const Deployment = require('../models/Deployment'); class Builder { constructor(deployment) { this.deployment = deployment; } get workdir() { return path.resolve(path.join(__dirname, '..', '..', 'nix')); } eval(args = {}) { const tmpFile = tmp.fileSync(); fs.write(tmpFile.fd, JSON.stringify(_.extend(this.deployment.args, args))); return Util.run( `nix-build --arg configuration ${this.deployment.file} --arg args ${tmpFile.name} --no-out-link ${this.workdir}/default.nix` ).then(result => { tmpFile.removeCallback(); // remove new lines from file const path = _.trimEnd(result); this.deployment.loadSpec(path); // construct new specs model return this.deployment; }); } } module.exports = Builder;
Update warn to info to make customer happy
package cli import ( "github.com/qiniu/log" "qshell" "strconv" ) func QiniuUpload(cmd string, params ...string) { if len(params) == 1 || len(params) == 2 { var uploadConfigFile string var threadCount int64 var err error if len(params) == 2 { threadCount, err = strconv.ParseInt(params[0], 10, 64) if err != nil { log.Error("Invalid <ThreadCount> value,", params[0]) return } uploadConfigFile = params[1] } else { uploadConfigFile = params[0] } if threadCount < qshell.MIN_UPLOAD_THREAD_COUNT || threadCount > qshell.MAX_UPLOAD_THREAD_COUNT { log.Info("You can set <ThreadCount> value between 1 and 100 to improve speed") threadCount = qshell.MIN_UPLOAD_THREAD_COUNT } qshell.QiniuUpload(int(threadCount), uploadConfigFile) } else { CmdHelp(cmd) } }
package cli import ( "github.com/qiniu/log" "qshell" "strconv" ) func QiniuUpload(cmd string, params ...string) { if len(params) == 1 || len(params) == 2 { var uploadConfigFile string var threadCount int64 var err error if len(params) == 2 { threadCount, err = strconv.ParseInt(params[0], 10, 64) if err != nil { log.Error("Invalid <ThreadCount> value,", params[0]) return } uploadConfigFile = params[1] } else { uploadConfigFile = params[0] } if threadCount < qshell.MIN_UPLOAD_THREAD_COUNT || threadCount > qshell.MAX_UPLOAD_THREAD_COUNT { log.Warn("<ThreadCount> can only between 1 and 100") threadCount = qshell.MIN_UPLOAD_THREAD_COUNT } qshell.QiniuUpload(int(threadCount), uploadConfigFile) } else { CmdHelp(cmd) } }
Revert "Set meta description for the main page."
import Vue from 'vue' import Router from 'vue-router' import index from '@/components/index' import four from '@/components/four' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', name: 'github', component: index }, { path: '/streams/:stream_id', name: 'stream', component: () => import('@/components/stream') }, { path: '/cves', name: 'cves', component: () => import('@/components/cves') }, { path: '/cves/:cve_id', name: 'cve', component: () => import('@/components/cve') }, { path: '/404', name: 'four', component: four }, { path: '*', redirect: '/404' } ] })
import Vue from 'vue' import Router from 'vue-router' import index from '@/components/index' import four from '@/components/four' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', name: 'github', component: index, meta: { title: 'Linux Kernel CVE Tracker', metaTags: [ { name: 'description', content: 'Security Tracker for the Linux Kernel. Provides details, fixed versions, and CVSS scores for CVEs affecting the Linux Kernel.' } ] } }, { path: '/streams/:stream_id', name: 'stream', component: () => import('@/components/stream') }, { path: '/cves', name: 'cves', component: () => import('@/components/cves') }, { path: '/cves/:cve_id', name: 'cve', component: () => import('@/components/cve') }, { path: '/404', name: 'four', component: four }, { path: '*', redirect: '/404' } ] })
Support for listener in component constructor
/** * A component * @constructor * @param {Object} options * @param {Element} options.element * @param {String} options.name * @param {Object} options.listen A listener */ hui.ui.Component = function(options) { this.name = options.name; if (!this.name) { hui.ui.latestObjectIndex++; this.name = 'unnamed'+hui.ui.latestObjectIndex; } this.element = hui.get(options.element); this.delegates = []; if (this.nodes) { this.nodes = hui.collect(this.nodes,this.element); } if (options.listen) { this.listen(options.listen); } hui.ui.registerComponent(this); } hui.ui.Component.prototype = { /** * Add event listener * @param {Object} listener An object with methods for different events */ listen : function(listener) { this.delegates.push(listener); }, fire : function(name,value,event) { return hui.ui.callDelegates(this,name,value,event); }, /** * Get the components root element * @returns Element */ getElement : function() { return this.element; }, destroy : function() { if (this.element) { hui.dom.remove(this.element); } } }
/** * A component * @constructor * @param {Object} options * @param {Element} options.element * @param {String} options.name */ hui.ui.Component = function(options) { this.name = options.name; if (!this.name) { hui.ui.latestObjectIndex++; this.name = 'unnamed'+hui.ui.latestObjectIndex; } this.element = hui.get(options.element); this.listeners = []; if (this.nodes) { this.nodes = hui.collect(this.nodes,this.element); } hui.ui.registerComponent(this); } hui.ui.Component.prototype = { /** * Add event listener * @param {Object} listener An object with methods for different events */ listen : function(listener) { this.listeners.push(listener); }, fire : function(name,value,event) { return hui.ui.callDelegates(this,name,value,event); }, /** * Get the components root element * @returns Element */ getElement : function() { return this.element; }, destroy : function() { if (this.element) { hui.dom.remove(this.element); } } }
Add fr translation for "Switch language"
<?php /* Section: global Language: French Français */ $translations = array( 'sitetitle1' => 'db4free.net', 'sitetitle2' => 'Base de données MySQL gratuite', 'topnav1' => 'Bienvenue', 'topnav2' => 'Base de données', 'topnav3' => 'Twitter', 'topnav4' => 'Blog mpopp.net', 'topnav5' => 'phpMyAdmin', 'sidebar_1_2' => 'Dons', 'sidebar_1_3' => 'Traductions', 'sidebar_1_4' => 'Changelog', 'sidebar_1_5' => 'Mentions', 'sidebar_2_1' => 'A propos de db4free.net', 'sidebar_2_2' => 'Conditions d\'utilisation', 'sidebar_2_3' => 'Se connecter', 'sidebar_2_4' => 'Modifier votre mot de passe', 'sidebar_2_5' => 'Supprimer votre compte', 'sidebar_2_6' => 'Mot de passe oublié&nbsp;?', 'pmalogin' => 'phpMyAdmin Login', 'username' => 'Nom d\'utilisateur', 'password' => 'Mot de passe', 'login' => 'Login', 'switch_language' => 'Changez la langue', ); ?>
<?php /* Section: global Language: French Français */ $translations = array( 'sitetitle1' => 'db4free.net', 'sitetitle2' => 'Base de données MySQL gratuite', 'topnav1' => 'Bienvenue', 'topnav2' => 'Base de données', 'topnav3' => 'Twitter', 'topnav4' => 'Blog mpopp.net', 'topnav5' => 'phpMyAdmin', 'sidebar_1_2' => 'Dons', 'sidebar_1_3' => 'Traductions', 'sidebar_1_4' => 'Changelog', 'sidebar_1_5' => 'Mentions', 'sidebar_2_1' => 'A propos de db4free.net', 'sidebar_2_2' => 'Conditions d\'utilisation', 'sidebar_2_3' => 'Se connecter', 'sidebar_2_4' => 'Modifier votre mot de passe', 'sidebar_2_5' => 'Supprimer votre compte', 'sidebar_2_6' => 'Mot de passe oublié&nbsp;?', 'pmalogin' => 'phpMyAdmin Login', 'username' => 'Nom d\'utilisateur', 'password' => 'Mot de passe', 'login' => 'Login', ); ?>
Disable Service Worker from registration
import swURL from 'file?name=sw.js!babel!./sw' // eslint-disable-line // Register Service Worker // if ('serviceWorker' in navigator) { // window.addEventListener('load', function () { // navigator.serviceWorker.register(swURL).then(function (registration) { // // Registration was successful // console.log('ServiceWorker registration successful with scope: ', registration.scope) // }).catch(function (err) { // // registration failed :( // console.log('ServiceWorker registration failed: ', err) // }) // }) // } else { // console.log('Service worker not supported') // } // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', components: { App } })
// import swURL from 'file?name=sw.js!babel!./../sw' // // // Register Service Worker // if ('serviceWorker' in navigator) { // window.addEventListener('load', function () { // // navigator.serviceWorker.register('/sw.js').then(function (registration) { // navigator.serviceWorker.register(swURL).then(function (registration) { // // Registration was successful // console.log('ServiceWorker registration successful with scope: ', registration.scope) // }).catch(function (err) { // // registration failed :( // console.log('ServiceWorker registration failed: ', err) // }) // }) // } else { // console.log('Service worker not supported') // } // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', components: { App } })
Fix a typing mistake in 'logical absurdity' message
/* Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //checkConditionTruth.js var plugin = { ruleId: "CC006", name: "Detect Logical Absurdities", message: "Conditions should not have internal logic conflicts.", fatal: false, severity: 2, //error nodeType: "Condition", enabled: true }; var onCondition = function(condition, cb) { var truthTable = condition.getTruthTable(), hadErr = false; //truthTable will be null if no condition was present if (truthTable && truthTable.getEvaluation() !== "valid") { condition.addMessage({ source: condition.getExpression(), line: condition.getElement().lineNumber, column: condition.getElement().columnNumber, plugin, message: "Condition may be a logical absurdity." }); hadErr = true; } if (typeof cb == "function") { cb(null, hadErr); } }; module.exports = { plugin, onCondition };
/* Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //checkConditionTruth.js var plugin = { ruleId: "CC006", name: "Detect Logical Absurdities", message: "Conditions should not have internal logic conflicts.", fatal: false, severity: 2, //error nodeType: "Condition", enabled: true }; var onCondition = function(condition, cb) { var truthTable = condition.getTruthTable(), hadErr = false; //truthTable will be null if no condition was present if (truthTable && truthTable.getEvaluation() !== "valid") { condition.addMessage({ source: condition.getExpression(), line: condition.getElement().lineNumber, column: condition.getElement().columnNumber, plugin, message: "Condition may be a logical absuridty." }); hadErr = true; } if (typeof cb == "function") { cb(null, hadErr); } }; module.exports = { plugin, onCondition };
Set HTTP client in UserVerifier
package bitbucket import ( "code.cloudfoundry.org/lager" api "github.com/SHyx0rmZ/go-bitbucket/bitbucket" "github.com/concourse/atc/auth/verifier" "net/http" ) type UserVerifier struct { users []string client api.Client } func NewUserVerifier(client api.Client, users []string) verifier.Verifier { return UserVerifier{ users: users, client: client, } } func (verifier UserVerifier) Verify(logger lager.Logger, c *http.Client) (bool, error) { verifier.client.SetHTTPClient(c) currentUser, err := verifier.client.CurrentUser() if err != nil { logger.Error("failed-to-get-current-user", err) return false, err } for _, user := range verifier.users { if user == currentUser { return true, nil } } logger.Info("not-validated-user", lager.Data{ "have": currentUser, "want": verifier.users, }) return false, nil }
package bitbucket import ( "code.cloudfoundry.org/lager" api "github.com/SHyx0rmZ/go-bitbucket/bitbucket" "github.com/concourse/atc/auth/verifier" "net/http" ) type UserVerifier struct { users []string client api.Client } func NewUserVerifier(client api.Client, users []string) verifier.Verifier { return UserVerifier{ users: users, } } func (verifier UserVerifier) Verify(logger lager.Logger, c *http.Client) (bool, error) { currentUser, err := verifier.client.CurrentUser() if err != nil { logger.Error("failed-to-get-current-user", err) return false, err } for _, user := range verifier.users { if user == currentUser { return true, nil } } logger.Info("not-validated-user", lager.Data{ "have": currentUser, "want": verifier.users, }) return false, nil }
Use map.computeIfAbsent to create the logger when needed
/* * Copyright (c) 2016 MCPhoton <http://mcphoton.org> and contributors. * * This file is part of the Photon Server Implementation <https://github.com/mcphoton/Photon-Server>. * * The Photon Server Implementation is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The Photon Server Implementation 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.slf4j.impl; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; public class PhotonLoggerFactory implements ILoggerFactory { private final ConcurrentMap<String, Logger> loggerMap = new ConcurrentHashMap<>(); @Override public Logger getLogger(String name) { return loggerMap.computeIfAbsent(name, (k) -> new PhotonLogger(name)); } }
/* * Copyright (c) 2016 MCPhoton <http://mcphoton.org> and contributors. * * This file is part of the Photon Server Implementation <https://github.com/mcphoton/Photon-Server>. * * The Photon Server Implementation is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The Photon Server Implementation 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.slf4j.impl; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; public class PhotonLoggerFactory implements ILoggerFactory { private final ConcurrentMap<String, Logger> loggerMap = new ConcurrentHashMap<>(); @Override public Logger getLogger(String name) { Logger logger = loggerMap.get(name); if (logger != null) { return logger; } else { Logger newInstance = new PhotonLogger(name); Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); return oldInstance == null ? newInstance : oldInstance; } } }
Fix dns-providers type missing from schema
from marshmallow import fields from lemur.common.fields import ArrowDateTime from lemur.common.schema import LemurInputSchema, LemurOutputSchema class DnsProvidersNestedOutputSchema(LemurOutputSchema): __envelope__ = False id = fields.Integer() name = fields.String() provider_type = fields.String() description = fields.String() credentials = fields.String() api_endpoint = fields.String() date_created = ArrowDateTime() class DnsProvidersNestedInputSchema(LemurInputSchema): __envelope__ = False name = fields.String() description = fields.String() provider_type = fields.Dict() dns_provider_output_schema = DnsProvidersNestedOutputSchema() dns_provider_input_schema = DnsProvidersNestedInputSchema()
from marshmallow import fields from lemur.common.fields import ArrowDateTime from lemur.common.schema import LemurInputSchema, LemurOutputSchema class DnsProvidersNestedOutputSchema(LemurOutputSchema): __envelope__ = False id = fields.Integer() name = fields.String() providerType = fields.String() description = fields.String() credentials = fields.String() api_endpoint = fields.String() date_created = ArrowDateTime() class DnsProvidersNestedInputSchema(LemurInputSchema): __envelope__ = False name = fields.String() description = fields.String() provider_type = fields.Dict() dns_provider_output_schema = DnsProvidersNestedOutputSchema() dns_provider_input_schema = DnsProvidersNestedInputSchema()
Improve error messages when the profile store XHR fails.
export function uploadBinaryProfileData(data, progressChangeCallback = undefined) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onload = () => { if (xhr.status === 200) { resolve(xhr.responseText); } else { reject(`xhr onload with status != 200, xhr.statusText: ${xhr.statusText}`); } }; xhr.onerror = () => { reject(`xhr onerror was called, xhr.statusText: ${xhr.statusText}`); }; xhr.upload.onprogress = e => { if (progressChangeCallback && e.lengthComputable) { progressChangeCallback(e.loaded / e.total); } }; xhr.open('POST', 'https://profile-store.appspot.com/compressed-store'); xhr.send(data); }); }
export function uploadBinaryProfileData(data, progressChangeCallback = undefined) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onload = () => { if (xhr.status === 200) { resolve(xhr.responseText); } else { reject(xhr.status); } }; xhr.onerror = () => { reject(xhr.status); }; xhr.upload.onprogress = e => { if (progressChangeCallback && e.lengthComputable) { progressChangeCallback(e.loaded / e.total); } }; xhr.open('POST', 'https://profile-store.appspot.com/compressed-store'); xhr.send(data); }); }
Create new exception to catch APIException
from rest_framework.views import exception_handler from rest_framework.exceptions import APIException from rest_framework_friendly_errors import settings from rest_framework_friendly_errors.utils import is_pretty def friendly_exception_handler(exc, context): response = exception_handler(exc, context) if not response and settings.CATCH_ALL_EXCEPTIONS: exc = APIException(exc) response = exception_handler(exc, context) if response is not None: if is_pretty(response): return response error_message = response.data['detail'] error_code = settings.FRIENDLY_EXCEPTION_DICT.get( exc.__class__.__name__) response.data.pop('detail', {}) response.data['code'] = error_code response.data['message'] = error_message response.data['status_code'] = response.status_code # response.data['exception'] = exc.__class__.__name__ return response
from rest_framework.views import exception_handler from rest_framework.exceptions import APIException from rest_framework_friendly_errors import settings from rest_framework_friendly_errors.utils import is_pretty def friendly_exception_handler(exc, context): response = exception_handler(exc, context) if not response and settings.CATCH_ALL_EXCEPTIONS: response = exception_handler(APIException(exc), context) if response is not None: if is_pretty(response): return response error_message = response.data['detail'] error_code = settings.FRIENDLY_EXCEPTION_DICT.get( exc.__class__.__name__) response.data.pop('detail', {}) response.data['code'] = error_code response.data['message'] = error_message response.data['status_code'] = response.status_code # response.data['exception'] = exc.__class__.__name__ return response
TeikeiNext: Revert to using timestamps in database.
exports.up = function(knex, Promise) { return Promise.all([ knex.schema.createTable('next_users', table => { table.bigIncrements() table.string('email') table.string('name') table.string('password') table.string('origin') table.string('baseurl') table.string('phone') table.boolean('isVerified') table.string('verifyToken') table.string('verifyShortToken') table.timestamp('verifyExpires') table.json('verifyChanges') table.string('resetToken') table.string('resetShortToken') table.timestamp('resetExpires') table.timestamps() table.unique(['email']) }) ]) } exports.down = function(knex, Promise) {}
exports.up = function(knex, Promise) { return Promise.all([ knex.schema.createTable('next_users', table => { table.bigIncrements() table.string('email') table.string('name') table.string('password') table.string('origin') table.string('baseurl') table.string('phone') table.boolean('isVerified') table.string('verifyToken') table.string('verifyShortToken') table.bigint('verifyExpires') table.json('verifyChanges') table.string('resetToken') table.string('resetShortToken') table.bigint('resetExpires') table.timestamps() table.unique(['email']) }) ]) } exports.down = function(knex, Promise) {}
MODIFY academic cohort method and schema to include acad year
import { Mongo } from 'meteor/mongo'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; class AcadCohortCollection extends Mongo.Collection{ insert(acadCohortData, callBack){ const cohortDocument = acadCohortData; let result; //validate document return super.insert( cohortDocument, callBack); }; update(selector, modifier){ const result = super.update(selector, modifier); return result; }; remove(selector){ const result = super.remove(selector); return result; }; } const acadCohortSchema ={ cohortName:{ type: String, regEx: /AY\s\d\d\d\d\/\d\d\d\d/ }, cohortFocusAreaID:{ type: [String], optional: true }, cohortGradRequirementID: { type: [String], optional: true } } export const AcademicCohort = new AcadCohortCollection("AcademicCohort"); AcademicCohort.attachSchema(acadCohortSchema);
import { Mongo } from 'meteor/mongo'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; class AcadCohortCollection extends Mongo.Collection{ insert(acadCohortData, callBack){ const cohortDocument = acadCohortData; let result; //validate document return super.insert( cohortDocument, callBack); }; update(selector, modifier){ const result = super.update(selector, modifier); return result; }; remove(selector){ const result = super.remove(selector); return result; }; } const acadCohortSchema ={ cohortName:{ type: String, regEx: /AY\s\d\d\d\d\/\d\d\d\d/ }, cohortFocusAreaID:{ type: [String], optional: true } } export const AcademicCohort = new AcadCohortCollection("AcademicCohort"); AcademicCohort.attachSchema(acadCohortSchema);
Add a nice background color
# Include the directory where cvui is so we can load it import sys sys.path.append('../../../') import numpy as np import cv2 import cvui cvui.random_number_generator(1, 2) # Create a black image img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('Window') # Change background color img[:] = (49, 52, 49) # Draw a diagonal blue line with thickness of 5 px cv2.line(img,(0,0),(511,511),(255,0,0),5) cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) cv2.circle(img,(447,63), 63, (0,0,255), -1) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA) cv2.imshow('Window', img) k = cv2.waitKey(0) if k == 27: # wait for ESC key to exit cv2.destroyAllWindows()
# Include the directory where cvui is so we can load it import sys sys.path.append('../../../') import numpy as np import cv2 import cvui cvui.random_number_generator(1, 2) # Create a black image img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('Window') # Draw a diagonal blue line with thickness of 5 px cv2.line(img,(0,0),(511,511),(255,0,0),5) cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) cv2.circle(img,(447,63), 63, (0,0,255), -1) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA) cv2.imshow('Window', img) k = cv2.waitKey(0) if k == 27: # wait for ESC key to exit cv2.destroyAllWindows()
Update map view to log out data from parent model
"use strict"; var Backbone = require('backbone'); var $ = require('jquery'); Backbone.$ = $; module.exports = Backbone.View.extend({ tagName: 'div', id: 'map-canvas', initialize: function(){ var mapOptions = { zoom: this.model.get('zoom'), }; var map = new google.maps.Map(this.el, mapOptions); this.getDirections(map); this.render(); console.log('We\'re in the view, and the model says: ' + this.model.get('start')); }, getDirections: function(map){ var directionsService = new google.maps.DirectionsService(); var directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); var request = { origin: this.model.get('start'), destination: this.model.get('end'), travelMode: google.maps.DirectionsTravelMode.WALKING }; directionsService.route(request, function(response, status) { if (status === google.maps.DirectionsStatus.OK){ directionsDisplay.setDirections(response); } }); this.render(); }, render: function(){ $('map-canvas').replaceWith(this.$el); return this; }, });
"use strict"; var Backbone = require('backbone'); var $ = require('jquery'); Backbone.$ = $; module.exports = Backbone.View.extend({ tagName: 'div', id: 'map-canvas', initialize: function(){ var mapOptions = { zoom: this.model.get('zoom'), }; var map = new google.maps.Map(this.el, mapOptions); this.getDirections(map); this.render(); }, getDirections: function(map){ var directionsService = new google.maps.DirectionsService(); var directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); var request = { origin: this.model.get('start'), destination: this.model.get('end'), travelMode: google.maps.DirectionsTravelMode.WALKING }; directionsService.route(request, function(response, status){ if (status === google.maps.DirectionsStatus.OK){ directionsDisplay.setDirections(response); } }); this.render(); }, render: function(){ $('map-canvas').replaceWith(this.$el); return this; }, });
Add extra documentation, remove use of __setstate__ and __getstate__ methods.
# -*- coding: utf-8 -*- import json import resources class JSRNEncoder(json.JSONEncoder): """ Encoder for JSRN resources. """ def default(self, o): if isinstance(o, resources.Resource): obj = {f.name: f.to_json(f.value_from_object(o)) for f in o._meta.fields} obj[resources.RESOURCE_TYPE_FIELD] = o._meta.resource_name return obj return super(JSRNEncoder, self) def build_object_graph(obj, resource_name=None): """ From the decoded JSON structure, generate an object graph. :raises ValidationError: During building of the object graph and issues discovered are raised as a ValidationError. """ if isinstance(obj, dict): return resources.create_resource_from_dict(obj, resource_name) if isinstance(obj, list): return [build_object_graph(o, resource_name) for o in obj] return obj
# -*- coding: utf-8 -*- import json import registration import resources class JSRNEncoder(json.JSONEncoder): """ Encoder for JSRN resources. """ def default(self, o): if isinstance(o, resources.Resource): state = o.__getstate__() state['$'] = o._meta.resource_name return state return super(JSRNEncoder, self) def build_object_graph(obj, resource_name=None): if isinstance(obj, dict): if not resource_name: resource_name = obj.pop("$", None) if resource_name: resource_type = registration.get_resource(resource_name) if resource_type: new_resource = resource_type() new_resource.__setstate__(obj) return new_resource else: raise TypeError("Unknown resource: %s" % resource_name) if isinstance(obj, list): return [build_object_graph(o, resource_name) for o in obj] return obj
Add value check for -limit
import praw import argparse parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) args = parser.parse_args() args.limit = 1000 if args.limit > 1000 else args.limit r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self] for post in posts: print("Title:", post.title) print("Score: {} | Comments: {}".format(post.score, post.num_comments)) print() print(post.selftext.replace('**', '').replace('*', '')) print() print("Link:", post.permalink) print('=' * 30)
import praw import argparse parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) args = parser.parse_args() r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self] for post in posts: print("Title:", post.title) print("Score: {} | Comments: {}".format(post.score, post.num_comments)) print() print(post.selftext.replace('**', '').replace('*', '')) print() print("Link:", post.permalink) print('=' * 30)
Change from increments to bigIncrements (unsure if this is adviseable...)
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTwoFactorAuthsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('two_factor_auths', function (Blueprint $table) { $table->string('id')->nullable(); $table->bigIncrements('user_id'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('two_factor_auths'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTwoFactorAuthsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('two_factor_auths', function (Blueprint $table) { $table->string('id')->nullable(); $table->unsignedInteger('user_id'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('two_factor_auths'); } }
Include quantity in shopping list API route
/**************************************************** * /path /shoppinglist * /params null * /brief Returns all items with quantity less than threshold * * /author Luke ****************************************************/ module.exports=(req,res) => { //first query the database //then return the results to the user res.app.locals.pool.connect(function(err, client, done) { if(err) { return console.error('error fetching client from pool', err); } client.query('SELECT item_name AS name, description, price, quantity FROM items WHERE quantity < threshold', [], function(err, result) { //call `done()` to release the client back to the pool done(); res.app.locals.helpers.errResultHandler(err, result.rows, res); }); }); };
/**************************************************** * /path /shoppinglist * /params null * /brief Returns all items with quantity less than threshold * * /author Luke ****************************************************/ module.exports=(req,res) => { //first query the database //then return the results to the user res.app.locals.pool.connect(function(err, client, done) { if(err) { return console.error('error fetching client from pool', err); } client.query('SELECT item_name AS name, description, price FROM items WHERE quantity < threshold', [], function(err, result) { //call `done()` to release the client back to the pool done(); res.app.locals.helpers.errResultHandler(err, result.rows, res); }); }); };
Remove mandatory requirement for AccessKey.Status and add default Fixes #43
package iam import ( "github.com/jagregory/cfval/constraints" . "github.com/jagregory/cfval/schema" ) // see: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html var AccessKey = Resource{ AwsType: "AWS::IAM::AccessKey", Attributes: map[string]Schema{ "SecretAccessKey": Schema{ Type: ValueString, }, }, // AccessKeyId ReturnValue: Schema{ Type: ValueString, }, Properties: Properties{ "Serial": Schema{ Type: ValueNumber, }, "Status": Schema{ Type: EnumValue{ Description: "Status", Options: []string{"Active", "Inactive"}, }, Default: "Active", }, "UserName": Schema{ Type: ValueString, Required: constraints.Always, }, }, }
package iam import ( "github.com/jagregory/cfval/constraints" . "github.com/jagregory/cfval/schema" ) // see: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html var AccessKey = Resource{ AwsType: "AWS::IAM::AccessKey", Attributes: map[string]Schema{ "SecretAccessKey": Schema{ Type: ValueString, }, }, // AccessKeyId ReturnValue: Schema{ Type: ValueString, }, Properties: Properties{ "Serial": Schema{ Type: ValueNumber, }, "Status": Schema{ Type: EnumValue{ Description: "Status", Options: []string{"Active", "Inactive"}, }, Required: constraints.Always, }, "UserName": Schema{ Type: ValueString, Required: constraints.Always, }, }, }
Update classes of closest('.fl_wrap') instead of parent() This allows it to work even for cases where the input is a descendant, but not a direct child, of the .fl_wrap element. This happens, for instance, if you use the conventional bootstrap control-group hierarchy.
(function($) { $.fn.FlowupLabels = function( options ){ var defaults = { // Useful if you pre-fill input fields or if localstorage/sessionstorage is used. feature_onLoadInit: false, // Class names used for focus and populated statuses class_focused: 'focused', class_populated: 'populated' }, settings = $.extend({}, defaults, options); return this.each(function(){ var $scope = $(this); $scope.on('focus.flowupLabelsEvt', '.fl_input', function() { $(this).closest('.fl_wrap').addClass(settings.class_focused); }) .on('blur.flowupLabelsEvt', '.fl_input', function() { var $this = $(this); if ($this.val().length) { $this.closest('.fl_wrap') .addClass(settings.class_populated) .removeClass(settings.class_focused); } else { $this.closest('.fl_wrap') .removeClass(settings.class_populated + ' ' + settings.class_focused); } }); // On page load, make sure it looks good if (settings.feature_onLoadInit) { $scope.find('.fl_input').trigger('blur.flowupLabelsEvt'); } }); }; })( jQuery );
(function($) { $.fn.FlowupLabels = function( options ){ var defaults = { // Useful if you pre-fill input fields or if localstorage/sessionstorage is used. feature_onLoadInit: false, // Class names used for focus and populated statuses class_focused: 'focused', class_populated: 'populated' }, settings = $.extend({}, defaults, options); return this.each(function(){ var $scope = $(this); $scope.on('focus.flowupLabelsEvt', '.fl_input', function() { $(this).parent().addClass(settings.class_focused); }) .on('blur.flowupLabelsEvt', '.fl_input', function() { var $this = $(this); if ($this.val().length) { $this.parent() .addClass(settings.class_populated) .removeClass(settings.class_focused); } else { $this.parent() .removeClass(settings.class_populated + ' ' + settings.class_focused); } }); // On page load, make sure it looks good if (settings.feature_onLoadInit) { $scope.find('.fl_input').trigger('blur.flowupLabelsEvt'); } }); }; })( jQuery );
Check if grid dimensions are positive
import React from 'react'; import SquareRow from './SquareRow'; import './Grid.css'; const Grid = ({ size, }) => { const [height, width] = size.split('x').map(el => Number(el)); if (isNaN(height) || isNaN(width)) { return null; } if (height <= 0 || width <= 0) { return null; } if (height * width > 10_000) { return ( <span className="error"> ⚠️ Sorry, there are too many elements to paint. Try again with a smaller size. </span> ); } const squareNodes = [...new Array(height)].map( (_, index) => <SquareRow key={index} index={index} width={width} /> ); return ( <div className="Grid"> {squareNodes} </div> ); }; export default Grid;
import React from 'react'; import SquareRow from './SquareRow'; import './Grid.css'; const Grid = ({ size, }) => { const [height, width] = size.split('x').map(el => Number(el)); if (isNaN(height) || isNaN(width)) { return null; } if (height * width > 10_000) { return ( <span className="error"> ⚠️ Sorry, there are too many elements to paint. Try again with a smaller size. </span> ); } const squareNodes = [...new Array(height)].map( (_, index) => <SquareRow key={index} index={index} width={width} /> ); return ( <div className="Grid"> {squareNodes} </div> ); }; export default Grid;
Change generic types' names to be less ambiguous (leave S,T for label class and feature vector class respectively)
package pl.edu.icm.yadda.analysis.classification.features; import java.util.Collection; import java.util.Set; /** * Feature vector builder (GoF factory pattern). The builder calculates * feature vectors for objects using a list of single feature calculators. * * @author Dominika Tkaczyk (dtkaczyk@icm.edu.pl) * * @param <X> Type of objects for whom features' values can be calculated. * @param <Y> Type of additional context objects that can be used * for calculation. */ public interface FeatureVectorBuilder<X, Y> { /** * Sets feature calculators used for building feature vectors. * * @param featureCalculators A collection of feature calculators. */ void setFeatureCalculators(Collection<FeatureCalculator<X, Y>> featureCalculators); /** * Returns calculated feature vector. * * @param object An object, whose feature vector is to be calculated. * @param context Context object * @return Calculated feature vector. */ FeatureVector getFeatureVector(X object, Y context); /** * Returns the names of features that are part of calculated feature vector. * * @return The set of feature names. */ Set<String> getFeatureNames(); }
package pl.edu.icm.yadda.analysis.classification.features; import java.util.Collection; import java.util.Set; /** * Feature vector builder (GoF factory pattern). The builder calculates * feature vectors for objects using a list of single feature calculators. * * @author Dominika Tkaczyk (dtkaczyk@icm.edu.pl) * * @param <S> Type of objects for whom features' values can be calculated. * @param <T> Type of additional context objects that can be used * for calculation. */ public interface FeatureVectorBuilder<S, T> { /** * Sets feature calculators used for building feature vectors. * * @param featureCalculators A collection of feature calculators. */ void setFeatureCalculators(Collection<FeatureCalculator<S, T>> featureCalculators); /** * Returns calculated feature vector. * * @param object An object, whose feature vector is to be calculated. * @param context Context object * @return Calculated feature vector. */ FeatureVector getFeatureVector(S object, T context); /** * Returns the names of features that are part of calculated feature vector. * * @return The set of feature names. */ Set<String> getFeatureNames(); }
Upgrade dependency python-slugify to ==1.2.1
import os from setuptools import setup from withtool import __version__ def read(fname): path = os.path.join(os.path.dirname(__file__), fname) with open(path, encoding='utf-8') as f: return f.read() setup( name='with', version=__version__, description='A shell context manager', long_description=read('README.rst'), author='Renan Ivo', author_email='renanivom@gmail.com', url='https://github.com/renanivo/with', keywords='context manager shell command line repl', scripts=['bin/with'], install_requires=[ 'appdirs==1.4.0', 'docopt==0.6.2', 'prompt-toolkit==1.0', 'python-slugify==1.2.1', ], packages=['withtool'], classifiers=[ 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ] )
import os from setuptools import setup from withtool import __version__ def read(fname): path = os.path.join(os.path.dirname(__file__), fname) with open(path, encoding='utf-8') as f: return f.read() setup( name='with', version=__version__, description='A shell context manager', long_description=read('README.rst'), author='Renan Ivo', author_email='renanivom@gmail.com', url='https://github.com/renanivo/with', keywords='context manager shell command line repl', scripts=['bin/with'], install_requires=[ 'appdirs==1.4.0', 'docopt==0.6.2', 'prompt-toolkit==1.0', 'python-slugify==1.2.0', ], packages=['withtool'], classifiers=[ 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ] )
Remove placeholder from state atom
'use strict' var State = require('dover') var Observ = require('observ') var emailRegex = require('email-regex')({exact: true}) var isEmail = emailRegex.test.bind(emailRegex) var h = require('virtual-dom/h') var changeEvent = require('value-event/change') module.exports = EmailInput function EmailInput (data) { data = data || {} var state = State({ value: Observ(data.value || ''), valid: Observ(isEmail(data.value) || false), channels: { change: change } }) state.value(function (email) { state.valid.set(isEmail(email)) }) return state } function change (state, data) { state.value.set(data.email) } EmailInput.render = function render (state) { return h('input', { type: 'email', value: state.value, name: 'email', 'ev-event': changeEvent(state.channels.change) }) }
'use strict' var State = require('dover') var Observ = require('observ') var emailRegex = require('email-regex')({exact: true}) var isEmail = emailRegex.test.bind(emailRegex) var h = require('virtual-dom/h') var changeEvent = require('value-event/change') module.exports = EmailInput function EmailInput (data) { data = data || {} var state = State({ value: Observ(data.value || ''), valid: Observ(isEmail(data.value) || false), placeholder: Observ(data.placeholder || ''), channels: { change: change } }) state.value(function (email) { state.valid.set(isEmail(email)) }) return state } function change (state, data) { state.value.set(data.email) } EmailInput.render = function render (state) { return h('input', { type: 'email', value: state.value, name: 'email', 'ev-event': changeEvent(state.channels.change), placeholder: state.placeholder }) }
Fix site name in index
@extends('layouts.master') @section('title', config('upste.site_name')) @section('content') <div class="container-sm text-center jumbotron"> <p>{{ config('upste.domain') }} is a private file hosting website.</p> <p>Accounts are given with approval from {{ config('upste.owner_name') }} &lt;<a href="mailto:{{ config('upste.owner_email') }}" title="Send an email to {{ config('upste.owner_name') }}">{{ config('upste.owner_email') }}</a>&gt;.</p> <p>Your request will <b class="text-danger">NOT</b> be accepted if I don't know you or I'm not expecting your request prior to you making it.</p> <a href="{{ route('login') }}" class="btn btn-primary">Login</a> <a href="{{ route('register') }}" class="btn btn-primary">Request Account</a> </div> @stop
@extends('layouts.master') @section('title', 'uPste') @section('content') <div class="container-sm text-center jumbotron"> <p>{{ config('upste.domain') }} is a private file hosting website.</p> <p>Accounts are given with approval from {{ config('upste.owner_name') }} &lt;<a href="mailto:{{ config('upste.owner_email') }}" title="Send an email to {{ config('upste.owner_name') }}">{{ config('upste.owner_email') }}</a>&gt;.</p> <p>Your request will <b class="text-danger">NOT</b> be accepted if I don't know you or I'm not expecting your request prior to you making it.</p> <a href="{{ route('login') }}" class="btn btn-primary">Login</a> <a href="{{ route('register') }}" class="btn btn-primary">Request Account</a> </div> @stop
[IMP] purchase: Remove useless default value for po_lead
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class StockConfigSettings(models.TransientModel): _inherit = 'stock.config.settings' po_lead = fields.Float(related='company_id.po_lead') use_po_lead = fields.Boolean( string="Security Lead Time for Purchase", oldname='default_new_po_lead', help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.") @api.onchange('use_po_lead') def _onchange_use_po_lead(self): if not self.use_po_lead: self.po_lead = 0.0 def get_default_fields(self, fields): return dict( use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead') ) def set_fields(self): self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class StockConfigSettings(models.TransientModel): _inherit = 'stock.config.settings' po_lead = fields.Float(related='company_id.po_lead', default=lambda self: self.env.user.company_id.po_lead) use_po_lead = fields.Boolean( string="Security Lead Time for Purchase", oldname='default_new_po_lead', help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.") @api.onchange('use_po_lead') def _onchange_use_po_lead(self): if not self.use_po_lead: self.po_lead = 0.0 def get_default_fields(self, fields): return dict( use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead') ) def set_fields(self): self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
Add support for branch arg to LocalHost.clone
import gitdir.host class LocalHost(gitdir.host.Host): def __iter__(self): for repo_dir in sorted(self.dir.iterdir()): if repo_dir.is_dir(): yield self.repo(repo_dir.name) def __repr__(self): return 'gitdir.host.localhost.LocalHost()' def __str__(self): return 'localhost' def clone(self, repo_spec, *, branch=None): repo_dir = self.repo_path(repo_spec) if not repo_dir.exists(): raise ValueError('No such repo on localhost: {!r}'.format(repo_spec)) return super().clone(repo_spec, branch=branch) def clone_stage(self, repo_spec): repo_dir = self.repo_path(repo_spec) if not repo_dir.exists(): raise ValueError('No such repo on localhost: {!r}'.format(repo_spec)) return super().clone_stage(repo_spec) def repo_remote(self, repo_spec, stage=False): return '/opt/git/localhost/{}/{}.git'.format(repo_spec, repo_spec)
import gitdir.host class LocalHost(gitdir.host.Host): def __iter__(self): for repo_dir in sorted(self.dir.iterdir()): if repo_dir.is_dir(): yield self.repo(repo_dir.name) def __repr__(self): return 'gitdir.host.localhost.LocalHost()' def __str__(self): return 'localhost' def clone(self, repo_spec): repo_dir = self.repo_path(repo_spec) if not repo_dir.exists(): raise ValueError('No such repo on localhost: {!r}'.format(repo_spec)) return super().clone(repo_spec) def clone_stage(self, repo_spec): repo_dir = self.repo_path(repo_spec) if not repo_dir.exists(): raise ValueError('No such repo on localhost: {!r}'.format(repo_spec)) return super().clone_stage(repo_spec) def repo_remote(self, repo_spec, stage=False): return '/opt/git/localhost/{}/{}.git'.format(repo_spec, repo_spec)
Support --v and --vmodule silently Allows compatibility with Kubernetes invocation directly
package flagtypes import ( "flag" "github.com/golang/glog" "github.com/spf13/pflag" ) // GLog binds the log flags from the default Google "flag" package into a pflag.FlagSet. func GLog(flags *pflag.FlagSet) { from := flag.CommandLine if flag := from.Lookup("v"); flag != nil { level := flag.Value.(*glog.Level) levelPtr := (*int32)(level) flags.Int32Var(levelPtr, "loglevel", 0, "Set the level of log output (0-10)") if flags.Lookup("v") == nil { flags.Int32Var(levelPtr, "v", 0, "Set the level of log output (0-10)") } flags.Lookup("v").Hidden = true } if flag := from.Lookup("vmodule"); flag != nil { value := flag.Value flags.Var(pflagValue{value}, "logspec", "Set per module logging with file|pattern=LEVEL,...") if flags.Lookup("vmodule") == nil { flags.Var(pflagValue{value}, "vmodule", "Set per module logging with file|pattern=LEVEL,...") } flags.Lookup("vmodule").Hidden = true } } type pflagValue struct { flag.Value } func (pflagValue) Type() string { return "string" }
package flagtypes import ( "flag" "github.com/golang/glog" "github.com/spf13/pflag" ) // GLog binds the log flags from the default Google "flag" package into a pflag.FlagSet. func GLog(flags *pflag.FlagSet) { from := flag.CommandLine if flag := from.Lookup("v"); flag != nil { level := flag.Value.(*glog.Level) levelPtr := (*int32)(level) flags.Int32Var(levelPtr, "loglevel", 0, "Set the level of log output (0-10)") } if flag := from.Lookup("vmodule"); flag != nil { value := flag.Value flags.Var(pflagValue{value}, "logspec", "Set per module logging with file|pattern=LEVEL,...") } } type pflagValue struct { flag.Value } func (pflagValue) Type() string { return "string" }
Use the right duration lib
const duration = require('@dnode/duration'); const Throttle = require('redis-throttle'); module.exports = config => { Throttle.configure(config); return (key, limit, callback, fallback) => { let span = '1 second'; if (typeof limit === 'string') { [limit, span] = limit.split(' per '); } span = duration(span).milliseconds(); const throttle = new Throttle(key, { span, accuracy: span / 10 }); return new Promise((resolve, reject) => { throttle.read((err, count) => { if (err) { reject(err); return; } if (count <= limit) { throttle.increment(1, err => { if (err) { reject(err); return; } resolve(callback()); }); } else { if (fallback) { resolve(fallback()); } else { resolve(); } } }); }); }; };
const duration = require('@maxdome/duration'); const Throttle = require('redis-throttle'); module.exports = config => { Throttle.configure(config); return (key, limit, callback, fallback) => { let span = '1 second'; if (typeof limit === 'string') { [limit, span] = limit.split(' per '); } span = duration(span).milliseconds(); const throttle = new Throttle(key, { span, accuracy: span / 10 }); return new Promise((resolve, reject) => { throttle.read((err, count) => { if (err) { reject(err); return; } if (count <= limit) { throttle.increment(1, err => { if (err) { reject(err); return; } resolve(callback()); }); } else { if (fallback) { resolve(fallback()); } else { resolve(); } } }); }); }; };
Add spacing to console output
/*jshint node:true*/ 'use strict'; var exec = require('child_process').exec; var colors = require('colors'); module.exports = title; /** * Sets title to current CLI tab or window. * * @param {strint} input - Title to set * @param {Boolean} win - Add title to window instead of tab */ function title(input, win) { var cmd = [ 'printf', '"\\e]%d;%s\\a"', win ? 2 : 1, '"' + input + '"' ].join(' '); console.log( '\n%s Changing %s title: %s\n', colors.green('>'), win ? 'window' : 'tab', colors.cyan(input) ); exec(cmd).stdout.pipe(process.stdout); }
/*jshint node:true*/ 'use strict'; var exec = require('child_process').exec; var colors = require('colors'); module.exports = title; /** * Sets title to current CLI tab or window. * * @param {strint} input - Title to set * @param {Boolean} win - Add title to window instead of tab */ function title(input, win) { var cmd = [ 'printf', '"\\e]%d;%s\\a"', win ? 2 : 1, '"' + input + '"' ].join(' '); console.log( '%s Changing %s title: %s', colors.green('>'), win ? 'window' : 'tab', colors.cyan(input) ); exec(cmd).stdout.pipe(process.stdout); }
Annotate with update instead of query
package com.bitbosh.dropwizardheroku.event.repository; import java.util.Date; import java.util.List; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import com.bitbosh.dropwizardheroku.event.api.Event; public interface EventDao { @SqlUpdate("create table if not exists event (id serial primary key, name varchar(100), location varchar(100), description varchar(100), date date)") void createEventDatabaseTable(); @SqlUpdate("insert into event (name, location, description, date) values (:name, :location, :description, :date)") void createEvent(@Bind("name") String name, @Bind("location") String location, @Bind("description") String description, @Bind("date") Date date); @Mapper(EventMapper.class) @SqlQuery("select * from event where name = :name") Event getEventByName(@Bind("name") String name); @Mapper(EventMapper.class) @SqlQuery("select * from event where date > now()") List<Event> getEvents(); @SqlUpdate("delete from event where id=:id") void deleteEventById(@Bind("id") int id); }
package com.bitbosh.dropwizardheroku.event.repository; import java.util.Date; import java.util.List; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import com.bitbosh.dropwizardheroku.event.api.Event; public interface EventDao { @SqlUpdate("create table if not exists event (id serial primary key, name varchar(100), location varchar(100), description varchar(100), date date)") void createEventDatabaseTable(); @SqlUpdate("insert into event (name, location, description, date) values (:name, :location, :description, :date)") void createEvent(@Bind("name") String name, @Bind("location") String location, @Bind("description") String description, @Bind("date") Date date); @Mapper(EventMapper.class) @SqlQuery("select * from event where name = :name") Event getEventByName(@Bind("name") String name); @Mapper(EventMapper.class) @SqlQuery("select * from event where date > now()") List<Event> getEvents(); @SqlQuery("delete from event where id=:id") void deleteEventById(@Bind("id") int id); }
Fix by Sylvain on duplicated name for serializers Record and Long
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.serialization.serializer.stream; import java.io.IOException; import com.orientechnologies.orient.core.serialization.OBinaryProtocol; public class OStreamSerializerLong implements OStreamSerializer { public static final String NAME = "lo"; public static final OStreamSerializerLong INSTANCE = new OStreamSerializerLong(); public String getName() { return NAME; } public Object fromStream(final byte[] iStream) throws IOException { return OBinaryProtocol.bytes2long(iStream); } public byte[] toStream(final Object iObject) throws IOException { return OBinaryProtocol.long2bytes((Long) iObject); } }
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.serialization.serializer.stream; import java.io.IOException; import com.orientechnologies.orient.core.serialization.OBinaryProtocol; public class OStreamSerializerLong implements OStreamSerializer { public static final String NAME = "l"; public static final OStreamSerializerLong INSTANCE = new OStreamSerializerLong(); public String getName() { return NAME; } public Object fromStream(final byte[] iStream) throws IOException { return OBinaryProtocol.bytes2long(iStream); } public byte[] toStream(final Object iObject) throws IOException { return OBinaryProtocol.long2bytes((Long) iObject); } }
Remove things related to 'document'
package edu.chl.proton.model; /** * @author Stina Werme * Created by stinawerme on 01/05/17. */ public class File extends FileSystemEntity { //private Document document; public File(String name) { this.setName(name); } public File(String name, Folder parentFolder) { this.setName(name); parentFolder.addFile(this); } //protected Document getDocument() { // return this.document; //} //protected void setDocument(Document document) { // this.document = document; //} // What should be saved? Shouldn't this be in document? protected void save(File file) { } protected boolean isSaved(File file) { return true; } }
package edu.chl.proton.model; /** * @author Stina Werme * Created by stinawerme on 01/05/17. */ public class File extends FileSystemEntity { private Document document; public File(String name, Document document) { this.setName(name); this.document = document; } public File(String name, Document document, Folder parentFolder) { this(name, document); parentFolder.addFile(this); } protected Document getDocument() { return this.document; } protected void setDocument(Document document) { this.document = document; } // What should be saved? Shouldn't this be in document? protected void save(File file) { } protected boolean isSaved() { return true; } }
Send error message to stderr
/* netcheck: check whether a given network or address overlaps with any existing routes */ package main import ( "fmt" "net" "os" weavenet "github.com/weaveworks/weave/net" ) func fatal(err error) { fmt.Fprintln(os.Stderr, err) os.Exit(1) } func main() { if len(os.Args) <= 1 { os.Exit(0) } cidrStr := os.Args[1] addr, ipnet, err := net.ParseCIDR(cidrStr) if err != nil { fatal(err) } if ipnet.IP.Equal(addr) { err = weavenet.CheckNetworkFree(ipnet) } else { err = weavenet.CheckAddressOverlap(addr) } if err != nil { fatal(err) } os.Exit(0) }
/* netcheck: check whether a given network or address overlaps with any existing routes */ package main import ( "fmt" "net" "os" weavenet "github.com/weaveworks/weave/net" ) func fatal(err error) { fmt.Println(err) os.Exit(1) } func main() { if len(os.Args) <= 1 { os.Exit(0) } cidrStr := os.Args[1] addr, ipnet, err := net.ParseCIDR(cidrStr) if err != nil { fatal(err) } if ipnet.IP.Equal(addr) { err = weavenet.CheckNetworkFree(ipnet) } else { err = weavenet.CheckAddressOverlap(addr) } if err != nil { fatal(err) } os.Exit(0) }
Fix borked jQuery targeting in input-password
import Component from '@ember/component'; import Util from 'ui/utils/util'; import { get, set } from '@ember/object'; import layout from './template'; import $ from 'jquery'; export default Component.extend({ layout, classNames: ['input-group'], value: '', question: null, actions: { generate() { let randomStr; if ( get(this, 'question.maxLength') !== 0 && get(this, 'question.maxLength') >= get(this, 'question.minLength') && get(this, 'question.validChars.length') > 0 ) { randomStr = Util.randomStr(get(this, 'question.minLength'), get(this, 'question.maxLength'), get(this, 'question.validChars')); } else { randomStr = Util.randomStr(16, 16, 'password'); } set(this, 'value', randomStr); var $field = $(this.element).find('INPUT'); $field.attr('type', 'text'); setTimeout(() => { $field[0].focus(); $field[0].select(); }, 50); if (this.generated) { this.generated(); } } } });
import Component from '@ember/component'; import Util from 'ui/utils/util'; import { get, set } from '@ember/object'; import layout from './template'; import $ from 'jquery'; export default Component.extend({ layout, classNames: ['input-group'], value: '', question: null, actions: { generate() { let randomStr; if ( get(this, 'question.maxLength') !== 0 && get(this, 'question.maxLength') >= get(this, 'question.minLength') && get(this, 'question.validChars.length') > 0 ) { randomStr = Util.randomStr(get(this, 'question.minLength'), get(this, 'question.maxLength'), get(this, 'question.validChars')); } else { randomStr = Util.randomStr(16, 16, 'password'); } set(this, 'value', randomStr); var $field = $('INPUT'); $field.attr('type', 'text'); setTimeout(() => { $field[0].focus(); $field[0].select(); }, 50); if (this.generated) { this.generated(); } } } });
Fix setStartDelay() is not reset by clear()
package jp.wasabeef.recyclerview.internal; import android.support.v4.view.ViewCompat; import android.view.View; /** * Copyright (C) 2015 Wasabeef * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public final class ViewHelper { public static void clear(View v) { ViewCompat.setAlpha(v, 1); ViewCompat.setScaleY(v, 1); ViewCompat.setScaleX(v, 1); ViewCompat.setTranslationY(v, 0); ViewCompat.setTranslationX(v, 0); ViewCompat.setRotation(v, 0); ViewCompat.setRotationY(v, 0); ViewCompat.setRotationX(v, 0); ViewCompat.setPivotY(v, v.getMeasuredHeight() / 2); ViewCompat.setPivotX(v, v.getMeasuredWidth() / 2); ViewCompat.animate(v) .setInterpolator(null) .setStartDelay(0); } }
package jp.wasabeef.recyclerview.internal; import android.support.v4.view.ViewCompat; import android.view.View; /** * Copyright (C) 2015 Wasabeef * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public final class ViewHelper { public static void clear(View v) { ViewCompat.setAlpha(v, 1); ViewCompat.setScaleY(v, 1); ViewCompat.setScaleX(v, 1); ViewCompat.setTranslationY(v, 0); ViewCompat.setTranslationX(v, 0); ViewCompat.setRotation(v, 0); ViewCompat.setRotationY(v, 0); ViewCompat.setRotationX(v, 0); ViewCompat.setPivotY(v, v.getMeasuredHeight() / 2); ViewCompat.setPivotX(v, v.getMeasuredWidth() / 2); ViewCompat.animate(v).setInterpolator(null); } }
Update to shorter Property syntax.
/** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ CLASS({ package: 'foam.ui', name: 'XMLView', extendsModel: 'foam.ui.TextAreaView', label: 'XML View', properties: [ [ 'displayWidth', 100 ], [ 'displayHeight', 100 ] ], methods: { textToValue: function(text) { return this.val_; // Temporary hack until XML parsing is implemented // TODO: parse XML return text; }, valueToText: function(val) { this.val_ = val; // Temporary hack until XML parsing is implemented return XMLUtil.stringify(val); } } });
/** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ CLASS({ package: 'foam.ui', name: 'XMLView', extendsModel: 'foam.ui.TextAreaView', label: 'XML View', properties: [ { name: 'displayWidth', defaultValue: 100 }, { name: 'displayHeight', defaultValue: 100 } ], methods: { textToValue: function(text) { return this.val_; // Temporary hack until XML parsing is implemented // TODO: parse XML return text; }, valueToText: function(val) { this.val_ = val; // Temporary hack until XML parsing is implemented return XMLUtil.stringify(val); } } });
Use the FilterNoMatchEvent to reset the notification mechanism
/* * Copyright 2015 John Scattergood * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package weatherAlarm.events; import weatherAlarm.model.WeatherAlarm; import java.time.Instant; /** * @author <a href="mailto:john.scattergood@gmail.com">John Scattergood</a> 1/4/2015 */ public class NotificationSentEvent implements IModuleEvent { private WeatherAlarm alarm; private Instant eventTime; public NotificationSentEvent(WeatherAlarm alarm, Instant eventTime) { this.alarm = alarm; this.eventTime = eventTime; } public WeatherAlarm getAlarm() { return alarm; } public Instant getEventTime() { return eventTime; } @Override public String toString() { return "NotificationSentEvent[" + "alarm=" + alarm + ", eventTime=" + eventTime + ']'; } }
/* * Copyright 2015 John Scattergood * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package weatherAlarm.events; import weatherAlarm.model.WeatherAlarm; import java.time.Instant; /** * @author <a href="mailto:john.scattergood@gmail.com">John Scattergood</a> 1/4/2015 */ public class NotificationSentEvent implements IModuleEvent { private WeatherAlarm alarm; private Instant eventTime; public NotificationSentEvent(WeatherAlarm alarm, Instant eventTime) { this.alarm = alarm; this.eventTime = eventTime; } public WeatherAlarm getAlarm() { return alarm; } public Instant getEventTime() { return eventTime; } }
Use promise's then() method instead of success due to error message
var app = angular.module('plugD', [ 'angularUtils.directives.dirPagination' ]); app.controller("PluginController",function(){ }); app.directive("pluginList", ['$http',function($http){ return { restrict:"E", templateUrl:"partials/plugin-list.html", controller: function($http){ var self = this; self.filter = {gmod:"", term:"", perPage:5}; self.sortKey = "name"; self.order ='+'; $http.get('api/plugins.json') .then(function(data){ self.plugins = data; }, function(data){ // todo: error }); }, controllerAs:"plug" } }]);
var app = angular.module('plugD', [ 'angularUtils.directives.dirPagination' ]); app.controller("PluginController",function(){ }); app.directive("pluginList", ['$http',function($http){ return { restrict:"E", templateUrl:"partials/plugin-list.html", controller: function($http){ var self = this; self.filter = {gmod:"", term:"", perPage:5}; self.sortKey = "name"; self.order ='+'; $http.get('api/plugins.json') .success(function(data){ self.plugins = data; }) .error(function(data){ // todo: error }); }, controllerAs:"plug" } }]);
Fix bug in ranges (to middle) - in SPOJ palin Signed-off-by: Karel Ha <70f8965fdfb04f1fc0e708a55d9e822c449f57d3@gmail.com>
#!/usr/bin/env python3 def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy: i = (n - 1) // 2 while i >= 0 and k[i] == '9': i -= 1 if i >= 0: palin[i] = str(int(k[i]) + 1) for j in range(i + 1, (n + 1) // 2): palin[j] = '0' for j in range((n + 1) // 2, n): mirrored = n - 1 - j palin[j] = palin[mirrored] else: # case 3: "99...9" -> "100..01" palin = ['0'] * (n + 1) palin[0] = palin[-1] = '1' return ''.join(palin) if __name__ == '__main__': t = int(input()) for _ in range(t): k = input() print(next_palindrome(k))
#!/usr/bin/env python3 def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy: i = (n - 1) // 2 while i >= 0 and k[i] == '9': i -= 1 if i >= 0: palin[i] = str(int(k[i]) + 1) for j in range(i + 1, mid): palin[j] = '0' for j in range(mid, n): mirrored = n - 1 - j palin[j] = palin[mirrored] else: # case 3: "99...9" -> "100..01" palin = ['0'] * (n + 1) palin[0] = palin[-1] = '1' return ''.join(palin) if __name__ == '__main__': t = int(input()) for _ in range(t): k = input() print(next_palindrome(k))
Make it easier to get a session from a sub-class
package org.openntf.domino.tests.ntf; import lotus.domino.NotesFactory; import org.openntf.domino.Database; import org.openntf.domino.Session; import org.openntf.domino.thread.DominoThread; import org.openntf.domino.utils.DominoUtils; import org.openntf.domino.utils.Factory; public class DominoRunnable implements Runnable { public static void main(final String[] args) { DominoThread thread = new DominoThread(new DominoRunnable(), "My thread"); thread.start(); } public DominoRunnable() { // whatever you might want to do in your constructor, but stay away from Domino objects } @Override public void run() { Session session = this.getSession(); Database db = session.getDatabase("", "names.nsf"); // whatever you're gonna do, do it fast! } protected Session getSession() { try { Session session = Factory.fromLotus(NotesFactory.createSession(), Session.class, null); return session; } catch (Throwable t) { DominoUtils.handleException(t); return null; } } }
package org.openntf.domino.tests.ntf; import lotus.domino.NotesFactory; import org.openntf.domino.Database; import org.openntf.domino.Session; import org.openntf.domino.thread.DominoThread; import org.openntf.domino.utils.Factory; public class DominoRunnable implements Runnable { public static void main(String[] args) { DominoThread thread = new DominoThread(new DominoRunnable(), "My thread"); thread.start(); } public DominoRunnable() { // whatever you might want to do in your constructor, but stay away from Domino objects } @Override public void run() { try { Session session = Factory.fromLotus(NotesFactory.createSession(), Session.class, null); Database db = session.getDatabase("", "names.nsf"); // whatever you're gonna do, do it fast! } catch (Throwable t) { t.printStackTrace(); } } }
Use assertNotNull instead of `if`
/* * Copyright 2015-2016 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html */ package extensions; import static org.junit.gen5.api.Assertions.assertNotNull; import org.junit.gen5.api.extension.AfterEachExtensionPoint; import org.junit.gen5.api.extension.ExceptionHandlerExtensionPoint; import org.junit.gen5.api.extension.ExtensionContext.Namespace; import org.junit.gen5.api.extension.ExtensionContext.Store; import org.junit.gen5.api.extension.TestExtensionContext; import org.opentest4j.AssertionFailedError; public class ExpectToFailExtension implements ExceptionHandlerExtensionPoint, AfterEachExtensionPoint { @Override public void handleException(TestExtensionContext context, Throwable throwable) throws Throwable { if (throwable instanceof AssertionFailedError) { getExceptionStore(context).put("exception", throwable); return; } throw throwable; } @Override public void afterEach(TestExtensionContext context) throws Exception { assertNotNull(getExceptionStore(context).get("exception"), "Test should have failed"); } private Store getExceptionStore(TestExtensionContext context) { return context.getStore(Namespace.of(context)); } }
/* * Copyright 2015-2016 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html */ package extensions; import org.junit.gen5.api.Assertions; import org.junit.gen5.api.extension.AfterEachExtensionPoint; import org.junit.gen5.api.extension.ExceptionHandlerExtensionPoint; import org.junit.gen5.api.extension.ExtensionContext.Namespace; import org.junit.gen5.api.extension.ExtensionContext.Store; import org.junit.gen5.api.extension.TestExtensionContext; import org.opentest4j.AssertionFailedError; public class ExpectToFailExtension implements ExceptionHandlerExtensionPoint, AfterEachExtensionPoint { @Override public void handleException(TestExtensionContext context, Throwable throwable) throws Throwable { if (throwable instanceof AssertionFailedError) { getExceptionStore(context).put("exception", throwable); return; } throw throwable; } private Store getExceptionStore(TestExtensionContext context) { return context.getStore(Namespace.of(context)); } @Override public void afterEach(TestExtensionContext context) throws Exception { if (getExceptionStore(context).get("exception") == null) Assertions.fail("Test should have failed"); } }
Clear input value after submission
function getCurrentUserEmail() { var currentUser = Meteor.user(); var emailsArray = currentUser.emails; var firstEmail = emailsArray[0]; return firstEmail.address; } Template.skills.helpers({ hasSkills: function () { var skillService = new SkillService(); var skillsArray = skillService.getSkills(getCurrentUserEmail()); return skillsArray.length > 0; }, getSkills: function () { var skillService = new SkillService(); return skillService.getSkills(getCurrentUserEmail()); } }); Template.skillEntry.events({ 'click button#add-skill-button': function (evt) { evt.preventDefault(); var template = Template.instance(); var skill = template.$('#add-skill-input').val(); Meteor.call('PutSkill', getCurrentUserEmail(), skill, function (err) { if (err) { alert('Error: ' + err); } else { template.$('#add-skill-input').val(''); } }); } });
function getCurrentUserEmail() { var currentUser = Meteor.user(); var emailsArray = currentUser.emails; var firstEmail = emailsArray[0]; return firstEmail.address; } Template.skills.helpers({ hasSkills: function () { var skillService = new SkillService(); var skillsArray = skillService.getSkills(getCurrentUserEmail()); return skillsArray.length > 0; }, getSkills: function () { var skillService = new SkillService(); return skillService.getSkills(getCurrentUserEmail()); } }); Template.skillEntry.events({ 'click button#add-skill-button': function (evt) { evt.preventDefault(); var skill = Template.instance().$('#add-skill-input').val(); Meteor.call('PutSkill', getCurrentUserEmail(), skill, function (err) { if (err) { alert('Error: ' + err); } }); } });
Fix errors in test file Fix errors and typos in 'test_queue.py'
#!/usr/bin/env python # -*- coding: utf-8 -*- """A series of pytest tests to test the quality of our Queue class and its methods """ from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): """Create a queue with numbers 1 - 5 """ new_queue = queue.Queue() for i in range(1, 6): new_queue.enqueue(i) return new_queue def test_dequeue(create_queue): """Test that the queue shrinks and returns first in """ first_queue = create_queue first_val = first_queue.dequeue() assert first_val is 1 assert first_queue.size() is 4 second_val = first_queue.dequeue() assert second_val is 2 assert first_queue.size() is 3 def test_enqueue(create_queue): """Test that the queue grows and returns first in """ second_queue = create_queue second_queue.enqueue(6) assert second_queue.size() is 6 foo = second_queue.dequeue() assert foo is 1 assert second_queue.size() is 5 def test_empty(create_queue): """Test that empty queue size method returns 0 and dequeue raises IndexError """ empty = queue.Queue() assert empty.size() is 0 with pytest.raises(IndexError): empty.dequeue()
#!/usr/bin/env python # -*- coding: utf-8 -*- """A series of pytest tests to test the quality of our Queue class and its methods """ from __future__ import unicode_literals import pytest import queue @pytest.fixture(scope="function") def create_queue(request): """Create a queue with numbers 1 - 5""" new_queue = queue.Queue() for i in range(1, 6): new_queue.enqueue(i) return new_queue def test_dequeue(create_queue): first_queue = create_queue() first_val = first_queue.dequeue() assert first_val is 1 assert first_queue.size() is 4 second_val = first_queue.dequeue() assert second_val is 2 assert first_queue.size() is 3 def test_enqueue(create_queue): second_queue = create_queue() second_queue.enqueue(6) assert second_queue.size() is 6 foo = second_queue.dequeue() assert foo is 1 assert second_queue.size() is 5 def test_empty(create_queue): empty = queue.Queue() assert empty.size() is 0 with pytest.raises("ValueError"): empty.dequeue
Remove top level imports to avoid cyclical import
# -*- coding: utf-8 -*- """ pyEDGAR SEC data library. ===================================== pyEDGAR is a general purpose library for all sorts of interactions with the SEC data sources, primarily the EDGAR distribution system. Files from the SEC reside at https://www.sec.gov/Archives/edgar/data/CIK/ACCESSION.txt :copyright: © 2018 by Mac Gaulin :license: MIT, see LICENSE for more details. """ __title__ = 'pyedgar' __version__ = '0.0.4a1' __author__ = 'Mac Gaulin' __license__ = 'MIT' __copyright__ = 'Copyright 2018 Mac Gaulin' # Include sub-modules from . import utilities from . import exceptions from .exceptions import (InputTypeError, WrongFormType, NoFormTypeFound, NoCIKFound) # __all__ = [edgarweb, forms, localstore, plaintext, #downloader, # InputTypeError, WrongFormType, NoFormTypeFound, NoCIKFound]
# -*- coding: utf-8 -*- """ pyEDGAR SEC data library. ===================================== pyEDGAR is a general purpose library for all sorts of interactions with the SEC data sources, primarily the EDGAR distribution system. Files from the SEC reside at https://www.sec.gov/Archives/edgar/data/CIK/ACCESSION.txt :copyright: © 2018 by Mac Gaulin :license: MIT, see LICENSE for more details. """ __title__ = 'pyedgar' __version__ = '0.0.3a1' __author__ = 'Mac Gaulin' __license__ = 'MIT' __copyright__ = 'Copyright 2018 Mac Gaulin' # Include top level modules from . import filing from . import downloader # Include sub-modules from . import utilities from . import exceptions from .exceptions import (InputTypeError, WrongFormType, NoFormTypeFound, NoCIKFound) # __all__ = [edgarweb, forms, localstore, plaintext, #downloader, # InputTypeError, WrongFormType, NoFormTypeFound, NoCIKFound]
Set react-ga to debug mode
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { BrowserRouter } from 'react-router-dom' import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { composeWithDevTools } from 'redux-devtools-extension'; import ReactGA from 'react-ga'; import rootReducer from './reducers/root'; import registerServiceWorker from './registerServiceWorker'; import App from './containers/App'; import 'semantic-ui-css/semantic.min.css'; import './index.css'; ReactGA.initialize('UA-106072204-1', { debug: true }); function logPageView() { ReactGA.set({ page: window.location.pathname + window.location.search }); ReactGA.pageview(window.location.pathname + window.location.search); } const composeEnhancers = composeWithDevTools({}); const store = createStore(rootReducer, /* preloadedState, */ composeEnhancers( applyMiddleware(thunk), )); ReactDOM.render( <Provider store={store}> <BrowserRouter onUpdate={logPageView}> <App/> </BrowserRouter> </Provider>, document.getElementById('root') ); registerServiceWorker();
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { BrowserRouter } from 'react-router-dom' import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { composeWithDevTools } from 'redux-devtools-extension'; import ReactGA from 'react-ga'; import rootReducer from './reducers/root'; import registerServiceWorker from './registerServiceWorker'; import App from './containers/App'; import 'semantic-ui-css/semantic.min.css'; import './index.css'; ReactGA.initialize('UA-106072204-1'); function logPageView() { ReactGA.set({ page: window.location.pathname + window.location.search }); ReactGA.pageview(window.location.pathname + window.location.search); } const composeEnhancers = composeWithDevTools({}); const store = createStore(rootReducer, /* preloadedState, */ composeEnhancers( applyMiddleware(thunk), )); ReactDOM.render( <Provider store={store}> <BrowserRouter onUpdate={logPageView}> <App/> </BrowserRouter> </Provider>, document.getElementById('root') ); registerServiceWorker();