text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Change location of default settings in WSGI
""" WSGI config for workout_manager project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
""" WSGI config for workout_manager project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "workout_manager.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Refactor the script file url
<?php /** * Application component for registering with the Grunt's live reload plugin. */ class LiveReload extends CApplicationComponent { /** * @var string the host name of the server running the live reload server. */ public $host = 'localhost'; /** * @var array live reload ports. */ public $port = 35729; /** * @var string the component ID for the client script component. */ public $clientScriptID = 'clientScript'; /** * Registers the live reload servers. */ public function register() { if (($cs = Yii::app()->getComponent($this->clientScriptID)) !== null) { $cs->registerScriptFile( "{$this->host}:{$this->port}/livereload.js", CClientScript::POS_END ); } } }
<?php /** * Application component for registering with the Grunt's live reload plugin. */ class LiveReload extends CApplicationComponent { /** * @var string the host name of the server running the live reload server. */ public $host = 'localhost'; /** * @var array live reload ports. */ public $port = 35729; /** * @var string the component ID for the client script component. */ public $clientScriptID = 'clientScript'; /** * Registers the live reload servers. */ public function register() { if (($cs = Yii::app()->getComponent($this->clientScriptID)) !== null) { $cs->registerScriptFile( $this->host . ':' . (string)$this->port . '/livereload.js', CClientScript::POS_END ); } } }
Fix LinkTag mit mehreren News Komponenten es wurde immer die erste ausgewählt = != ==
<?php class Vpc_Basic_LinkTag_News_Form extends Vpc_Abstract_Form { protected function _initFields() { parent::_initFields(); } public function __construct($name, $class, $id = null) { parent::__construct($name, $class, $id); $this->add(new Vps_Form_Field_Select('news_id', trlVps('News'))) ->setDisplayField('title') ->setStoreUrl( Vpc_Admin::getInstance($class)->getControllerUrl('News').'/json-data' ) ->setListWidth(210) ->setAllowBlank(false); } public function getIsCurrentLinkTag($parentRow) { $row = $this->getRow($parentRow); $c = Vps_Component_Data_Root::getInstance()->getComponentByDbId('news_'.$row->news_id); return 'news_'.$c->parent->dbId == $this->getName(); } }
<?php class Vpc_Basic_LinkTag_News_Form extends Vpc_Abstract_Form { protected function _initFields() { parent::_initFields(); } public function __construct($name, $class, $id = null) { parent::__construct($name, $class, $id); $this->add(new Vps_Form_Field_Select('news_id', trlVps('News'))) ->setDisplayField('title') ->setStoreUrl( Vpc_Admin::getInstance($class)->getControllerUrl('News').'/json-data' ) ->setListWidth(210) ->setAllowBlank(false); } public function getIsCurrentLinkTag($parentRow) { $row = $this->getRow($parentRow); $c = Vps_Component_Data_Root::getInstance()->getComponentByDbId('news_'.$row->news_id); return 'news_'.$c->parent->dbId = $this->getName(); } }
108536374: Change to a generic message for database errors. Need a story to handle db exceptions in the dao layer
from datetime import datetime from flask import render_template, redirect, jsonify from app.main import main from app.main.dao import users_dao from app.main.forms import RegisterUserForm from app.models import User @main.route("/register", methods=['GET']) def render_register(): return render_template('register.html', form=RegisterUserForm()) @main.route('/register', methods=['POST']) def process_register(): form = RegisterUserForm() if form.validate_on_submit(): user = User(name=form.name.data, email_address=form.email_address.data, mobile_number=form.mobile_number.data, password=form.password.data, created_at=datetime.now(), role_id=1) try: users_dao.insert_user(user) return redirect('/two-factor') except Exception as e: return jsonify(database_error='encountered database error'), 400 else: return jsonify(form.errors), 400
from datetime import datetime from flask import render_template, redirect, jsonify from app.main import main from app.main.dao import users_dao from app.main.forms import RegisterUserForm from app.models import User @main.route("/register", methods=['GET']) def render_register(): return render_template('register.html', form=RegisterUserForm()) @main.route('/register', methods=['POST']) def process_register(): form = RegisterUserForm() if form.validate_on_submit(): user = User(name=form.name.data, email_address=form.email_address.data, mobile_number=form.mobile_number.data, password=form.password.data, created_at=datetime.now(), role_id=1) try: users_dao.insert_user(user) return redirect('/two-factor') except Exception as e: return jsonify(database_error=e.message), 400 else: return jsonify(form.errors), 400
Add owner to API call for tournaments list
<?php namespace App\Transformers; use App\Models\Tournament; use League\Fractal\TransformerAbstract; class TournamentTransformer extends TransformerAbstract { public function transform(Tournament $tournament) { $teams = []; foreach ($tournament->tournamentTeams as $tournamentTeam) { $teams[] = $tournamentTeam->id; } return [ 'id' => $tournament->id, 'name' => $tournament->name, 'owner' => $tournament->owner, 'status' => $tournament->status, 'type' => $tournament->type, 'membersType' => $tournament->membersType, 'teams' => $teams, 'description' => $tournament->description, 'updated_at' => $tournament->updated_at->format('F d, Y') ]; } }
<?php namespace App\Transformers; use App\Models\Tournament; use League\Fractal\TransformerAbstract; class TournamentTransformer extends TransformerAbstract { public function transform(Tournament $tournament) { $teams = []; foreach ($tournament->tournamentTeams as $tournamentTeam) { $teams[] = $tournamentTeam->id; } return [ 'id' => $tournament->id, 'name' => $tournament->name, 'status' => $tournament->status, 'type' => $tournament->type, 'membersType' => $tournament->membersType, 'teams' => $teams, 'description' => $tournament->description, 'updated_at' => $tournament->updated_at->format('F d, Y') ]; } }
Add progress back into the reducer list
import { combineReducers } from 'redux'; import settings from './settings'; import application from './application'; import assessment from './assessment'; import assessmentProgress from './assessment_progress'; import jwt from './jwt'; import assessmentMeta from './assessment_meta'; import assessmentResults from './assessment_results'; const rootReducer = combineReducers({ settings, jwt, application, assessment, assessmentProgress, assessmentMeta, assessmentResults }); export default rootReducer;
import { combineReducers } from 'redux'; import settings from './settings'; import application from './application'; import assessment from './assessment'; import assessmentProgress from './assessment_progress'; import jwt from './jwt'; import assessmentMeta from './assessment_meta'; import assessmentResults from './assessment_results'; const rootReducer = combineReducers({ settings, jwt, application, assessment, assessmentMeta, assessmentResults }); export default rootReducer;
Use os.path.expanduser to find config directory Works on Windows and Unix.
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): ctx.config_dir = os.path.expanduser('~/.panoptes/') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'] ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import *
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): ctx.config_dir = os.path.join(os.environ['HOME'], '.panoptes') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { 'endpoint': 'https://panoptes.zooniverse.org', 'username': '', 'password': '', } try: with open(ctx.config_file) as conf_f: ctx.config.update(yaml.load(conf_f)) except IOError: pass if endpoint: ctx.config['endpoint'] = endpoint Panoptes.connect( endpoint=ctx.config['endpoint'], username=ctx.config['username'], password=ctx.config['password'] ) from panoptes_cli.commands.configure import * from panoptes_cli.commands.project import * from panoptes_cli.commands.subject import * from panoptes_cli.commands.subject_set import * from panoptes_cli.commands.workflow import *
Clear ResourceBundle cache on reload
package fr.aumgn.dac2; import fr.aumgn.bukkitutils.localization.PluginResourceBundles; import fr.aumgn.bukkitutils.localization.bundle.PluginResourceBundle; import fr.aumgn.dac2.config.DACConfig; public class DAC { private final DACPlugin plugin; private DACConfig config; private PluginResourceBundle cmdMessages; private PluginResourceBundle messages; public DAC(DACPlugin plugin) { this.plugin = plugin; reloadData(); } public DACPlugin getPlugin() { return plugin; } public DACConfig getConfig() { return config; } public PluginResourceBundle getCmdMessages() { return cmdMessages; } public PluginResourceBundle getMessages() { return messages; } public void reloadData() { config = plugin.reloadDACConfig(); PluginResourceBundles.clearCache(plugin); PluginResourceBundles bundles = new PluginResourceBundles(plugin, config.getLocale(), plugin.getDataFolder()); cmdMessages = bundles.get("commands"); messages = bundles.get("messages"); } }
package fr.aumgn.dac2; import fr.aumgn.bukkitutils.localization.PluginResourceBundles; import fr.aumgn.bukkitutils.localization.bundle.PluginResourceBundle; import fr.aumgn.dac2.config.DACConfig; public class DAC { private final DACPlugin plugin; private DACConfig config; private PluginResourceBundle cmdMessages; private PluginResourceBundle messages; public DAC(DACPlugin plugin) { this.plugin = plugin; reloadData(); } public DACPlugin getPlugin() { return plugin; } public DACConfig getConfig() { return config; } public PluginResourceBundle getCmdMessages() { return cmdMessages; } public PluginResourceBundle getMessages() { return messages; } public void reloadData() { config = plugin.reloadDACConfig(); PluginResourceBundles bundles = new PluginResourceBundles(plugin, config.getLocale(), plugin.getDataFolder()); cmdMessages = bundles.get("commands"); messages = bundles.get("messages"); } }
Check if any translations are present in file
<?php declare(strict_types=1); namespace Wingu\FluffyPoRobot\Translation\Loader; use Symfony\Component\Translation\Exception\InvalidResourceException; use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Parser as YamlParser; use Symfony\Component\Yaml\Yaml; use function array_values; use function is_array; use function Safe\file_get_contents; use function Safe\sprintf; class YamlFileLoader extends FileLoader { /** * {@inheritdoc} */ protected function loadResource(string $resource) : array { try { $yamlParser = new YamlParser(); $translations = $yamlParser->parse(file_get_contents($resource), Yaml::DUMP_OBJECT_AS_MAP); } catch (ParseException $e) { throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $resource), 0, $e); } if ($translations === null) { return []; } $messages = []; foreach ($translations as $key => $message) { $messages[$key] = is_array($message) ? array_values($message) : $message; } return $messages; } }
<?php declare(strict_types=1); namespace Wingu\FluffyPoRobot\Translation\Loader; use Symfony\Component\Translation\Exception\InvalidResourceException; use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Parser as YamlParser; use Symfony\Component\Yaml\Yaml; use function array_values; use function is_array; use function Safe\file_get_contents; use function Safe\sprintf; class YamlFileLoader extends FileLoader { /** * {@inheritdoc} */ protected function loadResource(string $resource) : array { try { $yamlParser = new YamlParser(); $translations = $yamlParser->parse(file_get_contents($resource), Yaml::DUMP_OBJECT_AS_MAP); } catch (ParseException $e) { throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $resource), 0, $e); } $messages = []; foreach ($translations as $key => $message) { $messages[$key] = is_array($message) ? array_values($message) : $message; } return $messages; } }
Add service name for replacement pattern registry
<?php /* * This file is part of the PcdxParameterEncryptionBundle package. * * (c) picodexter <https://picodexter.io/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Picodexter\ParameterEncryptionBundle\DependencyInjection; /** * ServiceNames. * * Contains names for this bundle's Symfony services that are referenced in the code. */ final class ServiceNames { const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration'; const ALGORITHM_PREFIX = 'pcdx_parameter_encryption.configuration.algorithm.'; const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer'; const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.'; const REPLACEMENT_PATTERN_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.registry'; /** * Constructor. * * Forbid instantiation. */ public function __construct() { throw new \BadMethodCallException('This class cannot be instantiated.'); } }
<?php /* * This file is part of the PcdxParameterEncryptionBundle package. * * (c) picodexter <https://picodexter.io/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Picodexter\ParameterEncryptionBundle\DependencyInjection; /** * ServiceNames. * * Contains names for this bundle's Symfony services that are referenced in the code. */ final class ServiceNames { const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration'; const ALGORITHM_PREFIX = 'pcdx_parameter_encryption.configuration.algorithm.'; const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer'; const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.'; /** * Constructor. * * Forbid instantiation. */ public function __construct() { throw new \BadMethodCallException('This class cannot be instantiated.'); } }
Switch to hex encoding for key values
package com.kryptnostic.api.v1.client; import java.io.File; import java.io.IOException; import org.apache.commons.codec.binary.Hex; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import com.google.common.io.Files; import com.kryptnostic.kodex.v1.storage.DataStore; /** * A simple implementation of the client datastore. The keys are used to generate filenames. * * @author Nick Hewitt &lt;nick@kryptnostic.com&gt; * */ public class FileStore implements DataStore { private final File rootDirectory; public FileStore(String name) { this.rootDirectory = new File(".kryptnostic", name); this.rootDirectory.mkdir(); } @Override public byte[] get(byte[] key) throws IOException { File keyFile = keyToFile(key); if (keyFile.isFile()) { byte[] data = Files.toByteArray(keyFile); return data; } return null; } @Override public void put(byte[] key, byte[] value) throws IOException { File keyFile = keyToFile(key); Files.write(value, keyFile); } private File keyToFile(byte[] key) { return new File(rootDirectory, Hex.encodeHexString( key ) ); } }
package com.kryptnostic.api.v1.client; import java.io.File; import java.io.IOException; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import com.google.common.io.Files; import com.kryptnostic.kodex.v1.storage.DataStore; /** * A simple implementation of the client datastore. The keys are used to generate filenames. * * @author Nick Hewitt &lt;nick@kryptnostic.com&gt; * */ public class FileStore implements DataStore { private final File rootDirectory; private static HashFunction hf = Hashing.murmur3_128(); public FileStore(String name) { this.rootDirectory = new File(System.getProperty("user.home"), name); this.rootDirectory.mkdir(); } @Override public byte[] get(byte[] key) throws IOException { File keyFile = keyToFile(key); if (keyFile.isFile()) { byte[] data = Files.toByteArray(keyFile); return data; } return null; } @Override public void put(byte[] key, byte[] value) throws IOException { File keyFile = keyToFile(key); Files.write(value, keyFile); } private File keyToFile(byte[] key) { Long longEncodedKey = hf.hashBytes(key).asLong(); return new File(rootDirectory, longEncodedKey.toString()); } }
Fix globus-sdk python package name To match recent change in SDK repo
from setuptools import setup, find_packages setup( name="globus-cli", version="0.1.0", packages=find_packages(), install_requires=['globus-sdk'], # for now, install directly from GitHub # TODO: once this is on pypi, install from there dependency_links=[ ('https://github.com/globusonline/globus-sdk-python/' 'archive/master.zip#egg=globus-sdk-0.1') ], entry_points={ 'console_scripts': ['globus = globus_cli:run_command'] }, # descriptive info, non-critical description="Globus CLI", long_description=open("README.md").read(), author="Stephen Rosen", author_email="sirosen@globus.org", url="https://github.com/globusonline/globus-cli", keywords=["globus", "cli", "command line"], classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: POSIX", "Programming Language :: Python", ], )
from setuptools import setup, find_packages setup( name="globus-cli", version="0.1.0", packages=find_packages(), install_requires=['globus-sdk-python'], # for now, install directly from GitHub # TODO: once this is on pypi, install from there dependency_links=[ ('https://github.com/globusonline/globus-sdk-python/' 'archive/master.zip#egg=globus-sdk-python-0.1') ], entry_points={ 'console_scripts': ['globus = globus_cli:run_command'] }, # descriptive info, non-critical description="Globus CLI", long_description=open("README.md").read(), author="Stephen Rosen", author_email="sirosen@globus.org", url="https://github.com/globusonline/globus-cli", keywords=["globus", "cli", "command line"], classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: POSIX", "Programming Language :: Python", ], )
Change EnumSet to Set for better polymorphism.
package language; import java.util.EnumSet; import java.util.Set; /** * {@code Difficulty} is an enumeration of properties which define how objects * of {@link Word} are formatted and also provides for "difficulty" properties * for use in a word game. * * <p> The properties defined in this class are designed to be * implementation-dependant and have no values stored to them other than their * names. * * @author Oliver Abdulrahim */ public enum Difficulty { /** * Defines a {@code Word} with easy difficulty. */ EASY, /** * Defines a {@code Word} with medium difficulty. */ MEDIUM, /** * Defines a {@code Word} with hard difficulty. */ HARD, /** * Defines a {@code Word} with default difficultly. */ DEFAULT; /** * Provides for a set of all properties enumerated in this class. */ public static final Set<Difficulty> ALL = // Pryda 10 VOL III is out EnumSet.allOf(Difficulty.class); }
package language; import java.util.EnumSet; /** * {@code Difficulty} is an enumeration of properties which define how objects * of {@link Word} are formatted and also provides for "difficulty" properties * for use in a word game. * * <p> The properties defined in this class are designed to be * implementation-dependant and have no values stored to them other than their * names. * * @author Oliver Abdulrahim */ public enum Difficulty { // Difficulty properties /** * Defines a {@code Word} with easy difficulty. */ EASY, /** * Defines a {@code Word} with medium difficulty. */ MEDIUM, /** * Defines a {@code Word} with hard difficulty. */ HARD, /** * Defines a {@code Word} with default difficultly. */ DEFAULT; /** * Provides for a set of all properties enumerated in this class. */ public static final EnumSet<Difficulty> ALL = // Pryda 10 VOL III is out EnumSet.allOf(Difficulty.class); }
Fix invalid reference before first scroll
'use strict'; // http://stackoverflow.com/a/872537 function getScrollTop(){ if ( typeof window.pageYOffset !== 'undefined' ) { // most browsers except IE before #9 return window.pageYOffset; } else { var b = document.body; // IE 'quirks' var d = document.documentElement; // IE with doctype return ((d.clientHeight) ? d : b).scrollTop; } } module.exports = [ '$rootScope', '$window', '$timeout', function BroadcastScrollPositionDirective($rootScope, $window, $timeout) { return { restrict: 'A', link: function($scope, $el, attrs) { var el = attrs.assBroadcastScrollPosition ? eval(attrs.assBroadcastScrollPosition) : document.body; $rootScope.assBroadcastScrollPosition = 0; var p = $timeout(); function updateScope() { $timeout.cancel(p); p = $timeout(function(){ $rootScope.$apply(function(){ $rootScope.assBroadcastScrollPosition = getScrollTop() - el.offsetHeight + window.innerHeight*2.5; }); }); } $window.addEventListener('scroll', updateScope); $window.addEventListener('touchstart', updateScope); updateScope(); } }; } ];
'use strict'; // http://stackoverflow.com/a/872537 function getScrollTop(){ if ( typeof window.pageYOffset !== 'undefined' ) { // most browsers except IE before #9 return window.pageYOffset; } else { var b = document.body; // IE 'quirks' var d = document.documentElement; // IE with doctype return ((d.clientHeight) ? d : b).scrollTop; } } module.exports = [ '$rootScope', '$window', '$timeout', function BroadcastScrollPositionDirective($rootScope, $window, $timeout) { return { restrict: 'A', link: function($scope, $el, attrs) { var el = attrs.assBroadcastScrollPosition ? eval(attrs.assBroadcastScrollPosition) : document.body; $rootScope.assBroadcastScrollPosition = 0; var p = $timeout(); function updateScope() { $timeout.cancel(p); p = $timeout(function(){ $rootScope.$apply(function(){ $rootScope.assBroadcastScrollPosition = getScrollTop() - el.offsetHeight + window.innerHeight*2.5; }); }); } $window.addEventListener('scroll', updateScope); $window.addEventListener('touchstart', updateScope); } }; } ];
Fix forceUpdate sometimes called on unmounted component.
/* @flow */ import React from 'react' import MessageView from '../Message' import type { Message } from 'types' import styles from './style.css' type Props = { messages: Array<Message> } export default class MessageList extends React.Component<*, Props, *> { timer: Object constructor (props: Props) { super(props) } componentDidMount () { // Every minute, update chat timestamps this.timer = setInterval(() => this.forceUpdate(), 60000) } componentDidUpdate () { this.refs.scroll.scrollTop += 10000 } componentWillUnmount () { clearInterval(this.timer) } render () { return <div className={ styles.messages } ref='scroll'> {this.props.messages.map(message => <MessageView key={message.key} message={message} /> )} <div className={ styles.spacer }>&nbsp;</div> </div> } }
/* @flow */ import React from 'react' import MessageView from '../Message' import type { Message } from 'types' import styles from './style.css' type Props = { messages: Array<Message> } export default class MessageList extends React.Component<*, Props, *> { constructor (props: Props) { super(props) // Every minute, update chat timestamps setInterval(() => this.forceUpdate(), 60000) } componentDidUpdate () { this.refs.scroll.scrollTop += 10000 } render () { return <div className={ styles.messages } ref='scroll'> {this.props.messages.map(message => <MessageView key={message.key} message={message} /> )} <div className={ styles.spacer }>&nbsp;</div> </div> } }
Use <div> instead of <span> when dynamically generating module routes and containers The `getModuleRoutes` method appears to generate a routing entry for all loaded stripes modules. It then maps those routes to a container node that sort of functions as a namespace for the different UI modules installed in the Folio instance. We were using spans here, but it's probably better to use divs to avoid nesting block-level elements inside inline elements. This isn't blocking anything that we know of, but we stumbled across it while doing some layout work and figured it was worthy of a quick patch.
import React from 'react'; import Route from 'react-router-dom/Route'; import { connectFor } from '@folio/stripes-connect'; import { modules } from 'stripes-loader'; // eslint-disable-line import AddContext from './AddContext'; if (!Array.isArray(modules.app) && modules.length < 0) { throw new Error('At least one module of type "app" must be enabled.'); } function getModuleRoutes(stripes) { return modules.app.map((module) => { const name = module.module.replace(/^@folio\//, ''); const perm = `module.${name}.enabled`; if (!stripes.hasPerm(perm)) return null; const connect = connectFor(module.module, stripes.epics, stripes.logger); const Current = connect(module.getModule()); const moduleStripes = stripes.clone({ connect }); return ( <Route path={module.route} key={module.route} render={props => ( <AddContext context={{ stripes: moduleStripes }}> <div id={`${name}-module-display`} data-module={module.module} data-version={module.version} > <Current {...props} connect={connect} stripes={moduleStripes} /> </div> </AddContext> )} /> ); }).filter(x => x); } export default getModuleRoutes;
import React from 'react'; import Route from 'react-router-dom/Route'; import { connectFor } from '@folio/stripes-connect'; import { modules } from 'stripes-loader'; // eslint-disable-line import AddContext from './AddContext'; if (!Array.isArray(modules.app) && modules.length < 0) { throw new Error('At least one module of type "app" must be enabled.'); } function getModuleRoutes(stripes) { return modules.app.map((module) => { const name = module.module.replace(/^@folio\//, ''); const perm = `module.${name}.enabled`; if (!stripes.hasPerm(perm)) return null; const connect = connectFor(module.module, stripes.epics, stripes.logger); const Current = connect(module.getModule()); const moduleStripes = stripes.clone({ connect }); return ( <Route path={module.route} key={module.route} render={props => ( <AddContext context={{ stripes: moduleStripes }}> <span id={`${name}-module-display`} data-module={module.module} data-version={module.version} > <Current {...props} connect={connect} stripes={moduleStripes} /> </span> </AddContext> )} /> ); }).filter(x => x); } export default getModuleRoutes;
Mark package as not zip_safe
#!/usr/bin/env python import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="statprof-smarkets", version="0.2.0c1", author="Smarkets", author_email="support@smarkets.com", description="Statistical profiling for Python", license=read('LICENSE'), keywords="profiling", url="https://github.com/smarkets/statprof", py_modules=['statprof'], long_description=read('README.rst'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], install_requires=[ 'six>=1.5.0', ], zip_safe=False, )
#!/usr/bin/env python import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="statprof-smarkets", version="0.2.0c1", author="Smarkets", author_email="support@smarkets.com", description="Statistical profiling for Python", license=read('LICENSE'), keywords="profiling", url="https://github.com/smarkets/statprof", py_modules=['statprof'], long_description=read('README.rst'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], install_requires=[ 'six>=1.5.0', ], )
Add own tuple_index function to stay compatible with python 2.5
from social_auth.backends import PIPELINE from social_auth.utils import setting PIPELINE_ENTRY = 'social_auth.backends.pipeline.misc.save_status_to_session' def tuple_index(t, e): for (i, te) in enumerate(t): if te == e: return i return None def save_status_to_session(request, auth, *args, **kwargs): """Saves current social-auth status to session.""" next_entry = setting('SOCIAL_AUTH_PIPELINE_RESUME_ENTRY') if next_entry: idx = tuple_index(PIPELINE, next_entry) else: idx = tuple_index(PIPELINE, PIPELINE_ENTRY) if idx: idx += 1 data = auth.to_session_dict(idx, *args, **kwargs) name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline') request.session[name] = data request.session.modified = True
from social_auth.backends import PIPELINE from social_auth.utils import setting PIPELINE_ENTRY = 'social_auth.backends.pipeline.misc.save_status_to_session' def save_status_to_session(request, auth, *args, **kwargs): """Saves current social-auth status to session.""" next_entry = setting('SOCIAL_AUTH_PIPELINE_RESUME_ENTRY') try: if next_entry: idx = PIPELINE.index(next_entry) else: idx = PIPELINE.index(PIPELINE_ENTRY) + 1 except ValueError: idx = None data = auth.to_session_dict(idx, *args, **kwargs) name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline') request.session[name] = data request.session.modified = True
Send annotation tags as array.
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", function($http) { return function(graph, scope) { var tags = graph.tags.map(function(e) { if (e.name) { return e.name.split(",").map(function(s) { return s.trim(); }); } else { return ""; } }) if (tags.length) { var range = Prometheus.Graph.parseDuration(graph.range); var until = Math.floor(graph.endTime || Date.now()) / 1000; tags.forEach(function(t) { $http.get('/annotations', { params: { 'tags[]': t, until: until, range: range } }) .then(function(payload) { scope.$broadcast('annotateGraph', payload.data.posts); }, function(response) { scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations."); }); }); } }; }]);
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", function($http) { return function(graph, scope) { var tags = graph.tags.map(function(e) { if (e.name) { return e.name.split(",").map(function(s) { return s.trim(); }); } else { return ""; } }) if (tags.length) { var range = Prometheus.Graph.parseDuration(graph.range); var until = Math.floor(graph.endTime || Date.now()) / 1000; tags.forEach(function(t) { $http.get('/annotations', { params: { tags: t.join(","), until: until, range: range } }) .then(function(payload) { scope.$broadcast('annotateGraph', payload.data.posts); }, function(response) { scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations."); }); }); } }; }]);
Load the group when we load the store page
import angular from "angular"; import uiRouter from "angular-ui-router"; import storeDetailComponent from "./storeDetail.component"; let storeDetailModule = angular.module("storeDetail", [ uiRouter ]) .component("storeDetail", storeDetailComponent) .config(($stateProvider, hookProvider) => { "ngInject"; $stateProvider .state("storeDetail", { parent: "main", url: "/store/:id", component: "storeDetail", resolve: { storedata: (Store, $stateParams) => { return Store.get($stateParams.id); }, /** Loads the group for this store, and sets it as the current group */ groupdata: (storedata, Group, CurrentGroup) => { "ngInject"; return Group.get(storedata.group).then((group) => { CurrentGroup.set(group); return group; }); } } }); hookProvider.setup("storeDetail", { authenticated: true, anonymous: "login" }); }) .name; export default storeDetailModule;
import angular from "angular"; import uiRouter from "angular-ui-router"; import storeDetailComponent from "./storeDetail.component"; let storeDetailModule = angular.module("storeDetail", [ uiRouter ]) .component("storeDetail", storeDetailComponent) .config(($stateProvider, hookProvider) => { "ngInject"; $stateProvider .state("storeDetail", { parent: "main", url: "/store/:id", component: "storeDetail", resolve: { storedata: (Store, $stateParams) => { return Store.get($stateParams.id); } } }); hookProvider.setup("storeDetail", { authenticated: true, anonymous: "login" }); }) .name; export default storeDetailModule;
Correct blocmetrics route to include v1
var elements = document.getElementsByTagName('script') Array.prototype.forEach.call(elements, function(element) { if (element.type.indexOf('math/tex') != -1) { // Extract math markdown var textToRender = element.innerText || element.textContent; // Create span for KaTeX var katexElement = document.createElement('span'); // Support inline and display math if (element.type.indexOf('mode=display') != -1){ katexElement.className += "math-display"; textToRender = '\\displaystyle {' + textToRender + '}'; } else { katexElement.className += "math-inline"; } katex.render(textToRender, katexElement); element.parentNode.insertBefore(katexElement, element); } }); var blocmetrics = {}; blocmetrics.report = function(eventName) { var event = {event: { name: eventName }}; var request = new XMLHttpRequest(); request.open("POST", "http://blocmetrics-boltz.herokuapp.com/api/v1/events", true); request.setRequestHeader('Content-Type', 'application/json'); request.send(JSON.stringify(event)); }; $(document).ready(function() { blocmetrics.report("page load"); });
var elements = document.getElementsByTagName('script') Array.prototype.forEach.call(elements, function(element) { if (element.type.indexOf('math/tex') != -1) { // Extract math markdown var textToRender = element.innerText || element.textContent; // Create span for KaTeX var katexElement = document.createElement('span'); // Support inline and display math if (element.type.indexOf('mode=display') != -1){ katexElement.className += "math-display"; textToRender = '\\displaystyle {' + textToRender + '}'; } else { katexElement.className += "math-inline"; } katex.render(textToRender, katexElement); element.parentNode.insertBefore(katexElement, element); } }); var blocmetrics = {}; blocmetrics.report = function(eventName) { var event = {event: { name: eventName }}; var request = new XMLHttpRequest(); request.open("POST", "http://blocmetrics-boltz.herokuapp.com/api/events", true); request.setRequestHeader('Content-Type', 'application/json'); request.send(JSON.stringify(event)); }; $(document).ready(function() { blocmetrics.report("page load"); });
Fix generics as a result of Java 7 upgrade
package io.mypojo.framework; import io.mypojo.felix.framework.ServiceRegistry; import io.mypojo.felix.framework.util.EventDispatcher; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceEvent; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; @SuppressWarnings("PackageAccessibility") public class PojoSRInternals { public BundleContext m_context; public final Map<String, Bundle> m_symbolicNameToBundle = new HashMap<>(); public final ServiceRegistry m_reg = new ServiceRegistry( new ServiceRegistry.ServiceRegistryCallbacks() { public void serviceChanged(ServiceEvent event, Dictionary oldProps) { m_dispatcher.fireServiceEvent(event, oldProps, null); } }); public final EventDispatcher m_dispatcher = new EventDispatcher(m_reg); public final Map<Long, Bundle> m_bundles = new HashMap<>(); public final Map bundleConfig = new HashMap(); }
package io.mypojo.framework; import io.mypojo.felix.framework.ServiceRegistry; import io.mypojo.felix.framework.util.EventDispatcher; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceEvent; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; @SuppressWarnings("PackageAccessibility") public class PojoSRInternals { public BundleContext m_context; public final Map<String, Bundle> m_symbolicNameToBundle = new HashMap<>(); public final ServiceRegistry m_reg = new ServiceRegistry( new ServiceRegistry.ServiceRegistryCallbacks() { public void serviceChanged(ServiceEvent event, Dictionary oldProps) { m_dispatcher.fireServiceEvent(event, oldProps, null); } }); public final EventDispatcher m_dispatcher = new EventDispatcher(m_reg); public final Map<Long, Bundle> m_bundles = new HashMap<Long, Bundle>(); public final Map bundleConfig = new HashMap(); }
Fix - call function on null in activity api
<?php namespace App\Repositories; use App\Models\Activity; use Illuminate\Database\Eloquent\Collection; class ActivityRepository { /** * @var mixed */ protected $model; /** * @param Activity $activity */ public function __construct(Activity $activity) { $this->model = $activity; } /** * Return all company wide activities. * * @return \Illuminate\Database\Eloquent\Collection */ public function getAllActivities(): Collection { $query = $this->model->with(['causer:id,name,username', 'subject:id,name,created_at']); $query = request('user') ? $query->where('causer_id', request('user')) : $query; $query = request('date') ? $query->whereDate('created_at', request('date')) : $query; return $query->get()->groupBy('date'); } }
<?php namespace App\Repositories; use App\Models\Activity; use Illuminate\Database\Eloquent\Collection; class ActivityRepository { /** * @var mixed */ protected $model; /** * @param Activity $activity */ public function __construct(Activity $activity) { $this->model = $activity; } /** * Return all company wide activities. * * @return \Illuminate\Database\Eloquent\Collection */ public function getAllActivities(): Collection { $query = $this->model->with(['causer:id,name,username', 'subject:id,name']); $query = request('user') ? $query->where('causer_id', request('user')) : $query; $query = request('date') ? $query->whereDate('created_at', request('date')) : $query; return $query->get()->groupBy('date'); } }
Remove docs count for user prompt - it simply took too long to query the DB for when the DB is more full (30+ secs) - put indexes on, however would only with with '_id' + 'url', and then querying per doc type ended up taking minutes even with index :/ - now do it async in the background and remove the count given to user
import db, { normaliseFindResult } from 'src/pouchdb' import { deleteDocs } from 'src/page-storage/deletion' import { addToBlacklist } from '..' /** * Handles confirmation and running of a quick blacklist request from the popup script. * * @param {string} url The URL being blacklisted. */ export default function quickBlacklistConfirm(url) { if (window.confirm(`Do you want to delete all data matching site:\n${url}`)) { getURLMatchingDocs({ url }) .then(result => deleteDocs(result.rows)) .catch(f => f) // Too bad } addToBlacklist(url) } /** * Get all docs with matching URLs. * * @param {string} {url} Value to use to match against doc URLs. */ const getURLMatchingDocs = async ({ url, selector = {} }) => normaliseFindResult( await db.find({ selector: { ...selector, url: { $regex: url }, // All docs whose URLs contain this value }, fields: ['_id', '_rev'], }) )
import db, { normaliseFindResult } from 'src/pouchdb' import { deleteDocs } from 'src/page-storage/deletion' import { addToBlacklist } from '..' /** * Handles confirmation and running of a quick blacklist request from the popup script. * * @param {string} url The URL being blacklisted. */ export default async function quickBlacklistConfirm(url) { const { rows } = await getURLMatchingDocs({ url }) if (window.confirm(`Do you want to delete ${rows.length} matching records to ${url}?`)) { deleteDocs(rows) } addToBlacklist(url) } /** * Get all docs with matching URLs. * * @param {string} {url} Value to use to match against doc URLs. */ const getURLMatchingDocs = async ({ url, selector = {} }) => normaliseFindResult( await db.find({ selector: { ...selector, url: { $regex: url }, // All docs whose URLs contain this value }, fields: ['_id', '_rev'], }) )
Allow js requests from any website
<?php // // NOTE! // Этот PHP скриптик вытаскивает все картинки с расписанием со странички: // http://lumenfilm.com/gusev/affishe // // и возвращает JSON, который затем используется в kino_lumen.html // header("Content-type:application/json"); header("Access-Control-Allow-Origin:*"); $html = file_get_contents('http://lumenfilm.com/gusev/affishe'); preg_match_all('/\/uploads\/[0-9_]+\.jpg/', $html, $matches); foreach ($matches[0] as &$match) { $match = 'http://lumenfilm.com' . $match; } echo json_encode($matches[0]); ?>
<?php // // NOTE! // Этот PHP скриптик вытаскивает все картинки с расписанием со странички: // http://lumenfilm.com/gusev/affishe // // и возвращает JSON, который затем используется в kino_lumen.html // header("Content-type:application/json"); $html = file_get_contents('http://lumenfilm.com/gusev/affishe'); preg_match_all('/\/uploads\/[0-9_]+\.jpg/', $html, $matches); foreach ($matches[0] as &$match) { $match = 'http://lumenfilm.com' . $match; } echo json_encode($matches[0]); ?>
Change of request (sensitive problem)
<?php class Search { protected static $_pdo; protected $_table = "aliments"; public function __construct() { try { self::$_pdo = new PDO('mysql:host=localhost; dbname=nutriproject', 'root', ''); self::$_pdo->exec("SET NAMES 'UTF8'"); } catch (Exception $e) { die('Erreur : ' . $e->getMessage()); } } public function search($request) { if (isset($request) && is_string($request)) { $request = '%' . $request . '%'; $sql = self::$_pdo->prepare("SELECT id, ORIGGPFR, ORIGFDNM FROM ". $this->_table . " WHERE UPPER(ORIGGPFR) LIKE UPPER(?) OR UPPER(ORIGFDNM) LIKE UPPER(?) "); $sql->execute(array($request, $request)); return $sql->fetchAll(PDO::FETCH_ASSOC); } } } ?>
<?php class Search { protected static $_pdo; protected $_table = "aliments"; public function __construct() { try { self::$_pdo = new PDO('mysql:host=localhost; dbname=nutriproject', 'root', ''); self::$_pdo->exec("SET NAMES 'UTF8'"); } catch (Exception $e) { die('Erreur : ' . $e->getMessage()); } } public function search($request) { if (isset($request) && is_string($request)) { $request = '%' . $request . '%'; $sql = self::$_pdo->prepare("SELECT id, ORIGGPFR, ORIGFDNM FROM ". $this->_table . " WHERE ORIGGPFR LIKE ? OR ORIGFDNM LIKE ? "); $sql->execute(array($request, $request)); return $sql->fetchAll(PDO::FETCH_ASSOC); } } } ?>
Add debug output to console in onBeforeSendRequestHeaders callback
/* Author: mythern Copyright (C) 2014, MIT License http://www.opensource.org/licenses/mit-license.php Adressaway is provided free of charge, to any person obtaining a copy of this software and associated documentation files, to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, and to permit persons to whom the software is furnished todo so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial parts of the software, including credits to the original author. */ var debug = true; chrome.webRequest.onBeforeSendHeaders.addListener( function (details) { if (debug) { console.log("Intercepting request headers, adding google referrer.") } details.requestHeaders.push( { name: "Referer", value: "https://www.google.com/" } ) return { requestHeaders: details.requestHeaders } }, { urls: ["*://*.adressa.no/*"] }, ["blocking", "requestHeaders"] )
/* Author: mythern Copyright (C) 2014, MIT License http://www.opensource.org/licenses/mit-license.php Adressaway is provided free of charge, to any person obtaining a copy of this software and associated documentation files, to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, and to permit persons to whom the software is furnished todo so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial parts of the software, including credits to the original author. */ chrome.webRequest.onBeforeSendHeaders.addListener( function (details) { details.requestHeaders.push( { name: "Referer", value: "https://www.google.com/" } ) return { requestHeaders: details.requestHeaders } }, { urls: ["*://*.adressa.no/*"] }, ["blocking", "requestHeaders"] )
Remove coverage options from default test run These were getting annoying for normal runs.
#!/usr/bin/env python import sys import logging from optparse import OptionParser from tests.config import configure logging.disable(logging.CRITICAL) def run_tests(*test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner() if not test_args: test_args = ['tests'] num_failures = test_runner.run_tests(test_args) if num_failures: sys.exit(num_failures) if __name__ == '__main__': parser = OptionParser() __, args = parser.parse_args() # If no args, then use 'progressive' plugin to keep the screen real estate # used down to a minimum. Otherwise, use the spec plugin nose_args = ['-s', '-x', '--with-progressive' if not args else '--with-spec'] #nose_args.extend([ # '--with-coverage', '--cover-package=oscar', '--cover-html', # '--cover-html-dir=htmlcov']) configure(nose_args) run_tests(*args)
#!/usr/bin/env python import sys import logging from optparse import OptionParser from tests.config import configure logging.disable(logging.CRITICAL) def run_tests(*test_args): from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner() if not test_args: test_args = ['tests'] num_failures = test_runner.run_tests(test_args) if num_failures: sys.exit(num_failures) if __name__ == '__main__': parser = OptionParser() __, args = parser.parse_args() # If no args, then use 'progressive' plugin to keep the screen real estate # used down to a minimum. Otherwise, use the spec plugin nose_args = ['-s', '-x', '--with-progressive' if not args else '--with-spec'] nose_args.extend([ '--with-coverage', '--cover-package=oscar', '--cover-html', '--cover-html-dir=htmlcov']) configure(nose_args) run_tests(*args)
Test update as lib, not in bin.
'use strict'; /** * Run package tests. * (C) 2014 Alex Fernández. */ // requires var testing = require('testing'); var Log = require('log'); // globals var log = new Log('info'); /** * Run all module tests. */ exports.test = function(callback) { log.debug('Running tests'); var tests = {}; var libs = ['estimation', 'db', 'badges', 'packages', 'update']; var factors = ['issues', 'versions', 'downloads']; var bin = ['all']; libs.forEach(function(lib) { tests[lib] = require('./lib/' + lib + '.js').test; }); factors.forEach(function(factor) { tests[factors] = require('./lib/factors/' + factor + '.js').test; }); bin.forEach(function(bin) { tests[bin] = require('./bin/' + bin + '.js').test; }); testing.run(tests, 4200, callback); }; // run tests if invoked directly if (__filename == process.argv[1]) { exports.test(testing.show); }
'use strict'; /** * Run package tests. * (C) 2014 Alex Fernández. */ // requires var testing = require('testing'); var Log = require('log'); // globals var log = new Log('info'); /** * Run all module tests. */ exports.test = function(callback) { log.debug('Running tests'); var tests = {}; var libs = ['estimation', 'db', 'badges', 'packages']; var factors = ['issues', 'versions', 'downloads']; var bin = ['all', 'update']; libs.forEach(function(lib) { tests[lib] = require('./lib/' + lib + '.js').test; }); factors.forEach(function(factor) { tests[factors] = require('./lib/factors/' + factor + '.js').test; }); bin.forEach(function(bin) { tests[bin] = require('./bin/' + bin + '.js').test; }); testing.run(tests, 4200, callback); }; // run tests if invoked directly if (__filename == process.argv[1]) { exports.test(testing.show); }
Fix watch was referring to subtask with typo
'use strict'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { scss: { files: ['app/styles/**/*.scss'], tasks: ['sass'] } }, sass: { dist: { files: [{ expand: true, cwd: 'app/styles', src: ['*.scss'], dest: 'app/styles', ext: '.css' }] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['sass']); };
'use strict'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { scss: { files: ['app/styles/**/*.scss'], tasks: ['scss'] } }, sass: { dist: { files: [{ expand: true, cwd: 'app/styles', src: ['*.scss'], dest: 'app/styles', ext: '.css' }] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['sass']); };
Make hex object id possible in path params.
package routes import ( "errors" "fmt" "strings" ) // Converts patterns like "/users/:id" to "/users/(?P<id>\d+)" func convertSimplePatternToRegexp(pattern string) string { parts := strings.Split(pattern, "/") for i, part := range parts { if len(part) != 0 && part[0] == ':' { parts[i] = fmt.Sprintf(`(?P<%s>(?:/^[a-f\d]{24}$/i))`, part[1:]) } } return strings.Join(parts, "/") } // Return path relative to "base" func relativePath(base string, absolute string) (string, error) { baseLen := len(base) absoluteLen := len(absolute) if absoluteLen < baseLen { return "", errors.New("absolute len shorter than base len") } if absolute[:baseLen] != base { return "", errors.New("absolute path doesn't start with base path") } return absolute[baseLen:], nil }
package routes import ( "errors" "fmt" "strings" ) // Converts patterns like "/users/:id" to "/users/(?P<id>\d+)" func convertSimplePatternToRegexp(pattern string) string { parts := strings.Split(pattern, "/") for i, part := range parts { if len(part) != 0 && part[0] == ':' { parts[i] = fmt.Sprintf(`(?P<%s>\d+)`, part[1:]) } } return strings.Join(parts, "/") } // Return path relative to "base" func relativePath(base string, absolute string) (string, error) { baseLen := len(base) absoluteLen := len(absolute) if absoluteLen < baseLen { return "", errors.New("absolute len shorter than base len") } if absolute[:baseLen] != base { return "", errors.New("absolute path doesn't start with base path") } return absolute[baseLen:], nil }
Remove existing JARs before building new ones
#!/usr/bin/env python import os import shutil from glob import glob from subprocess import call, check_output OUTPUT_DIR_NAME = 'jars' def call_unsafe(*args, **kwargs): kwargs['shell'] = True call(*args, **kwargs) call_unsafe('./gradlew clean javadocRelease jarRelease') try: os.mkdir(OUTPUT_DIR_NAME) except OSError: pass os.chdir(OUTPUT_DIR_NAME) call_unsafe('rm *.jar') call_unsafe('cp ../beansdk/build/libs/*.jar .') commit = check_output(['git', 'rev-parse', 'HEAD'])[:7] for src in glob('*.jar'): name, ext = os.path.splitext(src) dest = name + '-' + commit + ext shutil.move(src, dest) call_unsafe('open .')
#!/usr/bin/env python import os import shutil from glob import glob from subprocess import call, check_output OUTPUT_DIR_NAME = 'jars' def call_unsafe(*args, **kwargs): kwargs['shell'] = True call(*args, **kwargs) call_unsafe('./gradlew clean javadocRelease jarRelease') try: os.mkdir(OUTPUT_DIR_NAME) except OSError: pass os.chdir(OUTPUT_DIR_NAME) call_unsafe('cp ../beansdk/build/libs/*.jar .') commit = check_output(['git', 'rev-parse', 'HEAD'])[:7] for src in glob('*.jar'): name, ext = os.path.splitext(src) dest = name + '-' + commit + ext shutil.move(src, dest) call_unsafe('open .')
Increase history capable days from 15 to 60 for White Ninja
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta from comics.crawler.utils.lxmlparser import LxmlParser class ComicMeta(BaseComicMeta): name = 'White Ninja' language = 'en' url = 'http://www.whiteninjacomics.com/' start_date = '2002-01-01' history_capable_days = 60 time_zone = -6 rights = 'Scott Bevan & Kent Earle' class ComicCrawler(BaseComicCrawler): def _get_url(self): self.parse_feed('http://www.whiteninjacomics.com/rss/z-latest.xml') for entry in self.feed.entries: if (entry.updated_parsed and self.timestamp_to_date(entry.updated_parsed) == self.pub_date): self.title = entry.title.split(' - ')[0] self.web_url = entry.link break if self.web_url is None: return page = LxmlParser(self.web_url) page.remove('img[src^="http://www.whiteninjacomics.com/images/comics/t-"]') self.url = page.src('img[src^="http://www.whiteninjacomics.com/images/comics/"]')
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta from comics.crawler.utils.lxmlparser import LxmlParser class ComicMeta(BaseComicMeta): name = 'White Ninja' language = 'en' url = 'http://www.whiteninjacomics.com/' start_date = '2002-01-01' history_capable_days = 15 time_zone = -6 rights = 'Scott Bevan & Kent Earle' class ComicCrawler(BaseComicCrawler): def _get_url(self): self.parse_feed('http://www.whiteninjacomics.com/rss/z-latest.xml') for entry in self.feed.entries: if (entry.updated_parsed and self.timestamp_to_date(entry.updated_parsed) == self.pub_date): self.title = entry.title.split(' - ')[0] self.web_url = entry.link break if self.web_url is None: return page = LxmlParser(self.web_url) page.remove('img[src^="http://www.whiteninjacomics.com/images/comics/t-"]') self.url = page.src('img[src^="http://www.whiteninjacomics.com/images/comics/"]')
Add warning about failing functional test
#!/usr/bin/env python from unittest import TestCase import mechanize class ResponseTests(TestCase): def test_close_pickle_load(self): print ("This test is expected to fail unless Python standard library" "patch http://python.org/sf/1144636 has been applied") import pickle b = mechanize.Browser() r = b.open("http://wwwsearch.sf.net/bits/cctest2.txt") r.read() r.close() r.seek(0) self.assertEqual(r.read(), "Hello ClientCookie functional test suite.\n") HIGHEST_PROTOCOL = -1 p = pickle.dumps(b, HIGHEST_PROTOCOL) b = pickle.loads(p) r = b.response() r.seek(0) self.assertEqual(r.read(), "Hello ClientCookie functional test suite.\n") if __name__ == "__main__": import unittest unittest.main()
#!/usr/bin/env python from unittest import TestCase import mechanize class ResponseTests(TestCase): def test_close_pickle_load(self): import pickle b = mechanize.Browser() r = b.open("http://wwwsearch.sf.net/bits/cctest2.txt") r.read() r.close() r.seek(0) self.assertEqual(r.read(), "Hello ClientCookie functional test suite.\n") HIGHEST_PROTOCOL = -1 p = pickle.dumps(b, HIGHEST_PROTOCOL) b = pickle.loads(p) r = b.response() r.seek(0) self.assertEqual(r.read(), "Hello ClientCookie functional test suite.\n") if __name__ == "__main__": import unittest unittest.main()
refactor: Use promise instead async fn
import mapService from 'new-dashboard/core/map-service'; import { visualizations as fakeVisualizations } from '../fixtures/visualizations'; jest.mock('carto-node'); describe('mapService', () => { describe('.fetchMaps', () => { describe('when no parameters are given', () => { let response; beforeAll(done => { mapService.fetchMaps().then(data => { response = data; done(); }) }) it('should return a list of visualizations filtered and ordered by default', async () => { expect(response.visualizations).toEqual(fakeVisualizations); }); it('should return metadata values', async () => { expect(response.total_entries).toEqual(1); expect(response.total_likes).toEqual(1); expect(response.total_shared).toEqual(32); expect(response.total_user_entries).toEqual(6); }); }) }); });
import mapService from 'new-dashboard/core/map-service'; import { visualizations as fakeVisualizations } from '../fixtures/visualizations'; jest.mock('carto-node'); describe('mapService', () => { describe('.fetchMaps', () => { describe('when no parameters are given', () => { let response; beforeAll(async () => { response = await mapService.fetchMaps(); }) it('should return a list of visualizations filtered and ordered by default', async () => { expect(response.visualizations).toEqual(fakeVisualizations); }); it('should return metadata values', async () => { expect(response.total_entries).toEqual(1); expect(response.total_likes).toEqual(1); expect(response.total_shared).toEqual(32); expect(response.total_user_entries).toEqual(6); }); }) }); });
Fix hot pepper cheese hardness bug
package simplemods.cheesemod.blocks; import java.util.Random; import simplemods.cheesemod.BaseMod; import simplemods.cheesemod.CommonProxy; import simplemods.cheesemod.inventory.CCreativeTabs; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import net.minecraft.item.ItemPickaxe; /** * No, this is not a hopper... */ public class BlockHotPepperCheeseOre extends Block{ public BlockHotPepperCheeseOre(Material p_i45394_1_) { super(Material.rock); setCreativeTab(CCreativeTabs.tabBlock); setBlockName("pepper_cheese_ore"); setBlockTextureName("cheesemod:pepper_cheese_ore"); setLightLevel(0.325F); setHardness(0.4F); setHarvestLevel("pickaxe", 0); } @Override public Item getItemDropped(int p_149650_1_, Random p_149650_2_, int p_149650_3_) { return CommonProxy.hot_pepper_cheese; } }
package simplemods.cheesemod.blocks; import java.util.Random; import simplemods.cheesemod.BaseMod; import simplemods.cheesemod.CommonProxy; import simplemods.cheesemod.inventory.CCreativeTabs; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.Item; /** * No, this is not a hopper... */ public class BlockHotPepperCheeseOre extends Block{ public BlockHotPepperCheeseOre(Material p_i45394_1_) { super(Material.rock); setCreativeTab(CCreativeTabs.tabBlock); setBlockName("pepper_cheese_ore"); setBlockTextureName("cheesemod:pepper_cheese_ore"); setLightLevel(0.325F); } @Override public Item getItemDropped(int p_149650_1_, Random p_149650_2_, int p_149650_3_) { return CommonProxy.hot_pepper_cheese; } }
Stop polluting git workspace with temporary files created while running unit tests fix #156
package helper import ( "fmt" "io/ioutil" "os" ) func WithDummyCredentials(fn func(dir string)) { dir, err := ioutil.TempDir("", "dummy-credentials") if err != nil { panic(err) } // Remove all the contents in the dir including *.pem.enc created by ReadOrUpdateCompactTLSAssets() // Otherwise we end up with a lot of garbage directories we failed to remove as they aren't empty in // config/temp, nodepool/config/temp, test/integration/temp defer os.RemoveAll(dir) for _, pairName := range []string{"ca", "apiserver", "worker", "admin", "etcd", "etcd-client"} { certFile := fmt.Sprintf("%s/%s.pem", dir, pairName) if err := ioutil.WriteFile(certFile, []byte("dummycert"), 0644); err != nil { panic(err) } defer os.Remove(certFile) keyFile := fmt.Sprintf("%s/%s-key.pem", dir, pairName) if err := ioutil.WriteFile(keyFile, []byte("dummykey"), 0644); err != nil { panic(err) } defer os.Remove(keyFile) } fn(dir) }
package helper import ( "fmt" "io/ioutil" "os" ) func WithDummyCredentials(fn func(dir string)) { if _, err := ioutil.ReadDir("temp"); err != nil { if err := os.Mkdir("temp", 0755); err != nil { panic(err) } } dir, err := ioutil.TempDir("temp", "dummy-credentials") if err != nil { panic(err) } // Remove all the contents in the dir including *.pem.enc created by ReadOrUpdateCompactTLSAssets() // Otherwise we end up with a lot of garbage directories we failed to remove as they aren't empty in // config/temp, nodepool/config/temp, test/integration/temp defer os.RemoveAll(dir) for _, pairName := range []string{"ca", "apiserver", "worker", "admin", "etcd", "etcd-client"} { certFile := fmt.Sprintf("%s/%s.pem", dir, pairName) if err := ioutil.WriteFile(certFile, []byte("dummycert"), 0644); err != nil { panic(err) } defer os.Remove(certFile) keyFile := fmt.Sprintf("%s/%s-key.pem", dir, pairName) if err := ioutil.WriteFile(keyFile, []byte("dummykey"), 0644); err != nil { panic(err) } defer os.Remove(keyFile) } fn(dir) }
Change return object, use gulp from args
var modula = require('modula-loader'), _ = require('lodash'), plugins = require('gulp-load-plugins')() plugins.uglify = require('gulp-uglify') plugins.cleanCSS = require('gulp-clean-css') plugins.path = require('path') plugins.gutil = require('gulp-util') function taskify(config){ var opts = config.opts || {} var args = config.args || {} opts.es6 = opts.es6 === undefined ? true : opts.es6 opts.exclude = opts.exclude || [] opts.exclude = (opts.es6) ? opts.exclude.concat(['compile:es5']) : opts.exclude.concat(['compile:es6']) args.plugins = _.merge(plugins, args.plugins); var modules = modula('tasks', { args: args, opts: { include: opts.include, exclude: opts.exclude, flat: opts.flat } }) var obj = {} _.forOwn(modules, function(value, key){ if (_.isFunction(value)){ createTask(args.gulp, value, key) } }) return modules } function createTask(gulp, func, name){ gulp.task(name, function(done){ func() done() }) } module.exports = taskify
var gulp = require('gulp'), modula = require('modula-loader'), _ = require('lodash'), plugins = require('gulp-load-plugins')() plugins.uglify = require('gulp-uglify') plugins.minifycss = require('gulp-minify-css') plugins.path = require('path') plugins.gutil = require('gulp-util') function taskify(config){ var opts = config.opts || {} var args = config.args || {} opts.es6 = opts.es6 === undefined ? true : opts.es6 opts.exclude = opts.exclude || [] opts.exclude = (opts.es6) ? opts.exclude.concat(['compile:es5']) : opts.exclude.concat(['compile:es6']) args.plugins = _.merge(plugins, args.plugins); var modules = modula('tasks', { args: args, opts: { include: opts.include, exclude: opts.exclude, flat: opts.flat } }) var obj = {} _.forOwn(modules, function(value, key){ if (_.isFunction(value)){ createTask(value, key) } else if (_.isObject(value)) { obj[key] = _.keys(value) } }) return obj function createTask(func, name){ gulp.task(name, function(done){ func(done) }) } } module.exports = taskify
Disable secure cookies for admin development.
from datetime import timedelta from pathlib import Path DEBUG = True PERMANENT_SESSION_LIFETIME = timedelta(14) SECRET_KEY = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' SESSION_COOKIE_SECURE = False LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] SQLALCHEMY_DATABASE_URI = 'postgresql+pg8000://byceps:boioioing@127.0.0.1/byceps' SQLALCHEMY_ECHO = False REDIS_URL = 'redis://127.0.0.1:6379/0' MODE = 'admin' PATH_DATA = Path('./data') PATH_USER_AVATAR_IMAGES = PATH_DATA / 'users/avatars' BOARD_TOPICS_PER_PAGE = 10 BOARD_POSTINGS_PER_PAGE = 10 MAIL_DEBUG = True MAIL_DEFAULT_SENDER = 'BYCEPS <noreply@example.com>' MAIL_SUPPRESS_SEND = True ROOT_REDIRECT_TARGET = 'admin/orgas/birthdays'
from datetime import timedelta from pathlib import Path DEBUG = True PERMANENT_SESSION_LIFETIME = timedelta(14) SECRET_KEY = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' SESSION_COOKIE_SECURE = True LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] SQLALCHEMY_DATABASE_URI = 'postgresql+pg8000://byceps:boioioing@127.0.0.1/byceps' SQLALCHEMY_ECHO = False REDIS_URL = 'redis://127.0.0.1:6379/0' MODE = 'admin' PATH_DATA = Path('./data') PATH_USER_AVATAR_IMAGES = PATH_DATA / 'users/avatars' BOARD_TOPICS_PER_PAGE = 10 BOARD_POSTINGS_PER_PAGE = 10 MAIL_DEBUG = True MAIL_DEFAULT_SENDER = 'BYCEPS <noreply@example.com>' MAIL_SUPPRESS_SEND = True ROOT_REDIRECT_TARGET = 'admin/orgas/birthdays'
Add ability to customize default routing port
package main import ( "fmt" "net/http/httputil" "net/url" "os" docker "github.com/fsouza/go-dockerclient" ) type DestinationMap map[string]*Destination type Destination struct { targetUrl *url.URL proxy *httputil.ReverseProxy } func getDefaultPort() string { port := os.Getenv("DEFAULT_PORT") if port == "" { // This is a default foreman port port = "5000" } return port } func NewDestination(container *docker.Container) (*Destination, error) { ip := container.NetworkSettings.IPAddress port := getDefaultPort() for k, _ := range container.Config.ExposedPorts { port = k.Port() break } targetUrl, err := url.Parse(fmt.Sprintf("http://%v:%v", ip, port)) if err != nil { return nil, err } dest := &Destination{ targetUrl, httputil.NewSingleHostReverseProxy(targetUrl), } return dest, nil } func (d *Destination) String() string { return d.targetUrl.String() }
package main import ( "fmt" "net/http/httputil" "net/url" docker "github.com/fsouza/go-dockerclient" ) type DestinationMap map[string]*Destination type Destination struct { targetUrl *url.URL proxy *httputil.ReverseProxy } func NewDestination(container *docker.Container) (*Destination, error) { ip := container.NetworkSettings.IPAddress port := "5000" // default foreman port for k, _ := range container.Config.ExposedPorts { port = k.Port() break } targetUrl, err := url.Parse(fmt.Sprintf("http://%v:%v", ip, port)) if err != nil { return nil, err } dest := &Destination{ targetUrl, httputil.NewSingleHostReverseProxy(targetUrl), } return dest, nil } func (d *Destination) String() string { return d.targetUrl.String() }
Create chart set api updated
'use strict'; /** * @ngdoc function * @name eagleeye.controller:ChartSetCreationController * @description * # ChartSetCreationController * Controller of the eagleeye */ angular.module('eagleeye') .controller('ChartSetCreationController', [ '$state', 'EagleEyeWebService', function ($state, EagleEyeWebService) { var friendlyUrlPrefix = 's-', controller = this; EagleEyeWebService.getCharts().then(function(chartList) { controller.chartList = chartList; }); this.settings = { title: '', description: '', friendlyUrl: '', charts: [] }; this.addToChartSet = function(chart) { if (this.settings.charts.indexOf(chart._id) < 0) { this.settings.charts.push(chart._id); } }; this.save = function() { var data = JSON.stringify(this.settings); EagleEyeWebService.createChartSet(data).then(function(newChartSet) { $state.go('chartSet', { id: newChartSet._id }); }); }; } ]);
'use strict'; /** * @ngdoc function * @name eagleeye.controller:ChartSetCreationController * @description * # ChartSetCreationController * Controller of the eagleeye */ angular.module('eagleeye') .controller('ChartSetCreationController', [ '$state', 'EagleEyeWebService', function ($state, EagleEyeWebService) { var friendlyUrlPrefix = 's-', controller = this; EagleEyeWebService.getCharts().then(function(chartList) { controller.chartList = chartList; }); this.settings = { title: '', description: '', friendlyUrl: '', charts: [] }; this.addToChartSet = function(chart) { if (this.settings.charts.indexOf(chart._id) < 0) { this.settings.charts.push(chart._id); } }; this.save = function() { var data = JSON.stringify(this.settings); EagleEyeWebService.createChartSet(data).then(function(newChartSetId) { $state.go('chartSet', { id: newChartSetId }); }); }; } ]);
Fix token precedence for variable names / operators.
package org.nwapw.abacus.tree; /** * Enum to represent the type of the token that has been matched * by the lexer. */ public enum TokenType { INTERNAL_FUNCTION_END(-1), ANY(0), WHITESPACE(1), COMMA(2), VARIABLE(3), OP(4), TREE_VALUE_OP(4), NUM(5), FUNCTION(6), TREE_VALUE_FUNCTION(6), OPEN_PARENTH(7), CLOSE_PARENTH(7); /** * The priority by which this token gets sorted. */ public final int priority; /** * Creates a new token type with the given priority. * * @param priority the priority of this token type. */ TokenType(int priority) { this.priority = priority; } }
package org.nwapw.abacus.tree; /** * Enum to represent the type of the token that has been matched * by the lexer. */ public enum TokenType { INTERNAL_FUNCTION_END(-1), ANY(0), WHITESPACE(1), COMMA(2), OP(3), TREE_VALUE_OP(3), NUM(4), VARIABLE(5), FUNCTION(6), TREE_VALUE_FUNCTION(6), OPEN_PARENTH(7), CLOSE_PARENTH(8); /** * The priority by which this token gets sorted. */ public final int priority; /** * Creates a new token type with the given priority. * * @param priority the priority of this token type. */ TokenType(int priority) { this.priority = priority; } }
Add -- to git log call
import os from dateutil.parser import parse from ..common import run, chdir def check_dates(spec_id, username, spec, basedir): """ Port of the CheckDates program from C++ Finds the first submission date for an assignment by comparing first commits for all files in the spec and returning the earliest """ basedir = os.path.join(basedir, 'students', username, spec_id) dates = [] with chdir(basedir): for file in spec['files']: # Run a git log on each file with earliest commits listed first status, res, _ = run(['git', 'log', '--reverse', '--pretty=format:%ad', '--date=iso8601', '--', os.path.join(basedir, file['filename'])]) # If we didn't get an error and got an output, add date to array if status == 'success' and res: # Parse the first line dates.append(parse(res.splitlines()[0])) # Return earliest date as a string with the format mm/dd/yyyy hh:mm:ss if not dates: return "ERROR" return min(dates).strftime("%x %X")
import os from dateutil.parser import parse from ..common import run, chdir def check_dates(spec_id, username, spec, basedir): """ Port of the CheckDates program from C++ Finds the first submission date for an assignment by comparing first commits for all files in the spec and returning the earliest """ basedir = os.path.join(basedir, 'students', username, spec_id) dates = [] with chdir(basedir): for file in spec['files']: # Run a git log on each file with earliest commits listed first status, res, _ = run(['git', 'log', '--reverse', '--pretty=format:%ad', '--date=iso8601', os.path.join(basedir, file['filename'])]) # If we didn't get an error and got an output, add date to array if status == 'success' and res: # Parse the first line dates.append(parse(res.splitlines()[0])) # Return earliest date as a string with the format mm/dd/yyyy hh:mm:ss if not dates: return "ERROR" return min(dates).strftime("%x %X")
Add voluptuous as a dependency
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup from dlstats import version import os setup(name='dlstats', version=version.version, description='A python module that provides an interface between statistics providers and pandas.', author='Widukind team', author_email='dev@michaelmalter.fr', url='https://github.com/Widukind', package_dir={'dlstats': 'dlstats', 'dlstats.fetchers': 'dlstats/fetchers'}, packages=['dlstats', 'dlstats.fetchers'], data_files=[('/usr/local/bin',['dlstats/dlstats_server.py']), ('/etc/systemd/system',['os_specific/dlstats.service'])], install_requires=[ 'pandas>=0.12', 'docopt>=0.6.0' 'voluptuous>=0.8' ] ) with open('/etc/systemd/system/dlstats.service'): os.chmod('/etc/systemd/system/dlstats.service', 0o755) with open('/usr/local/bin/dlstats_server.py'): os.chmod('/usr/local/bin/dlstats_server.py', 0o755)
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup from dlstats import version import os setup(name='dlstats', version=version.version, description='A python module that provides an interface between statistics providers and pandas.', author='Widukind team', author_email='dev@michaelmalter.fr', url='https://github.com/Widukind', package_dir={'dlstats': 'dlstats', 'dlstats.fetchers': 'dlstats/fetchers'}, packages=['dlstats', 'dlstats.fetchers'], data_files=[('/usr/local/bin',['dlstats/dlstats_server.py']), ('/etc/systemd/system',['os_specific/dlstats.service'])], install_requires=[ 'pandas>=0.12', 'docopt>=0.6.0' ] ) with open('/etc/systemd/system/dlstats.service'): os.chmod('/etc/systemd/system/dlstats.service', 0o755) with open('/usr/local/bin/dlstats_server.py'): os.chmod('/usr/local/bin/dlstats_server.py', 0o755)
Revert "reverse changes to MorhiaFixtures which is specific to 1.2.1" This reverts commit 4e00685568a7eb9edcf39bd20d2c5272f5d365aa.
package play.test; import java.util.List; import play.Play; import play.modules.morphia.Model; import play.modules.morphia.MorphiaPlugin; import play.test.Fixtures; import com.google.code.morphia.Datastore; public class MorphiaFixtures extends Fixtures { private static Datastore ds() { return MorphiaPlugin.ds(); } public static void deleteAll() { idCache.clear(); Datastore ds = ds(); for (Class<Model> clz: Play.classloader.getAssignableClasses(Model.class)) { ds.getCollection(clz).drop(); } } public static void delete(Class<? extends Model> ... types) { idCache.clear(); for (Class<? extends Model> type: types) { ds().getCollection(type).drop(); } } public static void delete(List<Class<? extends Model>> classes) { idCache.clear(); for (Class<? extends Model> type: classes) { ds().getCollection(type).drop(); } } public static void deleteAllModels() { deleteAll(); } }
package play.test; import java.util.List; import play.Play; import play.modules.morphia.Model; import play.modules.morphia.MorphiaPlugin; import play.test.Fixtures; import com.google.code.morphia.Datastore; public class MorphiaFixtures extends Fixtures { private static Datastore ds() { return MorphiaPlugin.ds(); } public static void deleteAll() { Datastore ds = ds(); for (Class<Model> clz: Play.classloader.getAssignableClasses(Model.class)) { ds.getCollection(clz).drop(); } } public static void delete(Class<? extends Model> ... types) { for (Class<? extends Model> type: types) { ds().getCollection(type).drop(); } } public static void delete(List<Class<? extends Model>> classes) { for (Class<? extends Model> type: classes) { ds().getCollection(type).drop(); } } public static void deleteAllModels() { deleteAll(); } }
Add a doc string to make using this dataset easier
# -*- coding: utf-8 -*- # modified from https://github.com/CamDavidsonPilon/lifelines/ import pandas as pd from pkg_resources import resource_filename __all__ = [ 'load_cdnow', 'load_transaction_data', ] def load_dataset(filename, **kwargs): ''' Load a dataset from lifetimes.datasets Parameters: filename : for example "larynx.csv" usecols : list of columns in file to use Returns : Pandas dataframe ''' return pd.read_csv(resource_filename('lifetimes', 'datasets/' + filename), **kwargs) def load_cdnow(**kwargs): return load_dataset('cdnow_customers.csv', **kwargs) def load_transaction_data(**kwargs): """ Returns a Pandas dataframe of transactional data. Looks like: date id 0 2014-03-08 00:00:00 0 1 2014-05-21 00:00:00 1 2 2014-03-14 00:00:00 2 3 2014-04-09 00:00:00 2 4 2014-05-21 00:00:00 2 The data was artificially created using Lifetimes data generation routines. Data was generated between 2014-01-01 to 2014-12-31. """ return load_dataset('example_transactions.csv', **kwargs)
# -*- coding: utf-8 -*- # modified from https://github.com/CamDavidsonPilon/lifelines/ import pandas as pd from pkg_resources import resource_filename __all__ = [ 'load_cdnow', 'load_transaction_data', ] def load_dataset(filename, **kwargs): ''' Load a dataset from lifetimes.datasets Parameters: filename : for example "larynx.csv" usecols : list of columns in file to use Returns : Pandas dataframe ''' return pd.read_csv(resource_filename('lifetimes', 'datasets/' + filename), **kwargs) def load_cdnow(**kwargs): return load_dataset('cdnow_customers.csv', **kwargs) def load_transaction_data(**kwargs): return load_dataset('example_transactions.csv', **kwargs)
Make column numbers in Location mandatory
var esprima = require('esprima'); /** * Position in the source file. * * @see [SpiderMonkey Parser API] * {@link https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API} * * @typedef {Object} Position * @property {number} line - Line number, 1-indexed. * @property {?number} column - Column number, 0-indexed. */ /** * Location - position range. * * @typedef {Object} Location * @property {Position} start - Column number must be set. * @property {Position} end - Column number must be set. */ /** * Extract comments from code. * Each comment is represented by a string within its usual comment delimiters. * * @arg {string} code - JavaScript code. * @return {{text: string, loc: Location}[]} */ var extract = function (code) { return esprima.parse(code, { comment: true, loc: true }).comments.map(function (comment) { return { text: (comment.type == 'Line') ? '//' + comment.value : '/*' + comment.value + '*/', loc: comment.loc }; }); }; module.exports = extract;
var esprima = require('esprima'); /** * Position in the source file. * * @see [SpiderMonkey Parser API] * {@link https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API} * * @typedef {Object} Position * @property {number} line - Line number, 1-indexed. * @property {?number} column - Column number, 0-indexed. */ /** * Location - position range. * * @typedef {Object} Location * @property {Position} start * @property {Position} end */ /** * Extract comments from code. * Each comment is represented by a string within its usual comment delimiters. * Returned location always contains both line and column info. * * @arg {string} code - JavaScript code. * @return {{text: string, loc: Location}[]} */ var extract = function (code) { return esprima.parse(code, { comment: true, loc: true }).comments.map(function (comment) { return { text: (comment.type == 'Line') ? '//' + comment.value : '/*' + comment.value + '*/', loc: comment.loc }; }); }; module.exports = extract;
Javadoc: Correct typo and add missing return description git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1776143 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: cd0402100b64b469e5e64c92fc87013f44cb1a3c
/* * 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.jmeter.report.processor; /** * The interface ResultData represents a result from samples processing. * * @since 3.0 */ public interface ResultData { /** * Accepts the specified visitor. * * @param visitor * the visitor (must not be {@code null}) * @param <T> * type of the results of the {@link ResultDataVisitor} * @return result of the vist */ <T> T accept(ResultDataVisitor<T> visitor); }
/* * 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.jmeter.report.processor; /** * The interface ResultData represents a result from samples processing. * * @since 3.0 */ public interface ResultData { /** * Accepts the specified visitor. * * @param visitor * the visitor (must not be {@code null}) * @paran <T> type of the results of the {@link ResultDataVisitor} */ <T> T accept(ResultDataVisitor<T> visitor); }
Create packet assuming variable LiveID length Fixes #7
var dgram = require('dgram'); const PORT = 5050; module.exports = Xbox; function Xbox(ip, id) { this.ip = ip; this.id = id; return this; } Xbox.prototype.powerOn = function(callback) { callback = callback || function() {}; // Open socket var socket = dgram.createSocket('udp4'); // Create payload var powerPayload = Buffer.from('\x00' + String.fromCharCode(this.id.length) + this.id + '\x00'), powerPayloadLength = Buffer.from(String.fromCharCode(powerPayload.length)), powerHeader = Buffer.concat([Buffer.from('dd0200', 'hex'), powerPayloadLength, Buffer.from('0000', 'hex')]), powerPacket = Buffer.concat([powerHeader, powerPayload]); // Send socket.send(powerPacket, 0, powerPacket.length, PORT, this.ip, function(err) { if (err) throw err; socket.close(); callback(); }); };
var dgram = require('dgram'); const PORT = 5050 const PING_PAYLOAD = "dd00000a000000000000000400000002" const POWER_PAYLOAD = "dd02001300000010" module.exports = Xbox; function Xbox(ip, id) { this.ip = ip; this.id = id; return this; } Xbox.prototype.powerOn = function(callback) { callback = callback || function() {}; // Counter some older node compatibility issues with `new Buffer(1).fill(0)` var zeroBuffer = new Buffer(1); zeroBuffer.write('\u0000'); var message = Buffer.concat([new Buffer(POWER_PAYLOAD, 'hex'), new Buffer(this.id), zeroBuffer]); var socket = dgram.createSocket('udp4'); socket.send(message, 0, message.length, PORT, this.ip, function(err, bytes) { if (err) throw err; socket.close(); callback(); }); }
Remove unused import from label component spec
import React from 'react'; import { render } from 'enzyme'; import { expect } from 'chai'; import { Label } from '../../src/components/label'; import { Colors } from '../../src/enums'; // TODO: Add test cases for invalid enum values describe('Label component', () => { it('sets tag name', () => { const component = render(<Label/>); expect(component).to.have.tagName('span'); }); it('sets default class name', () => { const component = render(<Label/>); expect(component).to.have.className('label'); }); it('does not set default class name', () => { const component = render(<Label noDefaultClassName/>); expect(component).to.not.have.className('label'); }); it('sets custom class name', () => { const component = render(<Label className="my-label"/>); expect(component).to.have.className('my-label'); }); it('sets color', () => { const component = render(<Label color={Colors.SUCCESS}/>); expect(component).to.have.className('success'); expect(component).to.not.have.attr('color'); }); it('sets contents', () => { const component = render(<Label>Build passing</Label>); expect(component).to.have.text('Build passing'); }); });
import React from 'react'; import { render } from 'enzyme'; import { expect } from 'chai'; import { Label, LabelColors } from '../../src/components/label'; import { Colors } from '../../src/enums'; // TODO: Add test cases for invalid enum values describe('Label component', () => { it('sets tag name', () => { const component = render(<Label/>); expect(component).to.have.tagName('span'); }); it('sets default class name', () => { const component = render(<Label/>); expect(component).to.have.className('label'); }); it('does not set default class name', () => { const component = render(<Label noDefaultClassName/>); expect(component).to.not.have.className('label'); }); it('sets custom class name', () => { const component = render(<Label className="my-label"/>); expect(component).to.have.className('my-label'); }); it('sets color', () => { const component = render(<Label color={Colors.SUCCESS}/>); expect(component).to.have.className('success'); expect(component).to.not.have.attr('color'); }); it('sets contents', () => { const component = render(<Label>Build passing</Label>); expect(component).to.have.text('Build passing'); }); });
Fix Place spell with copy
package com.elmakers.mine.bukkit.plugins.magic.spells; import org.bukkit.block.Block; import com.elmakers.mine.bukkit.blocks.BlockList; import com.elmakers.mine.bukkit.blocks.MaterialBrush; import com.elmakers.mine.bukkit.plugins.magic.BrushSpell; import com.elmakers.mine.bukkit.plugins.magic.SpellResult; import com.elmakers.mine.bukkit.utilities.Target; import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode; public class PlaceSpell extends BrushSpell { @Override public SpellResult onCast(ConfigurationNode parameters) { Target attachToBlock = getTarget(); if (!attachToBlock.isBlock()) return SpellResult.NO_TARGET; Block placeBlock = getLastBlock(); MaterialBrush buildWith = getMaterialBrush(); buildWith.setTarget(attachToBlock.getLocation(), placeBlock.getLocation()); buildWith.setTarget(attachToBlock.getLocation()); if (!hasBuildPermission(placeBlock)) { return SpellResult.INSUFFICIENT_PERMISSION; } BlockList placedBlocks = new BlockList(); placedBlocks.add(placeBlock); buildWith.modify(placeBlock); registerForUndo(placedBlocks); controller.updateBlock(placeBlock); return SpellResult.CAST; } }
package com.elmakers.mine.bukkit.plugins.magic.spells; import org.bukkit.block.Block; import com.elmakers.mine.bukkit.blocks.BlockList; import com.elmakers.mine.bukkit.blocks.MaterialBrush; import com.elmakers.mine.bukkit.plugins.magic.BrushSpell; import com.elmakers.mine.bukkit.plugins.magic.SpellResult; import com.elmakers.mine.bukkit.utilities.Target; import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode; public class PlaceSpell extends BrushSpell { @Override public SpellResult onCast(ConfigurationNode parameters) { Target target = getTarget(); if (!target.isBlock()) return SpellResult.NO_TARGET; Block attachBlock = getLastBlock(); MaterialBrush buildWith = getMaterialBrush(); buildWith.setTarget(attachBlock.getLocation()); if (!hasBuildPermission(attachBlock)) { return SpellResult.INSUFFICIENT_PERMISSION; } BlockList placedBlocks = new BlockList(); placedBlocks.add(attachBlock); buildWith.modify(attachBlock); registerForUndo(placedBlocks); controller.updateBlock(attachBlock); return SpellResult.CAST; } }
Update Jasmine syntax examples to make them shorter.
describe("Gilded Rose", function() { // var foo; // beforeEach(function() { // foo = 0; // }); // afterEach(function() { // foo = 0; // }); it("should do something", function() { }); // it("is a syntax example", function() { // expect(true).toBe(true); // }); // it("can have a negative case", function() { // expect(false).not.toBe(true); // }); // describe("Another spec", function() { // it("is just a function, so it can contain any code", function() { // var foo = 0; // foo += 1; // expect(foo).toEqual(1); // }); // it("has mathematical comparisons", function() { // expect(2).toBeLessThan(3); // expect(3).not.toBeLessThan(2); // expect(3).toBeGreaterThan(2); // expect(2).not.toBeGreaterThan(3); // }); // }); });
describe("Gilded Rose", function() { var foo; // beforeEach(function() { // foo = 0; // foo += 1; // }); // afterEach(function() { // foo = 0; // }); it("should do something", function() { }); // it("is a syntax example", function() { // expect(true).toBe(true); // }); // it("can have a negative case", function() { // expect(false).not.toBe(true); // }); // describe("Another spec", function() { // it("is just a function, so it can contain any code", function() { // var foo = 0; // foo += 1; // expect(foo).toEqual(1); // }); // it("The 'toBeLessThan' matcher is for mathematical comparisons", function() { // var pi = 3, e = 2; // expect(e).toBeLessThan(pi); // expect(pi).not.toBeLessThan(e); // }); // it("The 'toBeGreaterThan' is for mathematical comparisons", function() { // var pi = 3, e = 2; // expect(pi).toBeGreaterThan(e); // expect(e).not.toBeGreaterThan(pi); // }); // }); });
Index location into a geopoint The geopoint is a geolocation type which amongst other things supports geohashing. KB-351
'use strict'; module.exports = metadata => { var coordinates; if (metadata.google_maps_coordinates) { coordinates = metadata.google_maps_coordinates; metadata.location_is_approximate = false; } else if (metadata.google_maps_coordinates_crowd) { coordinates = metadata.google_maps_coordinates_crowd; metadata.location_is_approximate = false; } else if (metadata.google_maps_coordinates_approximate) { coordinates = metadata.google_maps_coordinates_approximate; metadata.location_is_approximate = true; } if (coordinates) { coordinates = coordinates.split(',').map(parseFloat); if (coordinates.length >= 2) { metadata.latitude = coordinates[0]; metadata.longitude = coordinates[1]; } else { throw new Error('Encountered unexpected coordinate format.'); } } // Index into if (metadata.latitude && metadata.longitude) { metadata.location = { "lat": metadata.latitude, "lon": metadata.longitude } } return metadata; };
'use strict'; module.exports = metadata => { var coordinates; if (metadata.google_maps_coordinates) { coordinates = metadata.google_maps_coordinates; metadata.location_is_approximate = false; } else if (metadata.google_maps_coordinates_crowd) { coordinates = metadata.google_maps_coordinates_crowd; metadata.location_is_approximate = false; } else if (metadata.google_maps_coordinates_approximate) { coordinates = metadata.google_maps_coordinates_approximate; metadata.location_is_approximate = true; } if (coordinates) { coordinates = coordinates.split(',').map(parseFloat); if (coordinates.length >= 2) { metadata.latitude = coordinates[0]; metadata.longitude = coordinates[1]; } else { throw new Error('Encountered unexpected coordinate format.'); } } return metadata; };
Fix testing if element exists.
$(function() { var cookieName = '_wheelmap_splash_seen'; var setCookie = function() { $.cookie(cookieName, true, { expires: 1000 }); }; if(!$.cookie(cookieName)) { var width = 600; // splash width // calculate left edge so it is centered var left = (0.5 - (width / 2)/($(window).width())) * 100 + '%'; if ($('#splash').length > 0 ){ $.blockUI({ message: $("#splash"), css: { top: '25%', left: left, width: width + 'px' } }); } var clickHandler = function() { $.unblockUI(); setCookie(); return false; }; $("#splash .unblock-splash").click(clickHandler); $('.blockOverlay').css('cursor', 'auto').click(clickHandler); $('a.whatis').click(function() { setCookie(); return true; }); } });
$(function() { var cookieName = '_wheelmap_splash_seen'; var setCookie = function() { $.cookie(cookieName, true, { expires: 1000 }); }; if(!$.cookie(cookieName)) { var width = 600; // splash width // calculate left edge so it is centered var left = (0.5 - (width / 2)/($(window).width())) * 100 + '%'; if (!$('#splash').is(':empty')){ $.blockUI({ message: $("#splash"), css: { top: '25%', left: left, width: width + 'px' } }); } var clickHandler = function() { $.unblockUI(); setCookie(); return false; }; $("#splash .unblock-splash").click(clickHandler); $('.blockOverlay').css('cursor', 'auto').click(clickHandler); $('a.whatis').click(function() { setCookie(); return true; }); } });
Set 0.1.1 as minimum version of loam
from setuptools import setup with open('README.rst') as rdm: README = rdm.read() setup( name='qjobs', use_scm_version=True, description='Get a clean and flexible output from qstat', long_description=README, url='https://github.com/amorison/qjobs', author='Adrien Morison', author_email='adrien.morison@gmail.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=['qjobs'], entry_points={ 'console_scripts': ['qjobs = qjobs.__main__:main'] }, setup_requires=['setuptools_scm'], install_requires=['setuptools_scm', 'loam>=0.1.1'], )
from setuptools import setup with open('README.rst') as rdm: README = rdm.read() setup( name='qjobs', use_scm_version=True, description='Get a clean and flexible output from qstat', long_description=README, url='https://github.com/amorison/qjobs', author='Adrien Morison', author_email='adrien.morison@gmail.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=['qjobs'], entry_points={ 'console_scripts': ['qjobs = qjobs.__main__:main'] }, setup_requires=['setuptools_scm'], install_requires=['setuptools_scm', 'loam'], )
Use an iframe to create a testDocument… instead of `createHTMLDocument` since it isn't fully support by the browsers we care about. fixes #606 fixes #454
/** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule getTestDocument */ /** * We need to work around the fact that we have two different * test implementations: once that breaks if we clobber document * (open-source) and one that doesn't support createHTMLDocument() * (jst). */ function getTestDocument() { var iframe = document.createElement('iframe'); iframe.style.cssText = 'position:absolute; visibility:hidden; bottom:100%; right:100%'; iframe.src = 'data:text/html,<!doctype html><meta charset=utf-8><title>test doc</title>'; document.body.appendChild(iframe); var testDocument = iframe.contentDocument; iframe.parentNode.removeChild(iframe); return testDocument; } module.exports = getTestDocument;
/** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule getTestDocument */ /** * We need to work around the fact that we have two different * test implementations: once that breaks if we clobber document * (open-source) and one that doesn't support createHTMLDocument() * (jst). */ function getTestDocument() { if (document.implementation && document.implementation.createHTMLDocument) { return document.implementation.createHTMLDocument('test doc'); } return null; } module.exports = getTestDocument;
Fix potential NPE in constructor
/* * Copyright 2010 DTO Labs, Inc. (http://dtolabs.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtolabs.rundeck.core.authorization; import com.dtolabs.rundeck.core.CoreException; /** * AuthorizationException */ public class AuthorizationException extends CoreException { public AuthorizationException(final String msg) { super(msg); } public AuthorizationException(final Throwable e) { super(e.getMessage()); } public AuthorizationException(final String msg, final Throwable e) { super(msg + (null != e.getCause() ? ". cause: "+ e.getCause().getMessage() : "")); } public AuthorizationException(final String user, final String script, final String matchedRoles) { super("User: " + user + ", matching roles: " + matchedRoles + ", is not allowed to execute a script: " + script); } }
/* * Copyright 2010 DTO Labs, Inc. (http://dtolabs.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtolabs.rundeck.core.authorization; import com.dtolabs.rundeck.core.CoreException; /** * AuthorizationException */ public class AuthorizationException extends CoreException { public AuthorizationException(final String msg) { super(msg); } public AuthorizationException(final Throwable e) { super(e.getMessage()); } public AuthorizationException(final String msg, final Throwable e) { super(msg + ". cause: " + e.getCause().getMessage()); } public AuthorizationException(final String user, final String script, final String matchedRoles) { super("User: " + user + ", matching roles: " + matchedRoles + ", is not allowed to execute a script: " + script); } }
cmd/bintogo: Remove need to get file size in advance.
package main import ( "bufio" "io" "os" "text/template" ) const ( dataTmpl = `// This file was auto-generated. package {{.Pkg}} var {{.Name}}Data = [...]byte{ {{range .Data}} {{printf "0x%02X" .}}, {{end}}}` ) var tmpl = new(template.Template) func init() { template.Must(tmpl.New("data").Parse(dataTmpl)) } type Data struct { Pkg string Name string In *os.File } func (data *Data) Data() <-chan byte { out := make(chan byte) go func() { defer close(out) r := bufio.NewReader(data.In) for { c, err := r.ReadByte() if err != nil { if err == io.EOF { break } // Hmmm... I can't think of a good way to handle an error // here, so how about crashing? panic(err) } out <- c } }() return out }
package main import ( "bufio" "io" "os" "text/template" ) const ( dataTmpl = `// This file was auto-generated. package {{.Pkg}} var {{.Name}}Data = [{{.Size}}]byte{ {{range .Data}} {{printf "0x%02X" .}}, {{end}}}` ) var tmpl = new(template.Template) func init() { template.Must(tmpl.New("data").Parse(dataTmpl)) } type Data struct { Pkg string Name string In *os.File stat os.FileInfo } func (data *Data) Size() int { if data.stat == nil { data.stat, _ = data.In.Stat() } return int(data.stat.Size()) } func (data *Data) Data() <-chan byte { out := make(chan byte) go func() { defer close(out) r := bufio.NewReader(data.In) for { c, err := r.ReadByte() if err != nil { if err == io.EOF { break } // Hmmm... I can't think of a good way to handle an error // here, so how about crashing? panic(err) } out <- c } }() return out }
Remove fixture teardown since nothing should be saved (tmpdir)
import string import pytest @pytest.fixture def identity_fixures(): l = [] for i, c in enumerate(string.ascii_uppercase): l.append(dict( name='identity_{0}'.format(i), access_key_id='someaccesskey_{0}'.format(c), secret_access_key='notasecret_{0}_{1}'.format(i, c), )) return l @pytest.fixture def identity_store(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) return identity_store @pytest.fixture def identity_store_with_data(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) for data in identity_fixures(): identity_store.add_identity(data) return identity_store
import string import pytest @pytest.fixture def identity_fixures(): l = [] for i, c in enumerate(string.ascii_uppercase): l.append(dict( name='identity_{0}'.format(i), access_key_id='someaccesskey_{0}'.format(c), secret_access_key='notasecret_{0}_{1}'.format(i, c), )) return l @pytest.fixture def identity_store(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) def fin(): identity_store.identities.clear() identity_store.save_to_config() return identity_store @pytest.fixture def identity_store_with_data(tmpdir): from awsident.storage import IdentityStore identity_store = IdentityStore(config_path=str(tmpdir)) for data in identity_fixures(): identity_store.add_identity(data) def fin(): identity_store.identities.clear() identity_store.save_to_config() return identity_store
Test all the Jmbo content types
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Foundry provides high-level testing tools for other content types INSTALLED_APPS += ( 'banner', 'jmbo_calendar', 'chart', 'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', 'show', 'jmbo_twitter', ) CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # See setup.py for an explanation as to why these aren't enabled by default ''' INSTALLED_APPS += ( 'banner', #'jmbo_calendar', # requires atlas 'chart', #'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', #'show', # requires jmbo_calendar #'jmbo_twitter', ) ''' CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False
Use PORT env var for heroku demo
require('./lib/seed')() const { compose } = require('ramda') const http = require('http') const util = require('util') const { logger, methods, mount, parseJson, redirect, routes, static } = require('..') const { createCourse, fetchCourse, fetchCourses, updateCourse } = require('./api/courses') const { home } = require('./api/pages') const port = process.env.PORT || 3000 const listening = err => err ? console.error(err) : console.info(`Listening on port: ${port}`) const endpoints = routes({ '/': methods({ GET: home }), '/public/:path+': static({ root: 'demo/public' }), '/courses': methods({ GET: fetchCourses, POST: createCourse }), '/courses/:id': methods({ GET: fetchCourse, PATCH: updateCourse, PUT: updateCourse }), '/error': () => { throw new Error('this code is broken') }, '/old-courses': () => redirect('/courses') }) const app = compose(endpoints, parseJson) const opts = { errLogger: logger, logger } http.createServer(mount(app, opts)).listen(port, listening)
require('./lib/seed')() const { compose } = require('ramda') const http = require('http') const util = require('util') const { logger, methods, mount, parseJson, redirect, routes, static } = require('..') const { createCourse, fetchCourse, fetchCourses, updateCourse } = require('./api/courses') const { home } = require('./api/pages') const port = 3000 const listening = err => err ? console.error(err) : console.info(`Listening on port: ${port}`) const endpoints = routes({ '/': methods({ GET: home }), '/public/:path+': static({ root: 'demo/public' }), '/courses': methods({ GET: fetchCourses, POST: createCourse }), '/courses/:id': methods({ GET: fetchCourse, PATCH: updateCourse, PUT: updateCourse }), '/error': () => { throw new Error('this code is broken') }, '/old-courses': () => redirect('/courses') }) const app = compose(endpoints, parseJson) const opts = { errLogger: logger, logger } http.createServer(mount(app, opts)).listen(port, listening)
Add missing line of code (merge/rebase effect).
#!/usr/bin/env python from setuptools import setup setup( name="letsencrypt", version="0.1", description="Let's Encrypt", author="Let's Encrypt Project", license="", url="https://letsencrypt.org", packages=[ 'letsencrypt', 'letsencrypt.client', 'letsencrypt.scripts', ], install_requires=[ 'jsonschema', 'M2Crypto', 'pycrypto', 'python-augeas', 'python2-pythondialog', 'requests', ], dependency_links=[ # http://augeas.net/download.html 'https://fedorahosted.org/released/python-augeas/', ], entry_points={ 'console_scripts': [ 'letsencrypt = letsencrypt.scripts.main:main', ], }, zip_safe=False, include_package_data=True, )
#!/usr/bin/env python from setuptools import setup setup( name="letsencrypt", version="0.1", description="Let's Encrypt", author="Let's Encrypt Project", license="", url="https://letsencrypt.org", packages=[ 'letsencrypt', 'letsencrypt.client', 'letsencrypt.scripts', ], install_requires=[ 'jsonschema', 'M2Crypto', 'pycrypto', 'python-augeas', 'python2-pythondialog', 'requests', dependency_links=[ # http://augeas.net/download.html 'https://fedorahosted.org/released/python-augeas/', ], entry_points={ 'console_scripts': [ 'letsencrypt = letsencrypt.scripts.main:main', ], }, zip_safe=False, include_package_data=True, )
Remove "Bg" namespace from widgets
<?php class sfWidgetFormI18nSelect2ChoiceCurrency extends sfWidgetFormSelect2Choice { protected function configure($options = array(), $attributes = array()) { parent::configure($options, $attributes); $this->addOption('culture', sfContext::getInstance()->getUser()->getCulture()); $this->addOption('currencies'); $this->addOption('add_empty', false); // populate choices with all currencies $culture = isset($options['culture']) ? $options['culture'] : 'en'; $currencies = sfCultureInfo::getInstance($culture)->getCurrencies(isset($options['currencies']) ? $options['currencies'] : null); $addEmpty = isset($options['add_empty']) ? $options['add_empty'] : false; if (false !== $addEmpty) { $currencies = array_merge(array('' => true === $addEmpty ? '' : $addEmpty), $currencies); } $this->setOption('choices', $currencies); } }
<?php class sfWidgetFormI18nSelect2ChoiceCurrency extends BgWidgetFormSelect2Choice { protected function configure($options = array(), $attributes = array()) { parent::configure($options, $attributes); $this->addOption('culture', sfContext::getInstance()->getUser()->getCulture()); $this->addOption('currencies'); $this->addOption('add_empty', false); // populate choices with all currencies $culture = isset($options['culture']) ? $options['culture'] : 'en'; $currencies = sfCultureInfo::getInstance($culture)->getCurrencies(isset($options['currencies']) ? $options['currencies'] : null); $addEmpty = isset($options['add_empty']) ? $options['add_empty'] : false; if (false !== $addEmpty) { $currencies = array_merge(array('' => true === $addEmpty ? '' : $addEmpty), $currencies); } $this->setOption('choices', $currencies); } }
Add patient code number sequence
/* eslint-disable import/prefer-default-export */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ const HOURS_PER_DAY = 24; const MINUTES_PER_HOUR = 60; const SECONDS_PER_MINUTE = 60; const MILLISECONDS_PER_SECOND = 1000; export const MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE; export const MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * MINUTES_PER_HOUR; export const MILLISECONDS_PER_DAY = MILLISECONDS_PER_HOUR * HOURS_PER_DAY; export const NUMBER_SEQUENCE_KEYS = { CUSTOMER_INVOICE_NUMBER: 'customer_invoice_serial_number', INVENTORY_ADJUSTMENT_SERIAL_NUMBER: 'inventory_adjustment_serial_number', REQUISITION_SERIAL_NUMBER: 'requisition_serial_number', REQUISITION_REQUESTER_REFERENCE: 'requisition_requester_reference', STOCKTAKE_SERIAL_NUMBER: 'stocktake_serial_number', SUPPLIER_INVOICE_NUMBER: 'supplier_invoice_serial_number', PATIENT_CODE: 'patient_code', };
/* eslint-disable import/prefer-default-export */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ const HOURS_PER_DAY = 24; const MINUTES_PER_HOUR = 60; const SECONDS_PER_MINUTE = 60; const MILLISECONDS_PER_SECOND = 1000; export const MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE; export const MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * MINUTES_PER_HOUR; export const MILLISECONDS_PER_DAY = MILLISECONDS_PER_HOUR * HOURS_PER_DAY; export const NUMBER_SEQUENCE_KEYS = { CUSTOMER_INVOICE_NUMBER: 'customer_invoice_serial_number', INVENTORY_ADJUSTMENT_SERIAL_NUMBER: 'inventory_adjustment_serial_number', REQUISITION_SERIAL_NUMBER: 'requisition_serial_number', REQUISITION_REQUESTER_REFERENCE: 'requisition_requester_reference', STOCKTAKE_SERIAL_NUMBER: 'stocktake_serial_number', SUPPLIER_INVOICE_NUMBER: 'supplier_invoice_serial_number', };
Update recommended libspotify and pyspotify version
"""A backend for playing music from Spotify `Spotify <http://www.spotify.com/>`_ is a music streaming service. The backend uses the official `libspotify <http://developer.spotify.com/en/libspotify/overview/>`_ library and the `pyspotify <http://github.com/mopidy/pyspotify/>`_ Python bindings for libspotify. This backend handles URIs starting with ``spotify:``. See :ref:`music-from-spotify` for further instructions on using this backend. .. note:: This product uses SPOTIFY(R) CORE but is not endorsed, certified or otherwise approved in any way by Spotify. Spotify is the registered trade mark of the Spotify Group. **Issues:** https://github.com/mopidy/mopidy/issues?labels=Spotify+backend **Dependencies:** - libspotify >= 12, < 13 (libspotify12 package from apt.mopidy.com) - pyspotify >= 1.8, < 1.9 (python-spotify package from apt.mopidy.com) **Settings:** - :attr:`mopidy.settings.SPOTIFY_CACHE_PATH` - :attr:`mopidy.settings.SPOTIFY_USERNAME` - :attr:`mopidy.settings.SPOTIFY_PASSWORD` """ # flake8: noqa from .actor import SpotifyBackend
"""A backend for playing music from Spotify `Spotify <http://www.spotify.com/>`_ is a music streaming service. The backend uses the official `libspotify <http://developer.spotify.com/en/libspotify/overview/>`_ library and the `pyspotify <http://github.com/mopidy/pyspotify/>`_ Python bindings for libspotify. This backend handles URIs starting with ``spotify:``. See :ref:`music-from-spotify` for further instructions on using this backend. .. note:: This product uses SPOTIFY(R) CORE but is not endorsed, certified or otherwise approved in any way by Spotify. Spotify is the registered trade mark of the Spotify Group. **Issues:** https://github.com/mopidy/mopidy/issues?labels=Spotify+backend **Dependencies:** - libspotify >= 11, < 12 (libspotify11 package from apt.mopidy.com) - pyspotify >= 1.7, < 1.8 (python-spotify package from apt.mopidy.com) **Settings:** - :attr:`mopidy.settings.SPOTIFY_CACHE_PATH` - :attr:`mopidy.settings.SPOTIFY_USERNAME` - :attr:`mopidy.settings.SPOTIFY_PASSWORD` """ # flake8: noqa from .actor import SpotifyBackend
Allow to add a base url to find media
# -*- coding: utf-8 -*- from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, css_file_path=None, base_url=None): """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_content, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object html = HTML(string=raw_html, base_url=base_url) # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return
# -*- coding: utf-8 -*- from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, css_file_path=None): """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_content, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object html = HTML(string=raw_html) # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return
Declare egg to not be zip-safe If the egg is installed zipped, `python manage.py collectstatic` will fail to find the resources under `static`.
from os import path from setuptools import setup from subprocess import check_call from distutils.command.build import build from setuptools.command.develop import develop def get_submodules(): if path.exists('.git'): check_call(['rm', '-rf', 'pagedown/static/pagedown']) check_call(['git', 'reset', '--hard']) check_call(['git', 'submodule', 'init']) check_call(['git', 'submodule', 'update']) class build_with_submodules(build): def run(self): get_submodules() build.run(self) class develop_with_submodules(develop): def run(self): get_submodules() develop.run(self) setup( name="django-pagedown", version="0.1.0", author="Timmy O'Mahony", author_email="me@timmyomahony.com", url="https://github.com/timmyomahony/django-pagedown", description=("A django app that allows the easy addition of Stack Overflow's 'PageDown' markdown editor to a django form field"), long_description=open('README.md').read(), packages=['pagedown'], include_package_data=True, install_requires=[ "Django >= 1.3", ], license='LICENSE.txt', cmdclass={"build": build_with_submodules, "develop": develop_with_submodules}, zip_safe=False, )
from os import path from setuptools import setup from subprocess import check_call from distutils.command.build import build from setuptools.command.develop import develop def get_submodules(): if path.exists('.git'): check_call(['rm', '-rf', 'pagedown/static/pagedown']) check_call(['git', 'reset', '--hard']) check_call(['git', 'submodule', 'init']) check_call(['git', 'submodule', 'update']) class build_with_submodules(build): def run(self): get_submodules() build.run(self) class develop_with_submodules(develop): def run(self): get_submodules() develop.run(self) setup( name="django-pagedown", version="0.1.0", author="Timmy O'Mahony", author_email="me@timmyomahony.com", url="https://github.com/timmyomahony/django-pagedown", description=("A django app that allows the easy addition of Stack Overflow's 'PageDown' markdown editor to a django form field"), long_description=open('README.md').read(), packages=['pagedown'], include_package_data=True, install_requires=[ "Django >= 1.3", ], license='LICENSE.txt', cmdclass={"build": build_with_submodules, "develop": develop_with_submodules}, )
:bug: Fix NPE in protobuffer example test class [skip ci]
package org.restheart.examples; import java.io.IOException; import com.google.protobuf.InvalidProtocolBufferException; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; public class Test { public static void main(String[] args) throws Exception { testRequest(args.length < 1 ? "World" : args[0]); } public static void testRequest(String name) throws UnirestException, InvalidProtocolBufferException, IOException { var body = HelloRequest.newBuilder() .setName(name) .build(); var resp = Unirest.post("http://localhost:8080/proto") .header("Content-Type", "application/protobuf") .body(body.toByteArray()) .asBinary(); var reply = HelloReply.parseFrom(resp.getBody().readAllBytes()); System.out.println(reply.getMessage()); } }
package org.restheart.examples; import java.io.IOException; import com.google.protobuf.InvalidProtocolBufferException; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; public class Test { public static void main(String[] args) throws Exception { testRequest(args[0] == null ? "World" : args[0]); } public static void testRequest(String name) throws UnirestException, InvalidProtocolBufferException, IOException { var body = HelloRequest.newBuilder() .setName(name) .build(); var resp = Unirest.post("http://localhost:8080/proto") .header("Content-Type", "application/protobuf") .body(body.toByteArray()) .asBinary(); var reply = HelloReply.parseFrom(resp.getBody().readAllBytes()); System.out.println(reply.getMessage()); } }
Fix focus style for links.
import React from 'react' import Link from 'next/link' import {A} from './styled' import {css} from 'react-emotion' const common = ` position: relative; outline: none; color: inherit; text-decoration: none; text-transform: uppercase; letter-spacing: 1px; font-weight: 300; font-size: 1.25rem; line-height: 1.2em; margin-bottom: .6em; text-transform: capitalize; &:hover, &:focus { outline: none; }; ` const effect = ` &:after { position: absolute; top: 100%; left: 0; width: 100%; height: 4px; background: #D2D7D3; content: ''; opacity: 0; transition: opacity 0.3s, transform 0.3s; transform: translateY(5px); } &:hover::after { opacity: 1; transform: translateY(0px); } ` const customStyle = ` ${common} ${effect} ` const LinkComponent = ({item: {name, url, target}}) => ( <Link href={url} passHref> <A css={css` ${customStyle}; `} target={target} > {name} </A> </Link> ) LinkComponent.displayName = 'Link' export default LinkComponent
import React from 'react' import Link from 'next/link' import {A} from './styled' import {css} from 'react-emotion' const common = ` position: relative; outline: none; color: inherit; text-decoration: none; text-transform: uppercase; letter-spacing: 1px; font-weight: 300; font-size: 1.25rem; line-height: 1.2em; margin-bottom: .6em; text-transform: capitalize; &:hover, &:focus { outline: none; }; ` const effect = ` &:after { position: absolute; top: 100%; left: 0; width: 100%; height: 4px; background: #D2D7D3; content: ''; opacity: 0; transition: opacity 0.3s, transform 0.3s; transform: translateY(5px); } &:hover::after, &:focus::after { opacity: 1; transform: translateY(0px); } ` const customStyle = ` ${common} ${effect} ` const LinkComponent = ({item: {name, url, target}}) => ( <Link href={url} passHref> <A css={css` ${customStyle}; `} target={target} > {name} </A> </Link> ) LinkComponent.displayName = 'Link' export default LinkComponent
Raise system code on exit from `python -m detox`
import sys import py import detox from detox.proc import Detox def parse(args): from tox.session import prepare return prepare(args) def main(args=None): if args is None: args = sys.argv[1:] config = parse(args) #now = py.std.time.time() detox = Detox(config) detox.startloopreport() retcode = detox.runtestsmulti(config.envlist) #elapsed = py.std.time.time() - now #cumulated = detox.toxsession.report.cumulated_time #detox.toxsession.report.line( # "detox speed-up: %.2f (elapsed %.2f, cumulated %.2f)" % ( # cumulated / elapsed, elapsed, cumulated), bold=True) raise SystemExit(retcode)
import sys import py import detox from detox.proc import Detox def parse(args): from tox.session import prepare return prepare(args) def main(args=None): if args is None: args = sys.argv[1:] config = parse(args) #now = py.std.time.time() detox = Detox(config) detox.startloopreport() retcode = detox.runtestsmulti(config.envlist) #elapsed = py.std.time.time() - now #cumulated = detox.toxsession.report.cumulated_time #detox.toxsession.report.line( # "detox speed-up: %.2f (elapsed %.2f, cumulated %.2f)" % ( # cumulated / elapsed, elapsed, cumulated), bold=True) return retcode
Change output filename for combined results to avoid recursive accumulation
#!/usr/bin/env python """ Simple script to combine JUnit test results into a single XML file. Useful for Jenkins. TODO: Pretty indentation """ import os from xml.etree import cElementTree as ET def find_all(name, path): result = [] for root, dirs, files in os.walk(path): if name in files: yield os.path.join(root, name) def main(path, output): testsuite = ET.Element("testsuite", name="all", package="all", tests="0") for fname in find_all("results.xml", path): tree = ET.parse(fname) for element in tree.iter("testcase"): testsuite.append(element) result = ET.Element("testsuites", name="results") result.append(testsuite) ET.ElementTree(result).write(output, encoding="UTF-8") if __name__ == "__main__": main(".", "combined_results.xml")
#!/usr/bin/env python """ Simple script to combine JUnit test results into a single XML file. Useful for Jenkins. TODO: Pretty indentation """ import os from xml.etree import cElementTree as ET def find_all(name, path): result = [] for root, dirs, files in os.walk(path): if name in files: yield os.path.join(root, name) def main(path, output): testsuite = ET.Element("testsuite", name="all", package="all", tests="0") for fname in find_all("results.xml", path): tree = ET.parse(fname) for element in tree.iter("testcase"): testsuite.append(element) result = ET.Element("testsuites", name="results") result.append(testsuite) ET.ElementTree(result).write(output, encoding="UTF-8") if __name__ == "__main__": main(".", "results.xml")
Check for right kind of error in invalid creds test
from oauthlib.oauth2 import InvalidClientError import pytest from test import configure_mendeley, cassette def test_should_get_authenticated_session(): mendeley = configure_mendeley() auth = mendeley.start_client_credentials_flow() with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'): session = auth.authenticate() assert session.token['access_token'] assert session.host == 'https://api.mendeley.com' def test_should_throw_exception_on_incorrect_credentials(): mendeley = configure_mendeley() mendeley.client_secret += '-invalid' auth = mendeley.start_client_credentials_flow() # We should never get an access token back # and the OAuth library should be unhappy about that with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(MissingTokenError): auth.authenticate()
from oauthlib.oauth2 import InvalidClientError import pytest from test import configure_mendeley, cassette def test_should_get_authenticated_session(): mendeley = configure_mendeley() auth = mendeley.start_client_credentials_flow() with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'): session = auth.authenticate() assert session.token['access_token'] assert session.host == 'https://api.mendeley.com' def test_should_throw_exception_on_incorrect_credentials(): mendeley = configure_mendeley() mendeley.client_secret += '-invalid' auth = mendeley.start_client_credentials_flow() with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(InvalidClientError): auth.authenticate()
Fix test to run under Linux CI
<?php use Valet\PhpFpm; use Illuminate\Container\Container; class PhpFpmTest extends PHPUnit_Framework_TestCase { public function setUp() { $_SERVER['SUDO_USER'] = user(); Container::setInstance(new Container); } public function tearDown() { exec('rm -rf '.__DIR__.'/output'); mkdir(__DIR__.'/output'); touch(__DIR__.'/output/.gitkeep'); Mockery::close(); } public function test_fpm_is_configured_with_the_correct_user_group_and_port() { copy(__DIR__.'/files/fpm.conf', __DIR__.'/output/fpm.conf'); resolve(StubForUpdatingFpmConfigFiles::class)->updateConfiguration(); $contents = file_get_contents(__DIR__.'/output/fpm.conf'); $this->assertContains(sprintf("\nuser = %s", user()), $contents); $this->assertContains("\ngroup = staff", $contents); $this->assertContains("\nlisten = ".VALET_HOME_PATH."/valet.sock", $contents); } } class StubForUpdatingFpmConfigFiles extends PhpFpm { function fpmConfigPath() { return __DIR__.'/output/fpm.conf'; } }
<?php use Valet\PhpFpm; use Illuminate\Container\Container; class PhpFpmTest extends PHPUnit_Framework_TestCase { public function setUp() { $_SERVER['SUDO_USER'] = user(); Container::setInstance(new Container); } public function tearDown() { exec('rm -rf '.__DIR__.'/output'); mkdir(__DIR__.'/output'); touch(__DIR__.'/output/.gitkeep'); Mockery::close(); } public function test_fpm_is_configured_with_the_correct_user_group_and_port() { copy(__DIR__.'/files/fpm.conf', __DIR__.'/output/fpm.conf'); resolve(StubForUpdatingFpmConfigFiles::class)->updateConfiguration(); $contents = file_get_contents(__DIR__.'/output/fpm.conf'); $this->assertContains(sprintf("\nuser = %s", user()), $contents); $this->assertContains("\ngroup = staff", $contents); $this->assertContains("\nlisten = /Users/".user()."/.valet/valet.sock", $contents); } } class StubForUpdatingFpmConfigFiles extends PhpFpm { function fpmConfigPath() { return __DIR__.'/output/fpm.conf'; } }
Switch to function to supress error
<?php namespace Cjm\Behat; use Behat\Gherkin\Node\FeatureNode; use Behat\Gherkin\Node\ScenarioInterface; use Behat\Gherkin\Node\TaggedNodeInterface; use Cjm\Testing\SemVer\Tag; use Cjm\Testing\SemVer\Test; class TestFactory { /** * @return Test */ public function fromTaggedNode(TaggedNodeInterface $taggedNode) { return Test::taggedWith( array_map( function($tag) { return Tag::fromString($tag); }, $taggedNode->getTags() ) ); } }
<?php namespace Cjm\Behat; use Behat\Gherkin\Node\FeatureNode; use Behat\Gherkin\Node\ScenarioInterface; use Behat\Gherkin\Node\TaggedNodeInterface; use Cjm\Testing\SemVer\Test; class TestFactory { private $tagConstructor = ['Cjm\Testing\Semver\Tag', 'fromString']; /** * @return Test */ public function fromTaggedNode(TaggedNodeInterface $taggedNode) { return Test::taggedWith( array_map( $this->tagConstructor, $taggedNode->getTags() ) ); } }
[FIX] Fix array syntax for old PHP versions
<?php namespace N98\Magento\Command; use N98\Magento\Command\PHPUnit\TestCase; use Symfony\Component\Console\Tester\CommandTester; class ListCommandTest extends TestCase { public function testExecute() { $command = $this->getApplication()->find('list'); $commandTester = new CommandTester($command); $commandTester->execute( array( 'command' => 'list', ) ); $this->assertContains( sprintf('n98-magerun version %s by netz98 GmbH', $this->getApplication()->getVersion()), $commandTester->getDisplay() ); } }
<?php namespace N98\Magento\Command; use N98\Magento\Command\PHPUnit\TestCase; use Symfony\Component\Console\Tester\CommandTester; class ListCommandTest extends TestCase { public function testExecute() { $command = $this->getApplication()->find('list'); $commandTester = new CommandTester($command); $commandTester->execute( [ 'command' => 'list', ] ); $this->assertContains( sprintf('n98-magerun version %s by netz98 GmbH', $this->getApplication()->getVersion()), $commandTester->getDisplay() ); } }
Fix test - change in client redirection previously overlooked.
"""Unit test module for auth""" import json from flask.ext.login import login_user, logout_user from tests import TestCase, LAST_NAME, FIRST_NAME, TEST_USER_ID from portal.extensions import db from portal.models.auth import Client class TestAuth(TestCase): def test_client_edit(self): # Generate a minimal client belonging to test user client_id = 'test_client' client = Client(client_id=client_id, client_secret='tc_secret', user_id=TEST_USER_ID) db.session.add(client) db.session.commit() self.promote_user(role_name='application_developer') self.login() rv = self.app.post('/client/{0}'.format(client.client_id), data=dict(callback_url='http://tryme.com')) client = Client.query.get('test_client') self.assertEquals(client.callback_url, 'http://tryme.com')
"""Unit test module for auth""" import json from flask.ext.login import login_user, logout_user from tests import TestCase, LAST_NAME, FIRST_NAME, TEST_USER_ID from portal.extensions import db from portal.models.auth import Client class TestAuth(TestCase): def test_client_edit(self): # Generate a minimal client belonging to test user client_id = 'test_client' client = Client(client_id=client_id, client_secret='tc_secret', user_id=TEST_USER_ID) db.session.add(client) db.session.commit() self.promote_user(role_name='application_developer') self.login() rv = self.app.post('/client/{0}'.format(client.client_id), data=dict(callback_url='http://tryme.com')) self.assertEquals(rv.status_code, 200) client = Client.query.get('test_client') self.assertEquals(client.callback_url, 'http://tryme.com')
Remove fromToMultiplier and fix up lerp logic
/*! * tweensy - Copyright (c) 2017 Jacob Buck * https://github.com/jacobbuck/tweensy * Licensed under the terms of the MIT license. */ import now from "performance-now"; import rafq from "rafq"; const queue = rafq(); const defaultOptions = { duration: 0, easing: t => t, from: 0, onComplete: () => {}, onProgress: () => {}, to: 1, }; const tween = instanceOptions => { const options = { ...defaultOptions, ...instanceOptions, }; let isFinished = false; let startTime = null; const tick = () => { const time = now(); if (!startTime) { startTime = time; } var progress = isFinished ? 1 : Math.min((time - startTime) / options.duration, 1); options.onProgress( options.easing(progress) * (options.to - options.from) + options.from ); if (progress === 1) { options.onComplete(time); } else { queue.add(tick); } }; const stop = finish => { isFinished = true; if (!finish) { queue.remove(tick); } }; tick(); return stop; };
/*! * tweensy - Copyright (c) 2017 Jacob Buck * https://github.com/jacobbuck/tweensy * Licensed under the terms of the MIT license. */ import now from "performance-now"; import rafq from "rafq"; const queue = rafq(); const defaultOptions = { duration: 0, easing: t => t, from: 0, onComplete: () => {}, onProgress: () => {}, to: 1, }; const tween = instanceOptions => { const options = { ...defaultOptions, ...instanceOptions, }; const fromToMultiplier = options.to - options.from + options.from; let isFinished = false; let startTime = null; const tick = () => { const time = now(); if (!startTime) { startTime = time; } var progress = isFinished ? 1 : Math.min((time - startTime) / options.duration, 1); options.onProgress(options.easing(progress) * fromToMultiplier); if (progress === 1) { options.onComplete(time); } else { queue.add(tick); } }; const stop = finish => { isFinished = true; if (!finish) { queue.remove(tick); } }; tick(); return stop; };
Modify django orm filter, add only
"""info services.""" from info.models import Article, News, Column def get_column_object(uid): """Get column object.""" try: obj = Column.objects.get(uid=uid) except Column.DoesNotExist: obj = None return obj def get_articles_by_column(uid): """Get_articles_by_column.""" queryset = Article.objects.filter( column__uid=uid ).order_by('id') return queryset def get_columns_queryset(): """Get_columns_queryset.""" queryset = Column.objects.all().only('uid', 'name').order_by('-id') return queryset def get_article_queryset(): """Get article queryset.""" queryset = Article.objects.all().order_by('-id') return queryset def get_article_object(uid): """Get article object.""" return Article.objects.get(uid=uid) def get_news_queryset(): """Get news queryset.""" return News.objects.all().order_by('-id')
"""info services.""" from info.models import Article, News, Column def get_column_object(uid): """Get column object.""" try: obj = Column.objects.get(uid=uid) except Column.DoesNotExist: obj = None return obj def get_articles_by_column(uid): """Get_articles_by_column.""" queryset = Article.objects.filter(column__uid=uid).order_by('id') return queryset def get_columns_queryset(): """Get_columns_queryset.""" queryset = Column.objects.all().order_by('-id') return queryset def get_article_queryset(): """Get article queryset.""" queryset = Article.objects.all().order_by('-id') return queryset def get_article_object(uid): """Get article object.""" return Article.objects.get(uid=uid) def get_news_queryset(): """Get news queryset.""" return News.objects.all().order_by('-id')
Determine what to encode based in skip options.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) Ubuntu Podcast # http://www.ubuntupodcast.org # See the file "LICENSE" for the full license governing this code. from podpublish import configuration from podpublish import encoder def main(): config = configuration.Configuration('podcoder.ini') if not config.mp3['skip']: encoder.audio_encode(config, 'mp3') encoder.mp3_tag(config) encoder.mp3_coverart(config) if not config.ogg['skip']: encoder.audio_encode(config, 'ogg') encoder.ogg_tag(config) encoder.ogg_coverart(config) if not config.youtube['skip']: encoder.png_header(config) encoder.png_poster(config) encoder.mkv_encode(config) if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) Ubuntu Podcast # http://www.ubuntupodcast.org # See the file "LICENSE" for the full license governing this code. from podpublish import configuration from podpublish import encoder from podpublish import uploader def main(): config = configuration.Configuration('podcoder.ini') encoder.audio_encode(config, 'mp3') encoder.mp3_tag(config) encoder.mp3_coverart(config) encoder.audio_encode(config, 'ogg') encoder.ogg_tag(config) encoder.ogg_coverart(config) encoder.png_header(config) encoder.png_poster(config) encoder.mkv_encode(config) uploader.youtube_upload(config) if __name__ == '__main__': main()
Allow 'python -m glitch database' as well as with a dot
from . import config from . import apikeys import argparse # Hack: Allow "python -m glitch database" to be the same as "glitch.database" import sys if len(sys.argv) > 1 and sys.argv[1] == "database": from . import database import clize sys.exit(clize.run(*database.commands, args=sys.argv[1:])) import logging parser = argparse.ArgumentParser(description="Invoke the Infinite Glitch server(s)") parser.add_argument("server", help="Server to invoke", choices=["main", "renderer"], nargs="?", default="main") parser.add_argument("-l", "--log", help="Logging level", type=lambda x: x.upper(), choices=logging._nameToLevel, # NAUGHTY default="INFO") parser.add_argument("--dev", help="Dev mode (no logins)", action='store_true') arguments = parser.parse_args() log = logging.getLogger(__name__) logging.basicConfig(level=getattr(logging, arguments.log), format='%(asctime)s:%(levelname)s:%(name)s:%(message)s') if arguments.server == "renderer": from . import renderer renderer.run() # doesn't return else: from . import server server.run(disable_logins=arguments.dev) # doesn't return
from . import config from . import apikeys import argparse import logging parser = argparse.ArgumentParser(description="Invoke the Infinite Glitch server(s)") parser.add_argument("server", help="Server to invoke", choices=["main", "renderer"], nargs="?", default="main") parser.add_argument("-l", "--log", help="Logging level", type=lambda x: x.upper(), choices=logging._nameToLevel, # NAUGHTY default="INFO") parser.add_argument("--dev", help="Dev mode (no logins)", action='store_true') arguments = parser.parse_args() log = logging.getLogger(__name__) logging.basicConfig(level=getattr(logging, arguments.log), format='%(asctime)s:%(levelname)s:%(name)s:%(message)s') if arguments.server == "renderer": from . import renderer renderer.run() # doesn't return else: from . import server server.run(disable_logins=arguments.dev) # doesn't return
Improve async loading bar test The waitFor helper is allows us to wait for what we are actually testing instead of a time which sometimes blocks the rendering and causes the test to be flaky.
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, find, waitFor } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { later } from '@ember/runloop'; module('Integration | Component | loading bar', function(hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { const bar = '.bar'; const emptyBar = '.bar[value="0"]'; this.set('isLoading', true); // don't `await` this render as the internal task that never stops will keep this test running forever render(hbs`{{loading-bar isLoading=isLoading}}`); await waitFor(bar); // we need to give the bar a moment to actually change state and we // cannot use wait here because the task actually keeps running forever preventing // any kind of settled state await later(async () => { assert.ok(find(bar).getAttribute('value').trim() > 0); this.set('isLoading', false); await waitFor(emptyBar); assert.equal(find(bar).getAttribute('value').trim(), 0); }, 500); }); });
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, find } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { later } from '@ember/runloop'; module('Integration | Component | loading bar', function(hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { const bar = '.bar'; this.set('isLoading', true); // don't `await` this render as the internal task that never stops will keep this test running forever render(hbs`{{loading-bar isLoading=isLoading}}`); // we need to give the bar a moment to actually change state and we // cannot use wait here because the task actually keeps running forever preventing // any kind of settled state await later(async () => { assert.ok(find(bar).getAttribute('value').trim() > 0); this.set('isLoading', false); await later(() => { assert.equal(find(bar).getAttribute('value').trim(), 0); }, 2000); }, 1000); }); });
Disable test cleanup for debugging
/** * require dependencies */ WebdriverIO = require('webdriverio'); WebdriverCSS = require('../index.js'); fs = require('fs-extra'); gm = require('gm'); glob = require('glob'); async = require('async'); should = require('chai').should(); expect = require('chai').expect; capabilities = {logLevel: 'silent',desiredCapabilities:{browserName: 'phantomjs'}}; testurl = 'http://localhost:8080/test/site/index.html'; testurlTwo = 'http://localhost:8080/test/site/two.html'; testurlThree = 'http://localhost:8080/test/site/three.html'; testurlFour = 'http://localhost:8080/test/site/four.html'; /** * set some fix test variables */ screenshotRootDefault = 'webdrivercss'; failedComparisonsRootDefault = 'webdrivercss/diff'; screenshotRootCustom = '__screenshotRoot__'; failedComparisonsRootCustom = '__failedComparisonsRoot__'; afterHook = function(done) { var browser = this.browser; /** * close browser and clean up created directories */ async.parallel([ function(done) { browser.end(done); }, // function(done) { fs.remove(failedComparisonsRootDefault,done); }, // function(done) { fs.remove(screenshotRootDefault,done); }, // function(done) { fs.remove(failedComparisonsRootCustom,done); }, // function(done) { fs.remove(screenshotRootCustom,done); } ], done); };
/** * require dependencies */ WebdriverIO = require('webdriverio'); WebdriverCSS = require('../index.js'); fs = require('fs-extra'); gm = require('gm'); glob = require('glob'); async = require('async'); should = require('chai').should(); expect = require('chai').expect; capabilities = {logLevel: 'silent',desiredCapabilities:{browserName: 'phantomjs'}}; testurl = 'http://localhost:8080/test/site/index.html'; testurlTwo = 'http://localhost:8080/test/site/two.html'; testurlThree = 'http://localhost:8080/test/site/three.html'; testurlFour = 'http://localhost:8080/test/site/four.html'; /** * set some fix test variables */ screenshotRootDefault = 'webdrivercss'; failedComparisonsRootDefault = 'webdrivercss/diff'; screenshotRootCustom = '__screenshotRoot__'; failedComparisonsRootCustom = '__failedComparisonsRoot__'; afterHook = function(done) { var browser = this.browser; /** * close browser and clean up created directories */ async.parallel([ function(done) { browser.end(done); }, function(done) { fs.remove(failedComparisonsRootDefault,done); }, function(done) { fs.remove(screenshotRootDefault,done); }, function(done) { fs.remove(failedComparisonsRootCustom,done); }, function(done) { fs.remove(screenshotRootCustom,done); } ], done); };
Change karma log lvl to WARN
const browsers = ['Firefox']; if (!process.env.CI) { browsers.push('Chrome'); switch (process.platform) { case 'darwin': browsers.push('Safari'); break; case 'win32': browsers.push('IE'); browsers.push('Edge'); break; } } module.exports = (config) => { config.set({ basePath: '../', frameworks: ['mocha', 'chai'], files: [ 'dist/blowfish.js', 'test/common.js', 'test/browser.js' ], reporters: ['dots'], browsers: browsers, singleRun: true, logLevel: config.LOG_WARN }); };
const browsers = ['Firefox']; if (!process.env.CI) { browsers.push('Chrome'); switch (process.platform) { case 'darwin': browsers.push('Safari'); break; case 'win32': browsers.push('IE'); browsers.push('Edge'); break; } } module.exports = (config) => { config.set({ basePath: '../', frameworks: ['mocha', 'chai'], files: [ 'dist/blowfish.js', 'test/common.js', 'test/browser.js' ], reporters: ['dots'], browsers: browsers, singleRun: true }); };
Revert previous commit as fuse-python doesn't seem to play nicely with easy_install (at least on Ubuntu).
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2008 Jason Davies # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = 'CouchDB-FUSE', version = '0.1', description = 'CouchDB FUSE module', long_description = \ """This is a Python FUSE module for CouchDB. It allows CouchDB document attachments to be mounted on a virtual filesystem and edited directly.""", author = 'Jason Davies', author_email = 'jason@jasondavies.com', license = 'BSD', url = 'http://code.google.com/p/couchdb-fuse/', zip_safe = True, classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Database :: Front-Ends', ], packages = ['couchdbfuse'], entry_points = { 'console_scripts': [ 'couchmount = couchdbfuse:main', ], }, install_requires = ['CouchDB>=0.5'], )
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2008 Jason Davies # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = 'CouchDB-FUSE', version = '0.1', description = 'CouchDB FUSE module', long_description = \ """This is a Python FUSE module for CouchDB. It allows CouchDB document attachments to be mounted on a virtual filesystem and edited directly.""", author = 'Jason Davies', author_email = 'jason@jasondavies.com', license = 'BSD', url = 'http://code.google.com/p/couchdb-fuse/', zip_safe = True, classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Database :: Front-Ends', ], packages = ['couchdbfuse'], entry_points = { 'console_scripts': [ 'couchmount = couchdbfuse:main', ], }, install_requires = ['CouchDB>=0.5', 'fuse-python>=0.2'], )
Include default timeout value from interface Both the interface (`Interop\Queue\PsrConsumer`) and the implementation (for example `Enqueue\AmqpBunny\AmqpConsumer`) seem to have a default value for the `receive()` method's first and only parameter `$timeout`. This default value (`0`) isn't included in the `@method` annotation in `Interop\Queue\PsrConsumer\AmqpConsumer` which makes code completion in an IDE give a false positive when leaving out the (optional) parameter. Including this default value in the annotation fixes this problem. There is no effect on the actual functionality or operation of this interop library or any of it's decendants.
<?php namespace Interop\Amqp; use Interop\Queue\PsrConsumer; /** * @method AmqpMessage|null receiveNoWait() * @method AmqpMessage|null receive(int $timeout = 0) * @method AmqpQueue getQueue() * @method void acknowledge(AmqpMessage $message) * @method void reject(AmqpMessage $message, bool $requeue) */ interface AmqpConsumer extends PsrConsumer { const FLAG_NOPARAM = 0; const FLAG_NOLOCAL = 1; const FLAG_NOACK = 2; const FLAG_EXCLUSIVE = 4; const FLAG_NOWAIT = 8; /** * @param string $consumerTag */ public function setConsumerTag($consumerTag); /** * @return string */ public function getConsumerTag(); public function clearFlags(); /** * @param int $flag */ public function addFlag($flag); /** * @return int */ public function getFlags(); /** * @param int $flags */ public function setFlags($flags); }
<?php namespace Interop\Amqp; use Interop\Queue\PsrConsumer; /** * @method AmqpMessage|null receiveNoWait() * @method AmqpMessage|null receive(int $timeout) * @method AmqpQueue getQueue() * @method void acknowledge(AmqpMessage $message) * @method void reject(AmqpMessage $message, bool $requeue) */ interface AmqpConsumer extends PsrConsumer { const FLAG_NOPARAM = 0; const FLAG_NOLOCAL = 1; const FLAG_NOACK = 2; const FLAG_EXCLUSIVE = 4; const FLAG_NOWAIT = 8; /** * @param string $consumerTag */ public function setConsumerTag($consumerTag); /** * @return string */ public function getConsumerTag(); public function clearFlags(); /** * @param int $flag */ public function addFlag($flag); /** * @return int */ public function getFlags(); /** * @param int $flags */ public function setFlags($flags); }
Change HTTP method to GET
var express = require('express'); var Global = require('../global'); var search = require('../commands/search'); var router = express.Router(); router.get('/*', function(req, res) { var response = ''; var arg = req.body.text; console.log(req.body); //TODO delete console.log(req.body.token); //TODO delete //validate token if(req.body.token === Global.authToken) { switch(req.body.command) { case '/searchin': response = search(arg, res); break; default: res.status('500'); res.json({ text: 'Unknown command' }); } } else { res.status('403'); res.json({ text: 'Invalid token' }); } }); router.post('/*', function(req, res) { res.status('405'); res.json({ text: 'Method not allowed' }); }); module.exports = router;
var express = require('express'); var Global = require('../global'); var search = require('../commands/search'); var router = express.Router(); router.get('/*', function(req, res) { var response = ''; var arg = req.body.text; console.log(req.body); //TODO delete console.log(req.body.token); //TODO delete //validate token if(req.body.token === Global.authToken) { switch(req.body.command) { case '/searchin': response = search(arg, res); break; default: res.status('500'); res.json({ text: 'Unknown command' }); } } else { res.status('403'); res.json({ text: 'Invalid token' }); } }); module.exports = router;
Call of console was deleted
import { certificates, certificatesAsync } from './certificates'; import { sign, signAsync } from './sign'; import { paramsForDetachedSignature, paramsForDetachedSignatureAsync, } from './params_for_detached_signature'; import { digestValue, digestValueAsync } from './digest_value'; import { cadesplugin } from './constants'; /** * @class * @name CryptoProProvider * @description Module provide methods for signing requests with Crypto Pro * @author Vitaly Mashanov <vvmashanov@yandex.ru> */ /** * @function * @name isAsync * @description Checking, which method used by browser (Async or NPAPI) * @return {boolean} */ const isAsync = () => (cadesplugin.CreateObjectAsync || false); export default { certificates: isAsync() ? certificatesAsync : certificates, sign: isAsync() ? signAsync : sign, paramsForDetachedSignature: isAsync() ? paramsForDetachedSignatureAsync : paramsForDetachedSignature, digestValue: isAsync() ? digestValueAsync : digestValue, };
import { certificates, certificatesAsync } from './certificates'; import { sign, signAsync } from './sign'; import { paramsForDetachedSignature, paramsForDetachedSignatureAsync, } from './params_for_detached_signature'; import { digestValue, digestValueAsync } from './digest_value'; import { cadesplugin } from './constants'; console.log('----', cadesplugin); /** * @class * @name CryptoProProvider * @description Module provide methods for signing requests with Crypto Pro * @author Vitaly Mashanov <vvmashanov@yandex.ru> */ /** * @function * @name isAsync * @description Checking, which method used by browser (Async or NPAPI) * @return {boolean} */ const isAsync = () => (cadesplugin.CreateObjectAsync || false); export default { certificates: isAsync() ? certificatesAsync : certificates, sign: isAsync() ? signAsync : sign, paramsForDetachedSignature: isAsync() ? paramsForDetachedSignatureAsync : paramsForDetachedSignature, digestValue: isAsync() ? digestValueAsync : digestValue, };
Update Pretender version to ~0.10.1 Changes from version 0.9 include better synchronous xhr support, some fixes for content-type header and event firing on `passthrough`'d requests, better error messages. See the changes from Pretender 0.10.0 -> 0.10.1 [here](https://github.com/pretenderjs/pretender/blob/master/CHANGELOG.md).
/*jshint node:true*/ 'use strict'; var path = require('path'); module.exports = { normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, fileMapTokens: function() { return { __root__: function(options) { if (options.inAddon) { return path.join('tests', 'dummy', 'app'); } return 'app'; } }; }, afterInstall: function() { this.insertIntoFile('.jshintrc', ' "server",', { after: '"predef": [\n' }); this.insertIntoFile('tests/.jshintrc', ' "server",', { after: '"predef": [\n' }); return this.addBowerPackagesToProject([ {name: 'pretender', target: '~0.10.1'}, {name: 'lodash', target: '~3.7.0'}, {name: 'Faker', target: '~3.0.0'} ]); } };
/*jshint node:true*/ 'use strict'; var path = require('path'); module.exports = { normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, fileMapTokens: function() { return { __root__: function(options) { if (options.inAddon) { return path.join('tests', 'dummy', 'app'); } return 'app'; } }; }, afterInstall: function() { this.insertIntoFile('.jshintrc', ' "server",', { after: '"predef": [\n' }); this.insertIntoFile('tests/.jshintrc', ' "server",', { after: '"predef": [\n' }); return this.addBowerPackagesToProject([ {name: 'pretender', target: '~0.9.0'}, {name: 'lodash', target: '~3.7.0'}, {name: 'Faker', target: '~3.0.0'} ]); } };
Fix environment variable name in comment
// Copyright (c) 2016-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license 'use strict' const express = require('express') const app = express() const auth = require('http-auth') const port = process.env.PORT || 3000 // Basic auth // Set USERNAME and PASSWORD environment variables const basic = auth.basic({ realm: 'Salesforce Lightning Design System Prototype' }, (username, password, next) => { next(username === process.env.USERNAME && password === process.env.PASSWORD) }) if (process.env.USERNAME && process.env.PASSWORD) { app.use(auth.connect(basic)) } app.use('/', express.static('./dist')) app.listen(port, () => console.log(`Listening on port ${port}!\n\nDeveloping locally? Run "npm run dev" instead.`))
// Copyright (c) 2016-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license 'use strict' const express = require('express') const app = express() const auth = require('http-auth') const port = process.env.PORT || 3000 // Basic auth // Set USER and PASSWORD environment variables const basic = auth.basic({ realm: 'Salesforce Lightning Design System Prototype' }, (username, password, next) => { next(username === process.env.USERNAME && password === process.env.PASSWORD) }) if (process.env.USERNAME && process.env.PASSWORD) { app.use(auth.connect(basic)) } app.use('/', express.static('./dist')) app.listen(port, () => console.log(`Listening on port ${port}!\n\nDeveloping locally? Run "npm run dev" instead.`))
Change selector to take current_user from state
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ export function defaultSelector(state) { let data = state.toJS(); data.is_logged_in = !!data.current_user.id; if (data.is_logged_in) { let current_user_id = data.current_user.id; data.current_user_tags = data.current_user.tags; data.current_user = Object.assign(data.current_user, data.users[current_user_id]); data.current_user.likes = data.likes[current_user_id] || []; data.current_user.favourites = data.favourites[current_user_id] || []; data.i_am_following = data.following[current_user_id]; } else { data.current_user = null; } return data; }
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ export function defaultSelector(state) { let data = state.toJS(); data.is_logged_in = !!data.current_user.id; if (data.is_logged_in) { let current_user_id = data.current_user.id; data.current_user_tags = data.current_user.tags; data.current_user = data.users[current_user_id]; data.current_user.likes = data.likes[current_user_id] || []; data.current_user.favourites = data.favourites[current_user_id] || []; data.i_am_following = data.following[current_user_id]; } else { data.current_user = null; } return data; }
Add info on where to report a bug for the pear2 website.
<?php // Set the title for the main template $parent->context->page_title = 'Support - ' . $frontend->title; ?> <div class="support"> <h2>Support</h2> <ul> <li>There's a Pyrus section in <a href="http://pear.php.net/manual/en/pyrus.php">PEAR manual</a>.</li> <li>There are some PEAR-related mailing lists, check <a href="http://pear.php.net/support/lists.php">PEAR website</a> for more info.</li> <li>You can also ask for help on the <em><a href="irc://efnet/#pear">#pear</a></em> <acronym title="Internet Relay Chat">IRC</acronym> channel at the <a href="http://www.efnet.org/"> Eris Free Net</a>. </li> </ul> <p>If you'd like to report a problem or request a feature for the pear2.php.net website, you can submit an issue on <a href="https://github.com/pear2/pear2.php.net" title="Go to the pear2.php.net project page on GitHub">the project page</a>.</p> </div>
<?php // Set the title for the main template $parent->context->page_title = 'Support - ' . $frontend->title; ?> <div class="support"> <h2>Support</h2> <ul> <li>There's a Pyrus section in <a href="http://pear.php.net/manual/en/pyrus.php">PEAR manual</a>.</li> <li>There are some PEAR-related mailing lists, check <a href="http://pear.php.net/support/lists.php">PEAR website</a> for more info.</li> <li>You can also ask for help on the <em><a href="irc://efnet/#pear">#pear</a></em> <acronym title="Internet Relay Chat">IRC</acronym> channel at the <a href="http://www.efnet.org/"> Eris Free Net</a>. </li> </ul> </div>
Increase number of updated repos
const express = require('express'); const StorageHandler = require('../lib/storage-handler'); const router = express.Router(); const storageHandler = new StorageHandler(); const REPO_KEY = 'REPOSITORIES'; const WIKI_KEY = 'WIKI_EDITS'; const MAX_RETURN_ROWS_NEW = 200; const MAX_RETURN_ROWS_UPDATED = 200; /* GET home page. */ router.get('/', (req, res, next) => { const repos = storageHandler.getStorageItem(REPO_KEY).sort((a, b) => { return new Date(b.created_at) - new Date(a.created_at); }).slice(0, MAX_RETURN_ROWS_NEW);; const updatedRepos = storageHandler.getStorageItem(REPO_KEY).sort((a, b) => { return new Date(b.updated_at) - new Date(a.updated_at); }).slice(0, MAX_RETURN_ROWS_UPDATED); const wikiEdits = storageHandler.getStorageItem(WIKI_KEY); res.render('index', { title: 'What is happening inside Mozilla?', repos, updatedRepos, wikiEdits }); }); module.exports = router;
const express = require('express'); const StorageHandler = require('../lib/storage-handler'); const router = express.Router(); const storageHandler = new StorageHandler(); const REPO_KEY = 'REPOSITORIES'; const WIKI_KEY = 'WIKI_EDITS'; /* GET home page. */ router.get('/', (req, res, next) => { const repos = storageHandler.getStorageItem(REPO_KEY).sort((a, b) => { return new Date(b.created_at) - new Date(a.created_at); }).slice(0, 100);; const updatedRepos = storageHandler.getStorageItem(REPO_KEY).sort((a, b) => { return new Date(b.updated_at) - new Date(a.updated_at); }).slice(0, 100); const wikiEdits = storageHandler.getStorageItem(WIKI_KEY); res.render('index', { title: 'What is happening inside Mozilla?', repos, updatedRepos, wikiEdits }); }); module.exports = router;
Chrome: Throw an exception when a localised string is not found
/** * The MIT License * * Copyright (c) 2010 Steven G. Brown * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /* * ---------------------------------------------------------------------------- * Messages * ---------------------------------------------------------------------------- */ /** * @class Provides localised strings. */ Messages = {}; /** * Retrieve a localised string. * @param {string} key The key used to lookup the localised string. * @return {string} The localised string. */ Messages.get = function(key) { var message = chrome.i18n.getMessage(key); if (!message) { throw new Error('Messages.get(' + key + ') not found'); } return message; };
/** * The MIT License * * Copyright (c) 2010 Steven G. Brown * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /* * ---------------------------------------------------------------------------- * Messages * ---------------------------------------------------------------------------- */ /** * @class Provides localised strings. */ Messages = {}; /** * Retrieve a localised string. * @param {string} key The key used to lookup the localised string. * @return {string} The localised string. */ Messages.get = function(key) { return chrome.i18n.getMessage(key); };
Add Slash Command help text
var help = [ 'JukeBot - Slack-Enabled Syncronized Music Listening', 'Available Commands:', ' add [youtube-link] - Add a video to the queue', ' help - This help text' ]; module.exports = { slash: function(req, res) { var params = req.allParams(); if (params.token !== process.env.SLASH_TOKEN) { res.send(401); } else { var args = params.text.split(' '); var command = args.shift(); switch (command) { case 'add': var key = YouTubeService.parseYouTubeLink(args[0]); YouTubeService.getYouTubeVideo(key, params.user_name).then(SyncService.addVideo).then(SyncService.sendAddMessages).then(function(video) { res.send('Successfully added "' + video.title + '"'); }).catch(function(err) { res.send(err); }); break; case 'help': res.send(help.join('\n')); break; default: res.send('The command "' + command + '" is not currently supported. Run /jukebot help to see a list of available commands.'); break; } } } };
module.exports = { add: function(req, res) { YouTubeService.getYouTubeVideo(req.body.key, req.body.user).then(SyncService.addVideo).then(SyncService.sendAddMessages).then(function(video) { return res.send(200); }); }, slash: function(req, res) { var params = req.allParams(); if (params.token !== process.env.SLASH_TOKEN) { res.send(401); } else { var args = params.text.split(' '); var command = args.shift(); switch (command) { case 'add': var key = YouTubeService.parseYouTubeLink(args[0]); YouTubeService.getYouTubeVideo(key, params.user_name).then(SyncService.addVideo).then(SyncService.sendAddMessages).then(function(video) { res.send('Successfully added "' + video.title + '"'); }).catch(function(err) { res.send(err); }); break; default: res.send('The command "' + command + '" is not currently supported'); break; } } } };
Fix potential problem with sending admin value Parses a true value as a boolean true value and anything else as false
exports.action = { name: 'userCreate', description: 'Creates a User', version: 1, inputs: { required: [ 'name', 'organizationId', 'email', 'password', 'admin' ], optional: [] }, outputExample: {}, run: function (api, connection, next) { var id = api.mongoose.Types.ObjectId(connection.params.organizationId); var User = api.mongoose.model('User'); new User({ name: connection.params.name, email: connection.params.email, password: connection.params.password, admin: (connection.params.admin === "true") ? true : false }).save(function (err, user) { api.mongoose.model('Organization').findByIdAndUpdate(id, { $push: { users: user._id } }, function (err) { next(connection, true); }); }); } };
exports.action = { name: 'userCreate', description: 'Creates a User', version: 1, inputs: { required: [ 'name', 'organizationId', 'email', 'password', 'admin' ], optional: [] }, outputExample: {}, run: function (api, connection, next) { var id = api.mongoose.Types.ObjectId(connection.params.organizationId); var User = api.mongoose.model('User'); new User({ name: connection.params.name, email: connection.params.email, password: connection.params.password, admin: connection.params.admin }).save(function (err, user) { api.mongoose.model('Organization').findByIdAndUpdate(id, { $push: { users: user._id } }, function (err) { next(connection, true); }); }); } };
Fix return get_types for ClipboardXsel
''' Clipboard xsel: an implementation of the Clipboard using xsel command line tool. ''' __all__ = ('ClipboardXsel', ) from kivy.utils import platform from kivy.core.clipboard import ClipboardBase if platform != 'linux': raise SystemError('unsupported platform for xsel clipboard') try: import subprocess p = subprocess.Popen(['xsel'], stdout=subprocess.PIPE) p.communicate() except: raise class ClipboardXsel(ClipboardBase): def get(self, mimetype='text/plain'): p = subprocess.Popen(['xsel', '-bo'], stdout=subprocess.PIPE) data, _ = p.communicate() return data def put(self, data, mimetype='text/plain'): p = subprocess.Popen(['xsel', '-bi'], stdin=subprocess.PIPE) p.communicate(data) def get_types(self): return [u'text/plain']
''' Clipboard xsel: an implementation of the Clipboard using xsel command line tool. ''' __all__ = ('ClipboardXsel', ) from kivy.utils import platform from kivy.core.clipboard import ClipboardBase if platform != 'linux': raise SystemError('unsupported platform for xsel clipboard') try: import subprocess p = subprocess.Popen(['xsel'], stdout=subprocess.PIPE) p.communicate() except: raise class ClipboardXsel(ClipboardBase): def get(self, mimetype='text/plain'): p = subprocess.Popen(['xsel', '-bo'], stdout=subprocess.PIPE) data, _ = p.communicate() return data def put(self, data, mimetype='text/plain'): p = subprocess.Popen(['xsel', '-bi'], stdin=subprocess.PIPE) p.communicate(data) def get_types(self): return list('text/plain',)
Fix java chart install link broken issue
(function () { 'use strict'; var isMac = /Mac/i.test(navigator.platform), isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent), isAndroid = /Android/i.test(navigator.userAgent), isWindowsPhone = /Windows Phone/i.test(navigator.userAgent), isJavaInstalled = (deployJava.getJREs().length > 0) && deployJava.versionCheck("1.5+"), isMobile = isIOS || isAndroid || isWindowsPhone, canBeInstalled = isJavaInstalled && !isMobile; $('#install-java').toggle(!isJavaInstalled); $('#download-app').toggle(canBeInstalled); $('#install-java').on('click', function () { deployJava.installLatestJRE(); }); $('#download-app').on('click', function () { if (isMac) { alert('You need to change your security preferences!'); return; } if (isMobile) { alert('The charting app is not available on mobile devices!'); } }); })();
(function () { 'use strict'; var isMac = /Mac/i.test(navigator.platform), isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent), isAndroid = /Android/i.test(navigator.userAgent), isWindowsPhone = /Windows Phone/i.test(navigator.userAgent), isJavaInstalled = (deployJava.getJREs().length > 0) && deployJava.versionCheck("1.5+"), isMobile = isIOS || isAndroid || isWindowsPhone, canBeInstalled = isJavaInstalled && !isMobile; $('#install-java').toggle(!isJavaInstalled); $('#download-app').toggle(canBeInstalled); $('#install-java').on('click', function () { deployJava.installLatestJava(); }); $('#download-app').on('click', function () { if (isMac) { alert('You need to change your security preferences!'); return; } if (isMobile) { alert('The charting app is not available on mobile devices!'); } }); })();
Remove unobvious default limit for followers. Now its Infinity by default.
var _ = require('underscore'); var util = require('util'); var FeedBase = require('./feed-base'); function AccountFollowersFeed(session, accountId, limit) { this.accountId = accountId; this.limit = limit || Infinity; this.timeout = 10 * 60 * 1000; FeedBase.apply(this, arguments); } util.inherits(AccountFollowersFeed, FeedBase); module.exports = AccountFollowersFeed; var Request = require('../request'); var Account = require('../account'); AccountFollowersFeed.prototype.get = function () { var that = this; return new Request(that.session) .setMethod('GET') .setResource('followersFeed', { id: that.accountId, maxId: that.cursor }) .send() .then(function(data) { that.moreAvailable = !!data.next_max_id; if (that.moreAvailable) { that.setCursor(data.next_max_id); } return _.map(data.users, function (user) { return new Account(that.session, user); }); }) };
var _ = require('underscore'); var util = require('util'); var FeedBase = require('./feed-base'); function AccountFollowersFeed(session, accountId, limit) { this.accountId = accountId; this.limit = limit || 7500; // Should be enought for 7500 records this.timeout = 10 * 60 * 1000; FeedBase.apply(this, arguments); } util.inherits(AccountFollowersFeed, FeedBase); module.exports = AccountFollowersFeed; var Request = require('../request'); var Account = require('../account'); AccountFollowersFeed.prototype.get = function () { var that = this; return new Request(that.session) .setMethod('GET') .setResource('followersFeed', { id: that.accountId, maxId: that.cursor }) .send() .then(function(data) { that.moreAvailable = !!data.next_max_id; if (that.moreAvailable) { that.setCursor(data.next_max_id); } return _.map(data.users, function (user) { return new Account(that.session, user); }); }) };
Remove subsystem() usage in favor of fraction()
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.wildfly.swarm.examples.transactions; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.wildfly.swarm.container.Container; import org.wildfly.swarm.jaxrs.JAXRSArchive; import org.wildfly.swarm.transactions.TransactionsFraction; /** * @author nmcl */ public class Main { public static void main(String[] args) throws Exception { Container container = new Container(); /* * Use specific TransactionFraction even though it doesn't do * any more than the default one - for now. */ container.fraction(new TransactionsFraction(4712, 4713)); // Start the container container.start(); /* * Now register JAX-RS resource class. */ JAXRSArchive appDeployment = ShrinkWrap.create(JAXRSArchive.class); appDeployment.addResource(MyResource.class); container.deploy(appDeployment); } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.wildfly.swarm.examples.transactions; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.wildfly.swarm.container.Container; import org.wildfly.swarm.jaxrs.JAXRSArchive; import org.wildfly.swarm.transactions.TransactionsFraction; /** * @author nmcl */ public class Main { public static void main(String[] args) throws Exception { Container container = new Container(); /* * Use specific TransactionFraction even though it doesn't do * any more than the default one - for now. */ container.subsystem(new TransactionsFraction(4712, 4713)); // Start the container container.start(); /* * Now register JAX-RS resource class. */ JAXRSArchive appDeployment = ShrinkWrap.create(JAXRSArchive.class); appDeployment.addResource(MyResource.class); container.deploy(appDeployment); } }
Make scenarios pass in both Cucumber and Cucumber-Electron
const fs = require('fs') const path = require('path') const { setWorldConstructor } = require('cucumber') const TodoList = require('../../lib/TodoList') const mountBrowserApp = require('../../lib/mountBrowserApp') const DomTodoList = require('../../test_support/DomTodoList') class TodoWorld { constructor() { const todoList = new TodoList() this.contextTodoList = todoList if (global.document) { const domTodoList = createDomTodoList(todoList) this.actionTodoList = domTodoList } else { this.actionTodoList = todoList } this.outcomeTodoList = todoList } } function createDomTodoList(todoList) { const publicIndexHtmlPath = path.join(__dirname, '..', '..', 'public', 'index.html') const html = fs.readFileSync(publicIndexHtmlPath, 'utf-8') const domNode = document.createElement('div') domNode.innerHTML = html document.body.appendChild(domNode) mountBrowserApp({ domNode, todoList }) return new DomTodoList(domNode) } setWorldConstructor(TodoWorld)
const fs = require('fs') const path = require('path') const { setWorldConstructor } = require('cucumber') const TodoList = require('../../lib/TodoList') const mountBrowserApp = require('../../lib/mountBrowserApp') const DomTodoList = require('../../test_support/DomTodoList') class TodoWorld { constructor() { const todoList = new TodoList() const publicIndexHtmlPath = path.join(__dirname, '..', '..', 'public', 'index.html') const html = fs.readFileSync(publicIndexHtmlPath, 'utf-8') const domNode = document.createElement('div') domNode.innerHTML = html document.body.appendChild(domNode) mountBrowserApp({ domNode, todoList }) this.contextTodoList = todoList this.actionTodoList = new DomTodoList(domNode) this.outcomeTodoList = todoList } } setWorldConstructor(TodoWorld)