text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove siteIds from virtualPageView urls.
/* eslint-disable no-undef */ import { takeEvery } from 'redux-saga'; import { select } from 'redux-saga/effects'; import { capitalize } from 'lodash'; import * as deps from '../deps'; export function launchGTMEventsSaga(action) { const { type, ...props } = action; window.dataLayer.push({ event: type, props, }); } export function initDataLayerArray() { window.dataLayer = window.dataLayer || []; } export function* virtualPageView() { const service = yield select(deps.selectors.getSelectedService); const pkg = yield select(deps.selectors.getSelectedPackageName); const pathname = yield select(deps.selectors.getPathname); const titleFromUrl = capitalize(/\/?([^/]+)/.exec(pathname)[1]).replace(/-/g, ' '); const titleFromPkg = pkg ? capitalize(/(.+)-worona/.exec(pkg)[1].replace(/-/g, ' ')) : ''; const title = !service ? titleFromUrl : titleFromPkg; const url = pathname.replace(/(\/?.+)(\/[a-zA-Z0-9]{17})/, '$1'); window.dataLayer.push({ event: 'virtualPageView', virtualPage: { title, url, }, }); } export default function* gtmSagas() { initDataLayerArray(); yield [takeEvery('*', launchGTMEventsSaga)]; yield [takeEvery(deps.types.ROUTER_DID_CHANGE, virtualPageView)]; }
/* eslint-disable no-undef */ import { takeEvery } from 'redux-saga'; import { select } from 'redux-saga/effects'; import { capitalize } from 'lodash'; import * as deps from '../deps'; export function launchGTMEventsSaga(action) { const { type, ...props } = action; window.dataLayer.push({ event: type, props, }); } export function initDataLayerArray() { window.dataLayer = window.dataLayer || []; } export function* virtualPageView(action) { const service = yield select(deps.selectors.getSelectedService); const pkg = yield select(deps.selectors.getSelectedPackageName); const url = yield select(deps.selectors.getPathname); const titleFromUrl = capitalize(/\/?([^/]+)/.exec(url)[1]).replace(/-/g, ' '); const titleFromPkg = pkg ? capitalize(/(.+)-worona/.exec(pkg)[1].replace(/-/g, ' ')) : ''; const title = !service ? titleFromUrl : titleFromPkg; window.dataLayer.push({ event: 'virtualPageView', virtualPage: { title, url, }, }); } export default function* gtmSagas() { initDataLayerArray(); yield [takeEvery('*', launchGTMEventsSaga)]; yield [takeEvery(deps.types.ROUTER_DID_CHANGE, virtualPageView)]; }
Add support for data-event-key attribute to avoid polluting standard attributes and be more explicit
import { getDomNodePath } from './getDomNodePath'; export function getDomNodeProfile(el) { return { action: el.action, class: el.className, href: getElementProps(el, 'href'), id: getElementProps(el, 'id'), event_key: getElementProps(el, 'data-event-key'), method: el.method, name: el.name, node_name: el.nodeName, selector: getDomNodePath(el), text: getElementProps(el, 'text'), title: getElementProps(el, 'title'), type: el.type, x_position: el.offsetLeft || el.clientLeft || null, y_position: el.offsetTop || el.clientTop || null }; } const getElementProps = (el, prop) => { if (el[prop]) { return el[prop]; } if (el.parentNode) { return getElementProps(el.parentNode, prop); } return null; };
import { getDomNodePath } from './getDomNodePath'; export function getDomNodeProfile(el) { return { action: el.action, class: el.className, href: getElementProps(el, 'href'), id: getElementProps(el, 'id'), method: el.method, name: el.name, node_name: el.nodeName, selector: getDomNodePath(el), text: getElementProps(el, 'text'), title: getElementProps(el, 'title'), type: el.type, x_position: el.offsetLeft || el.clientLeft || null, y_position: el.offsetTop || el.clientTop || null }; } const getElementProps = (el, prop) => { if (el[prop]) { return el[prop]; } if (el.parentNode) { return getElementProps(el.parentNode, prop); } return null; };
Put log in /tmp to avoid perm issues
package q import ( "fmt" "os" "path/filepath" "runtime" ) var ( LogFile = "q.log" ) func Println(a ...interface{}) { f := filepath.Join("/tmp", LogFile) fd, err := os.OpenFile(f, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { panic(err) } defer fd.Close() ptr, file, line, ok := runtime.Caller(1) if ok { file = filepath.Base(file) s := []interface{}{ fmt.Sprintf("%s:%d", file, line), // filename:number runtime.FuncForPC(ptr).Name(), // caller name } s = append(s, a...) _, err = fmt.Fprintln(fd, s...) } else { _, err = fmt.Fprintln(fd, a...) } if err != nil { panic(err) } } func Printf(format string, a ...interface{}) { f := filepath.Join("/tmp", LogFile) fd, err := os.OpenFile(f, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { panic(err) } defer fd.Close() _, err = fmt.Fprintf(fd, format, a...) if err != nil { panic(err) } }
package q import ( "fmt" "os" "path/filepath" "runtime" ) var ( LogFile = "/var/log/q" ) func Println(a ...interface{}) { fd, err := os.OpenFile(LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { panic(err) } defer fd.Close() ptr, file, line, ok := runtime.Caller(1) if ok { file = filepath.Base(file) s := []interface{}{ fmt.Sprintf("%s:%d", file, line), // filename:number runtime.FuncForPC(ptr).Name(), // caller name } s = append(s, a...) _, err = fmt.Fprintln(fd, s...) } else { _, err = fmt.Fprintln(fd, a...) } if err != nil { panic(err) } } func Printf(format string, a ...interface{}) { fd, err := os.OpenFile(LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { panic(err) } defer fd.Close() _, err = fmt.Fprintf(fd, format, a...) if err != nil { panic(err) } }
Fix test broken by encodeURIComponent change
var test = require('tap').test, ecstatic = require('../lib/ecstatic'), http = require('http'), request = require('request'), path = require('path'); var root = __dirname + '/public', baseDir = 'base'; test('url encoding in href', function (t) { var port = Math.floor(Math.random() * ((1<<16) - 1e4) + 1e4); var uri = 'http://localhost:' + port + path.join('/', baseDir, 'show-dir-href-encoding'); var server = http.createServer( ecstatic({ root: root, baseDir: baseDir, showDir: true, autoIndex: false }) ); server.listen(port, function () { request.get({ uri: uri }, function(err, res, body) { t.match(body, /href="\/base\/show\-dir\-href\-encoding\/aname%2Baplus\.txt"/, 'We found the right href'); server.close(); t.end(); }); }); });
var test = require('tap').test, ecstatic = require('../lib/ecstatic'), http = require('http'), request = require('request'), path = require('path'); var root = __dirname + '/public', baseDir = 'base'; test('url encoding in href', function (t) { var port = Math.floor(Math.random() * ((1<<16) - 1e4) + 1e4); var uri = 'http://localhost:' + port + path.join('/', baseDir, 'show-dir-href-encoding'); var server = http.createServer( ecstatic({ root: root, baseDir: baseDir, showDir: true, autoIndex: false }) ); server.listen(port, function () { request.get({ uri: uri }, function(err, res, body) { t.match(body, /href="\/base\/show\-dir\-href\-encoding\/aname\+aplus\.txt"/, 'We found the right href'); server.close(); t.end(); }); }); });
Use Ember.create vs Object.create for polyfill fix
var get = Ember.get, set = Ember.set, meta = Ember.meta; Ember.attr = function(type) { return Ember.computed(function(key, value) { var data = get(this, 'data'), dataValue = data && get(data, key), beingCreated = meta(this).proto === this; if (arguments.length === 2) { if (beingCreated) { if (!data) { data = {}; set(this, 'data', data); data[key] = value; } return value; } var isEqual; if (type && type.isEqual) { isEqual = type.isEqual(dataValue, value); } else { isEqual = dataValue === value; } if (!isEqual) { if (!this._dirtyAttributes) { this._dirtyAttributes = Ember.A(); } this._dirtyAttributes.push(key); } else { if (this._dirtyAttributes) { this._dirtyAttributes.removeObject(key); } } return value; } if (typeof dataValue === 'object') { dataValue = Ember.create(dataValue); } return dataValue; }).property('data').meta({isAttribute: true, type: type}); };
var get = Ember.get, set = Ember.set, meta = Ember.meta; Ember.attr = function(type) { return Ember.computed(function(key, value) { var data = get(this, 'data'), dataValue = data && get(data, key), beingCreated = meta(this).proto === this; if (arguments.length === 2) { if (beingCreated) { if (!data) { data = {}; set(this, 'data', data); data[key] = value; } return value; } var isEqual; if (type && type.isEqual) { isEqual = type.isEqual(dataValue, value); } else { isEqual = dataValue === value; } if (!isEqual) { if (!this._dirtyAttributes) { this._dirtyAttributes = Ember.A(); } this._dirtyAttributes.push(key); } else { if (this._dirtyAttributes) { this._dirtyAttributes.removeObject(key); } } return value; } if (typeof dataValue === 'object') { dataValue = Object.create(dataValue); } return dataValue; }).property('data').meta({isAttribute: true, type: type}); };
Make sure we are checking that apply exists
(function() { /* globals define */ 'use strict'; function l(config) { var i = function() { i.c(arguments); }; i.q = []; i.c = function(args) { i.q.push(args); }; window.Intercom = i; var d = document; var s = d.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'https://widget.intercom.io/widget/' + config.intercom.appId; var x = d.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); } var ic = window.Intercom; if (typeof ic === 'function') { ic('reattach_activator'); ic('update', {}); } function generateModule(name, values) { define(name, [], function() { 'use strict'; // jshint ignore:line return values; }); } generateModule('intercom', { default: function() { if (window.Intercom && typeof window.Intercom.apply === 'function') { return window.Intercom.apply(null, arguments); } }, _setup: l }); })();
(function() { /* globals define */ 'use strict'; function l(config) { var i = function() { i.c(arguments); }; i.q = []; i.c = function(args) { i.q.push(args); }; window.Intercom = i; var d = document; var s = d.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'https://widget.intercom.io/widget/' + config.intercom.appId; var x = d.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); } var ic = window.Intercom; if (typeof ic === 'function') { ic('reattach_activator'); ic('update', {}); } function generateModule(name, values) { define(name, [], function() { 'use strict'; // jshint ignore:line return values; }); } generateModule('intercom', { default: function() { if (window.Intercom && typeof window.Intercom === 'function') { return window.Intercom.apply(null, arguments); } }, _setup: l }); })();
Change default retry to 7 from 8
package org.komamitsu.fluency.sender.retry; public abstract class RetryStrategy<C extends RetryStrategy.Config> { protected final C config; public RetryStrategy(C config) { this.config = config; } public abstract long getNextIntervalMillis(int retryCount); public boolean isRetriedOver(int retryCount) { return retryCount > config.getMaxRetryCount(); } public static abstract class Config<T extends RetryStrategy, C extends RetryStrategy.Config> { private int maxRetryCount = 7; public int getMaxRetryCount() { return maxRetryCount; } public C setMaxRetryCount(int maxRetryCount) { this.maxRetryCount = maxRetryCount; return (C)this; } public abstract T createInstance(); } }
package org.komamitsu.fluency.sender.retry; public abstract class RetryStrategy<C extends RetryStrategy.Config> { protected final C config; public RetryStrategy(C config) { this.config = config; } public abstract long getNextIntervalMillis(int retryCount); public boolean isRetriedOver(int retryCount) { return retryCount > config.getMaxRetryCount(); } public static abstract class Config<T extends RetryStrategy, C extends RetryStrategy.Config> { private int maxRetryCount = 8; public int getMaxRetryCount() { return maxRetryCount; } public C setMaxRetryCount(int maxRetryCount) { this.maxRetryCount = maxRetryCount; return (C)this; } public abstract T createInstance(); } }
Add description and test build stage
from conans import ConanFile, CMake class Core8(ConanFile): name = "core8" version = "0.1" url = "https://github.com/benvenutti/core8.git" description = """A Chip-8 VM implemented in C++""" settings = "os", "compiler", "build_type", "arch" license = "MIT" exports_sources = "*" def build(self): cmake = CMake(self.settings) self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line)) self.run("cmake --build . %s" % cmake.build_config) self.run("ctest .") def package(self): self.copy("*.hpp", dst="include/core8", src="include/core8") self.copy("*", dst="lib", src="lib") def package_info(self): self.cpp_info.libs = ["core8"]
from conans import ConanFile, CMake class Core8(ConanFile): name = "core8" version = "0.1" url = "https://github.com/benvenutti/core8.git" settings = "os", "compiler", "build_type", "arch" license = "MIT" exports_sources = "*" def build(self): cmake = CMake(self.settings) self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line)) self.run("cmake --build . %s" % cmake.build_config) def package(self): self.copy("*.hpp", dst="include/core8", src="include/core8") self.copy("*", dst="lib", src="lib") def package_info(self): self.cpp_info.libs = ["core8"]
Add placeholder to ID list field
from django import forms from main.fields import RegexField class IndexForm(forms.Form): id_list = forms.CharField( help_text='List of students IDs to query, one per line.', label='ID List', widget=forms.Textarea(attrs={ 'placeholder': 'Random text\n1234567\n7654321'})) student_id_regex = RegexField( label='Student ID regex', help_text='Regular expression used to match the student ID in each ' 'line. If cannot match (or a student is not found in the ' 'database), then the line is left as is.', initial=r'\b\d{7,}\b', widget=forms.TextInput(attrs={'placeholder': r'\b\d{7,}\b'}))
from django import forms from main.fields import RegexField class IndexForm(forms.Form): id_list = forms.CharField( widget=forms.Textarea, label='ID List', help_text='List of students IDs to query, one per line.') student_id_regex = RegexField( label='Student ID regex', help_text='Regular expression used to match the student ID in each ' 'line. If cannot match (or a student is not found in the ' 'database), then the line is left as is.', initial=r'\b\d{7,}\b', widget=forms.TextInput(attrs={'placeholder': r'\b\d{7,}\b'}))
Use literal for Command struct
package main import ( "encoding/json" "fmt" "net/http" "os" "github.com/vandosant/commandeer/models" ) var commands models.Commands func CommandHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/vnd.application+json; charset=UTF-8") w.WriteHeader(http.StatusOK) c := models.Command{Name: "say"} commands.CommandList = append(commands.CommandList, c) commands.Collection = "name" if err := json.NewEncoder(w).Encode(commands); err != nil { panic(err) } } func main() { port := os.Getenv("PORT") if port == "" { port = "8080" } http.HandleFunc("/", CommandHandler) fmt.Printf("Now running on port %s\n", port) http.ListenAndServe(":"+port, nil) }
package main import ( "encoding/json" "fmt" "net/http" "os" "github.com/vandosant/commandeer/models" ) var commands models.Commands func CommandHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/vnd.application+json; charset=UTF-8") w.WriteHeader(http.StatusOK) c := models.Command{"say"} commands.CommandList = append(commands.CommandList, c) commands.Collection = "name" if err := json.NewEncoder(w).Encode(commands); err != nil { panic(err) } } func main() { port := os.Getenv("PORT") if port == "" { port = "8080" } http.HandleFunc("/", CommandHandler) fmt.Printf("Now running on port %s\n", port) http.ListenAndServe(":"+port, nil) }
Revert "homedir: add cgo or osusergo buildtag constraints for unix" TL;DR: there is no way to do this right. We do know that in some combination of build tags set (or unset), linker flags, environment variables, and libc implementation, this package won't work right. In fact, there is one specific combination: 1. `CGO_ENABLED=1` (or unset) 2. static binary is being built (e.g. `go build` is run with `-extldflags -static`) 3. `go build` links the binary against glibc 4. `osusergo` is not set This particular combination results in the following legitimate linker warning: > cgo_lookup_unix.go: warning: Using 'getpwuid_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking If this warning is ignored and the resulting binary is used on a system with files from a different glibc version (or without those files), it could result in a segfault. The commit being reverted tried to guard against such possibility, but the problem is, we can only use build tags to account for items 1 and 4 from the above list, while items 2 and 3 do not result in any build tags being set or unset, making this guard excessive. Remove it. This reverts commit 023b072288eab3c9e768d4aeeb917f27f06034c7. Signed-off-by: Kir Kolyshkin <3a017b8ddb3f9cf3e4a59978b004111bdeb97f08@gmail.com>
// +build !windows package homedir // import "github.com/docker/docker/pkg/homedir" import ( "os" "os/user" ) // Key returns the env var name for the user's home dir based on // the platform being run on func Key() string { return "HOME" } // Get returns the home directory of the current user with the help of // environment variables depending on the target operating system. // Returned path should be used with "path/filepath" to form new paths. // If compiling statically, ensure the osusergo build tag is used. // If needing to do nss lookups, do not compile statically. func Get() string { home := os.Getenv(Key()) if home == "" { if u, err := user.Current(); err == nil { return u.HomeDir } } return home } // GetShortcutString returns the string that is shortcut to user's home directory // in the native shell of the platform running on. func GetShortcutString() string { return "~" }
// +build !windows,cgo !windows,osusergo package homedir // import "github.com/docker/docker/pkg/homedir" import ( "os" "os/user" ) // Key returns the env var name for the user's home dir based on // the platform being run on func Key() string { return "HOME" } // Get returns the home directory of the current user with the help of // environment variables depending on the target operating system. // Returned path should be used with "path/filepath" to form new paths. // If compiling statically, ensure the osusergo build tag is used. // If needing to do nss lookups, do not compile statically. func Get() string { home := os.Getenv(Key()) if home == "" { if u, err := user.Current(); err == nil { return u.HomeDir } } return home } // GetShortcutString returns the string that is shortcut to user's home directory // in the native shell of the platform running on. func GetShortcutString() string { return "~" }
Update Expert Databases columns in the footer
""" Copyright [2009-2015] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django import template from portal.config.expert_databases import expert_dbs register = template.Library() @register.assignment_tag def get_expert_databases_columns(): """ Return expert databases grouped and order for the website footer. """ dbs = sorted(expert_dbs, key=lambda x: x['name'].lower()) return [ dbs[:10], dbs[10:20], dbs[20:30], dbs[30:], ] @register.assignment_tag def get_expert_databases_list(): """ Get an alphabetically sorted list of imported expert databases. """ imported_dbs = [x for x in expert_dbs if x['imported']] return sorted(imported_dbs, key=lambda x: x['name'].lower())
""" Copyright [2009-2015] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django import template from portal.config.expert_databases import expert_dbs register = template.Library() @register.assignment_tag def get_expert_databases_columns(): """ Return expert databases grouped and order for the website footer. """ dbs = sorted(expert_dbs, key=lambda x: x['name'].lower()) return [ dbs[:10], dbs[10:19], dbs[19:28], dbs[28:], ] @register.assignment_tag def get_expert_databases_list(): """ Get an alphabetically sorted list of imported expert databases. """ imported_dbs = [x for x in expert_dbs if x['imported']] return sorted(imported_dbs, key=lambda x: x['name'].lower())
Update worker immediately when there is an API update The utility we were loading here doesn't seem to exist, but isn't necessary we can just ask the worker if it has an update.
/* eslint ember/order-in-components: 0 */ import { inject as service } from '@ember/service'; import Component from '@ember/component'; import ENV from 'ilios/config/environment'; const { apiVersion } = ENV.APP; export default Component.extend({ iliosConfig: service(), versionMismatch: false, didInsertElement() { this.loadAttributes(); }, async loadAttributes() { const iliosConfig = this.get('iliosConfig'); const serverApiVersion = await iliosConfig.get('apiVersion'); const versionMismatch = serverApiVersion !== apiVersion; if (versionMismatch && 'serviceWorker' in navigator) { const reg = await navigator.serviceWorker.getRegistration(); if (reg && reg.waiting) { reg.waiting.postMessage('skipWaiting'); } } this.set('versionMismatch', versionMismatch); }, });
/* eslint ember/order-in-components: 0 */ import { inject as service } from '@ember/service'; import Component from '@ember/component'; import ENV from 'ilios/config/environment'; import serviceWorkerHasUpdate from 'ilios/utils/service-worker-has-update'; const { apiVersion } = ENV.APP; export default Component.extend({ iliosConfig: service(), versionMismatch: false, didInsertElement() { this.loadAttributes(); }, async loadAttributes() { const iliosConfig = this.get('iliosConfig'); const serverApiVersion = await iliosConfig.get('apiVersion'); const versionMismatch = serverApiVersion !== apiVersion; if (versionMismatch && 'serviceWorker' in navigator) { const hasUpdate = await serviceWorkerHasUpdate(); if (hasUpdate) { const reg = await navigator.serviceWorker.getRegistration(); reg.waiting.postMessage('skipWaiting'); } } this.set('versionMismatch', versionMismatch); }, });
Remove unused parameter from function in Dashycode's unit tests
'use strict'; const assert = require('assert'); const Dashycode = require('./../../.lib-dist/dashycode'); describe('Dashycode', function () { // Technically we should be testing for values up to 0x10FFFF, but we will // never see any above 0xFFFF because of how SockJS works. const codepoints = Array.from({length: 0x10000}, (v, k) => k); const encoded = new Map(); const encode = (codepoint) => { const character = String.fromCodePoint(codepoint); const dashycode = Dashycode.encode(character); assert.strictEqual(encoded.has(dashycode), false); encoded.set(dashycode, character); }; const decode = (dashycode) => { const character = Dashycode.decode(dashycode); assert.strictEqual(encoded.get(dashycode), character); }; it('should encode all codepoints uniquely', function () { return codepoints.reduce((p, codepoint) => ( p.then(v => encode(codepoint)) ), Promise.resolve()); }); it('should decode all codepoints accurately', function () { return [...encoded.keys()].reduce((p, dashycode) => ( p.then(v => decode(dashycode)) ), Promise.resolve()); }); after(function () { encoded.clear(); }); });
'use strict'; const assert = require('assert'); const Dashycode = require('./../../.lib-dist/dashycode'); describe('Dashycode', function () { // Technically we should be testing for values up to 0x10FFFF, but we will // never see any above 0xFFFF because of how SockJS works. const codepoints = Array.from({length: 0x10000}, (v, k) => k); const encoded = new Map(); const encode = (codepoint, allowCaps) => { const character = String.fromCodePoint(codepoint); const dashycode = Dashycode.encode(character); assert.strictEqual(encoded.has(dashycode), false); encoded.set(dashycode, character); }; const decode = (dashycode) => { const character = Dashycode.decode(dashycode); assert.strictEqual(encoded.get(dashycode), character); }; it('should encode all codepoints uniquely', function () { return codepoints.reduce((p, codepoint) => ( p.then(v => encode(codepoint)) ), Promise.resolve()); }); it('should decode all codepoints accurately', function () { return [...encoded.keys()].reduce((p, dashycode) => ( p.then(v => decode(dashycode)) ), Promise.resolve()); }); after(function () { encoded.clear(); }); });
Add error message for data load failure to comp page
import React from "react"; import classes from "./RankingsList.module.css"; import RankingsListRow from "./RankingsListRow/RankingsListRow"; import RankingsListTitleRow from "./RankingsListTitleRow/RankingsListTitleRow"; import { Link } from "react-router-dom"; import ErrorMessage from "../ErrorMessage/ErrorMessage"; const RankingsList = (props) => { if (props.competitors === undefined) { return <ErrorMessage>competitors</ErrorMessage>; } const competitorList = props.competitors.map((competitor) => { return ( <RankingsListRow competitor={competitor} key={competitor.rank} ></RankingsListRow> ); }); return ( <div className={classes.List}> <RankingsListTitleRow></RankingsListTitleRow> {competitorList} </div> ); }; export default RankingsList;
import React from "react"; import classes from "./RankingsList.module.css"; import RankingsListRow from "./RankingsListRow/RankingsListRow"; import RankingsListTitleRow from "./RankingsListTitleRow/RankingsListTitleRow"; import { Link } from "react-router-dom"; const RankingsList = (props) => { const competitorList = props.competitors .map((competitor) => { return ( <RankingsListRow competitor={competitor} key={competitor.rank} ></RankingsListRow> ); }); return ( <div className={classes.List}> <RankingsListTitleRow></RankingsListTitleRow> {competitorList} </div> ); }; export default RankingsList;
Update test to be compatible with browsers that do not support err.stack
if (!chai) { var chai = require('..'); } var assert = chai.assert; suite('assert-config', function () { function fooThrows () { assert.equal('foo', 'bar'); } test('Assertion.includeStack is true, stack trace available', function () { chai.Assertion.includeStack = true; try { fooThrows(); assert.ok(false, 'should not get here because error thrown'); } catch (err) { if (typeof(err.stack) !== 'undefined') { // not all browsers support err.stack assert.include(err.stack, 'at fooThrows', 'should have stack trace in error message'); } } }); test('Assertion.includeStack is false, stack trace not available', function () { chai.Assertion.includeStack = false; try { fooThrows(); assert.ok(false, 'should not get here because error thrown'); } catch (err) { assert.ok(!err.stack || err.stack.indexOf('at fooThrows') === -1, 'should not have stack trace in error message'); } }); });
if (!chai) { var chai = require('..'); } var assert = chai.assert; suite('assert-config', function () { function fooThrows () { assert.equal('foo', 'bar'); } test('Assertion.includeStack is true, stack trace available', function () { chai.Assertion.includeStack = true; try { fooThrows(); assert.ok(false, 'should not get here because error thrown'); } catch (err) { assert.include(err.stack, 'at fooThrows', 'should have stack trace in error message'); } }); test('Assertion.includeStack is false, stack trace not available', function () { chai.Assertion.includeStack = false; try { fooThrows(); assert.ok(false, 'should not get here because error thrown'); } catch (err) { assert.equal(err.stack.indexOf('at fooThrows'), -1, 'should not have stack trace in error message'); } }); });
Fix deprecated view method passing.
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from qraz.frontend.views import handle404 urlpatterns = [ url( r'^api-auth/', include( 'rest_framework.urls', namespace='rest_framework' ) ), url( r'^oauth2/', include( 'oauth2_provider.urls', namespace='oauth2_provider' ) ), url( r'^admin/', include(admin.site.urls) ), url( r'^', include('social.apps.django_app.urls', namespace='social') ), url( r'^', include('qraz.frontend.urls', namespace='qraz') ), ] if settings.DEBUG: urlpatterns += [ url(r'^404$', handle404), ] handler404 = handle404
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url( r'^api-auth/', include( 'rest_framework.urls', namespace='rest_framework' ) ), url( r'^oauth2/', include( 'oauth2_provider.urls', namespace='oauth2_provider' ) ), url( r'^admin/', include(admin.site.urls) ), url( r'^', include('social.apps.django_app.urls', namespace='social') ), url( r'^', include('qraz.frontend.urls', namespace='qraz') ), ] if settings.DEBUG: urlpatterns += [ url(r'^404$', 'qraz.frontend.views.handle404'), ] handler404 = 'qraz.frontend.views.handle404'
Add test demonstrating aware comparisons
""" Facilities for common time operations in UTC. Inspired by the `utc project <https://pypi.org/project/utc>`_. >>> dt = now() >>> dt == fromtimestamp(dt.timestamp()) True >>> dt.tzinfo datetime.timezone.utc >>> from time import time as timestamp >>> now().timestamp() - timestamp() < 0.1 True >>> (now() - fromtimestamp(timestamp())).total_seconds() < 0.1 True >>> datetime(2018, 6, 26, 0).tzinfo datetime.timezone.utc >>> time(0, 0).tzinfo datetime.timezone.utc """ import datetime as std import functools __all__ = ['now', 'fromtimestamp', 'datetime', 'time'] now = functools.partial(std.datetime.now, std.timezone.utc) fromtimestamp = functools.partial( std.datetime.fromtimestamp, tz=std.timezone.utc, ) datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc) time = functools.partial(std.time, tzinfo=std.timezone.utc)
""" Facilities for common time operations in UTC. Inspired by the `utc project <https://pypi.org/project/utc>`_. >>> dt = now() >>> dt == fromtimestamp(dt.timestamp()) True >>> dt.tzinfo datetime.timezone.utc >>> from time import time as timestamp >>> now().timestamp() - timestamp() < 0.1 True >>> datetime(2018, 6, 26, 0).tzinfo datetime.timezone.utc >>> time(0, 0).tzinfo datetime.timezone.utc """ import datetime as std import functools __all__ = ['now', 'fromtimestamp', 'datetime', 'time'] now = functools.partial(std.datetime.now, std.timezone.utc) fromtimestamp = functools.partial( std.datetime.fromtimestamp, tz=std.timezone.utc, ) datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc) time = functools.partial(std.time, tzinfo=std.timezone.utc)
Make default color not required
from rest_framework import serializers class Tag(object): def __init__(self, name, related_tags, equivalent_names): self.name = name self.related_tags = related_tags self.equivalent_names = equivalent_names class TagSerializer(serializers.Serializer): name = serializers.CharField() related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True) equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True) def create(self, validated_data): return Tag(**validated_data) class Followable(object): def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs): self.name = name self.type = type self.game = game self.object_id = object_id self.thumbnail_url = thumbnail_url for field, value in kwargs.items(): setattr(self, field, value) class FollowableSerializer(serializers.Serializer): name = serializers.CharField() type = serializers.IntegerField() game = serializers.IntegerField() object_id = serializers.IntegerField() default_color = serializers.CharField(allow_null=True, allow_blank=True, required=False) thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True) def create(self, validated_data): return Followable(**validated_data)
from rest_framework import serializers class Tag(object): def __init__(self, name, related_tags, equivalent_names): self.name = name self.related_tags = related_tags self.equivalent_names = equivalent_names class TagSerializer(serializers.Serializer): name = serializers.CharField() related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True) equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True) def create(self, validated_data): return Tag(**validated_data) class Followable(object): def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs): self.name = name self.type = type self.game = game self.object_id = object_id self.thumbnail_url = thumbnail_url for field, value in kwargs.items(): setattr(self, field, value) class FollowableSerializer(serializers.Serializer): name = serializers.CharField() type = serializers.IntegerField() game = serializers.IntegerField() object_id = serializers.IntegerField() default_color = serializers.CharField(allow_null=True, allow_blank=True) thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True) def create(self, validated_data): return Followable(**validated_data)
Add test for merge sort
def merge(left, right): """Merge sort merging function.""" left_index, right_index = 0, 0 result = [] while left_index < len(left) and right_index < len(right): if left[left_index] < right[right_index]: result.append(left[left_index]) left_index += 1 else: result.append(right[right_index]) right_index += 1 result += left[left_index:] result += right[right_index:] return result def merge_sort(array): """Merge sort algorithm implementation.""" if len(array) <= 1: # base case return array # divide array in half and merge sort recursively half = len(array) // 2 left = merge_sort(array[:half]) right = merge_sort(array[half:]) return merge(left, right) def test(): list = [5, 7, 6, 2, 1, 7, 3] sorted_list = merge_sort(list) print 'Sorted: ', sorted_list if __name__ == '__main__': test()
def merge(left, right): """Merge sort merging function.""" left_index, right_index = 0, 0 result = [] while left_index < len(left) and right_index < len(right): if left[left_index] < right[right_index]: result.append(left[left_index]) left_index += 1 else: result.append(right[right_index]) right_index += 1 result += left[left_index:] result += right[right_index:] return result def merge_sort(array): """Merge sort algorithm implementation.""" if len(array) <= 1: # base case return array # divide array in half and merge sort recursively half = len(array) // 2 left = merge_sort(array[:half]) right = merge_sort(array[half:]) return merge(left, right)
Change return string type to hex string
package login; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.xml.bind.DatatypeConverter; public class PasswordHelper { private static String hashAlgorithm = "MD5"; private static String stringEncodingFormat = "UTF-8"; public static String generatePasswordHash(String password) { //Create instances of digest and password char array MessageDigest passDigest; byte[] passArray; try { //Create instance of MessageDigest we can use to passDigest = MessageDigest.getInstance(hashAlgorithm); //Convert password to byte array passArray = password.getBytes(stringEncodingFormat); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } //Use digest to get hash as an array of chars and return it as a hex string byte[] hashArray = passDigest.digest(passArray); return DatatypeConverter.printHexBinary(hashArray); } }
package login; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PasswordHelper { private static String hashAlgorithm = "MD5"; private static String stringEncodingFormat = "UTF-8"; public static String generatePasswordHash(String password) { //Create instances of digest and password char array MessageDigest passDigest; byte[] passArray; try { //Create instance of MessageDigest we can use to passDigest = MessageDigest.getInstance(hashAlgorithm); //Convert password to byte array passArray = password.getBytes(stringEncodingFormat); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } //Use digest to get an array of chars as a hash and return it as a string byte[] hashArray = passDigest.digest(passArray); return new String(hashArray); } }
Fix to allow non boolean options
'use strict'; module.exports = function(prompts) { // This method will only show prompts that haven't been supplied as options. This makes the generator more composable. const filteredPrompts = []; const props = new Map(); prompts.forEach(function prompts(prompt) { const option = this.options[prompt.name]; if (option === undefined) { // No option supplied, user will be prompted filteredPrompts.push(prompt); } else { // Options supplied, add to props props[prompt.name] = option; } }, this); if (filteredPrompts.length) { return this.prompt(filteredPrompts).then(function mergeProps(mergeProps) { // Merge mergeProps into props/ Object.assign(props, mergeProps); return props; }); } // No prompting required call the callback right away. return Promise.resolve(props); };
'use strict'; module.exports = function(prompts) { // This method will only show prompts that haven't been supplied as options. This makes the generator more composable. const filteredPrompts = []; const props = new Map(); prompts.forEach(function prompts(prompt) { this.option(prompt.name); const option = this.options[prompt.name]; if (option === undefined) { // No option supplied, user will be prompted filteredPrompts.push(prompt); } else { // Options supplied, add to props props[prompt.name] = option; } }, this); if (filteredPrompts.length) { return this.prompt(filteredPrompts).then(function mergeProps(mergeProps) { // Merge mergeProps into props/ Object.assign(props, mergeProps); return props; }); } // No prompting required call the callback right away. return Promise.resolve(props); };
Fix a couple of minor syntax errors in the test
var expect = require('chai').expect; var request = require('request'); var server = require('../server').server; var connection; describe('Server', function() { describe('presence', function() { beforeEach(function() { connection = server.listen(3000); }); afterEach(function() { connection.close(); }); it('should have no users logged in', function() { expect(server.get('users')).to.be.empty; }); it('should have foo logged in', function(done) { request.post('http://localhost:3000/signin', {form: {nick: 'foo'}}, function() { expect(server.get('users')).to.eql(['foo']); done(); }); }); it('should have no users logged in', function(done) { request.post('http://localhost:3000/signin', {form: {nick: 'foo'}}, function() { request.post('http://localhost:3000/signout', {form: {nick: 'foo'}}, function() { expect(server.get('users')).to.be.empty; done(); }); }); }); }); });
var expect = require('chai').expect; var request = require('request'); var server = require('../server').server; var connection; describe('Server', function() { describe('presence', function() { beforeEach(function() { connection = server.listen(3000) }); afterEach(function() { connection.close(); }); it('should have no users logged in', function() { expect(server.get('users')).to.be.empty; }); it('should have foo logged in', function(done) { request.post('http://localhost:3000/signin', {form: {nick: 'foo'}}, function() { expect(server.get('users')).to.eql(['foo']) done(); }); }); it('should have no users logged in', function(done) { request.post('http://localhost:3000/signin', {form: {nick: 'foo'}}, function() { request.post('http://localhost:3000/signout', {form: {nick: 'foo'}}, function() { expect(server.get('users')).to.be.empty; done(); }); }); }); }); });
Add new grammars to Combinator.DEFAULT_GRAMMARS
from copy import copy from collections import deque from yargy import FactParser from natasha.grammars import Person, Geo, Money, Date class Combinator(object): DEFAULT_GRAMMARS = [ Money, Person, Geo, Date, ] def __init__(self, grammars=None, cache_size=50000): self.grammars = grammars or self.DEFAULT_GRAMMARS self.parser = FactParser(cache_size=cache_size) def extract(self, text): tokens = deque(self.parser.tokenizer.transform(text)) for grammar in self.grammars: for grammar_type, rule in grammar.__members__.items(): for match in self.parser.extract(copy(tokens), rule.value): yield (grammar, grammar_type, match)
from copy import copy from collections import deque from yargy import FactParser from natasha.grammars import Person, Geo class Combinator(object): DEFAULT_GRAMMARS = [ Person, Geo, ] def __init__(self, grammars=None, cache_size=50000): self.grammars = grammars or self.DEFAULT_GRAMMARS self.parser = FactParser(cache_size=cache_size) def extract(self, text): tokens = deque(self.parser.tokenizer.transform(text)) for grammar in self.grammars: for grammar_type, rule in grammar.__members__.items(): for match in self.parser.extract(copy(tokens), rule.value): yield (grammar, grammar_type, match)
Fix tests since we changed imports. --HG-- branch : schema-invitations
from django.test import TestCase from .models import AwareModel, NaiveModel from ..templatetags.boardinghouse import schema_name, is_schema_aware, is_shared_model from ..models import Schema class TestTemplateTags(TestCase): def test_is_schema_aware_filter(self): self.assertTrue(is_schema_aware(AwareModel())) self.assertFalse(is_schema_aware(NaiveModel())) def test_is_shared_model_filter(self): self.assertFalse(is_shared_model(AwareModel())) self.assertTrue(is_shared_model(NaiveModel())) def test_schema_name_filter(self): Schema.objects.create(name='Schema Name', schema='foo') self.assertEquals('Schema Name', schema_name('foo')) self.assertEquals('no schema', schema_name(None)) self.assertEquals('no schema', schema_name('')) self.assertEquals('no schema', schema_name(False)) self.assertEquals('no schema', schema_name('foobar')) self.assertEquals('no schema', schema_name('foo_')) self.assertEquals('no schema', schema_name('foofoo'))
from django.test import TestCase from .models import AwareModel, NaiveModel from ..templatetags.boardinghouse import * class TestTemplateTags(TestCase): def test_is_schema_aware_filter(self): self.assertTrue(is_schema_aware(AwareModel())) self.assertFalse(is_schema_aware(NaiveModel())) def test_is_shared_model_filter(self): self.assertFalse(is_shared_model(AwareModel())) self.assertTrue(is_shared_model(NaiveModel())) def test_schema_name_filter(self): Schema.objects.create(name='Schema Name', schema='foo') self.assertEquals('Schema Name', schema_name('foo')) self.assertEquals('no schema', schema_name(None)) self.assertEquals('no schema', schema_name('')) self.assertEquals('no schema', schema_name(False)) self.assertEquals('no schema', schema_name('foobar')) self.assertEquals('no schema', schema_name('foo_')) self.assertEquals('no schema', schema_name('foofoo'))
Fix touchable list group item
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import BaseTouchable from '../../utils/rnw-compat/BaseTouchable'; import useActionElement from '../../hooks/useActionElement'; import action from '../../utils/action'; const propTypes = { // eslint-disable-next-line react/forbid-foreign-prop-types ...action.propTypes, children: PropTypes.node.isRequired, disabled: PropTypes.bool, active: PropTypes.bool, }; const defaultProps = { ...action.defaultProps, disabled: false, active: false, }; const ActionListGroupItem = React.forwardRef(function ActionListGroupItem( props, ref, ) { const { disabled, active, ...elementProps } = props; const classes = cx( // constant classes 'list-group-item', 'list-group-item-action', // variable classes disabled && 'disabled', active && 'active', ); const createElement = useActionElement( BaseTouchable, { disabled, ...elementProps, }, ref, ); return createElement({ className: classes, }); }); ActionListGroupItem.displayName = 'ActionListGroupItem'; ActionListGroupItem.propTypes = propTypes; ActionListGroupItem.defaultProps = defaultProps; export default ActionListGroupItem;
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import BaseTouchable from '../../utils/rnw-compat/BaseTouchable'; import useActionElement from '../../hooks/useActionElement'; import action from '../../utils/action'; const propTypes = { // eslint-disable-next-line react/forbid-foreign-prop-types ...action.propTypes, children: PropTypes.node.isRequired, disabled: PropTypes.bool, active: PropTypes.bool, }; const defaultProps = { ...action.defaultProps, disabled: false, active: false, }; const ActionListGroupItem = React.forwardRef(function ActionListGroupItem( props, ref, ) { const { disabled, active, ...elementProps } = props; const classes = cx( // constant classes 'list-group-item', 'list-group-item-action', // variable classes disabled && 'disabled', active && 'active', ); const createElement = useActionElement(BaseTouchable, { disabled, elementProps, ref, }); return createElement({ className: classes, }); }); ActionListGroupItem.displayName = 'ActionListGroupItem'; ActionListGroupItem.propTypes = propTypes; ActionListGroupItem.defaultProps = defaultProps; export default ActionListGroupItem;
Add info for mandelbrot set
#!/usr/local/bin/python3 # Python Challenge - 31 # http://www.pythonchallenge.com/pc/ring/grandpa.html # http://www.pythonchallenge.com/pc/rock/grandpa.html # Username: repeat; Password: switch # Keyword: kohsamui, thailand; ''' Uses Anaconda environment with Pillow for image processing - Python 3.7, numpy, and Pillow (PIL) - Run `source activate imgPIL`, `python chall_31.py` ''' from PIL import Image def main(): ''' Hint: where am I? Picture of rock near a beach short break, this ***REALLY*** has nothing to do with Python Login required: island: country -> search for Grandpa rock Next page: UFO's ? That was too easy. You are still on 31... Window element with iterations attribute of 128 ''' left = 0.34 top = 0.57 w_step = 0.036 # x-axis = reals h_step = 0.027 # y-axis = imaginaries max_iter = 128 with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot: w, h = mandelbrot.size print('W: {}, H: {}'.format(w, h)) # f_c(z) = z^2 + c for f_c(0), f_c(f_c(0)), etc. for n_iter in range(max_iter): pass return 0 if __name__ == '__main__': main()
#!/usr/local/bin/python3 # Python Challenge - 31 # http://www.pythonchallenge.com/pc/ring/grandpa.html # http://www.pythonchallenge.com/pc/rock/grandpa.html # Username: repeat; Password: switch # Keyword: kohsamui, thailand; ''' Uses Anaconda environment with Pillow for image processing - Python 3.7, numpy, and Pillow (PIL) - Run `source activate imgPIL`, `python chall_31.py` ''' from PIL import Image def main(): ''' Hint: where am I? Picture of rock near a beach short break, this ***REALLY*** has nothing to do with Python Login required: island: country Next page: UFO's ? That was too easy. You are still on 31... Window element with iterations attribute of 128 ''' left = 0.34 top = 0.57 width = 0.036 height = 0.027 max_iter = 128 with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot: pass return 0 if __name__ == '__main__': main()
Change for loop to use a more generally-accepted value of the number 5
<?php require_once __DIR__ . '/../bootstrap.php'; function generateAndOutput5(Broadway\Uuid\UuidGeneratorInterface $generator) { for ($i = 0; $i < 5; $i++) { echo sprintf("[%d] %s\n", $i, $generator->generate()); } } echo "A random generated uuid:\n"; $randomGenerator = new Broadway\Uuid\Rfc4122\Version4Generator(); generateAndOutput5($randomGenerator); echo "\n"; echo "A generator that will always return the same uuid (for testing):\n"; $mockUuidGenerator = new Broadway\Uuid\Testing\MockUuidGenerator(42); generateAndOutput5($mockUuidGenerator); echo "\n"; echo "A generator that will always return the same sequence of uuids and throw an exception if depleted (for testing):\n"; $mockUuidSequenceGenerator = new Broadway\Uuid\Testing\MockUuidSequenceGenerator(array(1, 1, 2, 3, 5, 8, 13, 21)); generateAndOutput5($mockUuidSequenceGenerator);
<?php require_once __DIR__ . '/../bootstrap.php'; function generateAndOutput5(Broadway\Uuid\UuidGeneratorInterface $generator) { for ($i = 0; $i < 8; $i++) { echo sprintf("[%d] %s\n", $i, $generator->generate()); } } echo "A random generated uuid:\n"; $randomGenerator = new Broadway\Uuid\Rfc4122\Version4Generator(); generateAndOutput5($randomGenerator); echo "\n"; echo "A generator that will always return the same uuid (for testing):\n"; $mockUuidGenerator = new Broadway\Uuid\Testing\MockUuidGenerator(42); generateAndOutput5($mockUuidGenerator); echo "\n"; echo "A generator that will always return the same sequence of uuids and throw an exception if depleted (for testing):\n"; $mockUuidSequenceGenerator = new Broadway\Uuid\Testing\MockUuidSequenceGenerator(array(1, 1, 2, 3, 5, 8, 13, 21)); generateAndOutput5($mockUuidSequenceGenerator);
Add project dependencies to install
#!/usr/bin/env python #coding: utf-8 from distribute_setup import use_setuptools use_setuptools() from aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__ from setuptools import setup setup( name = __title__, author = __authors__, author_email = __email__, version = __version__, license = __license__, url = __url__, download_url = __download_url__, packages = ['aero', 'aero.adapters'], package_data ={'aero': ['assets/*.ascii']}, description = [descr for descr in open('README.txt').read().splitlines() if descr.strip() and '===' not in descr][1], long_description=open('README.txt').read(), install_requires = ["argparse","Beaker","PyYAML"], scripts = ["aero/aero"], )
#!/usr/bin/env python #coding: utf-8 from distribute_setup import use_setuptools use_setuptools() from aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__ from setuptools import setup setup( name = __title__, author = __authors__, author_email = __email__, version = __version__, license = __license__, url = __url__, download_url = __download_url__, packages = ['aero', 'aero.adapters'], package_data ={'aero': ['assets/*.ascii']}, description = [descr for descr in open('README.txt').read().splitlines() if descr.strip() and '===' not in descr][1], long_description=open('README.txt').read(), scripts = ["aero/aero"], )
Make the heading doc string a bit more descriptive
# vim: tabstop=4 expandtab autoindent shiftwidth=4 fileencoding=utf-8 """ Provides Nose and Django test case assert functions """ from django.test.testcases import TestCase import re ## Python from nose import tools for t in dir(tools): if t.startswith('assert_'): vars()[t] = getattr(tools, t) ## Django caps = re.compile('([A-Z])') def pep8(name): return caps.sub(lambda m: '_' + m.groups()[0].lower(), name) class Dummy(TestCase): def nop(): pass _t = Dummy('nop') for at in [ at for at in dir(_t) if at.startswith('assert') and not '_' in at ]: pepd = pep8(at) vars()[pepd] = getattr(_t, at) del Dummy del _t del pep8 ## New def assert_code(response, status_code, msg_prefix=''): """Asserts the response was returned with the given status code """ if msg_prefix: msg_prefix = '%s: ' % msg_prefix assert response.status_code == status_code, \ 'Response code was %d (expected %d)' % \ (response.status_code, status_code) def assert_ok(response, msg_prefix=''): """Asserts the response was returned with status 200 (OK) """ return assert_code(response, 200, msg_prefix=msg_prefix) # EOF
# vim: tabstop=4 expandtab autoindent shiftwidth=4 fileencoding=utf-8 """ Assertions that sort of follow Python unittest/Django test cases """ from django.test.testcases import TestCase import re ## Python from nose import tools for t in dir(tools): if t.startswith('assert_'): vars()[t] = getattr(tools, t) ## Django caps = re.compile('([A-Z])') def pep8(name): return caps.sub(lambda m: '_' + m.groups()[0].lower(), name) class Dummy(TestCase): def nop(): pass _t = Dummy('nop') for at in [ at for at in dir(_t) if at.startswith('assert') and not '_' in at ]: pepd = pep8(at) vars()[pepd] = getattr(_t, at) del Dummy del _t del pep8 ## New def assert_code(response, status_code, msg_prefix=''): """Asserts the response was returned with the given status code """ if msg_prefix: msg_prefix = '%s: ' % msg_prefix assert response.status_code == status_code, \ 'Response code was %d (expected %d)' % \ (response.status_code, status_code) def assert_ok(response, msg_prefix=''): """Asserts the response was returned with status 200 (OK) """ return assert_code(response, 200, msg_prefix=msg_prefix) # EOF
Implement function to load data from directory
from nltk.tokenize import word_tokenize, sent_tokenize import getopt import sys import os import io def load_data(dir_doc): docs = {} for dirpath, dirnames, filenames in os.walk(dir_doc): for name in filenames: file = os.path.join(dirpath, name) with io.open(file, 'r+') as f: docs[name] = f.read() return docs def usage(): print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file") if __name__ == '__main__': dir_doc = dict_file = postings_file = None try: opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:') except getopt.GetoptError as err: usage() sys.exit(2) for o, a in opts: if o == '-i': dir_doc = a elif o == '-d': dict_file = a elif o == '-p': postings_file = a else: assert False, "unhandled option" if dir_doc == None or dict_file == None or postings_file == None: usage() sys.exit(2) load_data(dir_doc)
from nltk.tokenize import word_tokenize, sent_tokenize import getopt import sys import os import io def usage(): print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file") if __name__ == '__main__': dir_doc = dict_file = postings_file = None try: opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:') except getopt.GetoptError as err: usage() sys.exit(2) for o, a in opts: if o == '-i': dir_doc = a elif o == '-d': dict_file = a elif o == '-p': postings_file = a else: assert False, "unhandled option" if dir_doc == None or dict_file == None or postings_file == None: usage() sys.exit(2)
Add missing whitespace around link
import React from 'react'; import './App.css'; import Clock from './Clock.js'; function App() { return ( <div className="App"> <Clock></Clock> {/* If you add a Weatherclock launcher to your home screen on an iPhone, the page opened will not be in a web-browser (or at least look like it's not). So we add a reload button of our own here. */} {/* FIXME: Should be "onClick" not "onclick, then read console messages for further inspiration" */} <button type="button" onclick="location.reload();">Update forecast FIXME: Handler doesnt work</button> <p>Weather forecast from <a href="yr.no">yr.no</a>, delivered by the <a href="http://met.no/English/">Norwegian Meteorological Institute</a> and the <a href="http://www.nrk.no/">NRK</a>.</p> <p>Imagine a share-on-Facebook button here</p> <p> <a href="https://github.com/walles/weatherclock">Source code on GitHub</a> </p> </div> ); } export default App;
import React from 'react'; import './App.css'; import Clock from './Clock.js'; function App() { return ( <div className="App"> <Clock></Clock> {/* If you add a Weatherclock launcher to your home screen on an iPhone, the page opened will not be in a web-browser (or at least look like it's not). So we add a reload button of our own here. */} {/* FIXME: Should be "onClick" not "onclick, then read console messages for further inspiration" */} <button type="button" onclick="location.reload();">Update forecast FIXME: Handler doesnt work</button> <p>Weather forecast from <a href="yr.no">yr.no</a>, delivered by the <a href="http://met.no/English/">Norwegian Meteorological Institute</a> and the <a href="http://www.nrk.no/">NRK</a>.</p> <p>Imagine a share-on-Facebook button here</p> <p> <a href="https://github.com/walles/weatherclock">Source code on GitHub</a> </p> </div> ); } export default App;
Change celery and kombu requirements to match ckanext-datastorer
from setuptools import setup, find_packages from ckanext.qa import __version__ setup( name='ckanext-qa', version=__version__, description='Quality Assurance plugin for CKAN', long_description='', classifiers=[], keywords='', author='Open Knowledge Foundation', author_email='info@okfn.org', url='http://ckan.org/wiki/Extensions', license='mit', packages=find_packages(exclude=['tests']), namespace_packages=['ckanext', 'ckanext.qa'], include_package_data=True, zip_safe=False, install_requires=[ 'celery==2.4.2', 'kombu==2.1.3', 'kombu-sqlalchemy==1.1.0', 'SQLAlchemy>=0.6.6', 'requests==0.6.4', ], tests_require=[ 'nose', 'mock', ], entry_points=''' [paste.paster_command] qa=ckanext.qa.commands:QACommand [ckan.plugins] qa=ckanext.qa.plugin:QAPlugin [ckan.celery_task] tasks=ckanext.qa.celery_import:task_imports ''', )
from setuptools import setup, find_packages from ckanext.qa import __version__ setup( name='ckanext-qa', version=__version__, description='Quality Assurance plugin for CKAN', long_description='', classifiers=[], keywords='', author='Open Knowledge Foundation', author_email='info@okfn.org', url='http://ckan.org/wiki/Extensions', license='mit', packages=find_packages(exclude=['tests']), namespace_packages=['ckanext', 'ckanext.qa'], include_package_data=True, zip_safe=False, install_requires=[ 'celery==2.4.5', 'kombu==1.5.1', 'kombu-sqlalchemy==1.1.0', 'SQLAlchemy>=0.6.6', 'requests==0.6.4', ], tests_require=[ 'nose', 'mock', ], entry_points=''' [paste.paster_command] qa=ckanext.qa.commands:QACommand [ckan.plugins] qa=ckanext.qa.plugin:QAPlugin [ckan.celery_task] tasks=ckanext.qa.celery_import:task_imports ''', )
Use net.IP instead of IPAddr
package socks5 import ( "net" ) // RuleSet is used to provide custom rules to allow or prohibit actions type RuleSet interface { // AllowConnect is used to filter connect requests AllowConnect(dstIP net.IP, dstPort int, srcIP net.IP, srcPort int) bool // AllowBind is used to filter bind requests AllowBind(dstIP net.IP, dstPort int, srcIP net.IP, srcPort int) bool // AllowAssociate is used to filter associate requests AllowAssociate(dstIP net.IP, dstPort int, srcIP net.IP, srcPort int) bool } // PermitAll is an returns a RuleSet which allows all types of connections func PermitAll() RuleSet { return &PermitCommand{true, true, true} } // PermitCommand is an implementation of the RuleSet which // enables filtering supported commands type PermitCommand struct { EnableConnect bool EnableBind bool EnableAssociate bool } func (p *PermitCommand) AllowConnect(net.IP, int, net.IP, int) bool { return p.EnableConnect } func (p *PermitCommand) AllowBind(net.IP, int, net.IP, int) bool { return p.EnableBind } func (p *PermitCommand) AllowAssociate(net.IP, int, net.IP, int) bool { return p.EnableAssociate }
package socks5 import ( "net" ) // RuleSet is used to provide custom rules to allow or prohibit actions type RuleSet interface { // AllowConnect is used to filter connect requests AllowConnect(dstIP *net.IPAddr, dstPort int, srcIP *net.IPAddr, srcPort int) bool // AllowBind is used to filter bind requests AllowBind(dstIP *net.IPAddr, dstPort int, srcIP *net.IPAddr, srcPort int) bool // AllowAssociate is used to filter associate requests AllowAssociate(dstIP *net.IPAddr, dstPort int, srcIP *net.IPAddr, srcPort int) bool } // PermitAll is an returns a RuleSet which allows all types of connections func PermitAll() RuleSet { return &PermitCommand{true, true, true} } // PermitCommand is an implementation of the RuleSet which // enables filtering supported commands type PermitCommand struct { EnableConnect bool EnableBind bool EnableAssociate bool } func (p *PermitCommand) AllowConnect(*net.IPAddr, int, *net.IPAddr, int) bool { return p.EnableConnect } func (p *PermitCommand) AllowBind(*net.IPAddr, int, *net.IPAddr, int) bool { return p.EnableBind } func (p *PermitCommand) AllowAssociate(*net.IPAddr, int, *net.IPAddr, int) bool { return p.EnableAssociate }
BAP-3903: Create dashboard loading command - fix typo
<?php namespace Oro\Bundle\CalendarBundle\Migrations\Data\ORM; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Oro\Bundle\DashboardBundle\Migrations\Data\ORM\AbstractDashboardFixture; class LoadDashboardData extends AbstractDashboardFixture implements DependentFixtureInterface { /** * {@inheritdoc} */ public function getDependencies() { return ['Oro\Bundle\DashboardBundle\Migrations\Data\ORM\LoadDashboardData']; } /** * {@inheritdoc} */ public function load(ObjectManager $manager) { $mainDashboard = $this->findAdminDashboard($manager, 'main'); if ($mainDashboard) { $this->addNewDashboardWidget($manager, $mainDashboard, 'my_calendar') ->setLayoutPosition([1, 20]); $manager->flush(); } } }
<?php namespace Oro\Bundle\CalendarBundle\Migrations\Data\ORM; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Oro\Bundle\DashboardBundle\Migrations\Data\ORM\AbstractDashboardFixture; class LoadDashboardData extends AbstractDashboardFixture implements DependentFixtureInterface { /** * {@inheritdoc} */ public function getDependencies() { return ['Oro\Bundle\DashboardBundle\Migrations\Data\ORM\LoadDashboardData']; } /** * {@inheritdoc} */ public function load(ObjectManager $manager) { $mainDashboard = $this->findAdminDashboard($manager, 'main'); if (!$mainDashboard) { $this->addNewDashboardWidget($manager, $mainDashboard, 'my_calendar') ->setLayoutPosition([1, 20]); $manager->flush(); } } }
Add ability to configure a platform-specific type.
<?php /** * PHP version 7.1 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ namespace ComPHPPuebla\Fixtures\Connections; use Doctrine\DBAL\Connection as DbConnection; class DBALConnection implements Connection { /** @var DbConnection */ protected $connection; public function __construct(DbConnection $connection) { $this->connection = $connection; } public function insert(string $table, array $row): int { $this->connection->insert($table, $this->quoteIdentifiers($row)); return $this->connection->lastInsertId(); } private function quoteIdentifiers(array $row): array { $quoted = []; foreach ($row as $column => $value) { $quoted[$this->connection->quoteIdentifier($column)] = $value; } return $quoted; } public function getPrimaryKeyOf(string $table): string { $schema = $this->connection->getSchemaManager(); return $schema->listTableDetails($table)->getPrimaryKeyColumns()[0]; } public function registerPlatformType(string $platformType, string $dbalType) { $schema = $this->connection->getSchemaManager(); $schema->getDatabasePlatform()->registerDoctrineTypeMapping($platformType, $dbalType); } }
<?php /** * PHP version 7.1 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ namespace ComPHPPuebla\Fixtures\Connections; use Doctrine\DBAL\Connection as DbConnection; class DBALConnection implements Connection { /** @var DbConnection */ protected $connection; public function __construct(DbConnection $connection) { $this->connection = $connection; } public function insert(string $table, array $row): int { $this->connection->insert($table, $this->quoteIdentifiers($row)); return $this->connection->lastInsertId(); } private function quoteIdentifiers(array $row): array { $quoted = []; foreach ($row as $column => $value) { $quoted[$this->connection->quoteIdentifier($column)] = $value; } return $quoted; } public function getPrimaryKeyOf(string $table): string { $schema = $this->connection->getSchemaManager(); return $schema->listTableDetails($table)->getPrimaryKeyColumns()[0]; } }
Fix case where there's no subject in an email
"use strict"; var Immutable = require('immutable') const AUTHORS_BY_MSG_ID = {} const EMPTY_ITEM_MAP = Immutable.Map({ total: 0, trend: 0 }) , inc = n => n + 1 , incCounts = counts => counts.update('total', inc).update('trend', inc) , updateMapCounts = val => map => map.update(val, EMPTY_ITEM_MAP, incCounts) const RE_REGEX = /re:\s+/i const sortCountMap = map => map.sort((a, b) => { a = a.get('trend'); b = b.get('trend'); return a === b ? 0 : b > a ? 1 : -1; }) module.exports = function addCommunication(communications, msg) { let author = msg.from[0].name , inReplyTo = (msg.inReplyTo || [{}])[0] , pair , subject AUTHORS_BY_MSG_ID[msg.messageId] = author; if (!inReplyTo) { pair = Immutable.Set([author]); } else { pair = Immutable.Set([author, AUTHORS_BY_MSG_ID[inReplyTo]]).sort(); } subject = (msg.subject || '(no_subject)').replace(RE_REGEX, ''); return communications .update('pair', Immutable.Map(), updateMapCounts(pair)) .update('author', Immutable.Map(), updateMapCounts(author)) .update('subject', Immutable.Map(), updateMapCounts(subject)) .map(sortCountMap) }
"use strict"; var Immutable = require('immutable') const AUTHORS_BY_MSG_ID = {} const EMPTY_ITEM_MAP = Immutable.Map({ total: 0, trend: 0 }) , inc = n => n + 1 , incCounts = counts => counts.update('total', inc).update('trend', inc) , updateMapCounts = val => map => map.update(val, EMPTY_ITEM_MAP, incCounts) const RE_REGEX = /re:\s+/i const sortCountMap = map => map.sort((a, b) => { a = a.get('trend'); b = b.get('trend'); return a === b ? 0 : b > a ? 1 : -1; }) module.exports = function addCommunication(communications, msg) { let author = msg.from[0].name , inReplyTo = (msg.inReplyTo || [{}])[0] , pair , subject AUTHORS_BY_MSG_ID[msg.messageId] = author; if (!inReplyTo) { pair = Immutable.Set([author]); } else { pair = Immutable.Set([author, AUTHORS_BY_MSG_ID[inReplyTo]]).sort(); } subject = msg.subject.replace(RE_REGEX, ''); return communications .update('pair', Immutable.Map(), updateMapCounts(pair)) .update('author', Immutable.Map(), updateMapCounts(author)) .update('subject', Immutable.Map(), updateMapCounts(subject)) .map(sortCountMap) }
Update bootcode threshold to 3.7 MB
const fs = require('fs'), path = require('path'), expect = require('chai').expect, CACHE_DIR = path.join(__dirname, '/../../.cache'), THRESHOLD = 3.7 * 1024 * 1024; // 3.7 MB describe('bootcode size', function () { this.timeout(60 * 1000); it('should not exceed the threshold', function (done) { fs.readdir(CACHE_DIR, function (err, files) { if (err) { return done(err); } files.forEach(function (file) { var size = fs.statSync(CACHE_DIR + '/' + file).size; expect(size, (file + ' threshold exceeded')).to.be.below(THRESHOLD); }); done(); }); }); });
const fs = require('fs'), path = require('path'), expect = require('chai').expect, CACHE_DIR = path.join(__dirname, '/../../.cache'), THRESHOLD = 5.5 * 1024 * 1024; // 5.5 MB describe('bootcode size', function () { this.timeout(60 * 1000); it('should not exceed the threshold', function (done) { fs.readdir(CACHE_DIR, function (err, files) { if (err) { return done(err); } files.forEach(function (file) { var size = fs.statSync(CACHE_DIR + '/' + file).size; expect(size, (file + ' threshold exceeded')).to.be.below(THRESHOLD); }); done(); }); }); });
Add an argument allowing to toggle point sprites and texturing separately
package com.rabenauge.gl; import javax.microedition.khronos.opengles.GL11; /* * Wrapper class for point sprites (requires GL_OES_point_sprite). */ public class PointSprite extends Texture2D { public PointSprite(GL11 gl) { super(gl); } public void enable(boolean state) { enable(state, state); } public void enable(boolean spriting, boolean texturing) { super.enable(texturing); if (spriting) { gl.glEnable(GL11.GL_POINT_SPRITE_OES); gl.glTexEnvx(GL11.GL_POINT_SPRITE_OES, GL11.GL_COORD_REPLACE_OES, 1); } else { gl.glDisable(GL11.GL_POINT_SPRITE_OES); gl.glTexEnvx(GL11.GL_POINT_SPRITE_OES, GL11.GL_COORD_REPLACE_OES, 0); } } public void setSize(float size) { gl.glPointSize(size); } }
package com.rabenauge.gl; import javax.microedition.khronos.opengles.GL11; /* * Wrapper class for point sprites (requires GL_OES_point_sprite). */ public class PointSprite extends Texture2D { public PointSprite(GL11 gl) { super(gl); } public void enable(boolean state) { super.enable(state); if (state) { gl.glEnable(GL11.GL_POINT_SPRITE_OES); gl.glTexEnvx(GL11.GL_POINT_SPRITE_OES, GL11.GL_COORD_REPLACE_OES, 1); } else { gl.glDisable(GL11.GL_POINT_SPRITE_OES); gl.glTexEnvx(GL11.GL_POINT_SPRITE_OES, GL11.GL_COORD_REPLACE_OES, 0); } } public void setSize(float size) { gl.glPointSize(size); } }
Fix Unicode of emoji 'heart'
import emojione from 'emojione'; const newEmojiListWithOutPriorityList = (priorityList) => { const list = {}; for (const key in emojione.emojioneList) { // eslint-disable-line no-restricted-syntax if (priorityList.hasOwnProperty(key)) { // eslint-disable-line no-prototype-builtins continue; // eslint-disable-line no-continue } list[key] = emojione.emojioneList[key].unicode; } return { ...priorityList, ...list }; }; const emojiList = {}; emojiList.setPriorityList = (newPriorityList) => { // re-generate emojiList when set PriorityList emojiList.list = newEmojiListWithOutPriorityList(newPriorityList); }; // init emojiList const priorityList = { ':thumbsup:': ['1f44d'], ':smile:': ['1f604'], ':heart:': ['2764'], ':ok_hand:': ['1f44c'], ':joy:': ['1f602'], ':tada:': ['1f389'], ':see_no_evil:': ['1f648'], ':raised_hands:': ['1f64c'], ':100:': ['1f4af'], }; emojiList.setPriorityList(priorityList); export default emojiList;
import emojione from 'emojione'; const newEmojiListWithOutPriorityList = (priorityList) => { const list = {}; for (const key in emojione.emojioneList) { // eslint-disable-line no-restricted-syntax if (priorityList.hasOwnProperty(key)) { // eslint-disable-line no-prototype-builtins continue; // eslint-disable-line no-continue } list[key] = emojione.emojioneList[key].unicode; } return { ...priorityList, ...list }; }; const emojiList = {}; emojiList.setPriorityList = (newPriorityList) => { // re-generate emojiList when set PriorityList emojiList.list = newEmojiListWithOutPriorityList(newPriorityList); }; // init emojiList const priorityList = { ':thumbsup:': ['1f44d'], ':smile:': ['1f604'], ':heart:': ['2764-fe0f', '2764'], ':ok_hand:': ['1f44c'], ':joy:': ['1f602'], ':tada:': ['1f389'], ':see_no_evil:': ['1f648'], ':raised_hands:': ['1f64c'], ':100:': ['1f4af'], }; emojiList.setPriorityList(priorityList); export default emojiList;
Comment about the directory structure
# django-salesforce # # by Phil Christensen # (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org) # See LICENSE.md for details # """ Database backend for the Salesforce API. No code in this directory is used with standard databases, even if a standard database is used for running some application tests on objects defined by SalesforceModel. All code for SF models that can be used with non SF databases should be located directly in the 'salesforce' directory in files 'models.py', 'fields.py', 'manager.py', 'router.py', 'admin.py'. Incorrectly located files: (It is better not to change it now.) backend/manager.py => manager.py auth.py => backend/auth.py """ import socket from django.conf import settings import logging log = logging.getLogger(__name__) sf_alias = getattr(settings, 'SALESFORCE_DB_ALIAS', 'salesforce') # The maximal number of retries for requests to SF API. MAX_RETRIES = getattr(settings, 'REQUESTS_MAX_RETRIES', 1) def getaddrinfo_wrapper(host, port, family=socket.AF_INET, socktype=0, proto=0, flags=0): return orig_getaddrinfo(host, port, family, socktype, proto, flags) # patch to IPv4 if required and not patched by anything other yet if getattr(settings, 'IPV4_ONLY', False) and socket.getaddrinfo.__module__ in ('socket', '_socket'): log.info("Patched socket to IPv4 only") orig_getaddrinfo = socket.getaddrinfo # replace the original socket.getaddrinfo by our version socket.getaddrinfo = getaddrinfo_wrapper
# django-salesforce # # by Phil Christensen # (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org) # See LICENSE.md for details # """ Database backend for the Salesforce API. """ import socket from django.conf import settings import logging log = logging.getLogger(__name__) sf_alias = getattr(settings, 'SALESFORCE_DB_ALIAS', 'salesforce') # The maximal number of retries for requests to SF API. MAX_RETRIES = getattr(settings, 'REQUESTS_MAX_RETRIES', 1) def getaddrinfo_wrapper(host, port, family=socket.AF_INET, socktype=0, proto=0, flags=0): return orig_getaddrinfo(host, port, family, socktype, proto, flags) # patch to IPv4 if required and not patched by anything other yet if getattr(settings, 'IPV4_ONLY', False) and socket.getaddrinfo.__module__ in ('socket', '_socket'): log.info("Patched socket to IPv4 only") orig_getaddrinfo = socket.getaddrinfo # replace the original socket.getaddrinfo by our version socket.getaddrinfo = getaddrinfo_wrapper
Add path to script in FileService
const fs = require('fs') const path = require('path') class FileService { get scripts() { const folderContent = fs.readdirSync(path.join(this.configService.folderPath, 'scripts')) const authorizedExtensions = this.configService.scriptExtension return folderContent .filter(element => { const foundResults = [] for (const extension of authorizedExtensions) { foundResults.push(element.includes(extension)) } return foundResults.filter(element => element).length > 0 }) .map(element => { const [scriptName] = element.split('.') const scriptSlug = scriptName .toLowerCase() .replace(/ /g,'-') .replace(/[^\w-]+/g,'') return { script: scriptSlug, file : element, path: path.join(this.configService.folderPath, 'scripts', element) } }) } get modules() {} constructor(configService) { this.configService = configService this._scripts = [] this._modules = [] } } module.exports = exports = { FileService }
const fs = require('fs') const path = require('path') class FileService { get scripts() { const folderContent = fs.readdirSync(path.join(this.configService.folderPath, 'scripts')) const authorizedExtensions = this.configService.scriptExtension return folderContent .filter(element => { const foundResults = [] for (const extension of authorizedExtensions) { foundResults.push(element.includes(extension)) } return foundResults.filter(element => element).length > 0 }) .map(element => { const [scriptName] = element.split('.') const scriptSlug = scriptName .toLowerCase() .replace(/ /g,'-') .replace(/[^\w-]+/g,'') return { script: scriptSlug, file: element } }) } get modules() {} constructor(configService) { this.configService = configService this._scripts = [] this._modules = [] } } module.exports = exports = { FileService }
Deal with the .env file
<?php /* * This file is part of Laravel Core. * * (c) Graham Campbell <graham@alt-three.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GrahamCampbell\Tests\Core; use GrahamCampbell\Core\CoreServiceProvider; use GrahamCampbell\TestBench\AbstractPackageTestCase; /** * This is the abstract test case class. * * @author Graham Campbell <graham@alt-three.com> */ abstract class AbstractTestCase extends AbstractPackageTestCase { /** * Create an empty .env file for us to use. * * @before */ public function createEnvFile() { file_put_contents($this->app->environmentFilePath(), "APP_KEY=SomeRandomString\n"); } /** * Delete our .env file after use. * * @after */ { unlink($this->app->environmentFilePath()); } /** * Get the service provider class. * * @param \Illuminate\Contracts\Foundation\Application $app * * @return string */ protected function getServiceProviderClass($app) { return CoreServiceProvider::class; } }
<?php /* * This file is part of Laravel Core. * * (c) Graham Campbell <graham@alt-three.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GrahamCampbell\Tests\Core; use GrahamCampbell\Core\CoreServiceProvider; use GrahamCampbell\TestBench\AbstractPackageTestCase; /** * This is the abstract test case class. * * @author Graham Campbell <graham@alt-three.com> */ abstract class AbstractTestCase extends AbstractPackageTestCase { /** * Get the service provider class. * * @param \Illuminate\Contracts\Foundation\Application $app * * @return string */ protected function getServiceProviderClass($app) { return CoreServiceProvider::class; } }
Add comment that results depend on timezone
const startDate = new Date(Date.UTC(2007, 0, 10, 10, 0, 0)); // > 'Wed, 10 Jan 2007 10:00:00 GMT' const endDate = new Date(Date.UTC(2007, 0, 10, 11, 0, 0)); // > 'Wed, 10 Jan 2007 11:00:00 GMT' const dateTimeFormat = new Intl.DateTimeFormat('en', { hour: 'numeric', minute: 'numeric' }); const parts = dateTimeFormat.formatRangeToParts(startDate, endDate); for (const part of parts) { console.log(part); } // expected output (in GMT timezone) // Object { type: "hour", value: "2", source: "startRange" } // Object { type: "literal", value: ":", source: "startRange" } // Object { type: "minute", value: "00", source: "startRange" } // Object { type: "literal", value: " – ", source: "shared" } // Object { type: "hour", value: "3", source: "endRange" } // Object { type: "literal", value: ":", source: "endRange" } // Object { type: "minute", value: "00", source: "endRange" } // Object { type: "literal", value: " ", source: "shared" } // Object { type: "dayPeriod", value: "AM", source: "shared" }
const startDate = new Date(Date.UTC(2007, 0, 10, 10, 0, 0)); // > 'Wed, 10 Jan 2007 10:00:00 GMT' const endDate = new Date(Date.UTC(2007, 0, 10, 11, 0, 0)); // > 'Wed, 10 Jan 2007 11:00:00 GMT' const dateTimeFormat = new Intl.DateTimeFormat('en', { hour: 'numeric', minute: 'numeric' }); const parts = dateTimeFormat.formatRangeToParts(startDate, endDate); for (const part of parts) { console.log(part); } // expected output: // Object { type: "hour", value: "2", source: "startRange" } // Object { type: "literal", value: ":", source: "startRange" } // Object { type: "minute", value: "00", source: "startRange" } // Object { type: "literal", value: " – ", source: "shared" } // Object { type: "hour", value: "3", source: "endRange" } // Object { type: "literal", value: ":", source: "endRange" } // Object { type: "minute", value: "00", source: "endRange" } // Object { type: "literal", value: " ", source: "shared" } // Object { type: "dayPeriod", value: "AM", source: "shared" }
Add support for async routes
/** DO NOT MODIFY **/ import React, { Component } from "react"; import { render } from "react-dom"; import { Root } from "gluestick-shared"; import { match } from "react-router"; import routes from "./routes"; import store from "./.store"; // Make sure that webpack considers new dependencies introduced in the Index // file import "../../Index.js"; export default class Entry extends Component { static defaultProps = { store: store() }; render () { const { routingContext, radiumConfig, store } = this.props; return ( <Root routingContext={routingContext} radiumConfig={radiumConfig} routes={routes} store={store} /> ); } } Entry.start = function () { match({routes, location: window.location.pathname}, (error, redirectLocation, renderProps) => { render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} {...renderProps} />, document.getElementById("main")); }); };
/** DO NOT MODIFY **/ import React, { Component } from "react"; import { render } from "react-dom"; import { Root } from "gluestick-shared"; import routes from "./routes"; import store from "./.store"; // Make sure that webpack considers new dependencies introduced in the Index // file import "../../Index.js"; export default class Entry extends Component { static defaultProps = { store: store() }; render () { const { routingContext, radiumConfig, store } = this.props; return ( <Root routingContext={routingContext} radiumConfig={radiumConfig} routes={routes} store={store} /> ); } } Entry.start = function () { render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} />, document.getElementById("main")); };
Add path property to base entity node.
/* * Copyright 2011 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import com.splunk.Entity; import org.openide.nodes.Children; class EntityNode extends ExplorerNode { EntityNode(Entity entity) { super(entity); setDisplayName(entity.getName()); } protected PropertyList getMetadata() { return new PropertyList() {{ add(String.class, "getPath"); add(String.class, "getTitle"); }}; } }
/* * Copyright 2011 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import com.splunk.Entity; import org.openide.nodes.Children; class EntityNode extends ExplorerNode { EntityNode(Entity entity) { super(entity); String name = entity.getName(); setName(name); setDisplayName(name); } protected PropertyList getMetadata() { return new PropertyList() {{ add(String.class, "getTitle"); }}; } }
Add long description to the project
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup(name='logs-analyzer', version='0.5.1', description='Logs-analyzer is a library containing functions that can help you extract usable data from logs.', long_description=long_description, long_description_content_type="text/markdown", url='https://github.com/ddalu5/logs-analyzer', author='Salah OSFOR', author_email='osfor.salah@gmail.com', license='Apache V2', packages=find_packages(exclude=['docs', 'tests']), test_suite='tests', tests_require=['unittest'], classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Information Technology', 'Topic :: System :: Logging', 'Topic :: System :: Monitoring', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], zip_safe=False)
from setuptools import setup, find_packages setup(name='logs-analyzer', version='0.5', description='Logs-analyzer is a library containing functions that can help you extract usable data from logs.', url='https://github.com/ddalu5/logs-analyzer', author='Salah OSFOR', author_email='osfor.salah@gmail.com', license='Apache V2', packages=find_packages(exclude=['docs', 'tests']), test_suite='tests', tests_require=['unittest'], classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Information Technology', 'Topic :: System :: Logging', 'Topic :: System :: Monitoring', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], zip_safe=False)
Add timezone output to the momentjs dates
var moment = require('moment'); var coupon = require('./coupon'); var stripe = require('./stripe'); var BulkDelete = require('./bulk-delete'); var faye = require('./faye'); $(document).ready(function () { coupon(); stripe(); var bulk_delete = new BulkDelete(); bulk_delete.listenForEvents(); if (window.location.pathname === '/live_stream') { faye(); } $('.from-now').each(function (i, e) { (function updateTime() { var time = moment($(e).data('datetime')); $(e).text(time.fromNow()); $(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a Z')); setTimeout(updateTime, 1000); })(); }); $('.short-date').each(function (i, e) { var time = moment($(e).data('datetime')); $(e).text(time.format('MMM Do YYYY')); $(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a Z')); }); });
var moment = require('moment'); var coupon = require('./coupon'); var stripe = require('./stripe'); var BulkDelete = require('./bulk-delete'); var faye = require('./faye'); $(document).ready(function () { coupon(); stripe(); var bulk_delete = new BulkDelete(); bulk_delete.listenForEvents(); if (window.location.pathname === '/live_stream') { faye(); } $('.from-now').each(function (i, e) { (function updateTime() { var time = moment($(e).data('datetime')); $(e).text(time.fromNow()); $(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a')); setTimeout(updateTime, 1000); })(); }); $('.short-date').each(function (i, e) { var time = moment($(e).data('datetime')); $(e).text(time.format('MMM Do YYYY')); $(e).attr('title', time.format('MMMM Do YYYY, h:mm:ss a')); }); });
templates: Add django timesince filter to jinja2 filters.
from typing import Any from django.contrib.staticfiles.storage import staticfiles_storage from django.template.defaultfilters import slugify, pluralize from django.urls import reverse from django.utils import translation from django.utils.timesince import timesince from jinja2 import Environment from two_factor.templatetags.two_factor import device_action from .compressors import minified_js from zerver.templatetags.app_filters import display_list, render_markdown_path def environment(**options: Any) -> Environment: env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, 'render_markdown_path': render_markdown_path, 'minified_js': minified_js, }) env.install_gettext_translations(translation, True) env.filters['slugify'] = slugify env.filters['pluralize'] = pluralize env.filters['display_list'] = display_list env.filters['device_action'] = device_action env.filters['timesince'] = timesince return env
from typing import Any from django.contrib.staticfiles.storage import staticfiles_storage from django.template.defaultfilters import slugify, pluralize from django.urls import reverse from django.utils import translation from jinja2 import Environment from two_factor.templatetags.two_factor import device_action from .compressors import minified_js from zerver.templatetags.app_filters import display_list, render_markdown_path def environment(**options: Any) -> Environment: env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, 'render_markdown_path': render_markdown_path, 'minified_js': minified_js, }) env.install_gettext_translations(translation, True) env.filters['slugify'] = slugify env.filters['pluralize'] = pluralize env.filters['display_list'] = display_list env.filters['device_action'] = device_action return env
:racehorse: Tweak uglifyjs config to be faster
// @flow import { minify as processUglify } from 'uglify-es' import { minify as processTerser } from 'terser' import { createChunkTransformer } from 'pundle-api' import manifest from '../package.json' // TODO: Fix source maps const VALID_UGLIFIERS = new Set(['uglify', 'terser']) function createComponent({ options = {}, uglifier = 'uglify' }: { options?: Object, uglifier: 'terser' | 'uglify' } = {}) { if (!VALID_UGLIFIERS.has(uglifier)) { throw new Error(`options.uglifier must be either 'uglify' or 'terser'. Got: ${uglifier}`) } return createChunkTransformer({ name: 'pundle-chunk-transformer-js-uglify', version: manifest.version, async callback({ format, contents }) { if (format !== 'js') return null const uglify = uglifier === 'terser' ? processTerser : processUglify const { code, error } = uglify(typeof contents === 'string' ? contents : contents.toString(), { ...options, compress: { defaults: false, ...options.compress, }, }) if (error) { throw new Error(error) } return { contents: code, sourceMap: null, } }, }) } module.exports = createComponent
// @flow import { minify as processUglify } from 'uglify-es' import { minify as processTerser } from 'terser' import { createChunkTransformer } from 'pundle-api' import manifest from '../package.json' // TODO: Fix source maps const VALID_UGLIFIERS = new Set(['uglify', 'terser']) function createComponent({ options = {}, uglifier = 'uglify' }: { options?: Object, uglifier: 'terser' | 'uglify' } = {}) { if (!VALID_UGLIFIERS.has(uglifier)) { throw new Error(`options.uglifier must be either 'uglify' or 'terser'. Got: ${uglifier}`) } return createChunkTransformer({ name: 'pundle-chunk-transformer-js-uglify', version: manifest.version, async callback({ format, contents }) { if (format !== 'js') return null const uglify = uglifier === 'terser' ? processTerser : processUglify const { code, error } = uglify(typeof contents === 'string' ? contents : contents.toString(), { ...options, }) if (error) { throw new Error(error) } return { contents: code, sourceMap: null, } }, }) } module.exports = createComponent
Add extra-requirements for release management
try: from setuptools import setup except ImportError: from distutils.core import setup requirements = ['contextlib2', 'pysam', 'six', 'shutilwhich'] ENTRY_POINTS = ''' [console_scripts] tag_reads=tag_reads.tag_reads:main allow_dovetailing=tag_reads.allow_dovetailing:main ''' setup( name='tag_reads', version='0.1.5', packages=['tag_reads'], install_requires=requirements, entry_points=ENTRY_POINTS, keywords='Bioinformatics', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Environment :: Console', 'Operating System :: POSIX', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], extras_require={ 'testing': ["pytest", "pytest-datadir", "tox", "planemo", "cookiecutter", "bumpversion"], }, url='https://github.com/bardin-lab/tag_reads', license='MIT', author='Marius van den Beek', author_email='m.vandenbeek@gmail.com', description='Tags reads in BAM files based on alignments in additional BAM files.' )
try: from setuptools import setup except ImportError: from distutils.core import setup requirements = ['contextlib2', 'pysam', 'six', 'shutilwhich'] ENTRY_POINTS = ''' [console_scripts] tag_reads=tag_reads.tag_reads:main allow_dovetailing=tag_reads.allow_dovetailing:main ''' setup( name='tag_reads', version='0.1.5', packages=['tag_reads'], install_requires=requirements, entry_points=ENTRY_POINTS, keywords='Bioinformatics', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Environment :: Console', 'Operating System :: POSIX', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], extras_require={ 'testing': ["pytest", "pytest-datadir", "tox", "planemo"], }, url='https://github.com/bardin-lab/tag_reads', license='MIT', author='Marius van den Beek', author_email='m.vandenbeek@gmail.com', description='Tags reads in BAM files based on alignments in additional BAM files.' )
Add profile model signal test case
# -*- coding: utf-8 -*- from django.test import TestCase from django.http import HttpResponse from django.test import Client from django.core.urlresolvers import reverse_lazy, reverse from django.contrib.auth import get_user_model from pyconkr.helper import render_io_error User = get_user_model() class HelperFunctionTestCase(TestCase): def setUp(self): pass def tearDown(self): pass def test_render_io_error(self): a = render_io_error("test reason") self.assertEqual(a.status_code, 406, "render io error status code must be 406") class PaymentTestCase(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user('testname', 'test@test.com', 'testpassword') self.client.login(username='testname', password='testpassword') def tearDown(self): pass def test_view_registration_payment(self): url = reverse('registration_payment') response = self.client.post(url, {'test': 1}) self.assertEqual(response['content-type'], 'application/json', 'Result has to be JSON') class ProfileTest(TestCase): def test_profile_is_created_when_user_save(self): user = User.objects.create_user('test', 'test@email.com', 'password') self.assertNotEqual(user.profile, None)
# -*- coding: utf-8 -*- from django.test import TestCase from django.http import HttpResponse from django.test import Client from django.core.urlresolvers import reverse_lazy, reverse from django.contrib.auth import get_user_model from pyconkr.helper import render_io_error User = get_user_model() class HelperFunctionTestCase(TestCase): def setUp(self): pass def tearDown(self): pass def test_render_io_error(self): a = render_io_error("test reason") self.assertEqual(a.status_code, 406, "render io error status code must be 406") class PaymentTestCase(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user('testname', 'test@test.com', 'testpassword') self.client.login(username='testname', password='testpassword') def tearDown(self): pass def test_view_registration_payment(self): url = reverse('registration_payment') response = self.client.post(url, {'test': 1}) self.assertEqual(response['content-type'], 'application/javascript', 'error raise and must be ajax' ) print response.content
Fix install submodules on Windows
#!/usr/bin/env node var ted = require('../ted') var sh = require('shelljs') var path = require('path') var exec = require('child_process').execFile // Install an array of submodules with package.json var installModules = function (paths, whatTheyAre) { paths.forEach(function (path, index) { installModule(path) }) } // Installed a single module dependencie based on Path var installModule = function (modulePath) { var cwd = path.dirname(modulePath) //Hackish solution for windows users - npm isn't recognized as a executable, but npm.cmd is! var npm = (process.platform === "win32" ? "npm.cmd" : "npm") // What is going on log console.log( ted.say.happy('npm install'), ted.say.warn('->'), ted.say.happy(cwd) ) var installing = exec(npm, ['install', '-d', '-s'], { cwd: cwd }, function (err, out, erout) { // Good output if (out) { console.log(ted.say.debug(out)) } // Bad output if (err) { console.log(ted.say.error(err)) } }) // When everything is done, tell me what happened installing.on('close', function (exit, error) { if (exit === 0 && !error) { console.log(cwd, ted.say.happy('done')) } if (error) { console.log(ted.say.error(error)) } }) } module.exports = installModules
#!/usr/bin/env node var ted = require('../ted') var sh = require('shelljs') var path = require('path') var exec = require('child_process').execFile // Install an array of submodules with package.json var installModules = function (paths, whatTheyAre) { paths.forEach(function (path, index) { installModule(path) }) } // Installed a single module dependencie based on Path var installModule = function (modulePath) { var cwd = path.dirname(modulePath) // What is going on log console.log( ted.say.happy('npm install'), ted.say.warn('->'), ted.say.happy(cwd) ) var installing = exec('npm', ['install', '-d', '-s'], { cwd: cwd }, function (err, out, erout) { // Good output if (out) { console.log(ted.say.debug(out)) } // Bad output if (err) { console.log(ted.say.error(err)) } }) // When everything is done, tell me what happened installing.on('close', function (exit, error) { if (exit === 0 && !error) { console.log(cwd, ted.say.happy('done')) } if (error) { console.log(ted.say.error(error)) } }) } module.exports = installModules
Fix the broken test and remove only.
import { expect } from '../spec_helper' import { AUTHENTICATION, PROFILE } from '../../src/constants/action_types' import pushSubscriptionSaga from '../../src/sagas/push_subscription' import { isLoggedInSelector } from '../../src/sagas/selectors' import { registerForGCM, requestPushSubscription, } from '../../src/actions/profile' describe('push subscription saga', function () { const regId = 'my awesome registration id' describe('the saga itself', function () { it('registers for GCM when logged in', function () { const pushAction = requestPushSubscription(regId) const pushHandler = pushSubscriptionSaga() expect(pushHandler).to.take(PROFILE.REQUEST_PUSH_SUBSCRIPTION) expect(pushHandler.next(pushAction)).to.select(isLoggedInSelector) expect(pushHandler.next(true)).to.put(registerForGCM(regId)) }) it('defers registration for GCM until logged in', function () { const pushAction = requestPushSubscription(regId) const pushHandler = pushSubscriptionSaga() expect(pushHandler).to.take(PROFILE.REQUEST_PUSH_SUBSCRIPTION) expect(pushHandler.next(pushAction)).to.select(isLoggedInSelector) expect(pushHandler.next(false)).to.take(AUTHENTICATION.USER_SUCCESS) expect(pushHandler).to.put(registerForGCM(regId)) }) }) })
import { expect } from '../spec_helper' import { AUTHENTICATION, PROFILE } from '../../src/constants/action_types' import { pushSubscriptionSaga } from '../../src/sagas/push_subscription' import { isLoggedInSelector } from '../../src/sagas/selectors' import { registerForGCM, requestPushSubscription, } from '../../src/actions/profile' describe.only('push subscription saga', function () { const regId = 'my awesome registration id' describe('the saga itself', function () { it('registers for GCM when logged in', function () { const pushAction = requestPushSubscription(regId) const pushHandler = pushSubscriptionSaga() expect(pushHandler).to.take(PROFILE.REQUEST_PUSH_SUBSCRIPTION) expect(pushHandler.next(pushAction)).to.select(isLoggedInSelector) expect(pushHandler.next(true)).to.put(registerForGCM(regId)) }) it('defers registration for GCM until logged in', function () { const pushAction = requestPushSubscription(regId) const pushHandler = pushSubscriptionSaga() expect(pushHandler).to.take(PROFILE.REQUEST_PUSH_SUBSCRIPTION) expect(pushHandler.next(pushAction)).to.select(isLoggedInSelector) expect(pushHandler.next(false)).to.take(AUTHENTICATION.USER_SUCCESS) expect(pushHandler).to.put(registerForGCM(regId)) }) }) })
Remove disk space REST endpoint
module.exports = { activeUserCount: require('./activeUserCount.js'), activeUsers: require('./activeUsers.js'), slackPostMessage: require('./slackPostMessage.js'), createDir: require('./createDir.js'), createDirQVD: require('./createDirQVD.js'), mqttPublishMessage: require('./mqttPublishMessage.js'), senseStartTask: require('./senseStartTask.js'), senseQRSPing: require('./senseQRSPing.js'), senseAppDump: require('./senseAppDump.js'), senseListApps: require('./senseListApps.js'), butlerPing: require('./butlerPing.js'), base62ToBase16: require('./baseConversion.js'), base16ToBase62: require('./baseConversion.js') }; //getDiskSpace: require('./getDiskSpace.js'),
module.exports = { activeUserCount: require('./activeUserCount.js'), activeUsers: require('./activeUsers.js'), slackPostMessage: require('./slackPostMessage.js'), createDir: require('./createDir.js'), createDirQVD: require('./createDirQVD.js'), getDiskSpace: require('./getDiskSpace.js'), mqttPublishMessage: require('./mqttPublishMessage.js'), senseStartTask: require('./senseStartTask.js'), senseQRSPing: require('./senseQRSPing.js'), senseAppDump: require('./senseAppDump.js'), senseListApps: require('./senseListApps.js'), butlerPing: require('./butlerPing.js'), base62ToBase16: require('./baseConversion.js'), base16ToBase62: require('./baseConversion.js') };
Use utcfromtimestamp instead of fromtimestamp on Message
import os from datetime import datetime from jinja2 import Environment, FileSystemLoader, select_autoescape from bottery.conf import settings class Message: def __init__(self, id, platform, user, text, timestamp, raw): self.id = id self.platform = platform self.user = user self.text = text self.timestamp = timestamp self.raw = raw @property def datetime(self): return datetime.utcfromtimestamp(self.timestamp) def render(message, template_name, context={}): base_dir = os.path.join(os.getcwd(), 'templates') paths = [base_dir] paths.extend(settings.TEMPLATES) env = Environment( loader=FileSystemLoader(paths), autoescape=select_autoescape(['html'])) template = env.get_template(template_name) default_context = { 'user': message.user } default_context.update(context) return template.render(**default_context)
import os from datetime import datetime from jinja2 import Environment, FileSystemLoader, select_autoescape from bottery.conf import settings class Message: def __init__(self, id, platform, user, text, timestamp, raw): self.id = id self.platform = platform self.user = user self.text = text self.timestamp = timestamp self.raw = raw @property def datetime(self): return datetime.fromtimestamp(self.timestamp) def render(message, template_name, context={}): base_dir = os.path.join(os.getcwd(), 'templates') paths = [base_dir] paths.extend(settings.TEMPLATES) env = Environment( loader=FileSystemLoader(paths), autoescape=select_autoescape(['html'])) template = env.get_template(template_name) default_context = { 'user': message.user } default_context.update(context) return template.render(**default_context)
Add process_request method to Application This allows to override a process_request method without having to add webob to child project. Change-Id: Ic5369076704f1ba459b2872ed0f4632a15b75c25
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2014 Eugene Frolov <eugene@frolov.net.ru> # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from webob import dec from restalchemy.api import resources from restalchemy.api import routes DEFAULT_CONTENT_TYPE = 'application/json' class WSGIApp(object): def __init__(self, route_class): super(WSGIApp, self).__init__() self._main_route = routes.route(route_class) resources.ResourceMap.set_resource_map( routes.Route.build_resource_map(route_class)) def process_request(self, req): return self._main_route(req).do() @dec.wsgify def __call__(self, req): return self.process_request(req) Application = WSGIApp
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2014 Eugene Frolov <eugene@frolov.net.ru> # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from webob import dec from restalchemy.api import resources from restalchemy.api import routes DEFAULT_CONTENT_TYPE = 'application/json' class WSGIApp(object): def __init__(self, route_class): super(WSGIApp, self).__init__() self._main_route = routes.route(route_class) resources.ResourceMap.set_resource_map( routes.Route.build_resource_map(route_class)) @dec.wsgify def __call__(self, req): return self._main_route(req).do() Application = WSGIApp
Add header to allow AJAX call
<?php //response array with status code and message $response_array = array(); /*//check the name field if(empty($_POST['name'])){ //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Name is blank'; //check the email field } elseif(!checkEmail($_POST['email'])) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Email is blank or invalid'; //check the message field } elseif(empty($_POST['message'])) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Message is blank'; //form validated. send email } else { */ //send the email $body = $_POST['name'] . " sent you a message\n"; $body .= "Details:\n\n" . $_POST['message']; mail("mysisterskeeper@murraycox.com", "My Sister's Keeper App - New Question", $body); //set the response $response_array['status'] = 'success'; $response_array['message'] = 'Email sent!'; /*}*/ php header('Access-Control-Allow-Origin: *'); echo json_encode($response_array); ?>
<?php //response array with status code and message $response_array = array(); /*//check the name field if(empty($_POST['name'])){ //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Name is blank'; //check the email field } elseif(!checkEmail($_POST['email'])) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Email is blank or invalid'; //check the message field } elseif(empty($_POST['message'])) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Message is blank'; //form validated. send email } else { */ //send the email $body = $_POST['name'] . " sent you a message\n"; $body .= "Details:\n\n" . $_POST['message']; mail("mysisterskeeper@murraycox.com", "My Sister's Keeper App - New Question", $body); //set the response $response_array['status'] = 'success'; $response_array['message'] = 'Email sent!'; /*}*/ echo json_encode($response_array); ?>
Update dependencies and version number, NB from the OECD rates for all dates are now included, not only those that fall before FERD rates
from setuptools import setup, find_packages setup( name='exchangerates', version='0.3.0', description="A module to make it easier to handle historical exchange rates", long_description="", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", 'Programming Language :: Python :: 3.6' ], author='Mark Brough', author_email='mark@brough.io', url='http://github.com/markbrough/exchangerates', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples']), namespace_packages=[], include_package_data=True, zip_safe=False, install_requires=[ 'lxml == 4.4.0', 'requests == 2.22.0', 'six == 1.12.0' ], entry_points={ } )
from setuptools import setup, find_packages setup( name='exchangerates', version='0.2.0', description="A module to make it easier to handle historical exchange rates", long_description="", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", 'Programming Language :: Python :: 3.6' ], author='Mark Brough', author_email='mark@brough.io', url='http://github.com/markbrough/exchangerates', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples']), namespace_packages=[], include_package_data=True, zip_safe=False, install_requires=[ 'lxml == 3.7.3', 'requests == 2.13.0', 'six == 1.11.0' ], entry_points={ } )
Set user to empty object after submiting user
angular.module('voteApp').controller('createUserController', ['$scope', 'userService', 'alertService', 'cardKeyService', function($scope, userService, alertService, cardKeyService) { $scope.user = {}; $scope.createUser = function(user) { userService.createUser(user) .success(function(data) { alertService.addSuccess('Bruker registrert!'); $scope.user = {}; }) .error(function(data) { alertService.addError(); }); }; cardKeyService.listen(function(cardKey) { $scope.user.cardKey = cardKey; $scope.$apply(); }); }]);
angular.module('voteApp').controller('createUserController', ['$scope', 'userService', 'alertService', 'cardKeyService', function($scope, userService, alertService, cardKeyService) { $scope.user = {}; $scope.createUser = function(user) { userService.createUser(user) .success(function(data) { alertService.addSuccess('Bruker registrert!'); }) .error(function(data) { alertService.addError(); }); }; cardKeyService.listen(function(cardKey) { $scope.user.cardKey = cardKey; $scope.$apply(); }); }]);
Add install_requires for smoother pip installation See also: https://github.com/uwescience/shablona/pull/54
from setuptools import find_packages, setup import os # Get version and release info, which is all stored in pulse2percept/version.py ver_file = os.path.join('pulse2percept', 'version.py') with open(ver_file) as f: exec(f.read()) opts = dict(name=NAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, url=URL, download_url=DOWNLOAD_URL, license=LICENSE, classifiers=CLASSIFIERS, author=AUTHOR, author_email=AUTHOR_EMAIL, platforms=PLATFORMS, version=VERSION, packages=find_packages(), install_requires=REQUIRES, requires=REQUIRES) if __name__ == '__main__': setup(**opts)
from setuptools import find_packages, setup import os # Get version and release info, which is all stored in pulse2percept/version.py ver_file = os.path.join('pulse2percept', 'version.py') with open(ver_file) as f: exec(f.read()) opts = dict(name=NAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, url=URL, download_url=DOWNLOAD_URL, license=LICENSE, classifiers=CLASSIFIERS, author=AUTHOR, author_email=AUTHOR_EMAIL, platforms=PLATFORMS, version=VERSION, packages=find_packages(), requires=REQUIRES) if __name__ == '__main__': setup(**opts)
:speaker: Add Logs on Filed Creation of Folders
package zero.zd.zquestionnaire; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import java.io.File; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // create a folder File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/ZQuestionnaire/"); if (!folder.exists()) { if (!folder.mkdirs()) { Log.e(TAG, "Failed on creating folders."); } } } public void onClickAnswer(View view) { startActivity(LoadQnaActivity.getStartIntent(MainActivity.this)); } public void onClickBuilder(View view) { startActivity(QnaBuilderActivity.getStartIntent(MainActivity.this)); } }
package zero.zd.zquestionnaire; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import java.io.File; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // create a folder File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/ZQuestionnaire/"); if (!folder.exists()) folder.mkdirs(); } public void onClickAnswer(View view) { startActivity(LoadQnaActivity.getStartIntent(MainActivity.this)); } public void onClickBuilder(View view) { startActivity(QnaBuilderActivity.getStartIntent(MainActivity.this)); } }
Make sure key has the required size. see #867
# coding: utf-8 """Crypto related utilities.""" import base64 import random import string from Crypto.Cipher import AES from modoboa.lib import parameters def random_key(l=16): """Generate a random key. :param integer l: the key's length :return: a string """ population = string.digits + string.letters + string.punctuation while True: key = "".join(random.sample(population * l, l)) if len(key) == l: return key def encrypt(clear): key = parameters.get_admin("SECRET_KEY", app="core") obj = AES.new(key, AES.MODE_ECB) if type(clear) is unicode: clear = clear.encode("utf-8") if len(clear) % AES.block_size: clear += " " * (AES.block_size - len(clear) % AES.block_size) ciph = obj.encrypt(clear) ciph = base64.b64encode(ciph) return ciph def decrypt(ciph): obj = AES.new( parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB ) ciph = base64.b64decode(ciph) clear = obj.decrypt(ciph) return clear.rstrip(' ') def get_password(request): return decrypt(request.session["password"])
# coding: utf-8 from Crypto.Cipher import AES import base64 import random import string from modoboa.lib import parameters def random_key(l=16): """Generate a random key :param integer l: the key's length :return: a string """ char_set = string.digits + string.letters + string.punctuation return ''.join(random.sample(char_set * l, l)) def encrypt(clear): key = parameters.get_admin("SECRET_KEY", app="core") obj = AES.new(key, AES.MODE_ECB) if type(clear) is unicode: clear = clear.encode("utf-8") if len(clear) % AES.block_size: clear += " " * (AES.block_size - len(clear) % AES.block_size) ciph = obj.encrypt(clear) ciph = base64.b64encode(ciph) return ciph def decrypt(ciph): obj = AES.new( parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB ) ciph = base64.b64decode(ciph) clear = obj.decrypt(ciph) return clear.rstrip(' ') def get_password(request): return decrypt(request.session["password"])
Fix java modules sample on Windows
package org.gradle.sample.integtest.app; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import org.gradle.sample.app.Main; import static org.junit.jupiter.api.Assertions.assertEquals; public class MainIntegrationTest { @Test public void testMain() { PrintStream savedOut = System.out; try { ByteArrayOutputStream outStreamForTesting = new ByteArrayOutputStream(); System.setOut(new PrintStream(outStreamForTesting)); Main.main(new String[0]); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("Hello, World!"); pw.close(); assertEquals(sw.toString(), outStreamForTesting.toString()); } finally { System.setOut(savedOut); } } }
package org.gradle.sample.integtest.app; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.gradle.sample.app.Main; import static org.junit.jupiter.api.Assertions.assertEquals; public class MainIntegrationTest { @Test public void testMain() { PrintStream savedOut = System.out; try { ByteArrayOutputStream outStreamForTesting = new ByteArrayOutputStream(); System.setOut(new PrintStream(outStreamForTesting)); Main.main(new String[0]); assertEquals("Hello, World!\n", outStreamForTesting.toString()); } finally { System.setOut(savedOut); } } }
Allow Rdio to use default signature handling
from werkzeug.urls import url_decode import foauth.providers class Rdio(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.rdio.com/' docs_url = 'http://developer.rdio.com/docs/REST/' category = 'Music' # URLs to interact with the API request_token_url = 'http://api.rdio.com/oauth/request_token' authorize_url = None # Provided when the request token is granted access_token_url = 'http://api.rdio.com/oauth/access_token' api_domain = 'api.rdio.com' available_permissions = [ (None, 'access and manage your music'), ] https = False def parse_token(self, content): # Override standard token request to also get the authorization URL data = url_decode(content) if 'login_url' in data: self.authorize_url = data['login_url'] return super(Rdio, self).parse_token(content) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/1/', method='POST', data={ 'method': 'currentUser', }) return unicode(r.json[u'result'][u'key'])
from werkzeug.urls import url_decode from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY import foauth.providers class Rdio(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.rdio.com/' docs_url = 'http://developer.rdio.com/docs/REST/' category = 'Music' # URLs to interact with the API request_token_url = 'http://api.rdio.com/oauth/request_token' authorize_url = None # Provided when the request token is granted access_token_url = 'http://api.rdio.com/oauth/access_token' api_domain = 'api.rdio.com' available_permissions = [ (None, 'access and manage your music'), ] https = False signature_type = SIGNATURE_TYPE_BODY def parse_token(self, content): # Override standard token request to also get the authorization URL data = url_decode(content) if 'login_url' in data: self.authorize_url = data['login_url'] return super(Rdio, self).parse_token(content) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/1/', method='POST', data={ 'method': 'currentUser', }) return unicode(r.json[u'result'][u'key'])
Return subscription by subscription reference
<?php namespace ActiveCollab\Payments\Subscription\SubscriptionEvent; use ActiveCollab\Payments\Gateway\GatewayInterface; use ActiveCollab\Payments\Subscription\SubscriptionInterface; use RuntimeException; /** * @package ActiveCollab\Payments\Subscription\SubscriptionEvent */ trait Implementation { /** * @var string */ private $subscription_reference; /** * Return subscription reference (subscription ID) * * @return string */ public function getSubscriptionReference() { return $this->subscription_reference; } /** * Return subscription by subscription reference * * @return SubscriptionInterface */ public function getSubscription() { if ($this->getGateway() instanceof GatewayInterface) { return $this->getGateway()->getSubscriptionByReference($this->getSubscriptionReference()); } throw new RuntimeException('Gateway is not set'); } /** * Return parent gateway * * @return GatewayInterface */ abstract public function &getGateway(); }
<?php namespace ActiveCollab\Payments\Subscription\SubscriptionEvent; use ActiveCollab\Payments\Gateway\GatewayInterface; use ActiveCollab\Payments\Subscription\SubscriptionInterface; use RuntimeException; /** * @package ActiveCollab\Payments\Subscription\SubscriptionEvent */ trait Implementation { /** * @var string */ private $subscription_reference; /** * Return subscription reference (subscription ID) * * @return string */ public function getSubscriptionReference() { return $this->subscription_reference; } /** * Return subscription by subscription reference * * @return SubscriptionInterface */ public function getSubscription() { if ($this->getGateway() instanceof GatewayInterface) { return $this->getGateway()->getOrderByReference($this->getSubscriptionReference()); } throw new RuntimeException('Gateway is not set'); } /** * Return parent gateway * * @return GatewayInterface */ abstract public function &getGateway(); }
Simplify tests to new format.
""" Test suite for Reflex Axelrod PD player. """ import axelrod from test_player import TestPlayer class Reflex_test(TestPlayer): name = "Reflex" player = axelrod.Reflex stochastic = False def test_strategy(self): """ First response should always be cooperation. """ p1 = axelrod.Reflex() p2 = axelrod.Player() self.assertEqual(p1.strategy(p2), 'C') def test_reset_method(self): """ Does self.reset() reset the self? """ p1 = axelrod.Reflex() p1.history = ['C', 'D', 'C', 'C'] p1.reset() self.assertEqual(p1.history, []) self.assertEqual(p1.response, 'C')
""" Test suite for Reflex Axelrod PD player. """ import axelrod from test_player import TestPlayer class Reflex_test(TestPlayer): def test_initial_nice_strategy(self): """ First response should always be cooperation. """ p1 = axelrod.Reflex() p2 = axelrod.Player() self.assertEqual(p1.strategy(p2), 'C') def test_representation(self): """ How do we appear? """ p1 = axelrod.Reflex() self.assertEqual(str(p1), "Reflex") def test_reset_method(self): """ Does self.reset() reset the self? """ p1 = axelrod.Reflex() p1.history = ['C', 'D', 'C', 'C'] p1.reset() self.assertEqual(p1.history, []) self.assertEqual(p1.response, 'C') def test_stochastic(self): """ We are not stochastic. """ self.assertFalse(axelrod.Reflex().stochastic)
Add "dispatch_uid" to ensure we connect the signal only once
# -*- coding: utf-8 -*- from axes.models import AccessAttempt from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from importlib import import_module DEFAULT_ACTION = 'axes_login_actions.actions.email.notify' ACTIONS = getattr(settings, 'AXES_LOGIN_ACTIONS', [DEFAULT_ACTION]) #---------------------------------------------------------------------- def import_dotted_path(path): """ Takes a dotted path to a member name in a module, and returns the member after importing it. """ # stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path) try: module_path, member_name = path.rsplit(".", 1) module = import_module(module_path) return getattr(module, member_name) except (ValueError, ImportError, AttributeError), e: raise ImportError("Could not import the name: %s: %s" % (path, e)) #---------------------------------------------------------------------- @receiver(post_save, sender=AccessAttempt, dispatch_uid='axes_login_actions_post_save') def access_attempt_handler(sender, instance, **kwargs): for action_path in ACTIONS: action = import_dotted_path(action_path) action(instance, **kwargs)
# -*- coding: utf-8 -*- from axes.models import AccessAttempt from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from importlib import import_module DEFAULT_ACTION = 'axes_login_actions.actions.email.notify' ACTIONS = getattr(settings, 'AXES_LOGIN_ACTIONS', [DEFAULT_ACTION]) #---------------------------------------------------------------------- def import_dotted_path(path): """ Takes a dotted path to a member name in a module, and returns the member after importing it. """ # stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path) try: module_path, member_name = path.rsplit(".", 1) module = import_module(module_path) return getattr(module, member_name) except (ValueError, ImportError, AttributeError), e: raise ImportError("Could not import the name: %s: %s" % (path, e)) #---------------------------------------------------------------------- @receiver(post_save, sender=AccessAttempt) def access_attempt_handler(sender, instance, **kwargs): for action_path in ACTIONS: action = import_dotted_path(action_path) action(instance, **kwargs)
Add test to check that we do not overwrite input file
import pytest from pikepdf import Pdf from pikepdf._cpphelpers import fspath from io import BytesIO from shutil import copy import sys @pytest.fixture def sandwich(resources): # Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP return Pdf.open(resources / 'sandwich.pdf') class LimitedBytesIO(BytesIO): """Version of BytesIO that only accepts small reads/writes""" def write(self, b): amt = min(len(b), 100) return super().write(b[:amt]) def test_weird_output_stream(sandwich): bio = BytesIO() lbio = LimitedBytesIO() sandwich.save(bio, static_id=True) sandwich.save(lbio, static_id=True) assert bio.getvalue() == lbio.getvalue() def test_overwrite_with_memory_file(outdir): (outdir / 'example.pdf').touch() pdf = Pdf.new() pdf.save(outdir / 'example.pdf') @pytest.mark.skipif(sys.version_info < (3, 6), reason='pathlib and shutil') def test_overwrite_input(resources, outdir): copy(resources / 'sandwich.pdf', outdir / 'sandwich.pdf') p = Pdf.open(outdir / 'sandwich.pdf') with pytest.raises(ValueError, match=r'overwrite input file'): p.save(outdir / 'sandwich.pdf')
import pytest from pikepdf import Pdf from io import BytesIO @pytest.fixture def sandwich(resources): # Has XMP, docinfo, <?adobe-xap-filters esc="CRLF"?>, shorthand attribute XMP return Pdf.open(resources / 'sandwich.pdf') class LimitedBytesIO(BytesIO): """Version of BytesIO that only accepts small reads/writes""" def write(self, b): amt = min(len(b), 100) return super().write(b[:amt]) def test_weird_output_stream(sandwich): bio = BytesIO() lbio = LimitedBytesIO() sandwich.save(bio, static_id=True) sandwich.save(lbio, static_id=True) assert bio.getvalue() == lbio.getvalue() def test_overwrite_with_memory_file(outdir): (outdir / 'example.pdf').touch() pdf = Pdf.new() pdf.save(outdir / 'example.pdf')
Add meta version for build version
import '@/css/tailwind.css' import '@/css/prism.css' import { ThemeProvider } from 'next-themes' import Head from 'next/head' import moment from 'moment' import siteMetadata from '@/data/siteMetadata' import Analytics from '@/components/analytics' import LayoutWrapper from '@/components/LayoutWrapper' import { ClientReload } from '@/components/ClientReload' const isDevelopment = process.env.NODE_ENV === 'development' const isSocket = process.env.SOCKET const { version } = require('../package.json') const build = moment().format('YYYYMMDDHHmmss') export default function App({ Component, pageProps }) { return ( <ThemeProvider attribute="class" defaultTheme={siteMetadata.theme}> <Head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="version" content={version + '.' + build} /> </Head> {isDevelopment && isSocket && <ClientReload />} <Analytics /> <LayoutWrapper> <Component {...pageProps} /> </LayoutWrapper> </ThemeProvider> ) }
import '@/css/tailwind.css' import '@/css/prism.css' import { ThemeProvider } from 'next-themes' import Head from 'next/head' import siteMetadata from '@/data/siteMetadata' import Analytics from '@/components/analytics' import LayoutWrapper from '@/components/LayoutWrapper' import { ClientReload } from '@/components/ClientReload' const isDevelopment = process.env.NODE_ENV === 'development' const isSocket = process.env.SOCKET export default function App({ Component, pageProps }) { return ( <ThemeProvider attribute="class" defaultTheme={siteMetadata.theme}> <Head> <meta content="width=device-width, initial-scale=1" name="viewport" /> </Head> {isDevelopment && isSocket && <ClientReload />} <Analytics /> <LayoutWrapper> <Component {...pageProps} /> </LayoutWrapper> </ThemeProvider> ) }
Change test case item, as the previous one had been updated and fixed.
# http://www.openstreetmap.org/way/219071307 assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'kind_detail': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'kind_detail': 'j_bar' }) # http://www.openstreetmap.org/way/232074914 assert_has_feature( 16, 13304, 24998, 'roads', { 'id': 232074914, 'kind': 'aerialway', 'kind_detail': type(None) })
# http://www.openstreetmap.org/way/219071307 assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'kind_detail': 't_bar' }) # http://www.openstreetmap.org/way/256717307 assert_has_feature( 16, 18763, 24784, 'roads', { 'id': 256717307, 'kind': 'aerialway', 'kind_detail': 'j_bar' }) # http://www.openstreetmap.org/way/258132198 assert_has_feature( 16, 10910, 25120, 'roads', { 'id': 258132198, 'kind': 'aerialway', 'kind_detail': type(None) })
Fix API type & method name for picking values
# -*- coding: utf-8 -*- # © 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # © 2013 Camptocamp SA (author: Guewen Baconnier) # © 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class StockMove(models.Model): _inherit = 'stock.move' @api.multi def _get_new_picking_values(self): values = super(StockMove, self)._get_new_picking_values() if self.procurement_id.sale_line_id: sale = self.procurement_id.sale_line_id.order_id values['workflow_process_id'] = sale.workflow_process_id.id return values
# -*- coding: utf-8 -*- # © 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # © 2013 Camptocamp SA (author: Guewen Baconnier) # © 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class StockMove(models.Model): _inherit = 'stock.move' @api.model def _prepare_picking_assign(self, move): values = super(StockMove, self)._prepare_picking_assign(move) if move.procurement_id.sale_line_id: sale = move.procurement_id.sale_line_id.order_id values['workflow_process_id'] = sale.workflow_process_id.id return values
Move `wrap` task to run before `watch` task
// Use grunt to produce top-level javascript files, but not to run tests (Karma // has its own watcher). module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { js: { files: { 'instanthangouts-<%= pkg.version %>.js': ['instanthangouts-<%= pkg.version %>.uncompiled.js'] } } }, watch: { files: ['*.html', 'src/*.js', 'test/*.js'], tasks: ['wrap', 'uglify'] }, wrap: { js: { src: ['src/*.js'], dest: 'instanthangouts-<%= pkg.version %>.uncompiled.js', options: { indent: ' ', wrapper: ['(function () {\n', '}());\n'] } } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-wrap'); grunt.registerTask('default', ['uglify', 'wrap', 'watch']); }
// Use grunt to produce top-level javascript files, but not to run tests (Karma // has its own watcher). module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { js: { files: { 'instanthangouts-<%= pkg.version %>.js': ['instanthangouts-<%= pkg.version %>.uncompiled.js'] } } }, watch: { files: ['*.html', 'src/*.js', 'test/*.js'], tasks: ['wrap', 'uglify'] }, wrap: { js: { src: ['src/*.js'], dest: 'instanthangouts-<%= pkg.version %>.uncompiled.js', options: { indent: ' ', wrapper: ['(function () {\n', '}());\n'] } } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-wrap'); grunt.registerTask('default', ['uglify', 'watch', 'wrap']); }
Use isFinite instead of Number.isFinite for improved browser support
/** * Comma number formatter * @param {Number} number Number to format * @param {String} [separator=','] Value used to separate numbers * @returns {String} Comma formatted number */ module.exports = function commaNumber (number, separator) { separator = typeof separator === 'undefined' ? ',' : ('' + separator) // Convert to number if it's a non-numeric value if (typeof number !== 'number') number = Number(number) // NaN => 0 if (isNaN(number)) number = 0 // Return Infinity immediately if (!isFinite(number)) return '' + number var stringNumber = ('' + Math.abs(number)) .split('') .reverse() var result = [] for (var i = 0; i < stringNumber.length; i++) { if (i && i % 3 === 0) result.push(separator) result.push(stringNumber[i]) } // Handle negative numbers if (number < 0) result.push('-') return result .reverse() .join('') }
/** * Comma number formatter * @param {Number} number Number to format * @param {String} [separator=','] Value used to separate numbers * @returns {String} Comma formatted number */ module.exports = function commaNumber (number, separator) { separator = typeof separator === 'undefined' ? ',' : ('' + separator) // Convert to number if it's a non-numeric value if (typeof number !== 'number') number = Number(number) // NaN => 0 if (isNaN(number)) number = 0 // Return Infinity immediately if (!Number.isFinite(number)) return '' + number var stringNumber = ('' + Math.abs(number)) .split('') .reverse() var result = [] for (var i = 0; i < stringNumber.length; i++) { if (i && i % 3 === 0) result.push(separator) result.push(stringNumber[i]) } // Handle negative numbers if (number < 0) result.push('-') return result .reverse() .join('') }
Fix up linter and flow warnings
// @flow import React, { Component } from 'react' import { connect } from 'react-redux' import { editorials } from '../actions/editorials' import StreamContainer from '../containers/StreamContainer' import { MainView } from '../components/views/MainView' import { selectQueryPreview } from '../selectors/routing' import { media } from '../styles/jss' import { maxBreak2 } from '../styles/jso' const streamStyle = media(maxBreak2, { paddingLeft: '0 !important', paddingRight: '0 !important', }) const mapStateToProps = state => ({ isPreview: selectQueryPreview(state) === 'true', }) type Props = { isPreview: boolean, } class EditorialPage extends Component { props: Props shouldComponentUpdate() { return false } render() { return ( <MainView className="Editorial"> <StreamContainer action={editorials(this.props.isPreview)} className={`${streamStyle}`} shouldInfiniteScroll={false} /> </MainView> ) } } export default connect(mapStateToProps)(EditorialPage)
// @flow import React, { Component } from 'react' import { connect } from 'react-redux' import { editorials } from '../actions/editorials' import StreamContainer from '../containers/StreamContainer' import { MainView } from '../components/views/MainView' import { selectQueryPreview } from '../selectors/routing' import { getQueryParamValue } from '../helpers/uri_helper' import { media } from '../styles/jss' import { maxBreak2 } from '../styles/jso' const streamStyle = media(maxBreak2, { paddingLeft: '0 !important', paddingRight: '0 !important', }) const mapStateToProps = (state) => ({ isPreview: selectQueryPreview(state) === 'true', }) class EditorialPage extends Component { shouldComponentUpdate() { return false } render() { return ( <MainView className="Editorial"> <StreamContainer action={editorials(this.props.isPreview)} className={`${streamStyle}`} shouldInfiniteScroll={false} /> </MainView> ) } } export default connect(mapStateToProps)(EditorialPage)
Set new password action name change
function submitChange() { if ($("#passwdNew").val() != $("#passwdConfirm").val()) { $("#errMsg").text("Passwords do NOT match!"); $("#alertDiv").attr("style", "display: block;"); return false; } var oldPasswd = $("#passwdOld").val(); var newPasswd = $("#passwdNew").val(); $.post("setpassword.action", { oldPassword: oldPasswd, newPassword: newPasswd }, displayErr, "json" ); function displayErr(data) { if (data != null) { $("#errMsg").text(data); $("#alertDiv").attr("style", "display: block;"); } else { $("#alertDiv").attr("style", "display: none;"); $("#successDiv").attr("style", "display: block;"); $("#successMsg").text("Password set successful"); } }; } $("#setSave").click(submitChange);
function submitChange() { if ($("#passwdNew").val() != $("#passwdConfirm").val()) { $("#errMsg").text("Passwords do NOT match!"); $("#alertDiv").attr("style", "display: block;"); return false; } var oldPasswd = $("#passwdOld").val(); var newPasswd = $("#passwdNew").val(); $.post("userSetPsswd", { oldPassword: oldPasswd, newPassword: newPasswd }, displayErr, "json" ); function displayErr(data) { if (data.msg != null) { $("#errMsg").text(data.msg); $("#alertDiv").attr("style", "display: block;"); } else { $("#alertDiv").attr("style", "display: none;"); $("#successDiv").attr("style", "display: block;"); $("#successMsg").text("Password set successful"); } }; } $("#setSave").click(submitChange);
Update CLIP model URL to modelzoo bucket
# Copyright 2018 The Lucid 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. # ============================================================================== from lucid.modelzoo.vision_base import Model class CLIPImage(Model): image_value_range = (0, 255) input_name = 'input_image' model_name = "RN50_4x" image_shape = [288, 288, 3] model_path = "gs://modelzoo/vision/other_models/Clip_ResNet50.pb"
# Copyright 2018 The Lucid 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. # ============================================================================== from lucid.modelzoo.vision_base import Model class CLIPImage(Model): image_value_range = (0, 255) input_name = 'input_image' model_name = "RN50_4x" image_shape = [288, 288, 3] model_path = "https://openaipublic.blob.core.windows.net/clip/tf/RN50_4x/084ee9c176da32014b0ebe42cd7ca66e/image32.pb"
Fix Java regex syntax for disallowed characters The dash character needs to be escaped so that it is not treated as regular expression syntax for a range of characters between the colon and underscore (':-_').
package com.librato.metrics; import java.util.regex.Pattern; /** * Filters out unwanted characters */ public interface Sanitizer { /** * Performs an identity transform on the input */ @SuppressWarnings("unused") public static final Sanitizer NO_OP = new Sanitizer() { public String apply(String name) { return name; } }; /** * Metric names restrictions are described <a href="http://dev.librato.com/v1/metrics">here</a>. */ @SuppressWarnings("unused") public static final Sanitizer LAST_PASS = new Sanitizer() { private final Pattern disallowedCharacters = Pattern.compile("([^A-Za-z0-9.:\\-_]|[\\[\\]]|\\s)"); private final int lengthLimit = 256; public String apply(String name) { final String sanitized = disallowedCharacters.matcher(name).replaceAll(""); if (sanitized.length() > lengthLimit) { return sanitized.substring(sanitized.length() - lengthLimit, sanitized.length()); } return sanitized; } }; /** * Apply the sanitizer to the input * * @param name the input * @return the sanitized output */ public String apply(String name); }
package com.librato.metrics; import java.util.regex.Pattern; /** * Filters out unwanted characters */ public interface Sanitizer { /** * Performs an identity transform on the input */ @SuppressWarnings("unused") public static final Sanitizer NO_OP = new Sanitizer() { public String apply(String name) { return name; } }; /** * Metric names restrictions are described <a href="http://dev.librato.com/v1/metrics">here</a>. */ @SuppressWarnings("unused") public static final Sanitizer LAST_PASS = new Sanitizer() { private final Pattern disallowedCharacters = Pattern.compile("([^A-Za-z0-9.:-_]|[\\[\\]]|\\s)"); private final int lengthLimit = 256; public String apply(String name) { final String sanitized = disallowedCharacters.matcher(name).replaceAll(""); if (sanitized.length() > lengthLimit) { return sanitized.substring(sanitized.length() - lengthLimit, sanitized.length()); } return sanitized; } }; /** * Apply the sanitizer to the input * * @param name the input * @return the sanitized output */ public String apply(String name); }
Add knot vector normalization test
""" Tests for the NURBS-Python package Released under The MIT License. See LICENSE file for details. Copyright (c) 2018 Onur Rauf Bingol Tests geomdl.utilities module. Requires "pytest" to run. """ from geomdl import utilities def test_autogen_knot_vector(): degree = 4 num_ctrlpts = 12 autogen_kv = utilities.generate_knot_vector(degree, num_ctrlpts) result = [0.0, 0.0, 0.0, 0.0, 0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 1.0, 1.0, 1.0, 1.0] assert autogen_kv == result def test_check_knot_vector(): degree = 4 num_ctrlpts = 12 autogen_kv = utilities.generate_knot_vector(degree, num_ctrlpts) check_result = utilities.check_knot_vector(degree=degree, control_points_size=num_ctrlpts, knot_vector=autogen_kv) assert check_result def test_normalize_knot_vector(): input_kv = (-5, -5, -3, -2, 2, 3, 5, 5) output_kv = [0.0, 0.0, 0.2, 0.3, 0.7, 0.8, 1.0, 1.0] to_check = utilities.normalize_knot_vector(input_kv) assert to_check == output_kv
""" Tests for the NURBS-Python package Released under The MIT License. See LICENSE file for details. Copyright (c) 2018 Onur Rauf Bingol Tests geomdl.utilities module. Requires "pytest" to run. """ from geomdl import utilities def test_autogen_knotvector(): degree = 4 num_ctrlpts = 12 autogen_kv = utilities.generate_knot_vector(degree, num_ctrlpts) result = [0.0, 0.0, 0.0, 0.0, 0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 1.0, 1.0, 1.0, 1.0] assert autogen_kv == result def test_check_knotvector(): degree = 4 num_ctrlpts = 12 autogen_kv = utilities.generate_knot_vector(degree, num_ctrlpts) check_result = utilities.check_knot_vector(degree=degree, control_points_size=num_ctrlpts, knot_vector=autogen_kv) assert check_result == True
Use function errorHandler for htmlPreproc
'use strict'; var gulp = require('gulp'); var browserSync = require('browser-sync'); var $ = require('gulp-load-plugins')(); module.exports = function(options) { gulp.task('markups', function() { function renameToHtml(path) { path.extname = '.html'; } return gulp.src(options.src + '/{app,components}/**/*.<%= props.htmlPreprocessor.extension %>') <% if (props.htmlPreprocessor.key === 'jade') { %> .pipe($.consolidate('jade', { basedir: options.src, doctype: 'html', pretty: ' ' })).on('error', options.errorHandler('Jade')) <% } else if (props.htmlPreprocessor.key === 'haml') { %> .pipe($.consolidate('hamljs')).on('error', options.errorHandler('Haml')) <% } else if (props.htmlPreprocessor.key === 'handlebars') { %> .pipe($.consolidate('handlebars')).on('error', options.errorHandler('Handlebars')) <% } %> .pipe($.rename(renameToHtml)) .pipe(gulp.dest(options.tmp + '/serve/')) .pipe(browserSync.reload({ stream: true })); }); };
'use strict'; var gulp = require('gulp'); var browserSync = require('browser-sync'); var $ = require('gulp-load-plugins')(); module.exports = function(options) { gulp.task('markups', function() { function renameToHtml(path) { path.extname = '.html'; } return gulp.src(options.src + '/{app,components}/**/*.<%= props.htmlPreprocessor.extension %>') <% if (props.htmlPreprocessor.key === 'jade') { %> .pipe($.consolidate('jade', { basedir: options.src, doctype: 'html', pretty: ' ' })) <% } else if (props.htmlPreprocessor.key === 'haml') { %> .pipe($.consolidate('hamljs')) <% } else if (props.htmlPreprocessor.key === 'handlebars') { %> .pipe($.consolidate('handlebars')) <% } %> .on('error', function handleError(err) { console.error(err.toString()); this.emit('end'); }) .pipe($.rename(renameToHtml)) .pipe(gulp.dest(options.tmp + '/serve/')) .pipe(browserSync.reload({ stream: true })); }); };
Add hex check to basic info
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin from plugins.util import green, red __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'List some basic info about the string in a table' header = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') key = '--basic' def handle(self): table = VeryPrettyTable() table.field_names = ['String', 'Length', '# Digits', '# Alpha', '# Punct.', '# Control', 'Hex?'] for s in self.args['STRING']: table.add_row((s, len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s), green('✔') if all(x in string.hexdigits for x in s) else red('✗'))) return str(table) + '\n'
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'List some basic info about the string in a table' header = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') key = '--basic' def handle(self): table = VeryPrettyTable() table.field_names = ['String', 'Length', '# Digits', '# Alpha', '# Punct.', '# Control'] for s in self.args['STRING']: table.add_row((s, len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) return str(table) + '\n'
Add a minimum version requirement for numpy.
from setuptools import setup setup( name = 'PyFVCOM', packages = ['PyFVCOM'], version = '2.1.0', description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."), author = 'Pierre Cazenave', author_email = 'pica@pml.ac.uk', url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM', download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=2.1.0', keywords = ['fvcom', 'unstructured grid', 'mesh'], license = 'MIT', platforms = 'any', install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy>=1.10.0', 'matplotlib', 'netCDF4', 'lxml', 'pyproj', 'pytz', 'networkx', 'UTide'], classifiers = [] )
from setuptools import setup setup( name = 'PyFVCOM', packages = ['PyFVCOM'], version = '2.1.0', description = ("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."), author = 'Pierre Cazenave', author_email = 'pica@pml.ac.uk', url = 'https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM', download_url = 'http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=2.1.0', keywords = ['fvcom', 'unstructured grid', 'mesh'], license = 'MIT', platforms = 'any', install_requires = ['pyshp', 'jdcal', 'scipy', 'numpy', 'matplotlib', 'netCDF4', 'lxml', 'pyproj', 'pytz', 'networkx', 'UTide'], classifiers = [] )
Add a 'context' parameter to util functions, so we don't rely on a global 'document'.
import VNode from 'snabbdom/vnode'; export function createTextVNode(text, context) { return VNode(undefined, undefined, undefined, unescape(text, context)); } export function transformName(name) { // Replace -a with A to help camel case style property names. name = name.replace( /-(\w)/g, function _replace( $1, $2 ) { return $2.toUpperCase(); }); // Handle properties that start with a -. const firstChar = name.charAt(0).toLowerCase(); return `${firstChar}${name.substring(1)}`; } // Regex for matching HTML entities. const entityRegex = new RegExp('&[a-z0-9]+;', 'gi') // Element for setting innerHTML for transforming entities. let el = null; function unescape(text, context) { // Create the element using the context if it doesn't exist. if (!el) { el = context.createElement('div'); } return text.replace(entityRegex, (entity) => { el.innerHTML = entity; return el.textContent; }); }
import VNode from 'snabbdom/vnode'; export function createTextVNode(text) { return VNode(undefined, undefined, undefined, unescape(text)); } export function transformName(name) { // Replace -a with A to help camel case style property names. name = name.replace( /-(\w)/g, function _replace( $1, $2 ) { return $2.toUpperCase(); }); // Handle properties that start with a -. const firstChar = name.charAt(0).toLowerCase(); return `${firstChar}${name.substring(1)}`; } // Regex for matching HTML entities. const entityRegex = new RegExp('&[a-z0-9]+;', 'gi') // Element for setting innerHTML for transforming entities. const el = document.createElement('div'); function unescape(text) { return text.replace(entityRegex, (entity) => { el.innerHTML = entity; return el.textContent; }); }
Fix error message for invalid QT_API.
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: Qt API selector. Can be used to switch between pyQt and PySide #------------------------------------------------------------------------------ import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError("Invalid Qt API %r, valid values are: 'pyqt' or 'pyside'" % qt_api)
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: Qt API selector. Can be used to switch between pyQt and PySide #------------------------------------------------------------------------------ import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError('Invalid Qt API %r, valid values are: pyqt or pyside')
Fix rendering of the sudoku puzzle.
/* i-sudoku is an interactive command-line sudoku tool */ package main import ( "github.com/jkomoros/sudoku" "github.com/nsf/termbox-go" "log" "strings" ) type mainModel struct { grid *sudoku.Grid } func main() { if err := termbox.Init(); err != nil { log.Fatal("Termbox initialization failed:", err) } defer termbox.Close() model := &mainModel{ sudoku.NewGrid(), } model.grid.Fill() draw(model) mainloop: for { switch ev := termbox.PollEvent(); ev.Type { case termbox.EventKey: switch ev.Key { case termbox.KeyEsc, termbox.KeyCtrlC: break mainloop } } draw(model) } } func draw(model *mainModel) { drawGrid(model.grid) termbox.Flush() } func drawGrid(grid *sudoku.Grid) { for y, line := range strings.Split(grid.Diagram(), "\n") { x := 0 //The first number in range will be byte offset, but for some items like the bullet, it's two bytes. //But what we care about is that each item is a character. for _, ch := range line { termbox.SetCell(x, y, ch, termbox.ColorGreen, termbox.ColorDefault) x++ } } }
/* i-sudoku is an interactive command-line sudoku tool */ package main import ( "github.com/jkomoros/sudoku" "github.com/nsf/termbox-go" "log" "strings" ) type mainModel struct { grid *sudoku.Grid } func main() { if err := termbox.Init(); err != nil { log.Fatal("Termbox initialization failed:", err) } defer termbox.Close() model := &mainModel{ sudoku.NewGrid(), } model.grid.Fill() draw(model) mainloop: for { switch ev := termbox.PollEvent(); ev.Type { case termbox.EventKey: switch ev.Key { case termbox.KeyEsc, termbox.KeyCtrlC: break mainloop } } draw(model) } } func draw(model *mainModel) { drawGrid(model.grid) termbox.Flush() } func drawGrid(grid *sudoku.Grid) { for y, line := range strings.Split(grid.Diagram(), "\n") { for x, ch := range line { termbox.SetCell(x, y, ch, termbox.ColorGreen, termbox.ColorDefault) } } }
Set decodeEntities to false for cheerio.
'use strict'; var cheerio = require('cheerio'); module.exports = function (html, options) { var results = {}; var $ = cheerio.load(html, { decodeEntities: false }); results.hrefs = []; $('link').each(function (index, element) { var $el = $(element); if ($el.attr('rel').toLowerCase() === 'stylesheet') { if (options.applyLinkTags) { results.hrefs.push($el.attr('href')); } if (options.removeLinkTags) { $el.remove(); } } }); results.html = $.html(); return results; };
'use strict'; var cheerio = require('cheerio'); module.exports = function (html, options) { var results = {}; var $ = cheerio.load(html); results.hrefs = []; $('link').each(function (index, element) { var $el = $(element); if ($el.attr('rel').toLowerCase() === 'stylesheet') { if (options.applyLinkTags) { results.hrefs.push($el.attr('href')); } if (options.removeLinkTags) { $el.remove(); } } }); results.html = $.html(); return results; };
Make sure to require Image. Failure to do so is not automatically caught.
// Copyright 2014-2015, University of Colorado Boulder /** * Base class for Nodes that represent energy system elements in the view * that use images as part of their representation. * * @author John Blanco * @author Andrew Adare */ define( function( require ) { 'use strict'; var Image = require( 'SCENERY/nodes/Image' ); var inherit = require( 'PHET_CORE/inherit' ); var EFACBaseNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/EFACBaseNode' ); /** * @param {EnergySystemElement} element * @param {ModelViewTransform} modelViewTransform * @constructor */ function ImageBasedEnergySystemNode( element, modelViewTransform ) { EFACBaseNode.call( this, element, modelViewTransform ); this.modelViewTransform = modelViewTransform; } return inherit( EFACBaseNode, ImageBasedEnergySystemNode, { /** * [addImageNode description] * * @param {EFACModelImage} modelElementImage [description] */ addImageNode: function( modelElementImage ) { var imageNode = new Image( modelElementImage.image ); var widthInView = this.modelViewTransform( modelElementImage.width ); imageNode.setScale( widthInView / imageNode.getBounds().getWidth() ); var offset = this.ModelViewTransform.modelToViewDelta( modelElementImage.centerToCenterOffset ); imageNode.setCenterX( offset.x ); imageNode.setCenterY( offset.y ); return imageNode; } } ); } );
// Copyright 2014-2015, University of Colorado Boulder /** * Base class for Nodes that represent energy system elements in the view * that use images as part of their representation. * * @author John Blanco * @author Andrew Adare */ define( function( require ) { 'use strict'; var inherit = require( 'PHET_CORE/inherit' ); var EFACBaseNode = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/view/EFACBaseNode' ); /** * @param {EnergySystemElement} element * @param {ModelViewTransform} modelViewTransform * @constructor */ function ImageBasedEnergySystemNode( element, modelViewTransform ) { EFACBaseNode.call( this, element, modelViewTransform ); this.modelViewTransform = modelViewTransform; } return inherit( EFACBaseNode, ImageBasedEnergySystemNode, { /** * [addImageNode description] * * @param {EFACModelImage} modelElementImage [description] */ addImageNode: function( modelElementImage ) { var imageNode = new Image( modelElementImage.image ); var widthInView = this.modelViewTransform( modelElementImage.width ); imageNode.setScale( widthInView / imageNode.getBounds().getWidth() ); var offset = this.ModelViewTransform.modelToViewDelta( modelElementImage.centerToCenterOffset ); imageNode.setCenterX( offset.x ); imageNode.setCenterY( offset.y ); return imageNode; } } ); } );
Add alpha argument to eventplot().
__author__ = 'jgosmann' from matplotlib.cbook import iterable from prettyplotlib.utils import remove_chartjunk, maybe_get_ax from prettyplotlib.colors import set2 def eventplot(*args, **kwargs): ax, args, kwargs = maybe_get_ax(*args, **kwargs) show_ticks = kwargs.pop('show_ticks', False) alpha = kwargs.pop('alpha', 1.0) if len(args) > 0: positions = args[0] else: positions = kwargs['positions'] if any(iterable(p) for p in positions): size = len(positions) else: size = 1 kwargs.setdefault('colors', [c + (alpha,) for c in set2[:size]]) event_collections = ax.eventplot(*args, **kwargs) remove_chartjunk(ax, ['top', 'right'], show_ticks=show_ticks) return event_collections
__author__ = 'jgosmann' from matplotlib.cbook import iterable from prettyplotlib.utils import remove_chartjunk, maybe_get_ax from prettyplotlib.colors import set2 def eventplot(*args, **kwargs): ax, args, kwargs = maybe_get_ax(*args, **kwargs) show_ticks = kwargs.pop('show_ticks', False) if len(args) > 0: positions = args[0] else: positions = kwargs['positions'] if any(iterable(p) for p in positions): size = len(positions) else: size = 1 kwargs.setdefault('colors', [c + (1.0,) for c in set2[:size]]) event_collections = ax.eventplot(*args, **kwargs) remove_chartjunk(ax, ['top', 'right'], show_ticks=show_ticks) return event_collections
Remove mobile option due to gold plating
(function() { 'use strict'; angular.module('pagespeedApp').factory('pagespeedApi', pagespeedApi); pagespeedApi.$inject = ['$http']; function pagespeedApi($http) { var endpoint = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'; var options = { key: '' }; var cache = {}; var service = { cache: cache, endpoint: endpoint, options: options, get: get, run: run }; return service; function get(url) { var host = new URL(url).host; return service.cache[host] ? Promise.resolve(service.cache[host]) : service.run(url); } function run(url) { var params = { url: url, key: service.options.key }; return $http.get(service.endpoint, { params: params }).then(cacheResponse(url)); } function cacheResponse(url) { return function(data) { var requestHost = new URL(url).host; var resolveHost = new URL(data.data.id).host; service.cache[resolveHost] = data; if (requestHost != resolveHost) { service.cache[requestHost] = data; } return data; }; } } })();
(function() { 'use strict'; angular.module('pagespeedApp').factory('pagespeedApi', pagespeedApi); pagespeedApi.$inject = ['$http']; function pagespeedApi($http) { var endpoint = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'; var options = { key: '' }; var cache = {}; var service = { cache: cache, endpoint: endpoint, options: options, get: get, run: run }; return service; function get(url) { var host = new URL(url).host; return service.cache[host] ? Promise.resolve(service.cache[host]) : service.run(url); } function run(url, mobile, screenshot) { var params = { url: url, key: service.options.key }; return $http.get(service.endpoint, { params: params }).then(cacheResponse(url)); } function cacheResponse(url) { return function(data) { console.log(data); var requestHost = new URL(url).host; var resolveHost = new URL(data.data.id).host; service.cache[resolveHost] = data; if (requestHost != resolveHost) { service.cache[requestHost] = data; } return data; }; } } })();
Update to example with new optional arguments
var canvas, ctx, input, info; window.onload = function(){ canvas = document.getElementById("canvas"); ctx = canvas.getContext('2d'); input = document.getElementById("input"); info = document.getElementById("info"); input.onkeyup = newUPC; newUPC(); } function newUPC(){ var text = input.value; ctx.clearRect(0,0,1000,100); var ean = new EAN(text); var code128 = new CODE128(text); if(ean.valid()){ drawBinary(ean.encoded(), ctx); info.innerHTML = "Using EAN13"; } else if(code128.valid()){ drawBinary(code128.encoded(), ctx, {width:1,height:20}); info.innerHTML = "Using Code128"; } else{ info.innerHTML = "Not a supported input!"; } }
var canvas, ctx, input, info; window.onload = function(){ canvas = document.getElementById("canvas"); ctx = canvas.getContext('2d'); input = document.getElementById("input"); info = document.getElementById("info"); input.onkeyup = newUPC; newUPC(); } function newUPC(){ var text = input.value; ctx.clearRect(0,0,1000,100); var ean = new EAN(text); var code128 = new Code128(text); if(ean.valid()){ drawBinary(ean.encoded(), ctx, 100, 2); info.innerHTML = "Using EAN13"; } else if(code128.valid()){ drawBinary(code128.encoded(), ctx, 100, 2); info.innerHTML = "Using Code128"; } else{ info.innerHTML = "Not a supported input!"; } }
Remove blueprint comment in tests
import Ember from 'ember'; import DS from 'ember-data'; import EmberCliUuidInitializer from '../../../initializers/ember-cli-uuid'; import { module, test } from 'qunit'; let application; const regexIsUUID = /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i; module('Unit | Initializer | ember cli uuid', { beforeEach() { Ember.run(function() { application = Ember.Application.create(); application.deferReadiness(); }); } }); test('The DS.Adapter.generateIdForRecord now returns proper UUIDs v4', function(assert) { EmberCliUuidInitializer.initialize(application); const adapter = new DS.Adapter(); const generateIdForRecord = adapter.generateIdForRecord(); assert.ok(regexIsUUID.test(generateIdForRecord)); });
import Ember from 'ember'; import DS from 'ember-data'; import EmberCliUuidInitializer from '../../../initializers/ember-cli-uuid'; import { module, test } from 'qunit'; let application; const regexIsUUID = /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i; module('Unit | Initializer | ember cli uuid', { beforeEach() { Ember.run(function() { application = Ember.Application.create(); application.deferReadiness(); }); } }); // Replace this with your real tests. test('The DS.Adapter.generateIdForRecord now returns proper UUIDs v4', function(assert) { EmberCliUuidInitializer.initialize(application); const adapter = new DS.Adapter(); const generateIdForRecord = adapter.generateIdForRecord(); assert.ok(regexIsUUID.test(generateIdForRecord)); });
Use bytes for base-64 encoded data instead of strings git-svn-id: bdb5f82b9b83a1400e05d69d262344b821646179@1345 e217846f-e12e-0410-a4e5-89ccaea66ff7
package edu.usc.glidein.util; import java.io.IOException; import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder; /** * Convert to/from Base64-encoded data * * @author Gideon Juve <juve@usc.edu> */ public class Base64 { /** * Base64-encode a string * @param string The string to encode * @return The base64 encoding of the string */ public static byte[] toBase64(String string) { if(string==null) return null; byte[] buff = string.getBytes(); String s = new BASE64Encoder().encode(buff); return s.getBytes(); } /** * Decode a base64-encoded string * @param base64 Base64-encoded binary * @return The decoded string */ public static String fromBase64(byte[] base64) { if(base64==null) return null; try { String s = new String(base64); byte[] output = new BASE64Decoder().decodeBuffer(s); return new String(output); } catch(IOException ioe) { return null; /* I don't think this will actually happen */ } } }
package edu.usc.glidein.util; import java.io.IOException; import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder; /** * Convert to/from Base64-encoded data * * @author Gideon Juve <juve@usc.edu> */ public class Base64 { /** * Base64-encode a string * @param string The string to encode * @return The base64 encoding of the string */ public static String toBase64(String string) { if(string==null) return null; byte[] buff = string.getBytes(); return new BASE64Encoder().encode(buff); } /** * Decode a base64-encoded string * @param base64 Base64-encoded string * @return The decoded string */ public static String fromBase64(String base64) { if(base64==null) return null; try { byte[] output = new BASE64Decoder().decodeBuffer(base64); return new String(output); } catch(IOException ioe) { return null; /* I don't think this will actually happen */ } } public static void main(String[] args) { System.out.println(new String(Base64.toBase64("Hello, World!"))); System.out.println(Base64.fromBase64("SGVsbG8sIFdvcmxkIQ==")); } }
Remove code that really should not be there
<?php namespace Bundle\DoctrineUserBundle\Form; use Symfony\Component\Form\Form; use Symfony\Component\Form\TextField; use Symfony\Component\Form\RepeatedField; use Symfony\Component\Form\PasswordField; use Symfony\Component\Validator\ValidatorInterface; class UserForm extends Form { /** * Constructor. * * @param string $name * @param array|object $data * @param ValidatorInterface $validator * @param array $options */ public function __construct($title, $data, ValidatorInterface $validator, array $options = array()) { $this->addOption('theme'); parent::__construct($title, $data, $validator, $options); } public function configure() { $this->add(new TextField('username')); $this->add(new TextField('email')); $this->add(new RepeatedField(new PasswordField('password'))); } }
<?php namespace Bundle\DoctrineUserBundle\Form; use Symfony\Component\Form\Form; use Symfony\Component\Form\TextField; use Symfony\Component\Form\RepeatedField; use Symfony\Component\Form\PasswordField; use Symfony\Component\Validator\ValidatorInterface; class UserForm extends Form { /** * Constructor. * * @param string $name * @param array|object $data * @param ValidatorInterface $validator * @param array $options */ public function __construct($title, $data, ValidatorInterface $validator, array $options = array()) { $this->addOption('theme'); $this->addOption('categoryRepository'); $this->addOption('columnRepository'); $this->addOption('showPublishedAt'); parent::__construct($title, $data, $validator, $options); } public function configure() { $this->add(new TextField('username')); $this->add(new TextField('email')); $this->add(new RepeatedField(new PasswordField('password'))); } }
Remove extra <div id="content"> in many templates. git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@1471 44740490-163a-0410-bde0-09ae8108e29a
<?php $this->data['header'] = $this->t('{aggregator:dict:aggregator_header}'); $this->includeAtTemplateBase('includes/header.php'); echo('<h1>'. $this->data['header'] . '</h1>'); if (count($this->data['sources']) === 0) { echo('<p>' . $this->t('{aggregator:dict:no_aggregators}') . '</p>'); } else { echo('<ul>'); foreach ($this->data['sources'] as $source) { $encId = urlencode($source); $encName = htmlspecialchars($source); echo('<li>'); echo('<a href="?id=' . $encId . '">' . $encName . '</a>'); echo(' <a href="?id=' . $encId . '&amp;mimetype=text/plain">[' . $this->t('{aggregator:dict:text}') . ']</a>'); echo(' <a href="?id=' . $encId . '&amp;mimetype=application/xml">[xml]</a>'); echo('</li>'); } echo('</ul>'); } $this->includeAtTemplateBase('includes/footer.php'); ?>
<?php $this->data['header'] = $this->t('{aggregator:dict:aggregator_header}'); $this->includeAtTemplateBase('includes/header.php'); echo('<div id="content">'); echo('<h1>'. $this->data['header'] . '</h1>'); if (count($this->data['sources']) === 0) { echo('<p>' . $this->t('{aggregator:dict:no_aggregators}') . '</p>'); } else { echo('<ul>'); foreach ($this->data['sources'] as $source) { $encId = urlencode($source); $encName = htmlspecialchars($source); echo('<li>'); echo('<a href="?id=' . $encId . '">' . $encName . '</a>'); echo(' <a href="?id=' . $encId . '&amp;mimetype=text/plain">[' . $this->t('{aggregator:dict:text}') . ']</a>'); echo(' <a href="?id=' . $encId . '&amp;mimetype=application/xml">[xml]</a>'); echo('</li>'); } echo('</ul>'); } $this->includeAtTemplateBase('includes/footer.php'); ?>
Revert "debugging the ios directory issue" This reverts commit 03acb171f091c3228033a60adbacbe4a2a62e524.
#!/usr/bin/env node const yargs = require('yargs'); yargs .usage('$0 command') .command('all', 'run all bundled commands', yargs => { const operations = require('./src'); console.log("yargs" yargs) for (const key of Object.keys(operations)) { operations[key](); } }) .command('fix-libraries', 'add any missing build configurations to all xcode projects in node_modules', yargs => { require('./src/fix-libraries')(); }) .command('fix-script', 'replace the react native ios bundler with our scheme aware one', yargs => { require('./src/fix-script')(); }) .command('hide-library-schemes', `hide any schemes that come from your node modules directory so they don't clutter up the menu.`, yargs => { require('./src/hide-library-schemes')(); }) .command('verify-config', `check the configuration and ensure we have both a postinstall script and xcodeSchemes configurations.`, yargs => { require('./src/verify-config')(); }) .demand(1, 'must provide a valid command') .help('h') .alias('h', 'help') .argv;
#!/usr/bin/env node const yargs = require('yargs'); yargs .usage('$0 command') .command('all', 'run all bundled commands', yargs => { const operations = require('./src'); console.log("yargs", yargs) for (const key of Object.keys(operations)) { operations[key](); } }) .command('fix-libraries', 'add any missing build configurations to all xcode projects in node_modules', yargs => { require('./src/fix-libraries')(); }) .command('fix-script', 'replace the react native ios bundler with our scheme aware one', yargs => { require('./src/fix-script')(); }) .command('hide-library-schemes', `hide any schemes that come from your node modules directory so they don't clutter up the menu.`, yargs => { require('./src/hide-library-schemes')(); }) .command('verify-config', `check the configuration and ensure we have both a postinstall script and xcodeSchemes configurations.`, yargs => { require('./src/verify-config')(); }) .demand(1, 'must provide a valid command') .help('h') .alias('h', 'help') .argv;
Move var declarations to the top.
'use strict'; var assert = require('assert'), Batch = require('batch'), getStylesData = require('style-data'), getStylesheetList = require('list-stylesheets'), getHrefContent = require('href-content'); module.exports = function (html, options, callback) { var batch = new Batch(), data = getStylesheetList(html, options); batch.push(function (cb) { getStylesData(data.html, options, cb); }); if (data.hrefs.length) { assert.ok(options.url, 'options.url is required'); } data.hrefs.forEach(function (stylesheetHref) { batch.push(function (cb) { getHrefContent(stylesheetHref, options.url, cb); }); }); batch.end(function (err, results) { var stylesData, css; if (err) { return callback(err); } stylesData = results.shift(); results.forEach(function (content) { stylesData.css.push(content); }); css = stylesData.css.join('\n'); callback(null, stylesData.html, css); }); };
'use strict'; var assert = require('assert'), Batch = require('batch'), getStylesData = require('style-data'), getStylesheetList = require('list-stylesheets'), getHrefContent = require('href-content'); module.exports = function (html, options, callback) { var batch = new Batch(), data = getStylesheetList(html, options); batch.push(function (cb) { getStylesData(data.html, options, cb); }); if (data.hrefs.length) { assert.ok(options.url, 'options.url is required'); } data.hrefs.forEach(function (stylesheetHref) { batch.push(function (cb) { getHrefContent(stylesheetHref, options.url, cb); }); }); batch.end(function (err, results) { if (err) { return callback(err); } var stylesData = results.shift(), css; results.forEach(function (content) { stylesData.css.push(content); }); css = stylesData.css.join('\n'); callback(null, stylesData.html, css); }); };
Make speaker population code use get_or_create instead of exception
from django.core.management.base import NoArgsCommand import pprint from popit import PopIt from speeches.models import Speaker class Command(NoArgsCommand): help = 'Populates the database with people from Popit' def handle_noargs(self, **options): pp = pprint.PrettyPrinter(indent=4) # Do populating api = PopIt(instance = 'ukcabinet', hostname = 'ukcabinet.popit.mysociety.org', api_version = 'v1') results = api.person.get() for person in results['results']: speaker, created = Speaker.objects.get_or_create(popit_id=person['_id']) # we ignore created for now, just always set the name speaker.name = person['name'] speaker.save();
from django.core.management.base import NoArgsCommand import pprint from popit import PopIt from speeches.models import Speaker class Command(NoArgsCommand): help = 'Populates the database with people from Popit' def handle_noargs(self, **options): pp = pprint.PrettyPrinter(indent=4) # Do populating api = PopIt(instance = 'ukcabinet', hostname = 'ukcabinet.popit.mysociety.org', api_version = 'v1') results = api.person.get() self.stdout.write('Names will be:\n') for person in results['results']: self.stdout.write('Processing person: ' + pp.pformat(person) + '\n') try: speaker = Speaker.objects.get(popit_id=person['_id']) except Speaker.DoesNotExist: speaker = Speaker() speaker.popit_id = person['_id'] speaker.name = person['name'] speaker.save();
Add keystone to the request
default_settings = [ ('auth_url', str, 'http://localhost:5000/v3'), ('region', str, 'RegionOne'), ('user_domain_name', str, 'Default'), ('cacert', str, ''), ] def parse_settings(settings): parsed = {} def populate(name, convert, default): sname = '%s%s' % ('keystone.', name) value = convert(settings.get(sname, default)) parsed[sname] = value for name, convert, default in default_settings: populate(name, convert, default) return parsed def includeme(config): """ Set up standard configurator registrations. Use via: .. code-block:: python config = Configurator() config.include('pyramid_keystone') """ # We use an action so that the user can include us, and then add the # required variables, upon commit we will pick up those changes. def register(): registry = config.registry settings = parse_settings(registry.settings) registry.settings.update(settings) config.action('keystone-configure', register) # Allow the user to use our auth policy (recommended) config.add_directive('keystone_auth_policy', '.authentication.add_auth_policy') # Add the keystone property to the request config.add_request_method('.keystone.request_keystone', name='keystone', property=True, reify=True)
default_settings = [ ('auth_url', str, 'http://localhost:5000/v3'), ('region', str, 'RegionOne'), ('user_domain_name', str, 'Default'), ('cacert', str, ''), ] def parse_settings(settings): parsed = {} def populate(name, convert, default): sname = '%s%s' % ('keystone.', name) value = convert(settings.get(sname, default)) parsed[sname] = value for name, convert, default in default_settings: populate(name, convert, default) return parsed def includeme(config): """ Set up standard configurator registrations. Use via: .. code-block:: python config = Configurator() config.include('pyramid_keystone') """ # We use an action so that the user can include us, and then add the # required variables, upon commit we will pick up those changes. def register(): registry = config.registry settings = parse_settings(registry.settings) registry.settings.update(settings) config.action('keystone-configure', register) config.add_directive('keystone_auth_policy', '.authentication.add_auth_policy')
feat(Provider): Allow passing props to 'Notification' through 'Provider'
import React, { Children } from 'react'; import PropTypes from 'prop-types'; import Context from './context'; import Notification from './notification'; class Provider extends React.PureComponent { constructor(props) { super(props); this.showNotification = this.showNotification.bind(this); } showNotification(notificationOptions) { if (this.notification) { this.notification.show(notificationOptions); } } render() { return ( <Context.Provider value={this.showNotification}> {Children.only(this.props.children)} <Notification ref={(ref) => { this.notification = ref; }} {...this.props} /> </Context.Provider> ); } } Provider.propTypes = { ...Notification.propTypes, children: PropTypes.element.isRequired, }; export default Provider;
import React, { Children } from 'react'; import PropTypes from 'prop-types'; import Context from './context'; import Notification from './notification'; class Provider extends React.PureComponent { constructor(props) { super(props); this.showNotification = this.showNotification.bind(this); } showNotification(notificationOptions) { if (this.notification) { this.notification.show(notificationOptions); } } render() { return ( <Context.Provider value={this.showNotification}> {Children.only(this.props.children)} <Notification ref={(ref) => { this.notification = ref; }} /> </Context.Provider> ); } } Provider.propTypes = { children: PropTypes.element.isRequired, }; export default Provider;
docs: Use the current year in the copyright
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath('.'))) import youtube_dl_server as ydl_server # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinxcontrib.httpdomain', ] # The master toctree document. master_doc = 'index' # General information about the project. project = 'youtube-dl-api-server' copyright = '2013-{now:%Y}, Jaime Marquínez Ferrándiz'.format(now=datetime.datetime.now()) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = ydl_server.__version__ # The short X.Y version. version = '.'.join(release.split('.')[:2]) # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build']
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import sys import os sys.path.insert(0, os.path.dirname(os.path.abspath('.'))) import youtube_dl_server as ydl_server # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinxcontrib.httpdomain', ] # The master toctree document. master_doc = 'index' # General information about the project. project = 'youtube-dl-api-server' copyright = '2013, Jaime Marquínez Ferrándiz' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = ydl_server.__version__ # The short X.Y version. version = '.'.join(release.split('.')[:2]) # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build']