text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Move call to module scope
'use strict'; // MODULES // var keys = require( 'object-keys' ); var isPlainObject = require( '@stdlib/utils/is-plain-object' ); var hasSymbolSupport = require( '@stdlib/utils/detect-symbol-support' )(); // MAIN // /** * Tests if a value is an empty object. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an empty object * * @example * var bool = isEmptyObject( {} ); * // returns true * @example * var bool = isEmptyObject( { 'beep': 'boop' } ); * // returns false * @example * var bool = isEmptyObject( [] ); * // returns false */ function isEmptyObject( value ) { if ( !isPlainObject( value ) ) { return false; } if ( keys( value ).length > 0 ) { return false; } if ( hasSymbolSupport && Object.getOwnPropertySymbols( value ).length > 0 ) { return false; } return true; } // end FUNCTION isEmptyObject() // EXPORTS // module.exports = isEmptyObject;
'use strict'; // MODULES // var keys = require( 'object-keys' ); var isPlainObject = require( '@stdlib/utils/is-plain-object' ); var hasSymbolSupport = require( '@stdlib/utils/detect-symbol-support' ); // MAIN // /** * Tests if a value is an empty object. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an empty object * * @example * var bool = isEmptyObject( {} ); * // returns true * @example * var bool = isEmptyObject( { 'beep': 'boop' } ); * // returns false * @example * var bool = isEmptyObject( [] ); * // returns false */ function isEmptyObject( value ) { if ( !isPlainObject( value ) ) { return false; } if ( keys( value ).length > 0 ) { return false; } if ( hasSymbolSupport() && Object.getOwnPropertySymbols( value ).length > 0 ) { return false; } return true; } // end FUNCTION isEmptyObject() // EXPORTS // module.exports = isEmptyObject;
Fix swapped documentation for template methods
<?php namespace Podlove\Modules\Shows; use \Podlove\Modules\Shows\Model\Show; class TemplateExtensions { /** * List of all Podcast shows * * **Examples** * * ``` * This podcast features several shows: * <ul> * {% for show in podcast.shows %} * <li>{{ show.title }}</li> * {% endfor %} * </ul> * ``` * * @accessor * @dynamicAccessor podcast.shows */ public static function accessorPodcastShows($return, $method_name, $episode) { return $episode->with_blog_scope(function() use ($return, $method_name, $episode) { return Show::all(); }); } /** * Episode Show * * **Examples** * * ``` * This episode is part of the Show: {{ episode.show.title }} which deals with * {{ episode.show.summary }} * ``` * * @accessor * @dynamicAccessor episode.show */ public static function accessorEpisodesShow($return, $method_name, $episode) { return $episode->with_blog_scope(function() use ($return, $method_name, $episode) { return Show::find_one_by_episode_id($episode->id); }); } }
<?php namespace Podlove\Modules\Shows; use \Podlove\Modules\Shows\Model\Show; class TemplateExtensions { /** * Episode Show * * **Examples** * * ``` * This episode is part of the Show: {{ episode.show.title }} which deals with * {{ episode.show.summary }} * ``` * * @accessor * @dynamicAccessor episode.show */ public static function accessorPodcastShows($return, $method_name, $episode) { return $episode->with_blog_scope(function() use ($return, $method_name, $episode) { return Show::all(); }); } /** * List of all Podcast shows * * **Examples** * * ``` * This podcast features several shows: * <ul> * {% for show in podcast.shows %} * <li>{{ show.title }}</li> * {% endfor %} * </ul> * ``` * * @accessor * @dynamicAccessor podcast.shows */ public static function accessorEpisodesShow($return, $method_name, $episode) { return $episode->with_blog_scope(function() use ($return, $method_name, $episode) { return Show::find_one_by_episode_id($episode->id); }); } }
Change configuration on production Auth0
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), actions: { login () { var lockOptions = { allowedConnections: [ 'Default', ], autoclose: true, allowLogin: true, allowSignUp: false, rememberLastLogin: true, theme: { logo: 'https://s3-us-west-1.amazonaws.com/barberscore/static/images/bhs_logo.png', primaryColor: '#337ab7' }, languageDictionary: { title: "Barberscore" }, auth: { redirect: false, params: { scope: 'openid profile', } } }; this.get('session').authenticate('authenticator:auth0-lock', lockOptions); }, logout () { this.get('session').invalidate(); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), actions: { login () { var lockOptions = { allowedConnections: [ 'Username-Password-Authentication', ], autoclose: true, allowLogin: true, allowSignUp: false, rememberLastLogin: true, theme: { logo: 'https://s3-us-west-1.amazonaws.com/barberscore/static/images/bhs_logo.png', primaryColor: '#337ab7' }, languageDictionary: { title: "Barberscore" }, auth: { redirect: false, params: { scope: 'openid profile', } } }; this.get('session').authenticate('authenticator:auth0-lock', lockOptions); }, logout () { this.get('session').invalidate(); } } });
Send original and new directories
'use strict'; const fs = require('fs-extra'); function setDir(options) { return function setDirInner(dir) { return { to: function (location) { options.onStart(dir, location); fs.copy(dir, location, function(err) { if (err) { options.onError } options.onEnd(dir, location); }); } }; } } function generateCopy(options) { const onError = options.onError || () => true; const onStart = options.onStart || () => true; const onEnd = options.onEnd || () => true; return { dir: setDir(options) }; } module.exports = function (options) { return generateCopy(options); }
'use strict'; const fs = require('fs-extra'); function setDir(options) { return function setDirInner(dir) { return { to: function (location) { options.onStart(dir, location); fs.copy(dir, location, function(err) { if (err) { options.onError } options.onEnd(location); }); } }; } } function generateCopy(options) { const onError = options.onError || () => true; const onStart = options.onStart || () => true; const onEnd = options.onEnd || () => true; return { dir: setDir(options) }; } module.exports = function (options) { return generateCopy(options); }
Replace anonymous Runnable with lambda expression
package com.codeaffine.eclipse.swt.widget.scrollable; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import com.codeaffine.eclipse.swt.widget.scrollable.context.AdaptionContext; import com.codeaffine.eclipse.swt.widget.scrollbar.FlatScrollBar; class HorizontalSelectionListener extends SelectionAdapter { private final AdaptionContext<?> context; HorizontalSelectionListener( AdaptionContext<?> context ) { this.context = context; } @Override public void widgetSelected( SelectionEvent event ) { updateLocation( new Point( -getSelection( event ), computeHeight() ) ); } private int computeHeight() { if( context.isScrollableReplacedByAdapter() ) { return -context.getBorderWidth(); } return context.getScrollable().getLocation().y - context.getBorderWidth(); } private int getSelection( SelectionEvent event ) { return ( ( FlatScrollBar )event.widget ).getSelection() + context.getBorderWidth(); } private void updateLocation( final Point result ) { context.getReconciliation().runWhileSuspended( () -> context.getScrollable().setLocation( result ) ); } }
package com.codeaffine.eclipse.swt.widget.scrollable; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import com.codeaffine.eclipse.swt.widget.scrollable.context.AdaptionContext; import com.codeaffine.eclipse.swt.widget.scrollbar.FlatScrollBar; class HorizontalSelectionListener extends SelectionAdapter { private final AdaptionContext<?> context; HorizontalSelectionListener( AdaptionContext<?> context ) { this.context = context; } @Override public void widgetSelected( SelectionEvent event ) { updateLocation( new Point( -getSelection( event ), computeHeight() ) ); } private int computeHeight() { if( context.isScrollableReplacedByAdapter() ) { return -context.getBorderWidth(); } return context.getScrollable().getLocation().y - context.getBorderWidth(); } private int getSelection( SelectionEvent event ) { return ( ( FlatScrollBar )event.widget ).getSelection() + context.getBorderWidth(); } private void updateLocation( final Point result ) { context.getReconciliation().runWhileSuspended( new Runnable() { @Override public void run() { context.getScrollable().setLocation( result ); } } ); } }
Use CommandUnknown exception in the method create.
package com.obidea.semantika.cli2.command; import com.obidea.semantika.cli2.runtime.ConsoleSession; import com.obidea.semantika.cli2.runtime.UnknownCommandException; public class CommandFactory { public static Command create(String command, ConsoleSession session) throws UnknownCommandException { if (startsWith(command, Command.SELECT)) { return new SelectCommand(command, session); } else if (startsWith(command, Command.SET_PREFIX)) { return new SetPrefixCommand(command, session); } else if (startsWith(command, Command.SHOW_PREFIXES)) { return new ShowPrefixesCommand(command, session); } throw new UnknownCommandException(); //$NON-NLS-1$ } private static boolean startsWith(String command, String keyword) { return command.startsWith(keyword) || command.startsWith(keyword.toUpperCase()); } }
package com.obidea.semantika.cli2.command; import com.obidea.semantika.cli2.runtime.ConsoleSession; public class CommandFactory { public static Command create(String command, ConsoleSession session) throws Exception { if (startsWith(command, Command.SELECT)) { return new SelectCommand(command, session); } else if (startsWith(command, Command.SET_PREFIX)) { return new SetPrefixCommand(command, session); } else if (startsWith(command, Command.SHOW_PREFIXES)) { return new ShowPrefixesCommand(command, session); } throw new Exception("Unknown command"); //$NON-NLS-1$ } private static boolean startsWith(String command, String keyword) { return command.startsWith(keyword) || command.startsWith(keyword.toUpperCase()); } }
Fix wrong French resources for the developer guide. git-svn-id: bd781a9493159d57baabeab2b59de614917f0f5c@1713160 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sis.internal.book; /** * Localized resources, for internal usage only. * * @author Martin Desruisseaux (Geomatys) * @since 0.7 * @version 0.7 */ public final class Resources_fr extends Resources { @Override protected Object[][] getContents() { final Object[][] resources = super.getContents(); resources[0][1] = "Chapitre précédent"; resources[1][1] = "Chapitre suivant"; resources[2][1] = "Dans ce chapitre:"; return resources; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sis.internal.book; /** * Localized resources, for internal usage only. * * @author Martin Desruisseaux (Geomatys) * @since 0.7 * @version 0.7 */ public final class Resources_fr extends Resources { @Override protected Object[][] getContents() { final Object[][] resources = super.getContents(); resources[0][1] = "Chapitre suivant"; resources[1][1] = "Chapitre précédent"; resources[2][1] = "Dans ce chapitre:"; return resources; } }
PlaneLabelOverlay: Use `offsetWidth` instead of jQuery
import Component from '@ember/component'; import $ from 'jquery'; import ol from 'openlayers'; export default class PlaneLabelOverlay extends Component { tagName = ''; map = null; flight = null; position = null; overlay = null; init() { super.init(...arguments); let badgeStyle = `display: inline-block; text-align: center; background: ${this.get('flight.color')}`; let id = this.getWithDefault('flight.competition_id', '') || this.getWithDefault('flight.registration', ''); let badge = $(`<span class="badge plane_marker" style="${badgeStyle}"> ${id} </span>`); this.set( 'overlay', new ol.Overlay({ element: badge.get(0), }), ); } didReceiveAttrs() { super.didReceiveAttrs(...arguments); this.overlay.setPosition(this.position); } didInsertElement() { super.didInsertElement(...arguments); let overlay = this.overlay; this.map.addOverlay(overlay); let width = overlay.getElement().offsetWidth; overlay.setOffset([-width / 2, -40]); } willDestroyElement() { super.willDestroyElement(...arguments); let overlay = this.overlay; this.map.removeOverlay(overlay); } }
import Component from '@ember/component'; import $ from 'jquery'; import ol from 'openlayers'; export default class PlaneLabelOverlay extends Component { tagName = ''; map = null; flight = null; position = null; overlay = null; init() { super.init(...arguments); let badgeStyle = `display: inline-block; text-align: center; background: ${this.get('flight.color')}`; let id = this.getWithDefault('flight.competition_id', '') || this.getWithDefault('flight.registration', ''); let badge = $(`<span class="badge plane_marker" style="${badgeStyle}"> ${id} </span>`); this.set( 'overlay', new ol.Overlay({ element: badge.get(0), }), ); } didReceiveAttrs() { super.didReceiveAttrs(...arguments); this.overlay.setPosition(this.position); } didInsertElement() { super.didInsertElement(...arguments); let overlay = this.overlay; this.map.addOverlay(overlay); let width = $(overlay.getElement()).width(); overlay.setOffset([-width / 2, -40]); } willDestroyElement() { super.willDestroyElement(...arguments); let overlay = this.overlay; this.map.removeOverlay(overlay); } }
Make method to create an empty 'circuit element'
(function(app) { 'use strict'; var circuit = require('circuit'); var Wrapper = function(self) { this.unwrap = Wrapper.unwrap.bind(self); }; Wrapper.unwrap = function(key) { if (key === Wrapper.KEY) return this; }; Wrapper.KEY = {}; var CircuitElementMember = function(props) { this.label = props.label; this.name = props.name; this.type = props.type; this.callee = circuit[props.type](props.arg); this.sources = []; this.targets = []; this.wrapper = new Wrapper(this); }; var CircuitElement = function(members) { var memberTable = {}; var names = []; members.slice().reverse().forEach(function(props) { var name = props.name; if (name in memberTable) return; memberTable[name] = new CircuitElementMember(props); names.unshift(name); }); this.memberTable = memberTable; this.names = names; }; CircuitElement.prototype.get = function(name) { var member = this.memberTable[name]; if (!member) return null; return member.wrapper; }; CircuitElement.empty = function() { return new CircuitElement([]); }; if (typeof module !== 'undefined' && module.exports) module.exports = CircuitElement; else app.CircuitElement = CircuitElement; })(this.app || (this.app = {}));
(function(app) { 'use strict'; var circuit = require('circuit'); var Wrapper = function(self) { this.unwrap = Wrapper.unwrap.bind(self); }; Wrapper.unwrap = function(key) { if (key === Wrapper.KEY) return this; }; Wrapper.KEY = {}; var CircuitElementMember = function(props) { this.label = props.label; this.name = props.name; this.type = props.type; this.callee = circuit[props.type](props.arg); this.sources = []; this.targets = []; this.wrapper = new Wrapper(this); }; var CircuitElement = function(members) { var memberTable = {}; var names = []; members.slice().reverse().forEach(function(props) { var name = props.name; if (name in memberTable) return; memberTable[name] = new CircuitElementMember(props); names.unshift(name); }); this.memberTable = memberTable; this.names = names; }; CircuitElement.prototype.get = function(name) { var member = this.memberTable[name]; if (!member) return null; return member.wrapper; }; if (typeof module !== 'undefined' && module.exports) module.exports = CircuitElement; else app.CircuitElement = CircuitElement; })(this.app || (this.app = {}));
Use iota at log level enumeration.
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logger import ( "log" "os" ) const ( LogLevelFatal = iota LogLevelVerbose LogLevelDebug ) var ( logLevel = LogLevelFatal ) func init() { levels := []string{"fatal", "verbose", "debug"} envLogLevel := os.Getenv("DRIVEFUSE_LOGLEVEL") if envLogLevel == "" { return } for index, val := range levels { if envLogLevel == val { logLevel = index } } } func F(args ...interface{}) { if logLevel >= LogLevelFatal { log.Fatalln(args...) } } func D(args ...interface{}) { if logLevel >= LogLevelDebug { log.Println(args...) } } func V(args ...interface{}) { if logLevel >= LogLevelVerbose { log.Println(args...) } }
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logger import ( "log" "os" ) const ( LogLevelFatal = 0 LogLevelVerbose = 1 LogLevelDebug = 2 ) var ( logLevel = LogLevelFatal ) func init() { levels := []string{"fatal", "verbose", "debug"} envLogLevel := os.Getenv("DRIVEFUSE_LOGLEVEL") if envLogLevel == "" { return } for index, val := range levels { if envLogLevel == val { logLevel = index } } } func F(args ...interface{}) { if logLevel >= LogLevelFatal { log.Fatalln(args...) } } func D(args ...interface{}) { if logLevel >= LogLevelDebug { log.Println(args...) } } func V(args ...interface{}) { if logLevel >= LogLevelVerbose { log.Println(args...) } }
Create real channel object in tests
var EventEmitter = require("events").EventEmitter; var util = require("util"); var _ = require("lodash"); var express = require("express"); var Network = require("../src/models/network"); var Chan = require("../src/models/chan"); function MockClient(opts) { this.user = {nick: "test-user"}; for (var k in opts) { this[k] = opts[k]; } } util.inherits(MockClient, EventEmitter); MockClient.prototype.createMessage = function(opts) { var message = _.extend({ message: "dummy message", nick: "test-user", target: "#test-channel" }, opts); this.emit("privmsg", message); }; module.exports = { createClient: function() { return new MockClient(); }, createNetwork: function() { return new Network({ host: "example.com", channels: [new Chan({ name: "#test-channel" })] }); }, createWebserver: function() { return express(); } };
var EventEmitter = require("events").EventEmitter; var util = require("util"); var _ = require("lodash"); var express = require("express"); var Network = require("../src/models/network"); function MockClient(opts) { this.user = {nick: "test-user"}; for (var k in opts) { this[k] = opts[k]; } } util.inherits(MockClient, EventEmitter); MockClient.prototype.createMessage = function(opts) { var message = _.extend({ message: "dummy message", nick: "test-user", target: "#test-channel" }, opts); this.emit("privmsg", message); }; module.exports = { createClient: function() { return new MockClient(); }, createNetwork: function() { return new Network({ host: "example.com", channels: [{ name: "#test-channel", messages: [] }] }); }, createWebserver: function() { return express(); } };
Use python import lib (django import lib will be removed in 1.9).
""" gargoyle ~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ __all__ = ('gargoyle', 'ConditionSet', 'autodiscover', 'VERSION') try: VERSION = __import__('pkg_resources') \ .get_distribution('gargoyle').version except Exception, e: VERSION = 'unknown' from gargoyle.manager import gargoyle def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ import copy from django.conf import settings from importlib import import_module for app in settings.INSTALLED_APPS: # Attempt to import the app's gargoyle module. before_import_registry = copy.copy(gargoyle._registry) try: import_module('%s.gargoyle' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions gargoyle._registry = before_import_registry # load builtins __import__('gargoyle.builtins')
""" gargoyle ~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ __all__ = ('gargoyle', 'ConditionSet', 'autodiscover', 'VERSION') try: VERSION = __import__('pkg_resources') \ .get_distribution('gargoyle').version except Exception, e: VERSION = 'unknown' from gargoyle.manager import gargoyle def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ import copy from django.conf import settings from django.utils.importlib import import_module for app in settings.INSTALLED_APPS: # Attempt to import the app's gargoyle module. before_import_registry = copy.copy(gargoyle._registry) try: import_module('%s.gargoyle' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions gargoyle._registry = before_import_registry # load builtins __import__('gargoyle.builtins')
Remove hack for tab-key handling in Processing 2.0 - This is now fixed in Processing 2.1
package com.haxademic.core.system; import processing.core.PApplet; import com.haxademic.core.app.P; public class SystemUtil { public static String getJavaVersion() { return System.getProperty("java.version"); } public static String getTimestamp( PApplet p ) { // use P.nf to pad date components to 2 digits for more consistent ordering across systems return String.valueOf( P.year() ) + "-" + P.nf( P.month(), 2 ) + "-" + P.nf( P.day(), 2 ) + "-" + P.nf( P.hour(), 2 ) + "-" + P.nf( P.minute(), 2 ) + "-" + P.nf( P.second(), 2 ); } public static String getTimestampFine( PApplet p ) { return SystemUtil.getTimestamp(p) + "-" + P.nf( p.frameCount, 8 ); } // Patch TAB capture ability - Processing 2.0 broke this in 3D rendering contexts public static void p2TabKeyInputPatch() { // if(PJOGL.canvas != null) { PJOGL.canvas.setFocusTraversalKeysEnabled(false); } } }
package com.haxademic.core.system; import processing.core.PApplet; import processing.opengl.PGL; import com.haxademic.core.app.P; public class SystemUtil { public static String getJavaVersion() { return System.getProperty("java.version"); } public static String getTimestamp( PApplet p ) { // use P.nf to pad date components to 2 digits for more consistent ordering across systems return String.valueOf( P.year() ) + "-" + P.nf( P.month(), 2 ) + "-" + P.nf( P.day(), 2 ) + "-" + P.nf( P.hour(), 2 ) + "-" + P.nf( P.minute(), 2 ) + "-" + P.nf( P.second(), 2 ); } public static String getTimestampFine( PApplet p ) { return SystemUtil.getTimestamp(p) + "-" + P.nf( p.frameCount, 8 ); } // Patch TAB capture ability - Processing 2.0 broke this in 3D rendering contexts public static void p2TabKeyInputPatch() { if(PGL.canvas != null) { PGL.canvas.setFocusTraversalKeysEnabled(false); } } }
Make README.rst the package's long description
#!/usr/bin/env python3 from setuptools import setup setup( name='todoman', description='A simple CalDav-based todo manager.', author='Hugo Osvaldo Barrera', author_email='hugo@barrera.io', url='https://gitlab.com/hobarrera/todoman', license='MIT', packages=['todoman'], entry_points={ 'console_scripts': [ 'todo = todoman.cli:run', ] }, install_requires=[ open('requirements.txt').readlines() ], long_description=open('README.rst').read(), use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm'], # TODO: classifiers )
#!/usr/bin/env python3 from setuptools import setup setup( name='todoman', description='A simple CalDav-based todo manager.', author='Hugo Osvaldo Barrera', author_email='hugo@barrera.io', url='https://gitlab.com/hobarrera/todoman', license='MIT', packages=['todoman'], entry_points={ 'console_scripts': [ 'todo = todoman.cli:run', ] }, install_requires=[ open('requirements.txt').readlines() ], use_scm_version={'version_scheme': 'post-release'}, setup_requires=['setuptools_scm'], # TODO: classifiers )
Use items() instead of iteritems() for Python 2 and 3 compatibility
import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.items(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)
import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.iteritems(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)
Update - sáb nov 11 19:54:37 -02 2017
--- layout: null --- jQuery(document).ready(function($) { if (navigator.vendor == "" || navigator.vendor == undefined) { function show_alert(){ alert("This Browser is not printable with this page. If you print with Ctrl + P, errors will appear in the page structure. We recommend 'Google Chrome' or 'Safari'. \n\n(Este Navegador não é compátivel com impressão desta página. Caso imprima com Ctrl+P, aparecerá erros na estrutura da página. Recomendamos o 'Google Chrome' ou 'Safari'.)"); return false; } function verifyButtonCtrl(oEvent){ var oEvent = oEvent ? oEvent : window.event; var tecla = (oEvent.keyCode) ? oEvent.keyCode : oEvent.which; if(tecla == 17 || tecla == 44|| tecla == 106){ show_alert(); } } document.onkeypress = verifyButtonCtrl; document.onkeydown = verifyButtonCtrl; $("#btn-print").click(function() { show_alert(); }); } else { $("#btn-print").click(function() { window.print(); return false; }); } /* Method 2: */ /* var isFirefox = /^((?!chrome|android).)*firefox/i.test(navigator.userAgent); */ /*if (isFirefox == true) { alert("incompatible"); } */ });
--- layout: null --- jQuery(document).ready(function($) { /* Method 2: */ /* var isFirefox = /^((?!chrome|android).)*firefox/i.test(navigator.userAgent); */ $("#btn-print").click(function() { /* Method 1:*/ if (navigator.vendor == "" || navigator.vendor == undefined) { alert("This Browser is not printable with this page. If you print with Ctrl + P, errors will appear in the page structure. We recommend 'Google Chrome' or 'Safari'. \n\n(Este Navegador não é compátivel com impressão desta página. Caso imprima com Ctrl+P, aparecerá erros na estrutura da página. Recomendamos o 'Google Chrome' ou 'Safari'.)"); } else{ window.print(); return false; } /* Method 2: */ /*if (isFirefox == true) { alert("This Browser is not printable with this page. If you print with Ctrl + P, errors will appear in the page structure. We recommend 'Google Chrome' or 'Safari'. \n\n(Este Navegador não é compátivel com impressão desta página. Caso imprima com Ctrl+P, aparecerá erros na estrutura da página. Recomendamos o 'Google Chrome' ou 'Safari'.)"); } else { window.print(); return false; }*/ }); });
Set URL to github one.
# -*- coding: utf-8 -*- import os from setuptools import setup from setuptools.dist import Distribution with open(os.path.join(os.path.dirname(__file__), 'README')) as f: doc = f.read() class BinaryDistribution(Distribution): def is_pure(self): return False setup( name='json-stream', version='1.0.1', url='https://github.com/fireteam/python-json-stream', license='BSD', author='Fireteam Ltd.', author_email='info@fireteam.net', description='A small wrapper around YAJL\'s lexer', long_description=doc, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ], packages=['jsonstream'], include_package_data=True, distclass=BinaryDistribution, )
# -*- coding: utf-8 -*- import os from setuptools import setup from setuptools.dist import Distribution with open(os.path.join(os.path.dirname(__file__), 'README')) as f: doc = f.read() class BinaryDistribution(Distribution): def is_pure(self): return False setup( name='json-stream', version='1.0.1', url='http://fireteam.net/', license='BSD', author='Fireteam Ltd.', author_email='info@fireteam.net', description='A small wrapper around YAJL\'s lexer', long_description=doc, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ], packages=['jsonstream'], include_package_data=True, distclass=BinaryDistribution, )
Set praise list as home
"""pronto_praise URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('praises.urls')), ]
"""pronto_praise URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^praises/', include('praises.urls')), ]
Add log error if we run salt-api w/ no config Currently, the salt-api script will exit with no error or hint of why it failed if there is no netapi module configured. Added a short line if we find no api modules to start, warning the user that the config may be missing. Fixes #28240
# encoding: utf-8 ''' The main entry point for salt-api ''' from __future__ import absolute_import # Import python libs import logging # Import salt-api libs import salt.loader import salt.utils.process logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts self.process_manager = salt.utils.process.ProcessManager() self.netapi = salt.loader.netapi(self.opts) def run(self): ''' Load and start all available api modules ''' if not len(self.netapi): logger.error("Did not find any netapi configurations, nothing to start") for fun in self.netapi: if fun.endswith('.start'): logger.info('Starting {0} netapi module'.format(fun)) self.process_manager.add_process(self.netapi[fun]) self.process_manager.run()
# encoding: utf-8 ''' The main entry point for salt-api ''' from __future__ import absolute_import # Import python libs import logging # Import salt-api libs import salt.loader import salt.utils.process logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ''' def __init__(self, opts): self.opts = opts self.process_manager = salt.utils.process.ProcessManager() self.netapi = salt.loader.netapi(self.opts) def run(self): ''' Load and start all available api modules ''' for fun in self.netapi: if fun.endswith('.start'): logger.info('Starting {0} netapi module'.format(fun)) self.process_manager.add_process(self.netapi[fun]) self.process_manager.run()
Fix assessment metadata state for exercises
import { assessmentMetaDataState } from 'kolibri.coreVue.vuex.mappers'; export function SET_LESSON_CONTENTNODES(state, contentNodes) { state.pageState.contentNodes = [...contentNodes]; } export function SET_CURRENT_LESSON(state, lesson) { state.pageState.currentLesson = { ...lesson }; } export function SET_LEARNER_CLASSROOMS(state, classrooms) { state.pageState.classrooms = [...classrooms]; } export function SET_CURRENT_CLASSROOM(state, classroom) { state.pageState.currentClassroom = { ...classroom }; } export function SET_CURRENT_AND_NEXT_LESSON_RESOURCES(state, resources) { const firstResource = { ...resources[0] }; // HACK: duck-typing the pageState to work with content-page as-is state.pageState.content = { ...firstResource, id: firstResource.pk, ...assessmentMetaDataState(firstResource), }; // Needed for the content renderer to work if (resources[1]) { state.pageState.nextLessonResource = { ...resources[1] }; } else { state.pageState.nextLessonResource = null; } }
export function SET_LESSON_CONTENTNODES(state, contentNodes) { state.pageState.contentNodes = [...contentNodes]; } export function SET_CURRENT_LESSON(state, lesson) { state.pageState.currentLesson = { ...lesson }; } export function SET_LEARNER_CLASSROOMS(state, classrooms) { state.pageState.classrooms = [...classrooms]; } export function SET_CURRENT_CLASSROOM(state, classroom) { state.pageState.currentClassroom = { ...classroom }; } export function SET_CURRENT_AND_NEXT_LESSON_RESOURCES(state, resources) { const firstResource = { ...resources[0] }; // HACK: duck-typing the pageState to work with content-page as-is state.pageState.content = { ...firstResource, id: firstResource.pk }; if (resources[1]) { state.pageState.nextLessonResource = { ...resources[1] }; } else { state.pageState.nextLessonResource = null; } }
Remove deprecated SL 'syntax' property override Replaced by 'defaults/selector': http://www.sublimelinter.com/en/stable/linter_settings.html#selector
# # linter.py # Markdown Linter for SublimeLinter, a code checking framework # for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class MarkdownLint(NodeLinter): """Provides an interface to markdownlint.""" defaults = { 'selector': 'text.html.markdown,' 'text.html.markdown.multimarkdown,' 'text.html.markdown.extended,' 'text.html.markdown.gfm' } cmd = ('markdownlint', '${args}', '${file}') npm_name = 'markdownlint' config_file = ('--config', '.markdownlintrc') regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)' multiline = False line_col_base = (1, 1) tempfile_suffix = '-' error_stream = util.STREAM_STDERR word_re = None comment_re = r'\s*/[/*]'
# # linter.py # Markdown Linter for SublimeLinter, a code checking framework # for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class MarkdownLint(NodeLinter): """Provides an interface to markdownlint.""" syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended') cmd = ('markdownlint', '${args}', '${file}') npm_name = 'markdownlint' config_file = ('--config', '.markdownlintrc') regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)' multiline = False line_col_base = (1, 1) tempfile_suffix = '-' error_stream = util.STREAM_STDERR word_re = None comment_re = r'\s*/[/*]'
Move AWS_ setting imports under the check for AmazonS3 so Norc doesn't break without them.
import os from norc.settings import NORC_LOG_DIR, BACKUP_SYSTEM if BACKUP_SYSTEM == 'AmazonS3': from norc.norc_utils.aws import set_s3_key from norc.settings import (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_BUCKET_NAME) def s3_backup(fp, target): NUM_TRIES = 3 for i in range(NUM_TRIES): try: set_s3_key(target, fp) return True except: if i == NUM_TRIES - 1: raise return False BACKUP_SYSTEMS = { 'AmazonS3': s3_backup, } def backup_log(rel_log_path): log_path = os.path.join(NORC_LOG_DIR, rel_log_path) log_file = open(log_path, 'rb') target = os.path.join('norc_logs/', rel_log_path) try: return _backup_file(log_file, target) finally: log_file.close() def _backup_file(fp, target): if BACKUP_SYSTEM: return BACKUP_SYSTEMS[BACKUP_SYSTEM](fp, target) else: return False
import os from norc.settings import (NORC_LOG_DIR, BACKUP_SYSTEM, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_BUCKET_NAME) if BACKUP_SYSTEM == 'AmazonS3': from norc.norc_utils.aws import set_s3_key def s3_backup(fp, target): NUM_TRIES = 3 for i in range(NUM_TRIES): try: set_s3_key(target, fp) return True except: if i == NUM_TRIES - 1: raise return False BACKUP_SYSTEMS = { 'AmazonS3': s3_backup, } def backup_log(rel_log_path): log_path = os.path.join(NORC_LOG_DIR, rel_log_path) log_file = open(log_path, 'rb') target = os.path.join('norc_logs/', rel_log_path) try: return _backup_file(log_file, target) finally: log_file.close() def _backup_file(fp, target): if BACKUP_SYSTEM: return BACKUP_SYSTEMS[BACKUP_SYSTEM](fp, target) else: return False
Allow a specific address to be specified for sending
""" Client/Source Generates and sends E1.31 packets over UDP """ import socket import struct from packet import E131Packet def ip_from_universe(universe): # derive multicast IP address from Universe high_byte = (universe >> 8) & 0xff low_byte = universe & 0xff return "239.255.{}.{}".format(high_byte, low_byte) class DMXSource(object): """ bind_ip is the IP address assigned to a specific HW interface """ def __init__(self, universe=1, network_segment=1, bind_ip=None): self.universe = universe self.ip = ip_from_universe(universe) # open UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if bind_ip: self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(bind_ip)) # set ttl to limit network segment reach ttl = struct.pack('b', network_segment) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) def send_data(self, data): packet = E131Packet(universe=self.universe, data=data) self.sock.sendto(packet.packet_data, (self.ip, 5568))
""" Client/Source Generates and sends E1.31 packets over UDP """ import socket import struct from packet import E131Packet def ip_from_universe(universe): # derive multicast IP address from Universe high_byte = (universe >> 8) & 0xff low_byte = universe & 0xff return "239.255.{}.{}".format(high_byte, low_byte) class DMXSource(object): def __init__(self, universe=1, network_segment=1): self.universe = universe self.ip = ip_from_universe(universe) # open UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # set ttl to limit network segment reach ttl = struct.pack('b', network_segment) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) def send_data(self, data): packet = E131Packet(universe=self.universe, data=data) self.sock.sendto(packet.packet_data, (self.ip, 5568))
Fix timeout issue sending invoice email Xero has recently started return a `411 Length Required` response when a send email request is made. This commit adds the missing header.
<?php namespace XeroPHP\Traits; use XeroPHP\Remote\URL; use XeroPHP\Remote\Request; trait SendEmailTrait { public function sendEmail() { /** * Allows the document to be sent by email to the customer * currently only availbale for Invoices. * Invoice status should be SUBMITTED, AUTHORISED or PAID. * The email address for the Contact should also be set. * * Documentation here: * https://developer.xero.com/documentation/api/invoices#email * * @var \XeroPHP\Remote\Model */ $uri = sprintf('%s/%s/Email', $this::getResourceURI(), $this->getGUID()); $url = new URL($this->_application, $uri); $request = new Request($this->_application, $url, Request::METHOD_POST); $request->setBody(''); $request->send(); return $this; } }
<?php namespace XeroPHP\Traits; use XeroPHP\Remote\URL; use XeroPHP\Remote\Request; trait SendEmailTrait { public function sendEmail() { /** * Allows the document to be sent by email to the customer * currently only availbale for Invoices. * Invoice status should be SUBMITTED, AUTHORISED or PAID. * The email address for the Contact should also be set. * * Documentation here: * https://developer.xero.com/documentation/api/invoices#email * * @var \XeroPHP\Remote\Model */ $uri = sprintf('%s/%s/Email', $this::getResourceURI(), $this->getGUID()); $url = new URL($this->_application, $uri); $request = new Request($this->_application, $url, Request::METHOD_POST); $request->send(); return $this; } }
Add parse_var methode to the RustParser
var DocsParser = require("../docsparser"); var xregexp = require('../xregexp').XRegExp; function RustParser(settings) { DocsParser.call(this, settings); } RustParser.prototype = Object.create(DocsParser.prototype); RustParser.prototype.setup_settings = function() { this.settings = { 'curlyTypes': false, 'typeInfo': false, 'typeTag': false, 'varIdentifier': '.*', 'fnIdentifier': '.*', 'fnOpener': '^\\s*fn', 'commentCloser': ' */', 'bool': 'Boolean', 'function': 'Function' }; }; RustParser.prototype.parse_function = function(line) { var regex = xregexp('\\s*fn\\s+(?P<name>\\S+)'); var matches = xregexp.exec(line, regex); if(matches === null) return null; var name = [].join(matches.name); return [ name, []]; }; RustParser.prototype.parse_var = function(line) { return null; }; RustParser.prototype.format_function = function(name, args) { return name; }; module.exports = RustParser;
var DocsParser = require("../docsparser"); var xregexp = require('../xregexp').XRegExp; function RustParser(settings) { DocsParser.call(this, settings); } RustParser.prototype = Object.create(DocsParser.prototype); RustParser.prototype.setup_settings = function() { this.settings = { 'curlyTypes': false, 'typeInfo': false, 'typeTag': false, 'varIdentifier': '.*', 'fnIdentifier': '.*', 'fnOpener': '^\\s*fn', 'commentCloser': ' */', 'bool': 'Boolean', 'function': 'Function' }; }; RustParser.prototype.parse_function = function(line) { var regex = xregexp('\\s*fn\\s+(?P<name>\\S+)'); var matches = xregexp.exec(line, regex); if(matches === null) return null; var name = [].join(matches.name); return [ name, []]; }; RustParser.prototype.format_function = function(name, args) { return name; }; module.exports = RustParser;
Add info and error messages
const fs = require('fs'); const chalk = require('chalk'); const helpers = require('../helpers'); const settingsFilePath = 'settingsData.json'; function getSettings() { if (fs.existsSync(settingsFilePath)) { let data = fs.readFileSync(settingsFilePath); return JSON.parse(data); } return {}; } function update(argv) { let settingsData = getSettings(); let settingsDataUpdate = Object.create(settingsData); if (argv.timezone) { settingsDataUpdate.timezone = argv.timezone; } let settingsJSON = JSON.stringify(settingsDataUpdate); if (settingsData.timezone !== settingsDataUpdate.timezone) { return fs.writeFile(settingsFilePath, settingsJSON, (error) => { if (error) { return helpers.printError(error.message); } let message = chalk.bgGreen('Success!') + ' ' + 'The file has been saved!'; helpers.printMessage(message); }); } let message = chalk.bgGreen('OK') + ' ' + 'Settings are correct, no changes required.'; return helpers.printMessage(message); }; module.exports = { getSettings, update };
const fs = require('fs'); const helpers = require('../helpers'); const settingsFilePath = 'settingsData.json' function getSettings() { if (fs.existsSync(settingsFilePath)) { let data = fs.readFileSync(settingsFilePath); return JSON.parse(data); } return {}; } function update(argv) { let settingsData = getSettings(); let settingsDataUpdate = Object.create(settingsData); if (argv.timezone) { settingsDataUpdate.timezone = argv.timezone; } let settingsJSON = JSON.stringify(settingsDataUpdate); if (settingsData.timezone !== settingsDataUpdate.timezone) { fs.writeFile(settingsFilePath, settingsJSON, (err) => { if (err) throw err; helpers.printMessage('The file has been saved!'); }); } }; module.exports = { getSettings, update };
Simplify arguments passed to exec.
var gulp = require("gulp"); var CFG = require("./utils/config.js"); var $ = require("gulp-load-plugins")(); var exec = require("child_process").exec; var path = require("path"); var notify = require("./utils/notify-style-lint"); /** * style:lint * @see github.com/causes/scss-lint * @see rubygems.org/gems/scss-lint */ gulp.task("style:lint", function (callback) { var scsslintProcess = exec([ "bundle", "exec", "scss-lint", "--config", path.join(CFG.FILE.config.styleLint), path.join(CFG.DIR.src, CFG.DIR.style) ].join(" "), function(err, stdout, stderr) { $.util.log("[style:lint] stdout:", stdout); $.util.log("[style:lint] stderr: ", stderr); notify(stdout); if(null !== err) { $.util.log("[style:lint] err: ", err); } callback(); }); });
var gulp = require("gulp"); var CFG = require("./utils/config.js"); var $ = require("gulp-load-plugins")(); var exec = require("child_process").exec; var path = require("path"); var notify = require("./utils/notify-style-lint"); /** * style:lint * @see github.com/causes/scss-lint * @see rubygems.org/gems/scss-lint */ gulp.task("style:lint", function (callback) { var scsslintProcess = exec("bundle " + [ "exec", "scss-lint", "--config", path.join(CFG.FILE.config.styleLint), path.join(CFG.DIR.src, CFG.DIR.style) ].join(" "), function(err, stdout, stderr) { $.util.log("[style:lint] stdout:", stdout); $.util.log("[style:lint] stderr: ", stderr); notify(stdout); if(null !== err) { $.util.log("[style:lint] err: ", err); } callback(); }); });
Update page titles on Lessons.
import Passthrough from 'components/shared/passthrough.jsx'; import { getParameterByName } from 'libs/getParameterByName'; const playRoute = { path: ':lessonID', onEnter: (nextState, replaceWith) => { document.title = 'Quill Lessons'; }, getComponent: (nextState, cb) => { System.import(/* webpackChunkName: "teach-classroom-lesson" */'components/classroomLessons/play/container.tsx') .then((component) => { cb(null, component.default); }); }, }; const indexRoute = { component: Passthrough, onEnter: (nextState, replaceWith) => { const classroom_activity_id = getParameterByName('classroom_activity_id'); const lessonID = getParameterByName('uid'); document.title = 'Quill Lessons'; const student = getParameterByName('student'); if (lessonID) { document.location.href = `${document.location.origin + document.location.pathname}#/play/class-lessons/${lessonID}?student=${student}&classroom_activity_id=${classroom_activity_id}`; } }, }; const route = { path: 'class-lessons', indexRoute, childRoutes: [ playRoute ], component: Passthrough, }; export default route;
import Passthrough from 'components/shared/passthrough.jsx'; import { getParameterByName } from 'libs/getParameterByName'; const playRoute = { path: ':lessonID', getComponent: (nextState, cb) => { System.import(/* webpackChunkName: "teach-classroom-lesson" */'components/classroomLessons/play/container.tsx') .then((component) => { cb(null, component.default); }); }, }; const indexRoute = { component: Passthrough, onEnter: (nextState, replaceWith) => { const classroom_activity_id = getParameterByName('classroom_activity_id'); const lessonID = getParameterByName('uid'); const student = getParameterByName('student'); if (lessonID) { document.location.href = `${document.location.origin + document.location.pathname}#/play/class-lessons/${lessonID}?student=${student}&classroom_activity_id=${classroom_activity_id}`; } }, }; const route = { path: 'class-lessons', indexRoute, childRoutes: [ playRoute ], component: Passthrough, }; export default route;
Fix extension to work with latest state changes Refs flarum/core#2150.
import { extend } from 'flarum/extend'; import LinkButton from 'flarum/components/LinkButton'; import IndexPage from 'flarum/components/IndexPage'; import DiscussionListState from 'flarum/states/DiscussionListState'; export default function addSubscriptionFilter() { extend(IndexPage.prototype, 'navItems', function(items) { if (app.session.user) { const params = this.stickyParams(); params.filter = 'following'; items.add('following', LinkButton.component({ href: app.route('index.filter', params), children: app.translator.trans('flarum-subscriptions.forum.index.following_link'), icon: 'fas fa-star' }), 50); } }); extend(IndexPage.prototype, 'config', function () { if (m.route() == "/following") { app.setTitle(app.translator.trans('flarum-subscriptions.forum.following.meta_title_text')); } }); extend(DiscussionListState.prototype, 'requestParams', function(params) { if (this.params.filter === 'following') { params.filter.q = (params.filter.q || '') + ' is:following'; } }); }
import { extend } from 'flarum/extend'; import LinkButton from 'flarum/components/LinkButton'; import IndexPage from 'flarum/components/IndexPage'; import DiscussionList from 'flarum/components/DiscussionList'; export default function addSubscriptionFilter() { extend(IndexPage.prototype, 'navItems', function(items) { if (app.session.user) { const params = this.stickyParams(); params.filter = 'following'; items.add('following', LinkButton.component({ href: app.route('index.filter', params), children: app.translator.trans('flarum-subscriptions.forum.index.following_link'), icon: 'fas fa-star' }), 50); } }); extend(IndexPage.prototype, 'config', function () { if (m.route() == "/following") { app.setTitle(app.translator.trans('flarum-subscriptions.forum.following.meta_title_text')); } }); extend(DiscussionList.prototype, 'requestParams', function(params) { if (this.props.params.filter === 'following') { params.filter.q = (params.filter.q || '') + ' is:following'; } }); }
Update node-notifier initialization as per the new version.
var notifier = new require("node-notifier"); var extend = require("extend"); var path = require("path"); var CFG = require("./config.js"); var pkg = require(path.join("..", "..", CFG.FILE.config.pkg)); module.exports = { defaults: { title: pkg.name }, showNotification: function (options) { extend(options, this.defaults); if("undefined" !== typeof(process.env.REMEMBER_CI)) { // Running inside a CI environment, do not show notifications console.log("[notification]", options.message); } else { // Running inside a non-CI environment, okay to show notifications notifier.notify(options); } }, appIcon: { sass: __dirname + "/asset/image/sass-logo.png", karma: __dirname + "/asset/image/karma-logo.png" } };
var notifier = new require("node-notifier")({}); var extend = require("extend"); var path = require("path"); var CFG = require("./config.js"); var pkg = require(path.join("..", "..", CFG.FILE.config.pkg)); module.exports = { defaults: { title: pkg.name }, showNotification: function (options) { extend(options, this.defaults); if("undefined" !== typeof(process.env.REMEMBER_CI)) { // Running inside a CI environment, do not show notifications console.log("[notification]", options.message); } else { // Running inside a non-CI environment, okay to show notifications notifier.notify(options); } }, appIcon: { sass: __dirname + "/asset/image/sass-logo.png", karma: __dirname + "/asset/image/karma-logo.png" } };
Remove obsolete passed argument in config() call … and reuse already instantiated config object variable
<?php namespace Drubo\EventSubscriber; use Drubo\DruboAwareTrait; use Symfony\Component\Console\Event\ConsoleCommandEvent; /** * Event subscriber: Console command. */ class ConsoleCommandSubscriber { use DruboAwareTrait; /** * Check whether a console command is disabled. * * @param \Symfony\Component\Console\Event\ConsoleCommandEvent $event * An event object. */ public function onCheckDisabledState(ConsoleCommandEvent $event) { $config = $this->config(); $key = 'commands.' . $event->getCommand()->getName() . '.disabled'; // Command status configuration exists? if ($config->has($key)) { $access = $config->get($key); // Command is disabled? if ($access === TRUE) { throw new \RuntimeException('Command is disabled'); } } } /** * Check whether a console command requires an environment. * * @param \Symfony\Component\Console\Event\ConsoleCommandEvent $event * An event object. */ public function onCheckEnvironmentIsRequired(ConsoleCommandEvent $event) { $environment = $this->environment()->get(); // Environment is required, but not set? if (empty($environment) && $this->drubo()->commandRequiresEnvironment($event->getCommand()->getName())) { throw new \RuntimeException('Environment is missing'); } } }
<?php namespace Drubo\EventSubscriber; use Drubo\DruboAwareTrait; use Symfony\Component\Console\Event\ConsoleCommandEvent; /** * Event subscriber: Console command. */ class ConsoleCommandSubscriber { use DruboAwareTrait; /** * Check whether a console command is disabled. * * @param \Symfony\Component\Console\Event\ConsoleCommandEvent $event * An event object. */ public function onCheckDisabledState(ConsoleCommandEvent $event) { $config = $this->config($this->environment()->get()); $key = 'commands.' . $event->getCommand()->getName() . '.disabled'; // Command status configuration exists? if ($config->has($key)) { $access = $this->config($this->environment()->get()) ->get($key); // Command is disabled? if ($access === TRUE) { throw new \RuntimeException('Command is disabled'); } } } /** * Check whether a console command requires an environment. * * @param \Symfony\Component\Console\Event\ConsoleCommandEvent $event * An event object. */ public function onCheckEnvironmentIsRequired(ConsoleCommandEvent $event) { $environment = $this->environment()->get(); // Environment is required, but not set? if (empty($environment) && $this->drubo()->commandRequiresEnvironment($event->getCommand()->getName())) { throw new \RuntimeException('Environment is missing'); } } }
Fix timezone difference with travis.
import datetime from decimal import Decimal from mock import Mock import ubersmith.order # TODO: setup/teardown module with default request handler # TODO: mock out requests library vs mocking out request handler def test_order_list(): handler = Mock() response = { "60": { "client_id": "50", "activity": "1272400333", "ts": "1272400333", "total": "33.22", "order_id": "60", }, } handler.process_request.return_value = response expected = { 60: { u'client_id': 50, u'activity': datetime.datetime.fromtimestamp(float("1272400333")), u'ts': datetime.datetime.fromtimestamp(float("1272400333")), u'total': Decimal('33.22'), u'order_id': 60, } } result = ubersmith.order.list(client_id=50, request_handler=handler) assert expected == result
import datetime from decimal import Decimal from mock import Mock import ubersmith.order # TODO: setup/teardown module with default request handler # TODO: mock out requests library vs mocking out request handler def test_order_list(): handler = Mock() response = { "60": { "client_id": "50", "activity": "1272400333", "ts": "1272400333", "total": "33.22", "order_id": "60", }, } handler.process_request.return_value = response expected = { 60: { u'client_id': 50, u'activity': datetime.datetime(2010, 4, 27, 16, 32, 13), u'ts': datetime.datetime(2010, 4, 27, 16, 32, 13), u'total': Decimal('33.22'), u'order_id': 60, } } result = ubersmith.order.list(client_id=50, request_handler=handler) assert expected == result
Remove unsupported tags in php 5.3
<?php namespace alroniks\dtms\Test; use alroniks\dtms\DateInterval; class DateIntervalTest extends \PHPUnit_Framework_TestCase { public function setUp() { } public function tearDown() { } public function providerIntervalSpec() { } /** * @covers DateInterval::__construct * @param $intervalSpec Interval specification */ public function testConstruct() { // normal DateInterval $interval = new DateInterval('PT2S'); $this->assertInstanceOf('alroniks\\dtms\\DateInterval', $interval); $this->assertEquals('PT2S', $interval->format('PT%sS')); // with microseconds $interval = new DateInterval('PT2.2S'); $this->assertInstanceOf('alroniks\\dtms\\DateInterval', $interval); $this->assertEquals('PT2.200000S', $interval->format('PT%sS')); } }
<?php namespace alroniks\dtms\Test; use alroniks\dtms\DateInterval; class DateIntervalTest extends \PHPUnit_Framework_TestCase { public function setUp() { } public function tearDown() { } public function providerIntervalSpec() { return [ '' => '' ]; } /** * @covers DateInterval::__construct * @param $intervalSpec Interval specification */ public function testConstruct() { // normal DateInterval $interval = new DateInterval('PT2S'); $this->assertInstanceOf('alroniks\\dtms\\DateInterval', $interval); $this->assertEquals('PT2S', $interval->format('PT%sS')); // with microseconds $interval = new DateInterval('PT2.2S'); $this->assertInstanceOf('alroniks\\dtms\\DateInterval', $interval); $this->assertEquals('PT2.200000S', $interval->format('PT%sS')); } // public function testConstructWithSpec($intervalSpec) // { //// $interval = new DateInterval($intervalSpec); //// //// $this->assertEquals($intervalSpec->format('PT')); // } }
Allow script to be invoke from any directory
#!/usr/bin/env node var recast = require('recast'); var messages = require('./transform/messages'); var exec = require('child_process').exec; var fs = require('fs'); var glob = require('glob'); var usage = [ 'Usage: assertion-messages.js "globbing expression"', 'To generate assertion messages for a set of test files, provide a valid glob expression.', 'File search is relative to the `test/` sub-directory of the local', 'Test262 repository' ].join('\n'); var gexpr = process.argv[2]; if (!gexpr) { console.log(usage); return; } glob(__dirname + '/../test262/test/' + gexpr, function(err, list) { list.forEach(function(file) { var source = fs.readFileSync(file, 'utf8'); try { var ast = recast.parse(source); var result = messages(ast); fs.writeFileSync(file, recast.print(ast).code, 'utf8'); } catch (e) { console.log("failed: ", file); } }); });
#!/usr/bin/env node var recast = require('recast'); var messages = require('./transform/messages'); var exec = require('child_process').exec; var fs = require('fs'); var glob = require('glob'); var usage = [ 'Usage: assertion-messages.js "globbing expression"', 'To generate assertion messages for a set of test files, provide a valid glob expression.', 'File search begins at `../test262/test/`' ].join('\n'); var gexpr = process.argv[2]; if (!gexpr) { console.log(usage); return; } glob('../test262/test/' + gexpr, function(err, list) { list.forEach(function(file) { var source = fs.readFileSync(file, 'utf8'); try { var ast = recast.parse(source); var result = messages(ast); fs.writeFileSync(file, recast.print(ast).code, 'utf8'); } catch (e) { console.log("failed: ", file); } }); });
Fix floating IP unit test.
from django.test import TestCase from .. import factories class FloatingIpHandlersTest(TestCase): def test_floating_ip_count_quota_increases_on_floating_ip_creation(self): tenant = factories.TenantFactory() factories.FloatingIPFactory( service_project_link=tenant.service_project_link, tenant=tenant, status='UP') self.assertEqual(tenant.quotas.get(name='floating_ip_count').usage, 1) def test_floating_ip_count_quota_changes_on_floating_ip_status_change(self): tenant = factories.TenantFactory() floating_ip = factories.FloatingIPFactory( service_project_link=tenant.service_project_link, tenant=tenant, status='DOWN') self.assertEqual(tenant.quotas.get(name='floating_ip_count').usage, 0) floating_ip.status = 'UP' floating_ip.save() self.assertEqual(tenant.quotas.get(name='floating_ip_count').usage, 1) floating_ip.status = 'DOWN' floating_ip.save() self.assertEqual(tenant.quotas.get(name='floating_ip_count').usage, 0)
from django.test import TestCase from .. import factories class FloatingIpHandlersTest(TestCase): def test_floating_ip_count_quota_increases_on_floating_ip_creation(self): tenant = factories.TenantFactory() factories.FloatingIPFactory(service_project_link=tenant.service_project_link, status='UP') self.assertEqual(tenant.quotas.get(name='floating_ip_count').usage, 1) def test_floating_ip_count_quota_changes_on_floating_ip_status_change(self): tenant = factories.TenantFactory() floating_ip = factories.FloatingIPFactory(service_project_link=tenant.service_project_link, status='DOWN') self.assertEqual(tenant.quotas.get(name='floating_ip_count').usage, 0) floating_ip.status = 'UP' floating_ip.save() self.assertEqual(tenant.quotas.get(name='floating_ip_count').usage, 1) floating_ip.status = 'DOWN' floating_ip.save() self.assertEqual(tenant.quotas.get(name='floating_ip_count').usage, 0)
Use core enums for event
<?php /** * @package plugins.bpmEventNotificationIntegration * @subpackage lib.events */ class kBpmEventNotificationIntegrationFlowManager implements kBatchJobStatusEventConsumer { /* (non-PHPdoc) * @see kBatchJobStatusEventConsumer::updatedJob() */ public function updatedJob(BatchJob $dbBatchJob) { $data = $dbBatchJob->getData(); /* @var $data kIntegrationJobData */ $triggerData = $data->getTriggerData(); /* @var $triggerData kBpmEventNotificationIntegrationJobTriggerData */ $template = EventNotificationTemplatePeer::retrieveByPK($triggerData->getTemplateId()); /* @var $template BusinessProcessNotificationTemplate */ $template->setCaseId($dbBatchJob, $triggerData->getCaseId()); } /* (non-PHPdoc) * @see kBatchJobStatusEventConsumer::shouldConsumeJobStatusEvent() */ public function shouldConsumeJobStatusEvent(BatchJob $dbBatchJob) { if( $dbBatchJob->getJobType() == IntegrationPlugin::getBatchJobTypeCoreValue(IntegrationBatchJobType::INTEGRATION) && $dbBatchJob->getStatus() == BatchJob::BATCHJOB_STATUS_DONT_PROCESS && $dbBatchJob->getData()->getTriggerType() == BpmEventNotificationIntegrationPlugin::getIntegrationTriggerCoreValue(BpmEventNotificationIntegrationTrigger::BPM_EVENT_NOTIFICATION) ) { return true; } return false; } }
<?php /** * @package plugins.bpmEventNotificationIntegration * @subpackage lib.events */ class kBpmEventNotificationIntegrationFlowManager implements kBatchJobStatusEventConsumer { /* (non-PHPdoc) * @see kBatchJobStatusEventConsumer::updatedJob() */ public function updatedJob(BatchJob $dbBatchJob) { $data = $dbBatchJob->getData(); /* @var $data kIntegrationJobData */ $triggerData = $data->getTriggerData(); /* @var $triggerData kBpmEventNotificationIntegrationJobTriggerData */ $template = EventNotificationTemplatePeer::retrieveByPK($triggerData->getTemplateId()); /* @var $template BusinessProcessNotificationTemplate */ $template->setCaseId($dbBatchJob, $triggerData->getCaseId()); } /* (non-PHPdoc) * @see kBatchJobStatusEventConsumer::shouldConsumeJobStatusEvent() */ public function shouldConsumeJobStatusEvent(BatchJob $dbBatchJob) { if( $dbBatchJob->getJobType() == IntegrationPlugin::getBatchJobTypeCoreValue(IntegrationBatchJobType::INTEGRATION) && $dbBatchJob->getStatus() == KalturaBatchJobStatus::BATCHJOB_STATUS_DONT_PROCESS && $dbBatchJob->getData()->getTriggerType() == BpmEventNotificationIntegrationPlugin::getIntegrationTriggerCoreValue(BpmEventNotificationIntegrationTrigger::BPM_EVENT_NOTIFICATION) ) { return true; } return false; } }
Change the write method for the responses to pass in the http response object.
/** * The authenticate module is responsible to getting the authorization header from the request and attaching * the token to the request. If the credentials are not supplied then the request should fail and not proceed * any further. * * @param req HTTP Request * @param res HTTP Response * @param next Callback */ var authenticate = function(req, res, next){ var Strings = require('../strings'), Response = require('./response'), tokens = require('../entities/tokens'), strings = new Strings('en'), response = new Response(), authHeader = req.headers['authorization']; function onGetToken(err, identity){ if(err){ response.write(response.STATUS_CODES.UNAUTHORIZED, JSON.stringify({ message: strings.http[response.STATUS_CODES.UNAUTHORIZED]}), res); } else { req.identity = identity; next(); } } if(authHeader){ var token = authHeader.split(/\s+/).pop()||'' id = new Buffer(token, 'base64').toString(); tokens.getById(id, onGetToken); } else { response.write(response.STATUS_CODES.UNAUTHORIZED, JSON.stringify({message: strings.group('errors').missing_credentials}), res); } }; module.exports = authenticate;
/** * The authenticate module is responsible to getting the authorization header from the request and attaching * the token to the request. If the credentials are not supplied then the request should fail and not proceed * any further. * * @param req HTTP Request * @param res HTTP Response * @param next Callback */ var authenticate = function(req, res, next){ var Strings = require('../strings'), Response = require('./response'), tokens = require('../entities/tokens'), strings = new Strings('en'), response = new Response(res), authHeader = req.headers['authorization']; function onGetToken(err, identity){ if(err){ response.write(response.STATUS_CODES.UNAUTHORIZED, strings.http[response.STATUS_CODES.UNAUTHORIZED]); } else { req.identity = identity; next(); } } if(authHeader){ var token = authHeader.split(/\s+/).pop()||'' id = new Buffer(token, 'base64').toString(); tokens.getById(id, onGetToken); } else { response.write(response.STATUS_CODES.UNAUTHORIZED, strings.group('errors').missing_credentials); } }; module.exports = authenticate;
Add close to NoSQL directory.
package org.lumongo.storage.lucene; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 java.io.IOException; public interface NosqlDirectory { public String[] getFileNames() throws IOException; public NosqlFile getFileHandle(String fileName) throws IOException; public NosqlFile getFileHandle(String fileName, boolean createIfNotFound) throws IOException; public int getBlockSize(); public void updateFileMetadata(NosqlFile nosqlFile) throws IOException; public void deleteFile(NosqlFile nosqlFile) throws IOException; public void close(); }
package org.lumongo.storage.lucene; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 java.io.IOException; public interface NosqlDirectory { public String[] getFileNames() throws IOException; public NosqlFile getFileHandle(String fileName) throws IOException; public NosqlFile getFileHandle(String fileName, boolean createIfNotFound) throws IOException; public int getBlockSize(); public void updateFileMetadata(NosqlFile nosqlFile) throws IOException; public void deleteFile(NosqlFile nosqlFile) throws IOException; }
Update error message when flask sparql app does not work
(function() { 'use strict'; function SparqlController($scope, AuthenticationService, SparqlService) { this.resultText = ''; this.errorMessage = ''; AuthenticationService.ready.then(function() { SparqlService.doQuery().then(function (result){ if( typeof(result) === 'string' ){ if( result === '' ){ this.errorMessage = 'Something went wrong. Please check that the Flask app is running on https://shrouded-gorge-9256.herokuapp.com/ Or install locally.'; } else { this.errorMessage = result; } } }.bind(this)); }.bind(this)); } angular.module('uncertApp.sparql').controller('SparqlController', SparqlController); })();
(function() { 'use strict'; function SparqlController($scope, AuthenticationService, SparqlService) { this.resultText = ''; this.errorMessage = ''; AuthenticationService.ready.then(function() { SparqlService.doQuery().then(function (result){ if( typeof(result) === 'string' ){ if( result === '' ){ this.errorMessage = 'Please check whether the Flask app is running on http://127.0.0.1:5000/'; } else { this.errorMessage = result; } } }.bind(this), function (error){ }); }.bind(this)); } angular.module('uncertApp.sparql').controller('SparqlController', SparqlController); })();
Remove superfluous / outdated throw NoRecordException
<?php namespace Bugcache\Storage\Mysql; use Amp\Mysql\Pool; use Amp\Mysql\ResultSet; use Amp\Promise; use Bugcache\Storage; use Generator; use function Amp\resolve; class UserRepository implements Storage\UserRepository { private $mysql; public function __construct(Pool $mysql) { $this->mysql = $mysql; } public function findByName(string $username): Promise { $sql = "SELECT id, name FROM users WHERE name = ?"; return resolve($this->fetchUser($sql, [$username])); } private function fetchUser(string $sql, array $params = []): Generator { /** @var ResultSet $result */ $result = yield $this->mysql->prepare($sql, $params); if (yield $result->rowCount()) { $record = yield $result->fetchObject(); return $record; } else { return (object) [ "id" => 0, "name" => "anonymous", ]; } } }
<?php namespace Bugcache\Storage\Mysql; use Amp\Mysql\Pool; use Amp\Mysql\ResultSet; use Amp\Promise; use Bugcache\Storage; use Generator; use function Amp\resolve; class UserRepository implements Storage\UserRepository { private $mysql; public function __construct(Pool $mysql) { $this->mysql = $mysql; } public function findByName(string $username): Promise { $sql = "SELECT id, name FROM users WHERE name = ?"; return resolve($this->fetchUser($sql, [$username])); } private function fetchUser(string $sql, array $params = []): Generator { /** @var ResultSet $result */ $result = yield $this->mysql->prepare($sql, $params); if (yield $result->rowCount()) { $record = yield $result->fetchObject(); return $record; } else { return (object) [ "id" => 0, "name" => "anonymous", ]; } throw new Storage\NoRecordException; } }
Create log file on run
var fs = require("fs"); var logPath = __dirname + '/eyebleach.log'; function log(msg) { var d = new Date(); var data = '[' + d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '] ' + msg; console.log(data); fs.closeSync(fs.openSync(logPath, 'w')); fs.access(logPath, fs.R_OK | fs.W_OK, function(err) { if (err) { // cant save to file throw("Cannot Save to Log File"); } else { fs.appendFile(logPath, data + '\n', 'utf8', function(err) { if (err) { throw("Cannot Append to Log File"); } }); } }); } // HAVE MY FUNCTIONS module.exports = { log: log }
var fs = require("fs"); var logPath = __dirname + '/eyebleach.log'; function log(msg) { var d = new Date(); var data = '[' + d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '] ' + msg; console.log(data); fs.access(logPath, fs.R_OK | fs.W_OK, function(err) { if (err) { // cant save to file throw("Cannot Save to Log File"); } else { fs.appendFile(logPath, data + '\n', 'utf8', function(err) { if (err) { throw("Cannot Append to Log File"); } }); } }); } // HAVE MY FUNCTIONS module.exports = { log: log }
Add Numbers and Symbols Exception
# PyArt by MohamadKh75 # 2017-10-05 # ******************** from pathlib import Path # Set the Alphabet folder path folder_path = Path("Alphabet").resolve() # Read all Capital Letters - AA is Capital A def letter_reader(letter): # if it's Capital - AA is Capital A if 65 <= ord(letter) <= 90: letter_file = open(str(folder_path) + str("\\") + str(letter) + str(letter) + ".txt", 'r') letter_txt = letter_file.read() # if it's small - a is small a elif 97 <= ord(letter) <= 122: letter_file = open(str(folder_path) + str("\\") + str(letter) + ".txt", 'r') letter_txt = letter_file.read() # if it's symbol or number - NOT SUPPORTED in Ver. 1.0 else: print("Sorry, Numbers and Symbols are NOT supported yet :)\n" "I'll Add them in Ver. 2.0") return print(letter_txt) letter_file.close()
# PyArt by MohamadKh75 # 2017-10-05 # ******************** from pathlib import Path # Set the Alphabet folder path folder_path = Path("Alphabet").resolve() # Read all Capital Letters - AA is Capital A def letter_reader(letter): # if it's Capital - AA is Capital A if 65 <= ord(letter) <= 90: letter_file = open(str(folder_path) + str("\\") + str(letter) + str(letter) + ".txt", 'r') letter_txt = letter_file.read() # if it's small - a is small a elif 97 <= ord(letter) <= 122: letter_file = open(str(folder_path) + str("\\") + str(letter) + ".txt", 'r') letter_txt = letter_file.read() # if it's symbol else: letter_file = open(str(folder_path) + str("\\") + str(letter) + ".txt", 'r') letter_txt = letter_file.read() print(letter_txt) letter_file.close()
Make link to webpack context explanation permanent
/* eslint-disable prefer-arrow-callback, func-names, class-methods-use-this */ import loader from 'graphql-tag/loader'; export default class GraphQLCompiler { processFilesForTarget(files) { // Fake webpack context // @see https://github.com/apollographql/graphql-tag/blob/57a258713acecde5ebef0c5771a975d6446703c7/loader.js#L43 const context = { cacheable() {}, }; files .forEach(file => { const path = `${file.getPathInPackage()}.js`; const content = file.getContentsAsString().trim(); try { const data = loader.call(context, content); file.addJavaScript({ data, path, }); } catch (e) { if (e.locations) { file.error({ message: e.message, line: e.locations[0].line, column: e.locations[0].column, }); return null; } throw e; } }); } }
/* eslint-disable prefer-arrow-callback, func-names, class-methods-use-this */ import loader from 'graphql-tag/loader'; export default class GraphQLCompiler { processFilesForTarget(files) { // Fake webpack context // @see https://github.com/apollographql/graphql-tag/blob/master/loader.js#L43 const context = { cacheable() {}, }; files .forEach(file => { const path = `${file.getPathInPackage()}.js`; const content = file.getContentsAsString().trim(); try { const data = loader.call(context, content); file.addJavaScript({ data, path, }); } catch (e) { if (e.locations) { file.error({ message: e.message, line: e.locations[0].line, column: e.locations[0].column, }); return null; } throw e; } }); } }
Destroy HLS source before component unmount
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Hls from 'hls.js'; const propTypes = { src: PropTypes.string.isRequired, type: PropTypes.string, video: PropTypes.object, }; export default class HLSSource extends Component { constructor(props, context) { super(props, context); this.hls = new Hls(); } componentDidMount() { // `src` is the property get from this component // `video` is the property insert from `Video` component // `video` is the html5 video element const { src, video } = this.props; // load hls video source base on hls.js if (Hls.isSupported()) { this.hls.loadSource(src); this.hls.attachMedia(video); this.hls.on(Hls.Events.MANIFEST_PARSED, () => { video.play(); }); } } componentWillUnmount() { // destroy hls video source if (this.hls) { this.hls.destroy(); } } render() { return ( <source src={this.props.src} type={this.props.type || 'application/x-mpegURL'} /> ); } } HLSSource.propTypes = propTypes;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Hls from 'hls.js'; const propTypes = { src: PropTypes.string.isRequired, type: PropTypes.string, video: PropTypes.object, }; export default class HLSSource extends Component { constructor(props, context) { super(props, context); this.hls = new Hls(); } componentDidMount() { // `src` is the property get from this component // `video` is the property insert from `Video` component // `video` is the html5 video element const { src, video } = this.props; // load hls video source base on hls.js if (Hls.isSupported()) { this.hls.loadSource(src); this.hls.attachMedia(video); this.hls.on(Hls.Events.MANIFEST_PARSED, () => { video.play(); }); } } render() { return ( <source src={this.props.src} type={this.props.type || 'application/x-mpegURL'} /> ); } } HLSSource.propTypes = propTypes;
Fix LabelPart to always report the validated set value
from annotypes import Anno from malcolm.core import Part, PartRegistrar, StringMeta from ..infos import LabelInfo from ..util import set_tags with Anno("Initial value of Block label"): ALabelValue = str class LabelPart(Part): """Part representing a the title of the Block a GUI should display""" def __init__(self, value=None): # type: (ALabelValue) -> None super(LabelPart, self).__init__("label") meta = StringMeta("Label for the block") set_tags(meta, writeable=True) self.initial_value = value self.attr = meta.create_attribute_model(self.initial_value) def _report(self): self.registrar.report(LabelInfo(self.attr.value)) def setup(self, registrar): # type: (PartRegistrar) -> None super(LabelPart, self).setup(registrar) registrar.add_attribute_model(self.name, self.attr, self.set_label) self._report() def set_label(self, value, ts=None): self.attr.set_value(value, ts=ts) self._report()
from annotypes import Anno from malcolm.core import Part, PartRegistrar, StringMeta from ..infos import LabelInfo from ..util import set_tags with Anno("Initial value of Block label"): ALabelValue = str class LabelPart(Part): """Part representing a the title of the Block a GUI should display""" def __init__(self, value=None): # type: (ALabelValue) -> None super(LabelPart, self).__init__("label") meta = StringMeta("Label for the block") set_tags(meta, writeable=True) self.initial_value = value self.attr = meta.create_attribute_model(self.initial_value) def setup(self, registrar): # type: (PartRegistrar) -> None super(LabelPart, self).setup(registrar) registrar.add_attribute_model(self.name, self.attr, self.set_label) self.registrar.report(LabelInfo(self.initial_value)) def set_label(self, value, ts=None): self.attr.set_value(value, ts=ts) self.registrar.report(LabelInfo(value))
resource: Fix Lua resource wrapper function
package resource import ( "github.com/layeh/gopher-luar" "github.com/yuin/gopher-lua" ) // LuaRegisterBuiltin registers resource providers in Lua func LuaRegisterBuiltin(L *lua.LState) { for typ, provider := range providerRegistry { // Wrap resource providers, so that we can properly handle any // errors returned by providers during resource instantiation. // Since we don't want to return the error to Lua, this is the // place where we handle any errors returned by providers. wrapper := func(p Provider) lua.LGFunction { return func(L *lua.LState) int { // Create the resource by calling it's provider r, err := p(L.CheckString(1)) if err != nil { L.RaiseError(err.Error()) } L.Push(luar.New(L, r)) return 1 // Number of arguments returned to Lua } } tbl := L.NewTable() tbl.RawSetH(lua.LString("new"), L.NewFunction(wrapper(provider))) L.SetGlobal(typ, tbl) } }
package resource import ( "github.com/layeh/gopher-luar" "github.com/yuin/gopher-lua" ) // LuaRegisterBuiltin registers resource providers in Lua func LuaRegisterBuiltin(L *lua.LState) { for typ, provider := range providerRegistry { // Wrap resource providers, so that we can properly handle any // errors returned by providers during resource instantiation. // Since we don't want to return the error to Lua, this is the // place where we handle any errors returned by providers. wrapper := func(L *lua.LState) int { r, err := provider(L.CheckString(1)) if err != nil { L.RaiseError(err.Error()) } L.Push(luar.New(L, r)) return 1 } tbl := L.NewTable() tbl.RawSetH(lua.LString("new"), L.NewFunction(wrapper)) L.SetGlobal(typ, tbl) } }
Add missing return, add eslint hint for jsx
'use babel'; /** Eval Console @description Provides a console where user can enter input in order to evaluate Go expressions within the current scope of the debugger in a REPL-esque style TODO: We will need to listen for the enter key from the input element, after hitting enter: - send to DebuggerActions.evalExpression (should return promise w/ result) - get result & write under the input (need to figure out how we're going to pretty print the resulting Go code) - disable the "spent" input element - create a new input element at the bottom of the console **/ /* eslint no-unused-vars:0 */ import { createClass as createJSX, jsx } from 'vanilla-jsx'; /** @jsx jsx */ const EvalConsoleElement = createJSX({ createEvalInput() { return <input type="text" class="delve-eval-textbox" />; }, renderView() { return ( <div class="delve-terminal-panel delve-eval-console" ref="consoleContainer"> {this.createEvalInput()} </div> ); } }); export default class EvalConsole { constructor() { this.consoleElement = new EvalConsoleElement(); this.evalConsole = this.consoleElement.render(); } getElement() { return this.evalConsole; } destroy() { this.consoleElement.dispose(); } }
'use babel'; /** Eval Console @description Provides a console where user can enter input in order to evaluate Go expressions within the current scope of the debugger in a REPL-esque style TODO: We will need to listen for the enter key from the input element, after hitting enter: - send to DebuggerActions.evalExpression (should return promise w/ result) - get result & write under the input (need to figure out how we're going to pretty print the resulting Go code) - disable the "spent" input element - create a new input element at the bottom of the console **/ import { createClass as createJSX } from 'vanilla-jsx'; /** @jsx jsx */ const EvalConsoleElement = createJSX({ createEvalInput() { return <input type="text" class="delve-eval-textbox" />; }, renderView() { return ( <div class="delve-terminal-panel delve-eval-console" ref="consoleContainer"> {this.createEvalInput()} </div> ); } }); export default class EvalConsole { constructor() { this.consoleElement = new EvalConsoleElement(); this.evalConsole = this.consoleElement.render(); } getElement() { this.evalConsole.element; } destroy() { this.consoleElement.dispose(); } }
Update negative price exception test to use assertRaises.
import unittest from datetime import datetime from stock import Stock class StockTest(unittest.TestCase): def test_new_stock_price(self): """A new stock should have a price that is None. """ stock = Stock("GOOG") self.assertIsNone(stock.price) def test_stock_update(self): """An update should set the price on the stock object. Notes: We will be using the `datetime` module for the timestamp. """ stock = Stock("GOOG") stock.update(datetime(2014, 2, 12), price=10) self.assertEqual(10, stock.price) def test_negative_price_exception(self): """An update with a negative price should return a value error. """ stock = Stock("GOOG") self.assertRaises(ValueError, stock.update, datetime(2014, 2, 13), -10) if __name__ == "__main__": unittest.main()
import unittest from datetime import datetime from stock import Stock class StockTest(unittest.TestCase): def test_new_stock_price(self): """A new stock should have a price that is None. """ stock = Stock("GOOG") self.assertIsNone(stock.price) def test_stock_update(self): """An update should set the price on the stock object. Notes: We will be using the `datetime` module for the timestamp. """ stock = Stock("GOOG") stock.update(datetime(2014, 2, 12), price=10) self.assertEqual(10, stock.price) def test_negative_price_exception(self): """An update with a negative price should return a value error. """ stock = Stock("GOOG") try: stock.update(datetime(2014, 2, 12), price=-10) except ValueError: return self.fail("ValueError was not raised") if __name__ == "__main__": unittest.main()
Change source encoding from euckr to cp949
'use strict'; var request = require('request'); var iconv = new require('iconv').Iconv('cp949', 'utf8'); function rqkrCallback(err, response, body) { if (response && response.headers['content-type']) { if (/charset=(ks_c_5601-1987|euc-kr)/i.test(response.headers['content-type'])) { body = iconv.convert(new Buffer(body)).toString(); } } this._rqkrOriginalCallback.apply(this, [err, response, body]); } var originalInit = request.Request.prototype.init; request.Request.prototype.init = function (options) { this._rqkrOriginalCallback = this.callback; this.callback = rqkrCallback; if (this.encoding === undefined) { // If null, the body is returned as a Buffer. this.encoding = null; } return originalInit.apply(this, [options]); } module.exports = request;
'use strict'; var request = require('request'); var iconv = new require('iconv').Iconv('euckr', 'utf8'); function rqkrCallback(err, response, body) { if (response && response.headers['content-type']) { if (/charset=(ks_c_5601-1987|euc-kr)/i.test(response.headers['content-type'])) { body = iconv.convert(new Buffer(body)).toString(); } } this._rqkrOriginalCallback.apply(this, [err, response, body]); } var originalInit = request.Request.prototype.init; request.Request.prototype.init = function (options) { this._rqkrOriginalCallback = this.callback; this.callback = rqkrCallback; if (this.encoding === undefined) { // If null, the body is returned as a Buffer. this.encoding = null; } return originalInit.apply(this, [options]); } module.exports = request;
Use DI Extension instead of HttpKernel
<?php namespace Palmtree\CanonicalUrlBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader; class PalmtreeCanonicalUrlExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter('palmtree.canonical_url.site_url', $config['site_url']); $container->setParameter('palmtree.canonical_url.redirect_code', $config['redirect_code']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); } }
<?php namespace Palmtree\CanonicalUrlBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; /** * This is the class that loads and manages your bundle configuration. * * @link http://symfony.com/doc/current/cookbook/bundles/extension.html */ class PalmtreeCanonicalUrlExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter('palmtree.canonical_url.site_url', $config['site_url']); $container->setParameter('palmtree.canonical_url.redirect_code', $config['redirect_code']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); } }
Print Preview: Hook up the cancel button. BUG=57895 TEST=manual Review URL: http://codereview.chromium.org/5151009 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@66822 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var localStrings = new LocalStrings(); /** * Window onload handler, sets up the page. */ function load() { $('cancel-button').addEventListener('click', function(e) { window.close(); }); chrome.send('getPrinters'); }; /** * Fill the printer list drop down. */ function setPrinters(printers) { if (printers.length > 0) { for (var i = 0; i < printers.length; ++i) { var option = document.createElement('option'); option.textContent = printers[i]; $('printer-list').add(option); } } else { var option = document.createElement('option'); option.textContent = localStrings.getString('no-printer'); $('printer-list').add(option); $('printer-list').disabled = true; $('print-button').disabled = true; } } window.addEventListener('DOMContentLoaded', load);
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var localStrings = new LocalStrings(); /** * Window onload handler, sets up the page. */ function load() { chrome.send('getPrinters'); }; /** * Fill the printer list drop down. */ function setPrinters(printers) { if (printers.length > 0) { for (var i = 0; i < printers.length; ++i) { var option = document.createElement('option'); option.textContent = printers[i]; $('printer-list').add(option); } } else { var option = document.createElement('option'); option.textContent = localStrings.getString('no-printer'); $('printer-list').add(option); $('printer-list').disabled = true; $('print-button').disabled = true; } } window.addEventListener('DOMContentLoaded', load);
Make all astroplan warnings decend from an AstroplanWarning
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.utils.exceptions import AstropyWarning __all__ = ["TargetAlwaysUpWarning", "TargetNeverUpWarning", "OldEarthOrientationDataWarning", "PlotWarning", "PlotBelowHorizonWarning"] class AstroplanWarning(AstropyWarning): """Superclass for warnings used by astroplan""" class TargetAlwaysUpWarning(AstroplanWarning): """Target is circumpolar""" pass class TargetNeverUpWarning(AstroplanWarning): """Target never rises above horizon""" pass class OldEarthOrientationDataWarning(AstroplanWarning): """Using old Earth rotation data from IERS""" pass class PlotWarning(AstroplanWarning): """Warnings dealing with the plotting aspects of astroplan""" pass class PlotBelowHorizonWarning(PlotWarning): """Warning for when something is hidden on a plot because it's below the horizon""" pass
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.utils.exceptions import AstropyWarning __all__ = ["TargetAlwaysUpWarning", "TargetNeverUpWarning", "OldEarthOrientationDataWarning", "PlotWarning", "PlotBelowHorizonWarning"] class TargetAlwaysUpWarning(AstropyWarning): """Target is circumpolar""" pass class TargetNeverUpWarning(AstropyWarning): """Target never rises above horizon""" pass class OldEarthOrientationDataWarning(AstropyWarning): """Using old Earth rotation data from IERS""" pass class PlotWarning(AstropyWarning): """Warnings dealing with the plotting aspects of astroplan""" pass class PlotBelowHorizonWarning(PlotWarning): """Warning for when something is hidden on a plot because it's below the horizon""" pass
fix: Add PyQt5 to install requirements Add PyQt5 to install requirements
from setuptools import setup setup( name='broadbean', version='0.9', # We might as well require what we know will work # although older numpy and matplotlib version will probably work too install_requires=['numpy>=1.12.1', 'matplotlib>=2.0.1', 'PyQt5>5.7.1'], author='William H.P. Nielsen', author_email='whpn@mailbox.org', description=("Package for easily generating and manipulating signal " "pulses. Developed for use with qubits in the quantum " "computing labs of Copenhagen, Delft, and Sydney, but " "should be generally useable."), license='MIT', packages=['broadbean'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 3.5' ], keywords='Pulsebuilding signal processing arbitrary waveforms', url='https://github.com/QCoDeS/broadbean' )
from setuptools import setup setup( name='broadbean', version='0.9', # We might as well require what we know will work # although older numpy and matplotlib version will probably work too install_requires=['numpy>=1.12.1', 'matplotlib>=2.0.1'], author='William H.P. Nielsen', author_email='whpn@mailbox.org', description=("Package for easily generating and manipulating signal " "pulses. Developed for use with qubits in the quantum " "computing labs of Copenhagen, Delft, and Sydney, but " "should be generally useable."), license='MIT', packages=['broadbean'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 3.5' ], keywords='Pulsebuilding signal processing arbitrary waveforms', url='https://github.com/QCoDeS/broadbean' )
Revert "Simplify webpack image loading" This reverts commit 66322ccce2219656114bbc2697cc21956366c1f0.
const ExtractTextPlugin = require('extract-text-webpack-plugin'); const glob = require("glob"); module.exports = { entry: glob.sync("./dist/css/**/*.css"), output: { path: __dirname + '/dist', filename: 'pivotal-ui.js' }, module: { rules: [ { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }) }, { test: /\.(eot|ttf|woff)$/, loader: 'url-loader' }, { test: /\.(jpe?g|png|gif|svg)$/i, loaders: [ 'file-loader?hash=sha512&digest=hex&name=[hash].[ext]', 'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false' ] } ] }, plugins: [ new ExtractTextPlugin("components.css") ] };
const ExtractTextPlugin = require('extract-text-webpack-plugin'); const glob = require("glob"); module.exports = { entry: glob.sync("./dist/css/**/*.css"), output: { path: __dirname + '/dist', filename: 'pivotal-ui.js' }, module: { rules: [ { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }) }, { test: /\.(eot|ttf|woff)$/, loader: 'url-loader' }, { test: /\.(jpe?g|png|gif|svg)$/i, loaders: 'file-loader!image-webpack-loader' } ] }, plugins: [ new ExtractTextPlugin("components.css") ] };
Add LC fee to entity
<?php /* * This file is part of the PayBreak/basket package. * * (c) PayBreak <dev@paybreak.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PayBreak\Sdk\Entities\Product; use WNowicki\Generic\AbstractEntity; /** * Merchant Fees Entity * * @author EB * @method $this setPercentage(int $percentage) * @method int|null getPercentage() * @method $this setMinimumAmount(int $minimumAmount) * @method int|null getMinimumAmount() * @method $this setMaximumAmount(int $maximumAmount) * @method int|null getMaximumAmount() * @method $this setCancellation(int $cancellation) * @method int|null getCancellation() * @method $this setLiabilityClawback(int $liabilityClawback) * @method int|null getLiabilityClawback() * @package PayBreak\Sdk\Entities */ class MerchantFeesEntity extends AbstractEntity { protected $properties = [ 'percentage', 'minimum_amount', 'maximum_amount', 'cancellation', 'liability_clawback', ]; }
<?php /* * This file is part of the PayBreak/basket package. * * (c) PayBreak <dev@paybreak.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PayBreak\Sdk\Entities\Product; use WNowicki\Generic\AbstractEntity; /** * Merchant Fees Entity * * @author EB * @method $this setPercentage(int $percentage) * @method int|null getPercentage() * @method $this setMinimumAmount(int $minimumAmount) * @method int|null getMinimumAmount() * @method $this setMaximumAmount(int $maximumAmount) * @method int|null getMaximumAmount() * @method $this setCancellation(int $cancellation) * @method int|null getCancellation() * @package PayBreak\Sdk\Entities */ class MerchantFeesEntity extends AbstractEntity { protected $properties = [ 'percentage', 'minimum_amount', 'maximum_amount', 'cancellation', ]; }
Upgrade all dependencies to latest version.
from setuptools import setup setup( name='docker-ipsec', version='3.0.0', description='Scripts to start/stop ipsec VPN tunnels while adding/removing iptables rules for docker networking.', author='Christopher Brichford', author_email='chrisb@farmersbusinessnetwork.com', license='Apache License 2.0', keywords=['ipsec', 'docker'], # arbitrary keywords classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Topic :: Internet', 'Topic :: System :: Networking' ], scripts=['docker_ipsec/docker-ipsec.py'], install_requires=[ 'pyroute2>=0.5.7,<0.6.0', 'netaddr>=0.7.19,<0.8.0', 'python-iptables>=0.14.0,<0.15.0', 'ipsecparse', 'docker>=4.2.0,<4.3.0' ], url='https://github.com/cbrichford/docker-ipsec/', packages=[ 'docker_ipsec' ], )
from setuptools import setup setup( name='docker-ipsec', version='2.0.3', description='Scripts to start/stop ipsec VPN tunnels while adding/removing iptables rules for docker networking.', author='Christopher Brichford', author_email='chrisb@farmersbusinessnetwork.com', license='Apache License 2.0', keywords=['ipsec', 'docker'], # arbitrary keywords classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Topic :: Internet', 'Topic :: System :: Networking' ], scripts=['docker_ipsec/docker-ipsec.py'], install_requires=[ 'pyroute2>=0.4.13,<0.5.0', 'netaddr>=0.7.19,<0.8.0', 'python-iptables>=0.12.0,<0.13.0', 'ipsecparse', 'docker>=2.1.0,<2.5.0' ], url='https://github.com/cbrichford/docker-ipsec/', packages=[ 'docker_ipsec' ], )
Fix issues pointed out by JSHint
var test = require('tap').test, SDNV = require('../index'); var buff = new Buffer([0x0A, 0xBC]), sdnv = new SDNV(buff); test('make sure a valid buffer results in a valid SNDV', function (t) { t.ok(sdnv instanceof SDNV, 'should be able to create an SDNV instance'); t.type(sdnv.buffer, "Buffer", 'should contain buffer data'); t.end(); }); test('make sure the SDNV is valid when no buffer is passed', function (t) { var emptyBufferSDNV = new SDNV(), expectedBuffer = new Buffer(1); t.ok(emptyBufferSDNV instanceof SDNV, 'empty buffer should result ' + 'in a default SDNV'); t.type(emptyBufferSDNV.buffer, "Buffer", 'default SDNV should contain ' + 'buffer data'); t.end(); }); test('make sure the encoding works', function (t) { var encoded = SDNV.encode(buff), expected = new Buffer([0x95, 0x3C]); // test the sdnv contents t.equal(sdnv.buffer.toString('hex'), expected.toString('hex'), 'the SDNV buffer should match the expected one'); // test the utility method t.equal(encoded.toString('hex'), expected.toString('hex'), 'the encoded buffer by the utility method should match the expected one'); t.end(); }); test('make sure the decoding works', function (t) { t.end(); });
var test = require('tap').test, SDNV = require('../index'); var buff = new Buffer([0x0A, 0xBC]), sdnv = new SDNV(buff); test('make sure a valid buffer results in a valid SNDV', function (t) { t.ok(sdnv instanceof SDNV, 'should be able to create an SDNV instance'); t.type(sdnv.buffer, "Buffer", 'should contain buffer data'); t.end(); }); test('make sure the SDNV is valid when no buffer is passed', function (t) { var emptyBufferSDNV = new SDNV(), expectedBuffer = new Buffer(1); t.ok(emptyBufferSDNV instanceof SDNV, 'empty buffer should result in a \ default SDNV'); t.type(emptyBufferSDNV.buffer, "Buffer", 'default SDNV should contain \ buffer data'); t.end(); }); test('make sure the encoding works', function (t) { var encoded = SDNV.encode(buff), expected = new Buffer([0x95, 0x3C]); // test the sdnv contents t.equal(sdnv.buffer.toString('hex'), expected.toString('hex'), 'the SDNV buffer should match the expected one'); // test the utility method t.equal(encoded.toString('hex'), expected.toString('hex'), 'the encoded buffer by the utility method should match the expected one'); t.end(); }); test('make sure the decoding works', function (t) { t.end(); });
Fix rotation duplicating fragment in sample
package com.jenzz.materialpreference.sample; import android.os.Bundle; import android.preference.PreferenceFragment; import android.support.v7.app.ActionBarActivity; /** * Simple Activity to display example preferences. * * Created by jenzz on 28/01/15. */ public class SettingsActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(android.R.id.content, new SettingsFragment()) .commit(); } } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); } } }
package com.jenzz.materialpreference.sample; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceFragment; import android.support.v7.app.ActionBarActivity; /** * Created by jenzz on 28/01/15. */ public class SettingsActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // workaround for https://code.google.com/p/android/issues/detail?id=78701 new Handler().post(new Runnable() { @Override public void run() { getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } }); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); } } }
Put in the necessary pybit dependenies
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = os.path.join(here, 'README.rst') install_requirements = [ 'requests', # PyBit and dependencies 'pybit', # 'psycopg2', # 'amqplib', 'jsonpickle', ] test_requirements = [] # These requirements are specifically for the legacy module. legacy_requirements = [] setup( name='roadrunners', version='1.0', author="Connexions/Rhaptos Team", author_email="info@cnx.org", long_description=open(README).read(), url='https://github.com/connexions/roadrunners', license='AGPL', # See also LICENSE.txt packages=find_packages(), include_package_data=True, install_requires=install_requirements, extras_require={ 'tests': test_requirements, 'legacy': legacy_requirements, }, entry_points = """\ """, )
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = os.path.join(here, 'README.rst') install_requirements = [ 'pybit', 'jsonpickle', 'requests', ] test_requirements = [] # These requirements are specifically for the legacy module. legacy_requirements = [] setup( name='roadrunners', version='1.0', author="Connexions/Rhaptos Team", author_email="info@cnx.org", long_description=open(README).read(), url='https://github.com/connexions/roadrunners', license='AGPL', # See also LICENSE.txt packages=find_packages(), include_package_data=True, install_requires=install_requirements, extras_require={ 'tests': test_requirements, 'legacy': legacy_requirements, }, entry_points = """\ """, )
Make booksOwned of user be an empty array not 404 when there are no owned books of the user
/** * Created by esso on 02.09.15. */ var Books = require('../models/book'); var Crowds = require('../models/crowd.js'); module.exports = { getUser: function(req, res){ var username = req.params.username; var obj = {username: username}; // Add the username Books.findRentedBy(username, function(result){ obj.booksRented = result ? result: null; }); Books.findWithOwner(username, function(result){ obj.booksOwned = result !== 404 ? result : []; // The user's books Crowds.getAll(function(result){ obj.crowds = []; for (var i = 0; i < result.length; i++){ if (username in result[i]){ obj.crowds.push(result[i]._id); } } return res.json(obj); // send it }) }); } };
/** * Created by esso on 02.09.15. */ var Books = require('../models/book'); var Crowds = require('../models/crowd.js'); module.exports = { getUser: function(req, res){ var username = req.params.username; var obj = {username: username}; // Add the username Books.findRentedBy(username, function(result){ obj.booksRented = result ? result: null; }); Books.findWithOwner(username, function(result){ obj.booksOwned = result ? result : null; // The user's books Crowds.getAll(function(result){ obj.crowds = []; for (var i = 0; i < result.length; i++){ if (username in result[i]){ obj.crowds.push(result[i]._id); } } return res.json(obj); // send it }) }); } };
Use thenShowInternal on action condition to avoid visibility colision (cherry picked from commit 2bf2404b3c89ce318481ef9dcc26088a9b472a93)
package fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.bootstrap.confirm.component; import org.apache.wicket.model.IModel; import fr.openwide.core.wicket.more.markup.html.action.IAjaxAction; public class AjaxConfirmLinkBuilder<O> extends AbstractConfirmLinkBuilder<AjaxConfirmLink<O>, O> { private static final long serialVersionUID = 5629930352899730245L; @Override public AjaxConfirmLink<O> create(String wicketId, IModel<O> model) { if (onAjaxClick == null) { throw new IllegalStateException(String.format("%s must be used with a %s", getClass().getName(), IAjaxAction.class.getName())); } AjaxConfirmLink<O> ajaxConfirmLink = new FunctionalAjaxConfirmLink<O>( wicketId, model, form, titleModelFactory, contentModelFactory, yesLabelModel, noLabelModel, yesIconModel, noIconModel, yesButtonModel, noButtonModel, cssClassNamesModel, keepMarkup, onAjaxClick ); ajaxConfirmLink.add(onAjaxClick.getActionAvailableCondition(model).thenShowInternal()); return ajaxConfirmLink; } }
package fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.bootstrap.confirm.component; import org.apache.wicket.model.IModel; import fr.openwide.core.wicket.more.markup.html.action.IAjaxAction; public class AjaxConfirmLinkBuilder<O> extends AbstractConfirmLinkBuilder<AjaxConfirmLink<O>, O> { private static final long serialVersionUID = 5629930352899730245L; @Override public AjaxConfirmLink<O> create(String wicketId, IModel<O> model) { if (onAjaxClick == null) { throw new IllegalStateException(String.format("%s must be used with a %s", getClass().getName(), IAjaxAction.class.getName())); } AjaxConfirmLink<O> ajaxConfirmLink = new FunctionalAjaxConfirmLink<O>( wicketId, model, form, titleModelFactory, contentModelFactory, yesLabelModel, noLabelModel, yesIconModel, noIconModel, yesButtonModel, noButtonModel, cssClassNamesModel, keepMarkup, onAjaxClick ); ajaxConfirmLink.add(onAjaxClick.getActionAvailableCondition(model).thenShow()); return ajaxConfirmLink; } }
Update test to accept compTarget array
var assert = require("chai").assert; var fs = require("fs-extra"); var glob = require("glob"); var Box = require("truffle-box"); var Profiler = require("truffle-compile/profiler.js"); var Resolver = require("truffle-resolver"); var Artifactor = require("truffle-artifactor"); // TOOD: Move this to truffle-compile! describe('profiler', function() { var config; before("Create a sandbox", function(done) { this.timeout(10000); Box.sandbox(function(err, result) { if (err) return done(err); config = result; config.resolver = new Resolver(config); config.artifactor = new Artifactor(config.contracts_build_directory); config.network = "development"; done(); }); }); after("Cleanup tmp files", function(done){ glob('tmp-*', (err, files) => { if(err) done(err); files.forEach(file => fs.removeSync(file)); done(); }) }) it('profiles example project successfully', function(done) { Profiler.required_sources(config.with({ paths: ["./ConvertLib.sol"], base_path: config.contracts_directory }), function(err, allSources, compilationTargets) { if (err) return done(err); assert.equal(Object.keys(allSources).length, 3); assert.equal(compilationTargets.length, 2); done(); }); }); });
var assert = require("chai").assert; var fs = require("fs-extra"); var glob = require("glob"); var Box = require("truffle-box"); var Profiler = require("truffle-compile/profiler.js"); var Resolver = require("truffle-resolver"); var Artifactor = require("truffle-artifactor"); // TOOD: Move this to truffle-compile! describe('profiler', function() { var config; before("Create a sandbox", function(done) { this.timeout(10000); Box.sandbox(function(err, result) { if (err) return done(err); config = result; config.resolver = new Resolver(config); config.artifactor = new Artifactor(config.contracts_build_directory); config.network = "development"; done(); }); }); after("Cleanup tmp files", function(done){ glob('tmp-*', (err, files) => { if(err) done(err); files.forEach(file => fs.removeSync(file)); done(); }) }) it('profiles example project successfully', function(done) { Profiler.required_sources(config.with({ paths: ["./ConvertLib.sol"], base_path: config.contracts_directory }), function(err, allSources, compilationTargets) { if (err) return done(err); assert.equal(Object.keys(allSources).length, 3); assert.equal(Object.keys(compilationTargets).length, 2); done(); }); }); });
Add 'Primary' annotation so that it is clear for AutoWired
/* * DatasourceConfig.java * * Copyright (C) 2017 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.config; import javax.sql.DataSource; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.datasource.DriverManagerDataSource; @Configuration public class DatasourceConfig { @Bean @Primary DataSource datasource(final DataSourceProperties datasourceProperties) { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(datasourceProperties.getDriverClassName()); dataSource.setUsername(datasourceProperties.getUsername()); dataSource.setPassword(datasourceProperties.getPassword()); dataSource.setUrl(datasourceProperties.getUrl()); return dataSource; } }
/* * DatasourceConfig.java * * Copyright (C) 2017 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.config; import javax.sql.DataSource; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; @Configuration public class DatasourceConfig { @Bean DataSource datasource(final DataSourceProperties datasourceProperties) { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(datasourceProperties.getDriverClassName()); dataSource.setUsername(datasourceProperties.getUsername()); dataSource.setPassword(datasourceProperties.getPassword()); dataSource.setUrl(datasourceProperties.getUrl()); return dataSource; } }
Fix next step for OMIS order creation When removing the subscribers step the next step for market was missed. This fixes that which caused an error after saving the primary market.
const { ClientDetailsController, MarketController, ConfirmController, } = require('./controllers') module.exports = { '/': { entryPoint: true, resetJourney: true, skip: true, next: 'client-details', }, '/client-details': { heading: 'Client details', backLink: null, editable: true, next: 'market', fields: ['company', 'contact'], controller: ClientDetailsController, templatePath: 'omis/apps/create/views', template: 'client-details', }, '/market': { heading: 'Market (country) of interest', editable: true, next: 'confirm', fields: ['primary_market'], controller: MarketController, }, '/confirm': { heading: 'Check order details', backLink: null, templatePath: 'omis/apps/create/views', template: 'summary', controller: ConfirmController, }, }
const { ClientDetailsController, MarketController, ConfirmController, } = require('./controllers') module.exports = { '/': { entryPoint: true, resetJourney: true, skip: true, next: 'client-details', }, '/client-details': { heading: 'Client details', backLink: null, editable: true, next: 'market', fields: ['company', 'contact'], controller: ClientDetailsController, templatePath: 'omis/apps/create/views', template: 'client-details', }, '/market': { heading: 'Market (country) of interest', editable: true, next: 'subscribers', fields: ['primary_market'], controller: MarketController, }, '/confirm': { heading: 'Check order details', backLink: null, templatePath: 'omis/apps/create/views', template: 'summary', controller: ConfirmController, }, }
Fix videoLength issue (API.totalTime.getTime() -> API.totalTime)
(function(){ 'use strict'; angular.module('uk.ac.soton.ecs.videogular.plugins.cuepoints', []) .directive( 'vgCuepoints', [function() { return { restrict: 'E', require: '^videogular', templateUrl: 'bower_components/videogular-cuepoints/cuepoints.html', scope: { cuepoints: '=vgCuepointsConfig', theme: '=vgCuepointsTheme', }, link: function($scope, elem, attr, API) { // shamelessly stolen from part of videogular's updateTheme function function updateTheme(value) { if (value) { var headElem = angular.element(document).find("head"); headElem.append("<link rel='stylesheet' href='" + value + "'>"); } } $scope.calcLeft = function(cuepoint) { if (API.totalTime === 0) return '-1000'; var videoLength = API.totalTime / 1000; return (cuepoint.time * 100 / videoLength).toString(); }; updateTheme($scope.theme); }, }; }]); })();
(function(){ 'use strict'; angular.module('uk.ac.soton.ecs.videogular.plugins.cuepoints', []) .directive( 'vgCuepoints', [function() { return { restrict: 'E', require: '^videogular', templateUrl: 'bower_components/videogular-cuepoints/cuepoints.html', scope: { cuepoints: '=vgCuepointsConfig', theme: '=vgCuepointsTheme', }, link: function($scope, elem, attr, API) { // shamelessly stolen from part of videogular's updateTheme function function updateTheme(value) { if (value) { var headElem = angular.element(document).find("head"); headElem.append("<link rel='stylesheet' href='" + value + "'>"); } } $scope.calcLeft = function(cuepoint) { if (API.totalTime === 0) return '-1000'; var videoLength = API.totalTime.getTime() / 1000; return (cuepoint.time * 100 / videoLength).toString(); }; updateTheme($scope.theme); }, }; }]); })();
:sparkles: Add a bugsnag deploy command
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ \App\Console\Commands\AddToken::class, \App\Console\Commands\UpdateOrg::class, \App\Console\Commands\JoinOrg::class, \App\Console\Commands\EncryptOrgPasswords::class, \Bugsnag\BugsnagLaravel\Commands\DeployCommand::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); } /** * Register the Closure based commands for the application. * * @return void */ protected function commands() { require base_path('routes/console.php'); } }
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ \App\Console\Commands\AddToken::class, \App\Console\Commands\UpdateOrg::class, \App\Console\Commands\JoinOrg::class, \App\Console\Commands\EncryptOrgPasswords::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); } /** * Register the Closure based commands for the application. * * @return void */ protected function commands() { require base_path('routes/console.php'); } }
Change test to only run once
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '../../', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: ['html', 'lcovonly'], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: true }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '../../', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: ['html', 'lcovonly'], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
Revert CreatedAware fpr now as adds complexity to proxy delegate replacement on rollup.
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.om', name: 'OM', documentation: `An Operational Measure which captures the count of some event.`, javaImports: [ 'foam.core.X' ], properties: [ { class: 'Class', name: 'classType' }, { class: 'String', name: 'name' }, { name: 'created', class: 'DateTime', factory: function() { return new Date(); }, javaFactory: `return new java.util.Date();` } ], methods: [ { name: 'log', type: 'Void', args: [ { name: 'x', type: 'X' } ], javaCode: ` if ( x == null ) return; OMLogger logger = (OMLogger) x.get(DAOOMLogger.SERVICE_NAME); if ( logger != null ) logger.log(this); ` } ] });
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.om', name: 'OM', documentation: `An Operational Measure which captures the count of some event.`, implements: [ 'foam.nanos.auth.CreatedAware' ], javaImports: [ 'foam.core.X' ], properties: [ { class: 'Class', name: 'classType' }, { class: 'String', name: 'name' }, { name: 'created', class: 'DateTime' } ], methods: [ { name: 'log', type: 'Void', args: [ { name: 'x', type: 'X' } ], javaCode: ` if ( x == null ) return; OMLogger logger = (OMLogger) x.get(DAOOMLogger.SERVICE_NAME); if ( logger != null ) logger.log(this); ` } ] });
Use env value for client token
import discord import asyncio import os #Set up Client State CLIENT_TOKEN=os.environ['TOKEN'] client = discord.Client() @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') @client.event async def on_message(message): if message.content.startswith('!test'): counter = 0 tmp = await client.send_message(message.channel, 'Calculating messages...') async for log in client.logs_from(message.channel, limit=100): if log.author == message.author: counter += 1 await client.edit_message(tmp, 'You have {} messages.'.format(counter)) elif message.content.startswith('!sleep'): await asyncio.sleep(5) await client.send_message(message.channel, 'Done sleeping') client.run(CLIENT_TOKEN)
import discord import asyncio client = discord.Client() @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') @client.event async def on_message(message): if message.content.startswith('!test'): counter = 0 tmp = await client.send_message(message.channel, 'Calculating messages...') async for log in client.logs_from(message.channel, limit=100): if log.author == message.author: counter += 1 await client.edit_message(tmp, 'You have {} messages.'.format(counter)) elif message.content.startswith('!sleep'): await asyncio.sleep(5) await client.send_message(message.channel, 'Done sleeping') client.run('token')
Fix path to the config file
<?php setlocale(LC_ALL, 'it_IT.UTF-8'); $fname = $_SERVER['DOCUMENT_ROOT'].'/config/config.json'; $data = @file_get_contents($fname); $config = (array)json_decode($data); $start_date = strtotime($config['firstDate']); $now = strtotime("now"); $days = 1 + floor(($start_date - $now)/(60*60*24)); if ($days <= 0) { return; } $header = $config['firstDateFormatted']; if ($days == 1) { $manca = "E' <mark>già domani</mark>!"; } else { $manca = "Mancano <mark>solo ".$days." giorni</mark>!"; } ?> <section data-nosnippet> <h2><mark><?php echo $header; ?></mark></h2> <p>La prima lezione del nuovo corso per principianti, intermedi e avanzati. <?php echo $manca; ?> Ti aspettiamo, contataci! </p> </section>
<?php setlocale(LC_ALL, 'it_IT.UTF-8'); $fname = 'config/config.json'; $data = @file_get_contents($fname); $config = (array)json_decode($data); $start_date = strtotime($config['firstDate']); $now = strtotime("now"); $days = 1 + floor(($start_date - $now)/(60*60*24)); if ($days <= 0) { return; } $header = $config['firstDateFormatted']; if ($days == 1) { $manca = "E' <mark>già domani</mark>!"; } else { $manca = "Mancano <mark>solo ".$days." giorni</mark>!"; } ?> <section data-nosnippet> <h2><mark><?php echo $header; ?></mark></h2> <p>La prima lezione del nuovo corso per principianti, intermedi e avanzati. <?php echo $manca; ?> Ti aspettiamo, contataci! </p> </section>
Fix Iron Grip calculations using incorrect values.
package com.gmail.nossr50.skills.unarmed; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.gmail.nossr50.datatypes.SkillType; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Users; public class IronGripEventHandler { private UnarmedManager manager; private Player defender; protected int skillModifier; protected IronGripEventHandler(UnarmedManager manager, Player defender) { this.manager = manager; this.defender = defender; calculateSkillModifier(); } protected void calculateSkillModifier() { this.skillModifier = Misc.skillCheck(Users.getProfile(defender).getSkillLevel(SkillType.UNARMED), Unarmed.IRON_GRIP_MAX_BONUS_LEVEL); } protected void sendAbilityMessages() { defender.sendMessage(ChatColor.GREEN + "Your iron grip kept you from being disarmed!"); //TODO: Use locale manager.getPlayer().sendMessage(ChatColor.RED + "Your opponent has an iron grip!"); //TODO: Use locale } }
package com.gmail.nossr50.skills.unarmed; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.gmail.nossr50.util.Misc; public class IronGripEventHandler { private UnarmedManager manager; private Player defender; protected int skillModifier; protected IronGripEventHandler(UnarmedManager manager, Player defender) { this.manager = manager; this.defender = defender; calculateSkillModifier(); } protected void calculateSkillModifier() { this.skillModifier = Misc.skillCheck(manager.getSkillLevel(), Unarmed.DISARM_MAX_BONUS_LEVEL); } protected void sendAbilityMessages() { defender.sendMessage(ChatColor.GREEN + "Your iron grip kept you from being disarmed!"); //TODO: Use locale manager.getPlayer().sendMessage(ChatColor.RED + "Your opponent has an iron grip!"); //TODO: Use locale } }
Add needed constant for SearchImage tests
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Test / Unit */ use PH7\Framework\Loader\Autoloader as FrameworkLoader; define('PH7', 1); define('PH7_DEFAULT_TIMEZONE', 'America/Chicago'); if (!ini_get('date.timezone')) { date_default_timezone_set(PH7_DEFAULT_TIMEZONE); } // Charset Constant define('PH7_ENCODING', 'utf-8'); // General Kernel Constants define('PH7_PATH_PROTECTED', dirname(dirname(__DIR__)) . '/_protected/'); define('PH7_PATH_FRAMEWORK', PH7_PATH_PROTECTED . 'framework/'); define('PH7_PATH_TEST', __DIR__ . '/'); // Config Constants define('PH7_CONFIG', ''); define('PH7_PATH_APP_CONFIG', PH7_PATH_TEST . 'fixtures/config/'); define('PH7_PATH_SYS', PH7_PATH_APP_CONFIG); define('PH7_CONFIG_FILE', 'test.ini'); // Max Values Constants define('PH7_MAX_URL_LENGTH', 120); require PH7_PATH_FRAMEWORK . 'Loader/Autoloader.php'; FrameworkLoader::getInstance()->init();
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Test / Unit */ use PH7\Framework\Loader\Autoloader as FrameworkLoader; define('PH7', 1); define('PH7_DEFAULT_TIMEZONE', 'America/Chicago'); if (!ini_get('date.timezone')) { date_default_timezone_set(PH7_DEFAULT_TIMEZONE); } // Charset Constant define('PH7_ENCODING', 'utf-8'); // General Kernel Constants define('PH7_PATH_PROTECTED', dirname(dirname(__DIR__)) . '/_protected/'); define('PH7_PATH_FRAMEWORK', PH7_PATH_PROTECTED . 'framework/'); define('PH7_PATH_TEST', __DIR__ . '/'); // Config Constants define('PH7_CONFIG', ''); define('PH7_PATH_APP_CONFIG', PH7_PATH_TEST . 'fixtures/config/'); define('PH7_PATH_SYS', PH7_PATH_APP_CONFIG); define('PH7_CONFIG_FILE', 'test.ini'); require PH7_PATH_FRAMEWORK . 'Loader/Autoloader.php'; FrameworkLoader::getInstance()->init();
Check if its Laravel, avoid publishing the configuration file if its Lumen
<?php namespace NicolasMahe\SlackOutput; use Illuminate\Support\ServiceProvider as ServiceProviderParent; class ServiceProvider extends ServiceProviderParent { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap any application services. * * @return void */ public function boot() { //config if (class_exists('Illuminate\Foundation\Application', false)) { $this->publishes([__DIR__ . '/config.php' => config_path('slack-output.php')]); } //command $this->commands( Command\SlackPost::class ); } /** * Register the application services. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__ . '/config.php', 'slack-output'); $this->app->singleton(Service::class, function () { return new Service(config('slack-output')); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [ Service::class ]; } }
<?php namespace NicolasMahe\SlackOutput; use Illuminate\Support\ServiceProvider as ServiceProviderParent; class ServiceProvider extends ServiceProviderParent { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap any application services. * * @return void */ public function boot() { //config $this->publishes([__DIR__ . '/config.php' => config_path('slack-output.php')]); //command $this->commands( Command\SlackPost::class ); } /** * Register the application services. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__ . '/config.php', 'slack-output'); $this->app->singleton(Service::class, function () { return new Service(config('slack-output')); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [ Service::class ]; } }
Fix typo "dump" => "dumper"
#!/usr/bin/env node // Requires var _ = require('underscore'); var fs = require('fs'); // Comannder var prog = require('commander'); // etcd-dump's package.json file var pkg = require('../package.json'); // Dumper class var dumper = require('../')(); // General options prog .version(pkg.version) .option('-f, --file [json_file]', 'Path to JSON dump file for dumping/storing', './etcd_dump.json'); // Dump command prog .command('dump') .action(function() { return dumper.dump() .then(function(data) { // Write file to disk fs.writeFileSync(prog.file, JSON.stringify(data)); }) .done(); }); prog .command('restore') .action(function() { var entries = JSON.parse(fs.readFileSync(prog.file)); return dumper.restore(entries) .then(function() { console.log('Restore succeeded'); }) .done(); }); // Parse and fallback to help if no args if(_.isEmpty(prog.parse(process.argv).args)) prog.help();
#!/usr/bin/env node // Requires var _ = require('underscore'); var fs = require('fs'); // Comannder var prog = require('commander'); // etcd-dump's package.json file var pkg = require('../package.json'); // Dumper class var dumper = require('../')(); // General options prog .version(pkg.version) .option('-f, --file [json_file]', 'Path to JSON dump file for dumping/storing', './etcd_dump.json'); // Dump command prog .command('dump') .action(function() { return dumper.dump() .then(function(data) { // Write file to disk fs.writeFileSync(prog.file, JSON.stringify(data)); }) .done(); }); prog .command('restore') .action(function() { var entries = JSON.parse(fs.readFileSync(prog.file)); return dump.restore(entries) .then(function() { console.log('Restore succeeded'); }) .done(); }); // Parse and fallback to help if no args if(_.isEmpty(prog.parse(process.argv).args)) prog.help();
Make class final if private constructor git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1379860 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: 3f465bf45bb0be0db7dd847ad468f1bff0cc6eb0
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jorphan.gui; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; /** * Utility class for Renderers */ public final class RendererUtils { private RendererUtils(){ // uninstantiable } public static void applyRenderers(final JTable table, final TableCellRenderer [] renderers){ final TableColumnModel columnModel = table.getColumnModel(); for(int i = 0; i < renderers.length; i++){ final TableCellRenderer rend = renderers[i]; if (rend != null) { columnModel.getColumn(i).setCellRenderer(rend); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jorphan.gui; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; /** * Utility class for Renderers */ public class RendererUtils { private RendererUtils(){ // uninstantiable } public static void applyRenderers(final JTable table, final TableCellRenderer [] renderers){ final TableColumnModel columnModel = table.getColumnModel(); for(int i = 0; i < renderers.length; i++){ final TableCellRenderer rend = renderers[i]; if (rend != null) { columnModel.getColumn(i).setCellRenderer(rend); } } } }
Define the provider method in service provider to defer loading
<?php namespace EGALL\Transformer; use Illuminate\Support\ServiceProvider; use EGALL\Transformer\Contracts\Transformer as TransformerContract; use EGALL\Transformer\Contracts\CollectionTransformer as CollectionTransformerContract; /** * Transformer service provider. * * @package EGALL\Transformer * @author Erik Galloway <erik@mybarnapp.com> */ class TransformerServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind(TransformerContract::class, Transformer::class); $this->app->bind(CollectionTransformerContract::class, CollectionTransformer::class); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [Transformer::class, CollectionTransformer::class]; } }
<?php namespace EGALL\Transformer; use Illuminate\Support\ServiceProvider; use EGALL\Transformer\Contracts\Transformer as TransformerContract; use EGALL\Transformer\Contracts\CollectionTransformer as CollectionTransformerContract; /** * Transformer service provider. * * @package EGALL\Transformer * @author Erik Galloway <erik@mybarnapp.com> */ class TransformerServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind(TransformerContract::class, Transformer::class); $this->app->bind(CollectionTransformerContract::class, CollectionTransformer::class); } }
Remove pointer-events: none from title bar, fixing window drag
import React from "react"; import styled from "styled-components"; import AddIcon from "@atlaskit/icon/glyph/add"; import ListIcon from "@atlaskit/icon/glyph/list"; import Button, { ButtonGroup } from "@atlaskit/button"; import { createNewDoc, switchToList } from "../actions"; const TitleBarWrapper = styled.div` height: 26px; padding: 0 12px 12px 52px; display: flex; align-items: center; -webkit-app-region: drag; `; const Center = styled.div`flex-grow: 1;`; export default function TitleBar({ onAction }) { return ( <TitleBarWrapper> <Center /> <ButtonGroup> <Button appearance="subtle-link" spacing="none" iconBefore={<AddIcon size="small" label="some label" />} onClick={() => onAction(createNewDoc())} /> <Button appearance="subtle-link" spacing="none" iconBefore={<ListIcon size="small" label="some label" />} onClick={() => onAction(switchToList())} /> </ButtonGroup> </TitleBarWrapper> ); }
import React from "react"; import styled from "styled-components"; import AddIcon from "@atlaskit/icon/glyph/add"; import ListIcon from "@atlaskit/icon/glyph/list"; import Button, { ButtonGroup } from "@atlaskit/button"; import { createNewDoc, switchToList } from "../actions"; const TitleBarWrapper = styled.div` height: 26px; padding: 0 12px 12px 52px; display: flex; align-items: center; -webkit-app-region: drag; pointer-events: none; `; const Center = styled.div`flex-grow: 1;`; export default function TitleBar({ onAction }) { return ( <TitleBarWrapper> <Center /> <ButtonGroup> <Button appearance="subtle-link" spacing="none" iconBefore={<AddIcon size="small" label="some label" />} onClick={() => onAction(createNewDoc())} /> <Button appearance="subtle-link" spacing="none" iconBefore={<ListIcon size="small" label="some label" />} onClick={() => onAction(switchToList())} /> </ButtonGroup> </TitleBarWrapper> ); }
Remove person resource methods for photo User photos are only fetched by img tags
/* * Copyright 2016 Studentmediene i Trondheim AS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; angular.module('momusApp.resources') .factory('Person', $resource => { return $resource('/api/person/:id/:resource', { id: '@id' }, { me: { method: 'GET' , params: {id: 'me'}, cache: true }, updateFavouritesection: {method: 'PATCH', params: {id: 'me', resource: 'favouritesection'} } }) });
/* * Copyright 2016 Studentmediene i Trondheim AS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; angular.module('momusApp.resources') .factory('Person', $resource => { return $resource('/api/person/:id/:resource', { id: '@id' }, { me: { method: 'GET' , params: {id: 'me'}, cache: true }, updateFavouritesection: {method: 'PATCH', params: {id: 'me', resource: 'favouritesection'} }, myPhoto: { method: 'GET', params: {id: 'me', resource: 'photo'} }, photo: { method: 'GET', params: {resource: 'photo'}, bypassInterceptor: true} }) });
Use moduleDirectory instead of paths for import/resolver
module.exports = { parser: 'babel-eslint', extends: [ 'airbnb', 'plugin:flowtype/recommended', 'prettier', 'prettier/flowtype', 'prettier/react', ], env: { browser: true, node: true, es6: true, }, plugins: ['flowtype'], rules: { // import 'import/prefer-default-export': 'off', // conflict when there is only 1 action // jsx-a11y 'jsx-a11y/anchor-is-valid': 'off', // react 'react/jsx-filename-extension': ['error', { extensions: ['.js', '.jsx'] }], }, settings: { 'import/resolver': { node: { moduleDirectory: ['node_modules', 'app'], }, }, }, };
const paths = require('./paths'); module.exports = { parser: 'babel-eslint', extends: [ 'airbnb', 'plugin:flowtype/recommended', 'prettier', 'prettier/flowtype', 'prettier/react', ], env: { browser: true, node: true, es6: true, }, plugins: ['flowtype'], rules: { // import 'import/prefer-default-export': 'off', // conflict when there is only 1 action // jsx-a11y 'jsx-a11y/anchor-is-valid': 'off', // react 'react/jsx-filename-extension': ['error', { extensions: ['.js', '.jsx'] }], }, settings: { 'import/resolver': { node: { paths: [paths.appMain, paths.appResources], }, }, }, };
Add Artist ordering by name
from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) image_url = models.URLField(blank=True) thumb_url = models.URLField(blank=True) events = models.ManyToManyField( 'event.Event', related_name='artists', blank=True, ) class Meta: ordering = ['name'] def __str__(self): return self.name class Event(models.Model): title = models.CharField(max_length=200) datetime = models.DateTimeField() venue = models.ForeignKey( 'event.Venue', related_name='events', on_delete=models.CASCADE, ) def __str__(self): return self.title class Venue(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100) country = models.CharField(max_length=100) def __str__(self): return self.name
from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) image_url = models.URLField(blank=True) thumb_url = models.URLField(blank=True) events = models.ManyToManyField( 'event.Event', related_name='artists', blank=True, ) def __str__(self): return self.name class Event(models.Model): title = models.CharField(max_length=200) datetime = models.DateTimeField() venue = models.ForeignKey( 'event.Venue', related_name='events', on_delete=models.CASCADE, ) def __str__(self): return self.title class Venue(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100) country = models.CharField(max_length=100) def __str__(self): return self.name
Fix broken password reset page
@extends('layouts.master') @section('content') <div class="container"> @include('layouts.alerts') <h1 class="header">Reset Password</h1> <form method="POST" action="/password/email"> {!! csrf_field() !!} <p> <div class="input-field col s12"> <input id="email" name="email" type="email" value="{{ old('email') }}"/> <label for="email">Email</label> </div> </p> <p> <button class="btn waves-effect waves-light" type="submit" name="action">Send Password Reset Link </button> </p> </form> </div> @endsection
@extends('layouts.master') @section('content') <div class="container"> @include('layouts.alerts') <h1 class="header">Reset Password</h1> <form method="POST" action="/password/email"> {!! csrf_field() !!} <input type="hidden" name="token" value="{{ $token }}"> <p> <div class="input-field col s12"> <input id="email" name="email" type="email" value="{{ old('email') }}"/> <label for="email">Email</label> </div> </p> <p> <button class="btn waves-effect waves-light" type="submit" name="action">Send Password Reset Link </button> </p> </form> </div> @endsection
Make offlineimap sync every minute
#!/usr/bin/env python3 import subprocess import threading import time import os # Sync accounts asynchronously, but wait for all syncs to finish def offlineimap(): AAU = subprocess.Popen(['offlineimap', '-a AAU'], stderr = AAUlog) AU = subprocess.Popen(['offlineimap', '-a AU'], stderr = AUlog) AAU.communicate() AU.communicate() # Sync every wait_time seconds, and when mutt closes def autosync(): while not mutt_has_closed: offlineimap() for i in range(wait_time): if not mutt_has_closed: time.sleep(1) else: offlineimap() break wait_time = 60 # Seconds to wait between syncs mutt_has_closed = False imap_thread = threading.Thread(target=autosync) # Open log files, start autosync, start mutt. When Mutt closes, wait for autosync to finish. with open(os.path.expanduser('~/.config/offlineimap/AAU.log'),'w') as AAUlog, open(os.path.expanduser('~/.config/offlineimap/AU.log'),'w') as AUlog: imap_thread.start() subprocess.call('mutt') mutt_has_closed = True print('Synchronizing mailboxes. This may take a while.') imap_thread.join()
#!/usr/bin/env python3 import subprocess import threading import time import os # Sync accounts asynchronously, but wait for all syncs to finish def offlineimap(): AAU = subprocess.Popen(['offlineimap', '-a AAU'], stderr = AAUlog) AU = subprocess.Popen(['offlineimap', '-a AU'], stderr = AUlog) AAU.communicate() AU.communicate() # Sync every wait_time seconds, and when mutt closes def autosync(): while not mutt_has_closed: offlineimap() for i in range(wait_time): if not mutt_has_closed: time.sleep(1) else: offlineimap() break wait_time = 300 # Seconds to wait between syncs mutt_has_closed = False imap_thread = threading.Thread(target=autosync) # Open log files, start autosync, start mutt. When Mutt closes, wait for autosync to finish. with open(os.path.expanduser('~/.config/offlineimap/AAU.log'),'w') as AAUlog, open(os.path.expanduser('~/.config/offlineimap/AU.log'),'w') as AUlog: imap_thread.start() subprocess.call('mutt') mutt_has_closed = True print('Synchronizing mailboxes. This may take a while.') imap_thread.join()
Test for compatibility python2 and python3
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name = 'ferretmagic', packages = ['ferretmagic'], py_modules = ['ferretmagic'], version = '20181001', description = 'ipython extension for pyferret', author = 'Patrick Brockmann', author_email = 'Patrick.Brockmann@lsce.ipsl.fr', long_description=long_description, long_description_content_type="text/markdown", url = 'https://github.com/PBrockmann/ipython_ferretmagic', download_url = 'https://github.com/PBrockmann/ipython_ferretmagic/tarball/master', keywords = ['jupyter', 'ipython', 'ferret', 'pyferret', 'magic', 'extension'], classifiers = [ 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Framework :: Jupyter', 'Framework :: IPython' ], )
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name = 'ferretmagic', packages = ['ferretmagic'], py_modules = ['ferretmagic'], version = '20181001', description = 'ipython extension for pyferret', author = 'Patrick Brockmann', author_email = 'Patrick.Brockmann@lsce.ipsl.fr', long_description=long_description, long_description_content_type="text/markdown", url = 'https://github.com/PBrockmann/ipython_ferretmagic', download_url = 'https://github.com/PBrockmann/ipython_ferretmagic/tarball/master', keywords = ['jupyter', 'ipython', 'ferret', 'pyferret', 'magic', 'extension'], classifiers = [ 'Programming Language :: Python', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Framework :: Jupyter', 'Framework :: IPython' ], )
Add optional callback to `reload` method in helpers hook
var path = require('path'); var loadHelpers = require('./load-helpers'); module.exports = function(sails) { return { /** * Before any hooks have begun loading... * (called automatically by Sails core) */ configure: function() { sails.helpers = {}; }, initialize: function(cb) { var self = this; // Load helpers from the specified folder loadHelpers.apply(this, [sails, cb]); }, reload: function(helpers, cb) { if (typeof helpers === 'function') { cb = helpers; helpers = null; } // If we received an explicit set of helpers to load, use them. if (helpers) { sails.helpers = helpers; return; } // Otherwise reload helpers from disk. loadHelpers.apply(this, [sails, function(err) { if (cb) { return cb(err); } if (err) { throw err; } }]); } }; };
var path = require('path'); var loadHelpers = require('./load-helpers'); module.exports = function(sails) { return { /** * Before any hooks have begun loading... * (called automatically by Sails core) */ configure: function() { sails.helpers = {}; }, initialize: function(cb) { var self = this; // Load helpers from the specified folder loadHelpers.apply(this, [sails, cb]); }, reload: function(helpers) { // If we received an explicit set of helpers to load, use them. if (helpers) { sails.helpers = helpers; return; } // Otherwise reload helpers from disk. loadHelpers.apply(this, [sails, function(err) { if (err) {throw err;} }]); } }; };
Update a version number from trunk r9016 https://mediawiki.org/wiki/Special:Code/pywikipedia/9040
# -*- coding: utf-8 -*- __version__ = '$Id$' import family # The Wikia Search family # user-config.py: usernames['wikia']['wikia'] = 'User name' class Family(family.Family): def __init__(self): family.Family.__init__(self) self.name = u'wikia' self.langs = { u'wikia': None, } def hostname(self, code): return u'www.wikia.com' def version(self, code): return "1.16.2" def scriptpath(self, code): return '' def apipath(self, code): return '/api.php'
# -*- coding: utf-8 -*- __version__ = '$Id$' import family # The Wikia Search family # user-config.py: usernames['wikia']['wikia'] = 'User name' class Family(family.Family): def __init__(self): family.Family.__init__(self) self.name = u'wikia' self.langs = { u'wikia': None, } def hostname(self, code): return u'www.wikia.com' def version(self, code): return "1.15.1" def scriptpath(self, code): return '' def apipath(self, code): return '/api.php'
Add spaces around === to clarify intent
// Static synchronous definition in global context // Implementation of scopeornot API // https://github.com/eric-brechemier/scopeornot /* Function: scope(code,needs,name) Run code immediately, without taking needs into account, and set the return value, if any, to a property with given name in the global context. Parameters: code - function(context), the code to run with the global context provided as parameter needs - array of strings, the names of the properties that this code would like to find in the global context (for documentation purpose) name - string, optional, name of the global context property to set the value that the code may return Note: The global context is accessed using "this" when scope() is called. A different context may be used if the scope() function is applied to another object instead. */ var scope = (function(){ // global context var context = this; function scope(code,needs,name){ // call code synchronously, without taking needs into account var result = code(context); if (typeof name === "string"){ context[name] = result; } } return scope; }());
// Static synchronous definition in global context // Implementation of scopeornot API // https://github.com/eric-brechemier/scopeornot /* Function: scope(code,needs,name) Run code immediately, without taking needs into account, and set the return value, if any, to a property with given name in the global context. Parameters: code - function(context), the code to run with the global context provided as parameter needs - array of strings, the names of the properties that this code would like to find in the global context (for documentation purpose) name - string, optional, name of the global context property to set the value that the code may return Note: The global context is accessed using "this" when scope() is called. A different context may be used if the scope() function is applied to another object instead. */ var scope = (function(){ // global context var context = this; function scope(code,needs,name){ // call code synchronously, without taking needs into account var result = code(context); if (typeof name==="string"){ context[name] = result; } } return scope; }());
Change code style to google code style.
package com.saintdan.framework.annotation; import org.springframework.security.core.annotation.AuthenticationPrincipal; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Get current user.{@link AuthenticationPrincipal} * * <pre> * @Controller * public class MyController { * @RequestMapping("/user/current/show") * public String show(@CurrentUser CustomUser customUser) { * // do something with CustomUser * return "view"; * } * </pre> * * @author <a href="http://github.com/saintdan">Liao Yifan</a> * @date 10/29/15 * @since JDK1.8 */ @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @AuthenticationPrincipal public @interface CurrentUser { }
package com.saintdan.framework.annotation; import org.springframework.security.core.annotation.AuthenticationPrincipal; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Get current user.{@link AuthenticationPrincipal} * * <pre> * @Controller * public class MyController { * @RequestMapping("/user/current/show") * public String show(@CurrentUser CustomUser customUser) { * // do something with CustomUser * return "view"; * } * </pre> * * @author <a href="http://github.com/saintdan">Liao Yifan</a> * @date 10/29/15 * @since JDK1.8 */ @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @AuthenticationPrincipal public @interface CurrentUser { }
Purge from all 11ty template languages.
// @see https://github.com/postcss/postcss-loader#configuration // Standard lib. import { join as joinPath } from 'path'; // Package modules. import autoprefixer from 'autoprefixer'; import purgecss from '@fullhuman/postcss-purgecss'; import reporter from 'postcss-reporter'; import stylelint from 'stylelint'; // Local modules. import { config } from './package.json'; // Constants. const INPUT_DIRECTORY = config.input; // const INTERMEDIATE_DIRECTORY = config.intermediate; // const OUTPUT_DIRECTORY = config.output; const PRODUCTION = process.env.NODE_ENV === 'production'; // @see https://www.11ty.io/docs/languages/ const ELEVENTY_TEMPLATE_LANGUAGES = [ 'html', 'md', '11ty.js', 'liquid', 'njk', 'hbs', 'mustache', 'ejs', 'haml', 'pug', 'jstl' ].join(','); // Helpers. const isTruthy = x => !!x; // Exports. export default { plugins: [ stylelint(), PRODUCTION && purgecss({ // Purge using templates rather than the full output. content: [ joinPath(INPUT_DIRECTORY, `**/*.{${ELEVENTY_TEMPLATE_LANGUAGES}}`) ], fontFace: true, keyframes: true }), autoprefixer(), reporter({ clearReportedMessages: true }) ].filter(isTruthy) };
// @see https://github.com/postcss/postcss-loader#configuration // Standard lib. import { join as joinPath } from 'path'; // Package modules. import autoprefixer from 'autoprefixer'; import purgecss from '@fullhuman/postcss-purgecss'; import reporter from 'postcss-reporter'; import stylelint from 'stylelint'; // Local modules. import { config } from './package.json'; // Constants. const INPUT_DIRECTORY = config.input; // const INTERMEDIATE_DIRECTORY = config.intermediate; // const OUTPUT_DIRECTORY = config.output; const PRODUCTION = process.env.NODE_ENV === 'production'; // Helpers. const isTruthy = x => !!x; // Exports. export default { plugins: [ stylelint(), PRODUCTION && purgecss({ content: [ joinPath(INPUT_DIRECTORY, '**/*.njk') ], fontFace: true, keyframes: true }), autoprefixer(), reporter({ clearReportedMessages: true }) ].filter(isTruthy) };
Fix comment-no-loud only catching first line This changes the approach to looking up comments for the comment-no-loud rule. This rule had an issue where it would only identify comments if they were the first node within an SCSS file. Previously this check matched a regex against `source.input.css` of the comment node. `source.input.css` is actually the full input of the source file and not the input of the node (as I imagine was expected when this was initially authored). This meant that only comments that were not preceded by any other nodes matched the rule. The tests all succeeded for this as they all checked against the first node. This new approach instead takes the source input and splits into an array based on a `\n` separator. It then looks up the first line of the comment with `source.start.line` variable. This provides the first line of the comment input as was given in the source file. I did also try using `comment.toString()` as a simpler means to get the original source value, however this approach didn't provide an exact copy of the original input and instead converted SCSS comments (`//`) into CSS ones (`/*`) meaning that all SCSS comments were identified as loud.
import { utils } from "stylelint"; import { namespace } from "../../utils"; export const ruleName = namespace("comment-no-loud"); export const messages = utils.ruleMessages(ruleName, { expected: "Expected // for comments instead of /*" }); function rule(primary) { return (root, result) => { const validOptions = utils.validateOptions(result, ruleName, { actual: primary }); if (!validOptions) { return; } root.walkComments(comment => { if (isLoudComment(comment)) { utils.report({ message: messages.expected, node: comment, result, ruleName }); } }); }; } function isLoudComment(comment) { const regex = new RegExp(/^[ \t\n]*\/\*/); const splitComment = comment.source.input.css.split("\n"); const commentFirstLine = splitComment[comment.source.start.line - 1]; return regex.test(commentFirstLine); } export default rule;
import { utils } from "stylelint"; import { namespace } from "../../utils"; export const ruleName = namespace("comment-no-loud"); export const messages = utils.ruleMessages(ruleName, { expected: "Expected // for comments instead of /*" }); function rule(primary) { return (root, result) => { const validOptions = utils.validateOptions(result, ruleName, { actual: primary }); if (!validOptions) { return; } root.walkComments(comment => { if (isLoudComment(comment)) { utils.report({ message: messages.expected, node: comment, result, ruleName }); } }); }; } function isLoudComment(comment) { const regex = new RegExp(/^[ \t\n]*\/\*/); return regex.test(comment.source.input.css); } export default rule;
[Routing][Config] Allow patterns of resources to be excluded from config loading
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\GlobFileLoader; class GlobFileLoaderTest extends TestCase { public function testSupports() { $loader = new GlobFileLoader(new ContainerBuilder(), new FileLocator()); $this->assertTrue($loader->supports('any-path', 'glob'), '->supports() returns true if the resource has the glob type'); $this->assertFalse($loader->supports('any-path'), '->supports() returns false if the resource is not of glob type'); } public function testLoadAddsTheGlobResourceToTheContainer() { $loader = new GlobFileLoaderWithoutImport($container = new ContainerBuilder(), new FileLocator()); $loader->load(__DIR__.'/../Fixtures/config/*'); $this->assertEquals(new GlobResource(__DIR__.'/../Fixtures/config', '/*', false), $container->getResources()[1]); } } class GlobFileLoaderWithoutImport extends GlobFileLoader { public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null, $exclude = null) { } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Tests\Loader; use PHPUnit\Framework\TestCase; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\GlobFileLoader; class GlobFileLoaderTest extends TestCase { public function testSupports() { $loader = new GlobFileLoader(new ContainerBuilder(), new FileLocator()); $this->assertTrue($loader->supports('any-path', 'glob'), '->supports() returns true if the resource has the glob type'); $this->assertFalse($loader->supports('any-path'), '->supports() returns false if the resource is not of glob type'); } public function testLoadAddsTheGlobResourceToTheContainer() { $loader = new GlobFileLoaderWithoutImport($container = new ContainerBuilder(), new FileLocator()); $loader->load(__DIR__.'/../Fixtures/config/*'); $this->assertEquals(new GlobResource(__DIR__.'/../Fixtures/config', '/*', false), $container->getResources()[1]); } } class GlobFileLoaderWithoutImport extends GlobFileLoader { public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null) { } }
Fix LineAnimator example to adhere to new pixel edges axis_ranges API.
""" ============= LineAnimator ============= This example shows off some ways in which you can use the LineAnimator object to animate line plots. """ import numpy as np import matplotlib.pyplot as plt from sunpy.visualization.animator import LineAnimator ############################################################################### # Animate a 2D cube of random data as a line plot along an # axis where the x-axis drifts with time. # Define some random data data_shape0 = (10, 20) data0 = np.random.rand(*data_shape0) ############################################################################### # Define the axis that will make up the line plot plot_axis0 = 1 slider_axis0 = 0 ############################################################################### # Define value along x axis which drift with time. To do this, define # xdata to be the same shape as the data where each row/column # (depending on axis to be animated) represents the x-axis values for # a single frame of the animations. xdata = np.tile(np.linspace(0, 100, (data_shape0[plot_axis0]+1)), (data_shape0[slider_axis0], 1)) ############################################################################### # Generate animation object with variable x-axis data. ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata]) ############################################################################### # Show plot plt.show()
""" ============= LineAnimator ============= This example shows off some ways in which you can use the LineAnimator object to animate line plots. """ import numpy as np import matplotlib.pyplot as plt from sunpy.visualization.animator import LineAnimator ############################################################################### # Animate a 2D cube of random data as a line plot along an # axis where the x-axis drifts with time. # Define some random data data_shape0 = (10, 20) data0 = np.random.rand(*data_shape0) ############################################################################### # Define the axis that will make up the line plot plot_axis0 = 1 slider_axis0 = 0 ############################################################################### # Define value along x axis which drift with time. To do this, define # xdata to be the same shape as the data where each row/column # (depending on axis to be animated) represents the x-axis values for # a single frame of the animations. xdata = np.tile(np.linspace(0, 100, data_shape0[plot_axis0]), (data_shape0[slider_axis0], 1)) ############################################################################### # Generate animation object with variable x-axis data. ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata]) ############################################################################### # Show plot plt.show()
Add consistancy to port logging
var WebSocket = require('faye-websocket'), http = require('http'), reject = require('lodash/collection/reject'), without = require('lodash/array/without'); module.exports = function (config) { var server = http.createServer(), connections = []; // Send to everyone except sender function broadcastMessageFrom(sender, data) { var sockets = reject(connections, function (c) { return c === sender; }); console.log('Broadcast to %s of %s connections', sockets.length, connections.length); sockets.forEach(function (s) { s.send(data); }); } server.on('upgrade', function(request, socket, body) { if (WebSocket.isWebSocket(request)) { var ws = new WebSocket(request, socket, body); // Keep track of new WebSocket connection connections.push(ws); ws.on('message', function(event) { console.log('New message', event.data); broadcastMessageFrom(ws, event.data); }); // Remove from connections ws.on('close', function(event) { console.log('close', event.code, event.reason); connections = without(connections, ws); ws = null; }); } }); console.log('Listening on port', config.port); server.listen(config.port); }
var WebSocket = require('faye-websocket'), http = require('http'), reject = require('lodash/collection/reject'), without = require('lodash/array/without'); module.exports = function (config) { var server = http.createServer(), connections = []; // Send to everyone except sender function broadcastMessageFrom(sender, data) { var sockets = reject(connections, function (c) { return c === sender; }); console.log('Broadcast to %s of %s connections', sockets.length, connections.length); sockets.forEach(function (s) { s.send(data); }); } server.on('upgrade', function(request, socket, body) { if (WebSocket.isWebSocket(request)) { var ws = new WebSocket(request, socket, body); // Keep track of new WebSocket connection connections.push(ws); ws.on('message', function(event) { console.log('New message', event.data); broadcastMessageFrom(ws, event.data); }); // Remove from connections ws.on('close', function(event) { console.log('close', event.code, event.reason); connections = without(connections, ws); ws = null; }); } }); console.log('Listening on ', config.port); server.listen(config.port); }
Fix bug where chip cannot be placed in last row
import _ from 'underscore'; class Grid { // The state of a particular game grid constructor({ columnCount = 7, rowCount = 6, columns = _.times(columnCount, () => []), lastPlacedChip = null }) { this.columnCount = columnCount; this.rowCount = rowCount; this.columns = columns; this.lastPlacedChip = lastPlacedChip; } // Reset the grid by removing all placed chips resetGrid() { this.columns.forEach((column) => { column.length = 0; }); this.lastPlacedChip = null; } // Place the given chip into the column defined on it placeChip(chip) { if (chip.column >= 0 && chip.column < this.columnCount && this.columns[chip.column].length < this.rowCount) { this.columns[chip.column].push(chip); this.lastPlacedChip = chip; chip.row = this.columns[chip.column].length - 1; } } toJSON() { return { columnCount: this.columnCount, rowCount: this.rowCount, columns: this.columns, lastPlacedChip: this.lastPlacedChip }; } } export default Grid;
import _ from 'underscore'; class Grid { // The state of a particular game grid constructor({ columnCount = 7, rowCount = 6, columns = _.times(columnCount, () => []), lastPlacedChip = null }) { this.columnCount = columnCount; this.rowCount = rowCount; this.columns = columns; this.lastPlacedChip = lastPlacedChip; } // Reset the grid by removing all placed chips resetGrid() { this.columns.forEach((column) => { column.length = 0; }); this.lastPlacedChip = null; } // Place the given chip into the column defined on it placeChip(chip) { if (chip.column >= 0 && chip.column < this.columnCount && (this.columns[chip.column].length + 1) < this.rowCount) { this.columns[chip.column].push(chip); this.lastPlacedChip = chip; chip.row = this.columns[chip.column].length - 1; } } toJSON() { return { columnCount: this.columnCount, rowCount: this.rowCount, columns: this.columns, lastPlacedChip: this.lastPlacedChip }; } } export default Grid;
[core] Fix import error for Python3 Import exceptions module only for Python2. fixes #22
import shlex import subprocess try: from exceptions import RuntimeError except ImportError: # Python3 doesn't require this anymore pass def bytefmt(num): for unit in [ "", "Ki", "Mi", "Gi" ]: if num < 1024.0: return "{:.2f}{}B".format(num, unit) num /= 1024.0 return "{:05.2f%}{}GiB".format(num) def durationfmt(duration): minutes, seconds = divmod(duration, 60) hours, minutes = divmod(minutes, 60) res = "{:02d}:{:02d}".format(minutes, seconds) if hours > 0: res = "{:02d}:{}".format(hours, res) return res def execute(cmd): args = shlex.split(cmd) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = p.communicate() if p.returncode != 0: raise RuntimeError("{} exited with {}".format(cmd, p.returncode))
import shlex import exceptions import subprocess def bytefmt(num): for unit in [ "", "Ki", "Mi", "Gi" ]: if num < 1024.0: return "{:.2f}{}B".format(num, unit) num /= 1024.0 return "{:05.2f%}{}GiB".format(num) def durationfmt(duration): minutes, seconds = divmod(duration, 60) hours, minutes = divmod(minutes, 60) res = "{:02d}:{:02d}".format(minutes, seconds) if hours > 0: res = "{:02d}:{}".format(hours, res) return res def execute(cmd): args = shlex.split(cmd) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = p.communicate() if p.returncode != 0: raise exceptions.RuntimeError("{} exited with {}".format(cmd, p.returncode))
Add multiline test for canonical representation
package net.sf.jabref.model.entry; import org.junit.Assert; import org.junit.Test; public class CanonicalBibEntryTest { @Test public void simpleCanonicalRepresentation() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("author", "abc"); e.setField("title", "def"); e.setField("journal", "hij"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n author = {abc},\n journal = {hij},\n title = {def}\n}", canonicalRepresentation); } @Test public void canonicalRepresentationWithNewlines() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("abstract", "line 1\nline 2"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n abstract = {line 1\nline 2}\n}", canonicalRepresentation); } }
package net.sf.jabref.model.entry; import org.junit.Assert; import org.junit.Test; public class CanonicalBibEntryTest { /** * Simple test for the canonical format */ @Test public void canonicalRepresentation() { BibEntry e = new BibEntry("id", BibtexEntryTypes.ARTICLE); e.setField(BibEntry.KEY_FIELD, "key"); e.setField("author", "abc"); e.setField("title", "def"); e.setField("journal", "hij"); String canonicalRepresentation = CanonicalBibtexEntry.getCanonicalRepresentation(e); Assert.assertEquals("@article{key,\n author = {abc},\n journal = {hij},\n title = {def}\n}", canonicalRepresentation); } }
Fix routing to /bolt to / in tests
'use strict'; describe('Routing', function () { var $route; beforeEach(module('bolt')); beforeEach(inject(function ($injector) { $route = $injector.get('$route'); })); it('Should have /signup route, template, and controller', function () { expect($route.routes['/signup']).to.be.defined; expect($route.routes['/signup'].controller).to.equal('AuthController'); expect($route.routes['/signup'].templateUrl).to.equal('app/auth/signup.html'); }); it('Should have /signin route, template, and controller', function () { expect($route.routes['/signin']).to.be.defined; expect($route.routes['/signin'].controller).to.equal('AuthController'); expect($route.routes['/signin'].templateUrl).to.equal('app/auth/signin.html'); }); it('Should have /bolt route, template, and controller', function () { expect($route.routes['/']).to.be.defined; expect($route.routes['/'].controller).to.equal('BoltController'); expect($route.routes['/'].templateUrl).to.equal('app/views/bolt.html'); }); // it('Should have /shorten route, template, and controller', function () { // expect($route.routes['/shorten']).to.be.defined; // expect($route.routes['/shorten'].controller).to.equal('ShortenController'); // expect($route.routes['/shorten'].templateUrl).to.equal('app/shorten/shorten.html'); // }); });
'use strict'; describe('Routing', function () { var $route; beforeEach(module('bolt')); beforeEach(inject(function ($injector) { $route = $injector.get('$route'); })); it('Should have /signup route, template, and controller', function () { expect($route.routes['/signup']).to.be.defined; expect($route.routes['/signup'].controller).to.equal('AuthController'); expect($route.routes['/signup'].templateUrl).to.equal('app/auth/signup.html'); }); it('Should have /signin route, template, and controller', function () { expect($route.routes['/signin']).to.be.defined; expect($route.routes['/signin'].controller).to.equal('AuthController'); expect($route.routes['/signin'].templateUrl).to.equal('app/auth/signin.html'); }); it('Should have /bolt route, template, and controller', function () { expect($route.routes['/bolt']).to.be.defined; expect($route.routes['/bolt'].controller).to.equal('BoltController'); expect($route.routes['/bolt'].templateUrl).to.equal('app/views/bolt.html'); }); // it('Should have /shorten route, template, and controller', function () { // expect($route.routes['/shorten']).to.be.defined; // expect($route.routes['/shorten'].controller).to.equal('ShortenController'); // expect($route.routes['/shorten'].templateUrl).to.equal('app/shorten/shorten.html'); // }); });
Fix system defaults overriding all args
'use strict'; const { mapValues, omitBy } = require('../../../utilities'); const { defaults } = require('./defaults'); // Apply system-defined defaults to input, including input arguments const systemDefaults = async function (nextFunc, input) { const { serverOpts } = input; const argsA = getDefaultArgs({ serverOpts, input }); const inputA = Object.assign({}, input, { args: argsA }); const response = await nextFunc(inputA); return response; }; // Retrieve default arguments const getDefaultArgs = function ({ serverOpts, input, input: { command, args }, }) { const filteredDefaults = omitBy( defaults, ({ commands, test: testFunc }, attrName) => // Whitelist by command.name (commands && !commands.includes(command.name)) || // Whitelist by tests (testFunc && !testFunc({ serverOpts, input })) || // Only if user has not specified that argument args[attrName] !== undefined ); // Reduce to a single object const defaultArgs = mapValues(filteredDefaults, ({ value }) => (typeof value === 'function' ? value({ serverOpts, input }) : value) ); return Object.assign({}, args, defaultArgs); }; module.exports = { systemDefaults, };
'use strict'; const { mapValues, omitBy } = require('../../../utilities'); const { defaults } = require('./defaults'); // Apply system-defined defaults to input, including input arguments const systemDefaults = async function (nextFunc, input) { const { serverOpts } = input; const argsA = getDefaultArgs({ serverOpts, input }); const inputA = Object.assign({}, input, { args: argsA }); const response = await nextFunc(inputA); return response; }; // Retrieve default arguments const getDefaultArgs = function ({ serverOpts, input, input: { command, args }, }) { const filteredDefaults = omitBy( defaults, ({ commands, test: testFunc }, attrName) => // Whitelist by command.name (commands && !commands.includes(command.name)) || // Whitelist by tests (testFunc && !testFunc({ serverOpts, input })) || // Only if user has not specified that argument args[attrName] !== undefined ); // Reduce to a single object const defaultArgs = mapValues(filteredDefaults, ({ value }) => (typeof value === 'function' ? value({ serverOpts, input }) : value) ); return defaultArgs; }; module.exports = { systemDefaults, };
Remove dependency on apply() since it gets injected anyways.
/** * Provides a bridge to provide configuration data for plugins. Consumes an * optional config object containing the configuration data and produces a * function. This function consumes a plugin and returns another plugin with * the given configuration applied to it. * Several configure() calls can be made successively on the returned plugin, * with the outer config objects overwriting the keys in the innermost configs. * @param {Object} [config={}] - An object containing the configuration data to * pass to the plugin. * @returns {Function} A function consuming a plugin and producing another plugin * with the provided config applied to it. */ export default (config = {}) => { return plugin => (generatorApi) => { // merge the original config and the trickled config const { apply, config: trickledConfig = {}, ...rest } = generatorApi; const updatedConfig = { ...config, ...trickledConfig }; let command = plugin({ ...rest, apply, config: updatedConfig }); // extract default keys const { triggers: [], middleware: [], description, } = updatedConfig; // update the command accordingly if (triggers.length) { command.react(...triggers); } else if (middleware.length) { command = apply(...middleware)(command); } else if (description) { command.describe(description); } return command; }; };
import apply from './apply'; /** * Provides a bridge to provide configuration data for plugins. Consumes an * optional config object containing the configuration data and produces a * function. This function consumes a plugin and returns another plugin with * the given configuration applied to it. * Several configure() calls can be made successively on the returned plugin, * with the outer config objects overwriting the keys in the innermost configs. * @param {Object} [config={}] - An object containing the configuration data to * pass to the plugin. * @returns {Function} A function consuming a plugin and producing another plugin * with the provided config applied to it. */ export default (config = {}) => { return plugin => (generatorApi) => { // merge the original config and the trickled config const { config: trickledConfig = {}, ...rest } = generatorApi; const updatedConfig = { ...config, ...trickledConfig }; let command = plugin({ ...rest, config: updatedConfig }); // extract default keys const { triggers: [], middleware: [], description, } = updatedConfig; // update the command accordingly if (triggers.length) { command.react(...triggers); } else if (middleware.length) { command = apply(...middleware)(command); } else if (description) { command.describe(description); } return command; }; };
Update consumer key and secret usage in auth tests
import random import unittest from .config import * from tweepy import API, OAuthHandler class TweepyAuthTests(unittest.TestCase): def testoauth(self): auth = OAuthHandler(consumer_key, consumer_secret) # test getting access token auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() self.assertTrue(len(verifier) > 0) access_token = auth.get_access_token(verifier) self.assertTrue(access_token is not None) # build api object test using oauth api = API(auth) s = api.update_status(f'test {random.randint(0, 1000)}') api.destroy_status(s.id) def testaccesstype(self): auth = OAuthHandler(consumer_key, consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = input('Did Twitter only request read permissions? (y/n) ') self.assertEqual('y', answer.lower())
import random import unittest from .config import * from tweepy import API, OAuthHandler class TweepyAuthTests(unittest.TestCase): def testoauth(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) # test getting access token auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() self.assertTrue(len(verifier) > 0) access_token = auth.get_access_token(verifier) self.assertTrue(access_token is not None) # build api object test using oauth api = API(auth) s = api.update_status(f'test {random.randint(0, 1000)}') api.destroy_status(s.id) def testaccesstype(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = input('Did Twitter only request read permissions? (y/n) ') self.assertEqual('y', answer.lower())
Make Diagnosis come before PMH closes #5
""" Define acute schemas. """ from acute import models list_columns = [ models.Demographics, models.Location, models.Diagnosis, models.PastMedicalHistory, models.Plan, models.Rescuscitation ] list_columns_take = [ models.Demographics, models.Location, models.Clerking, models.Diagnosis, models.PastMedicalHistory, models.Plan, models.Rescuscitation ] list_columns_specialist_teams = [ models.Demographics, models.Location, models.Diagnosis, models.PastMedicalHistory, models.Plan, models.Treatment, models.Investigation, models.DischargeDue, ] list_schemas = { 'default': list_columns, 'take': { 'default': list_columns_take }, 'cardiology': { 'default': list_columns_specialist_teams }, 'respiratory': list_columns_specialist_teams } detail_columns = list_columns
""" Define acute schemas. """ from acute import models list_columns = [ models.Demographics, models.Location, models.PastMedicalHistory, models.Diagnosis, models.Plan, models.Rescuscitation ] list_columns_take = [ models.Demographics, models.Location, models.Clerking, models.PastMedicalHistory, models.Diagnosis, models.Plan, models.Rescuscitation ] list_columns_specialist_teams = [ models.Demographics, models.Location, models.PastMedicalHistory, models.Diagnosis, models.Plan, models.Treatment, models.Investigation, models.DischargeDue, ] list_schemas = { 'default': list_columns, 'take': { 'default': list_columns_take }, 'cardiology': { 'default': list_columns_specialist_teams }, 'respiratory': list_columns_specialist_teams } detail_columns = list_columns