text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix the infinite recursion when calling runtime +/-.
builtins = import operator = import functools = import importlib = import # Choose a function based on the number of arguments. varary = (*fs) -> (*xs) -> (fs !! (len: xs)): (*): xs builtins . $ = (f, *xs) -> f: (*): xs builtins . : = (f, *xs) -> f: (*): xs builtins . , = (*xs) -> xs builtins . < = operator.lt builtins . <= = operator.le builtins . == = operator.eq builtins . != = operator.ne builtins . > = operator.gt builtins . >= = operator.ge builtins . is = operator.is_ builtins . in = (a, b) -> operator.contains: b a builtins . not = operator.not_ builtins . ~ = operator.invert builtins . + = varary: None operator.pos operator.add builtins . - = varary: None operator.neg operator.sub builtins . * = operator.mul builtins . ** = operator.pow builtins . / = operator.truediv builtins . // = operator.floordiv builtins . % = operator.mod builtins . !! = operator.getitem builtins . & = operator.and_ builtins . ^ = operator.xor builtins . | = operator.or_ builtins . << = operator.lshift builtins . >> = operator.rshift builtins.import = importlib.import_module builtins.foldl = functools.reduce builtins . ~: = functools.partial builtins . ... = Ellipsis
builtins = import operator = import functools = import importlib = import # Choose a function based on the number of arguments. varary = (*fs) -> (*xs) -> (fs !! (len: xs - 1)): (*): xs builtins . $ = (f, *xs) -> f: (*): xs builtins . : = (f, *xs) -> f: (*): xs builtins . , = (*xs) -> xs builtins . < = operator.lt builtins . <= = operator.le builtins . == = operator.eq builtins . != = operator.ne builtins . > = operator.gt builtins . >= = operator.ge builtins . is = operator.is_ builtins . in = (a, b) -> operator.contains: b a builtins . not = operator.not_ builtins . ~ = operator.invert builtins . + = varary: operator.pos operator.add builtins . - = varary: operator.neg operator.sub builtins . * = operator.mul builtins . ** = operator.pow builtins . / = operator.truediv builtins . // = operator.floordiv builtins . % = operator.mod builtins . !! = operator.getitem builtins . & = operator.and_ builtins . ^ = operator.xor builtins . | = operator.or_ builtins . << = operator.lshift builtins . >> = operator.rshift builtins.import = importlib.import_module builtins.foldl = functools.reduce builtins . ~: = functools.partial builtins . ... = Ellipsis
Add sanitisation strategy for translation
'use strict'; // Start by defining the main module and adding the module dependencies var app = angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies); // Setting HTML5 Location Mode app.config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix('!'); }]); // Configure translation app.config(['$translateProvider', function($translateProvider) { $translateProvider.useSanitizeValueStrategy('sanitize'); $translateProvider.useStaticFilesLoader({ prefix: 'languages/', suffix: '.json' }); $translateProvider.preferredLanguage('en_GB'); }]); app.controller('LanguageController', ['$scope', '$translate', function($scope, $translate) { $scope.lang = 'en_GB'; $scope.changeLanguage = function(lang) { $translate.use(lang); }; }]); // Then define the function to start up the application angular.element(document).ready(function() { // Fixing facebook bug with redirect if (window.location.hash === '#_=_') { window.location.hash = '#!'; } // Then init the app angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]); });
'use strict'; // Start by defining the main module and adding the module dependencies var app = angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies); // Setting HTML5 Location Mode app.config(['$locationProvider', function($locationProvider) { $locationProvider.hashPrefix('!'); }]); // Configure translation app.config(['$translateProvider', function($translateProvider) { $translateProvider.useStaticFilesLoader({ prefix: 'languages/', suffix: '.json' }); $translateProvider.preferredLanguage('en_GB'); }]); app.controller('LanguageController', ['$scope', '$translate', function($scope, $translate) { $scope.lang = 'en_GB'; $scope.changeLanguage = function(lang) { $translate.use(lang); }; }]); // Then define the function to start up the application angular.element(document).ready(function() { // Fixing facebook bug with redirect if (window.location.hash === '#_=_') { window.location.hash = '#!'; } // Then init the app angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]); });
Correct URI in example request for PHP
```php $client = new \GuzzleHttp\Client(); $response = $client->{{ strtolower($route['methods'][0]) }}("{{ rtrim($baseUrl, '/') . '/' . ltrim($route['boundUri'], '/') }}", [ @if(!empty($route['headers'])) 'headers' => [ @foreach($route['headers'] as $header => $value) "{{$header}}" => "{{$value}}", @endforeach ], @endif @if(!empty($route['cleanQueryParameters'])) 'query' => [ @foreach($route['cleanQueryParameters'] as $parameter => $value) "{{$parameter}}" => "{{$value}}", @endforeach ], @endif @if(!empty($route['cleanBodyParameters'])) 'json' => [ @foreach($route['cleanBodyParameters'] as $parameter => $value) "{{$parameter}}" => "{{$value}}", @endforeach ], @endif ]); $body = $response->getBody(); print_r(json_decode((string) $body)); ```
```php $client = new \GuzzleHttp\Client(); $response = $client->{{ strtolower($route['methods'][0]) }}("{{ rtrim($baseUrl, '/') . '/' . $route['boundUri'] }}", [ @if(!empty($route['headers'])) 'headers' => [ @foreach($route['headers'] as $header => $value) "{{$header}}" => "{{$value}}", @endforeach ], @endif @if(!empty($route['cleanQueryParameters'])) 'query' => [ @foreach($route['cleanQueryParameters'] as $parameter => $value) "{{$parameter}}" => "{{$value}}", @endforeach ], @endif @if(!empty($route['cleanBodyParameters'])) 'json' => [ @foreach($route['cleanBodyParameters'] as $parameter => $value) "{{$parameter}}" => "{{$value}}", @endforeach ], @endif ]); $body = $response->getBody(); print_r(json_decode((string) $body)); ```
Allow specifying a title to Box component
import React from 'react' import PropTypes from 'prop-types' const Box = ({ children, title }) => ( <div className='wrapper'> {title && <h3>{title}</h3>} <div className='inner'> {children} </div> <style jsx>{` @import 'colors'; .wrapper { background-color: $white; box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3); border-radius: 2px; margin-bottom: 20px; overflow: hidden; } h3 { background: darken($blue, 7%); color: $white; margin: 0; padding: 0.6em 1em; max-width: 100%; overflow: hidden; text-overflow: ellipsis; } .inner { padding: 1.6em 2em; @media (max-width: 551px) { padding: 1em; } } `}</style> </div> ) Box.propTypes = { children: PropTypes.node, title: PropTypes.string } export default Box
import React from 'react' import PropTypes from 'prop-types' const Box = ({ children }) => ( <div> {children} <style jsx>{` @import 'colors'; div { background-color: $white; box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3); padding: 1.6em 2em; border-radius: 2px; margin-bottom: 20px; @media (max-width: 551px) { padding: 0.6em 1em; } } `}</style> </div> ) Box.propTypes = { children: PropTypes.node } export default Box
Make get_by_id return representation without id, for consistency
#!/usr/bin/python from setuptools import setup with open("README.rst") as readme: long_description = readme.read() setup( name = 'cosmic', version = "0.3.0.alpha3", url = "http://www.cosmic-api.com/docs/cosmic/python/", packages = ['cosmic'], description = 'A high-level web API framework', license = "MIT", author = "8313547 Canada Inc.", author_email = "alexei@boronine.com", long_description = long_description, install_requires = [ "teleport==0.2.1", "Flask==0.10", "Werkzeug==0.9.1", "requests==2.0.0", ], classifiers=[ 'Development Status :: 3 - Alpha', ], )
#!/usr/bin/python from setuptools import setup with open("README.rst") as readme: long_description = readme.read() setup( name = 'cosmic', version = "0.3.0.alpha2", url = "http://www.cosmic-api.com/docs/cosmic/python/", packages = ['cosmic'], description = 'A high-level web API framework', license = "MIT", author = "8313547 Canada Inc.", author_email = "alexei@boronine.com", long_description = long_description, install_requires = [ "teleport==0.2.1", "Flask==0.10", "Werkzeug==0.9.1", "requests==2.0.0", ], classifiers=[ 'Development Status :: 3 - Alpha', ], )
Use SymfonyAdapter for legacy event Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net>
<?php /** * @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net> * * @author Julius Härtl <jus@bitgrid.net> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ OCP\Util::addStyle('deck', 'globalstyles'); OCP\Util::addScript('deck', 'deck-main'); \OCP\Server::get(\OC\EventDispatcher\SymfonyAdapter::class) ->dispatch('\OCP\Collaboration\Resources::loadAdditionalScripts');
<?php /** * @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net> * * @author Julius Härtl <jus@bitgrid.net> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ OCP\Util::addStyle('deck', 'globalstyles'); OCP\Util::addScript('deck', 'deck-main'); \OCP\Server::get(\OCP\EventDispatcher\IEventDispatcher::class) ->dispatch('\OCP\Collaboration\Resources::loadAdditionalScripts');
Test that Badge->toJson() returns JSON
<?php namespace UoMCS\OpenBadges\Backend; class BadgeTest extends DatabaseTestCase { const BADGE_EXISTS_ID = 1; const BADGE_DOES_NOT_EXIST_ID = 99999; public function testBadgeExistsDB() { $badge = Badge::get(self::BADGE_EXISTS_ID); $this->assertInstanceOf('UoMCS\\OpenBadges\\Backend\\Badge', $badge, 'Could not fetch badge'); $this->assertEquals(self::BADGE_EXISTS_ID, $badge->data['id']); } public function testBadgeDoesNotExistDB() { $badge = Badge::get(self::BADGE_DOES_NOT_EXIST_ID); $this->assertNull($badge); } public function testToJson() { $badge = Badge::get(self::BADGE_EXISTS_ID); $data = json_decode($badge->toJson()); $this->assertNotNull($data, 'Badge->toJson() does not return valid JSON'); } public function testBadgesUrl() { $url = WEB_SERVER_BASE_URL . '/badges'; $client = new \Zend\Http\Client(); $client->setUri($url); $response = $client->send(); $this->assertTrue($response->isOk(), 'Accessing /badges did not return 2xx code'); $body = $response->getBody(); $json_body = json_decode($body, true); $this->assertNotNull($json_body, 'Body is not valid JSON'); } }
<?php namespace UoMCS\OpenBadges\Backend; class BadgeTest extends DatabaseTestCase { const BADGE_EXISTS_ID = 1; const BADGE_DOES_NOT_EXIST_ID = 99999; public function testBadgeExistsDB() { $badge = Badge::get(self::BADGE_EXISTS_ID); $this->assertInstanceOf('UoMCS\\OpenBadges\\Backend\\Badge', $badge, 'Could not fetch badge'); $this->assertEquals(self::BADGE_EXISTS_ID, $badge->data['id']); } public function testBadgeDoesNotExistDB() { $badge = Badge::get(self::BADGE_DOES_NOT_EXIST_ID); $this->assertNull($badge); } public function testBadgesUrl() { $url = WEB_SERVER_BASE_URL . '/badges'; $client = new \Zend\Http\Client(); $client->setUri($url); $response = $client->send(); $this->assertTrue($response->isOk(), 'Accessing /badges did not return 2xx code'); $body = $response->getBody(); $json_body = json_decode($body, true); $this->assertNotNull($json_body, 'Body is not valid JSON'); } }
Refactor combat code to be more concise
import places from character import Character import actions import options from multiple_choice import MultipleChoice def main(): """ The goal is to have the main function operate as follows: Set up the initial state Display the initial message Display the initial options Choose an action Get an outcome Display results of the outcomes Outcome changes game state """ character = Character(place=places.tavern) choices = MultipleChoice() options.set_initial_actions(choices) print("\n---The St. George Game---\n") print("You are in a tavern. The local assassins hate you.") while character.alive and character.alone and not character.lose: action = choices.choose_action() if not character.threatened or action.combat_action: outcome = action.get_outcome(character) else: outcome = actions.Attack(character.person).get_outcome(character) outcome.execute() options.add_actions(choices, character, outcome) choices.generate_actions(character) if __name__ == "__main__": main()
import places from character import Character import actions import options from multiple_choice import MultipleChoice def combat(character): """ takes in a character, returns outcome of fight """ return actions.Attack(character.person).get_outcome(character) def main(): """ The goal is to have the main function operate as follows: Set up the initial state Display the initial message Display the initial options Choose an action Get an outcome Display results of the outcomes Outcome changes game state """ character = Character() character.place = places.tavern choices = MultipleChoice() options.set_initial_actions(choices) print("\n---The St. George Game---\n") print("You are in a tavern. The local assassins hate you.") while character.alive and character.alone and not character.lose: action = choices.choose_action() if not character.threatened or action.combat_action: outcome = action.get_outcome(character) else: outcome = combat(character) if not character.alive: break outcome.execute() options.add_actions(choices, character, outcome) choices.generate_actions(character) if __name__ == "__main__": main()
Support for post id/opions page in responsive svg
<?php /** * The default template for displaying content. Used for both single and index/archive/search. * * @subpackage cerulean * @since cerulean 4.0 */ global $responsive_svg; ?> <?php if (!empty(get_field($responsive_svg['img_field'],$responsive_svg['post_id']))){ ?> <?php $path = get_attached_file(get_field($responsive_svg['img_field'],$responsive_svg['post_id']) ); $file = file_get_contents($path); preg_match('/viewBox="[0-9\s]+"/i', $file, $viewbox); $viewbox = explode(' ', $viewbox[0]) ; $ratio = floor($viewbox[3] / $viewbox[2] *10000) /100; //var_dump($ratio); $file = preg_replace('/<svg.+(viewBox="[0-9\s]+").+>/i', '<svg version="1.1" preserveAspectRatio="xMinYMin meet" class="u-svg__content" $1>', $file); ?> <div class="u-svg <?php echo $responsive_svg['class_svg-container'];?>" <?php echo $responsive_svg['attr_svg-container'];?> style="padding-bottom:<?php echo $ratio; ?>%"> <?php echo $file; ?> </div> <?php } ?>
<?php /** * The default template for displaying content. Used for both single and index/archive/search. * * @subpackage cerulean * @since cerulean 4.0 */ global $responsive_svg; ?> <?php if (!empty(get_field_img($responsive_svg['img_field']))){ ?> <?php $path = get_attached_file(get_field($responsive_svg['img_field']) ); $file = file_get_contents($path); preg_match('/viewBox="[0-9\s]+"/i', $file, $viewbox); $viewbox = explode(' ', $viewbox[0]) ; $ratio = floor($viewbox[3] / $viewbox[2] *10000) /100; //var_dump($ratio); $file = preg_replace('/<svg.+(viewBox="[0-9\s]+").+>/i', '<svg version="1.1" preserveAspectRatio="xMinYMin meet" class="u-svg__content" $1>', $file); ?> <div class="u-svg <?php echo $responsive_svg['class_svg-container'];?>" <?php echo $responsive_svg['attr_svg-container'];?> style="padding-bottom:<?php echo $ratio; ?>%"> <?php echo $file; ?> </div> <?php } ?>
Remove view model in presenter
package lib.morkim.mfw.ui; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceFragment; import lib.morkim.mfw.app.AppContext; import lib.morkim.mfw.app.MorkimApp; @SuppressLint("NewApi") public abstract class MPreferenceFragment extends PreferenceFragment implements Viewable { private static final String TAG_CONTROLLER_FRAGMENT = "fragment.controller.fragment.tag"; protected Navigation navigation; protected Controller controller; private Presenter presenter; @Override public void onAttach(Activity activity) { super.onAttach(activity); MorkimApp morkimApp = (MorkimApp) activity.getApplication(); navigation = morkimApp.acquireNavigation(); controller = morkimApp.acquireController(this); presenter = morkimApp.acquirePresenter(this); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } protected abstract Controller createController(); @Override public AppContext getMorkimContext() { return ((Screen) getActivity()).getMorkimContext(); } @Override public void keepScreenOn(boolean keepOn) { ((Screen) getActivity()).keepScreenOn(keepOn); } }
package lib.morkim.mfw.ui; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceFragment; import lib.morkim.mfw.app.MorkimApp; @SuppressLint("NewApi") public abstract class MPreferenceFragment extends PreferenceFragment implements Viewable { private static final String TAG_CONTROLLER_FRAGMENT = "fragment.controller.fragment.tag"; protected Navigation navigation; protected Controller controller; private Presenter presenter; @Override public void onAttach(Activity activity) { super.onAttach(activity); MorkimApp morkimApp = (MorkimApp) activity.getApplication(); navigation = morkimApp.acquireNavigation(); controller = morkimApp.acquireController(this); presenter = morkimApp.acquirePresenter(this); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } protected abstract Controller createController(); }
Allow passing format option to helper function
from collections import namedtuple __all__ = ['identity', 'print_generated_sequence'] def identity(x): """ Helper function which returns its argument unchanged. That is, `identity(x)` returns `x` for any input `x`. """ return x def print_generated_sequence(gen, num, *, sep=", ", fmt='', seed=None): """ Helper function which prints a sequence of `num` items produced by the random generator `gen`. """ if seed: gen.reset(seed) elems = [format(next(gen), fmt) for _ in range(num)] sep_initial = "\n\n" if '\n' in sep else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems))) def make_dummy_tuples(chars='abcde'): Quux = namedtuple('Quux', ['x', 'y']) some_tuples = [Quux((c*2).upper(), c*2) for c in chars] return some_tuples
from collections import namedtuple __all__ = ['identity', 'print_generated_sequence'] def identity(x): """ Helper function which returns its argument unchanged. That is, `identity(x)` returns `x` for any input `x`. """ return x def print_generated_sequence(gen, num, *, sep=", ", seed=None): """ Helper function which prints a sequence of `num` items produced by the random generator `gen`. """ if seed: gen.reset(seed) elems = [str(next(gen)) for _ in range(num)] sep_initial = "\n\n" if '\n' in sep else " " print("Generated sequence:{}{}".format(sep_initial, sep.join(elems))) def make_dummy_tuples(chars='abcde'): Quux = namedtuple('Quux', ['x', 'y']) some_tuples = [Quux((c*2).upper(), c*2) for c in chars] return some_tuples
Fix getDefaultRange, wrong order of parameters
package pokefenn.totemic.apiimpl.totem; import pokefenn.totemic.api.totem.TotemEffect; import pokefenn.totemic.api.totem.TotemEffectAPI; import pokefenn.totemic.api.totem.TotemEffectContext; public enum TotemEffectApiImpl implements TotemEffectAPI { INSTANCE; @Override public int getDefaultRange(TotemEffect effect, int repetition, TotemEffectContext context) { return getDefaultRange(effect, repetition, DEFAULT_BASE_RANGE, context); } @Override public int getDefaultRange(TotemEffect effect, int repetition, int baseRange, TotemEffectContext context) { return baseRange + context.getTotemEffectMusic() / 32 + (context.getPoleSize() >= TotemEffectAPI.MAX_POLE_SIZE ? 1 : 0); } }
package pokefenn.totemic.apiimpl.totem; import pokefenn.totemic.api.totem.TotemEffect; import pokefenn.totemic.api.totem.TotemEffectAPI; import pokefenn.totemic.api.totem.TotemEffectContext; public enum TotemEffectApiImpl implements TotemEffectAPI { INSTANCE; @Override public int getDefaultRange(TotemEffect effect, int repetition, TotemEffectContext context) { return getDefaultRange(effect, DEFAULT_BASE_RANGE, repetition, context); } @Override public int getDefaultRange(TotemEffect effect, int repetition, int baseRange, TotemEffectContext context) { return baseRange + context.getTotemEffectMusic() / 32 + (context.getPoleSize() >= TotemEffectAPI.MAX_POLE_SIZE ? 1 : 0); } }
Use history push instead of replace
import React, { Component, PropTypes } from "react" import styles from "./index.css" import { Treebeard } from "react-treebeard" import treeStyle from "./treeStyle" import decorators from "./decorators" // import Link from "./LinkWithActiveClass" import data from "../../content/toc.json" import { browserHistory } from "phenomic/lib/client" const cx = require("classnames/bind").bind(styles) export default class Menu extends Component { static propTypes = { visible: PropTypes.bool.isRequired, }; constructor(props) { super(props) this.state = {} } handleOnToggle = (node, toggled) => { if (this.state.cursor) { // eslint-disable-next-line this.state.cursor.active = false } node.active = true console.log(node) if (node.children) { node.toggled = toggled } this.setState({ cursor: node }) if (node.path) { browserHistory.push(node.path) } } render() { const wrapperClass = cx("menu", "toc-menu", { menuVisible: this.props.visible, }) return ( <div className={ wrapperClass }> <Treebeard style={ treeStyle } data={ data } decorators={ decorators } onToggle={ this.handleOnToggle } /> </div> ) } }
import React, { Component, PropTypes } from "react" import styles from "./index.css" import { Treebeard } from "react-treebeard" import treeStyle from "./treeStyle" import decorators from "./decorators" // import Link from "./LinkWithActiveClass" import data from "../../content/toc.json" import { browserHistory } from "phenomic/lib/client" const cx = require("classnames/bind").bind(styles) export default class Menu extends Component { static propTypes = { visible: PropTypes.bool.isRequired, }; constructor(props) { super(props) this.state = {} } handleOnToggle = (node, toggled) => { if (this.state.cursor) { // eslint-disable-next-line this.state.cursor.active = false } node.active = true console.log(node) if (node.children) { node.toggled = toggled } this.setState({ cursor: node }) if (node.path) { browserHistory.replace(node.path) } } render() { const wrapperClass = cx("menu", "toc-menu", { menuVisible: this.props.visible, }) return ( <div className={ wrapperClass }> <Treebeard style={ treeStyle } data={ data } decorators={ decorators } onToggle={ this.handleOnToggle } /> </div> ) } }
Change log level to lowercase
'use strict'; var winston = require('winston'); var expressWinston = require('express-winston'); var requestLogger = expressWinston.logger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ], meta: true, msg: 'HTTP {{req.method}} {{req.url}}', expressFormat: true, colorStatus: true }); var errorLogger = expressWinston.errorLogger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ] }); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ timestamp: function() { return Date.now(); }, formatter: function(options) { // Return string will be passed to logger. return options.timestamp() +' '+ options.level.toLowerCase() + ': '+ (undefined !== options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' ); } }) ] }); module.exports = { request: requestLogger, error: errorLogger, logger: logger };
'use strict'; var winston = require('winston'); var expressWinston = require('express-winston'); var requestLogger = expressWinston.logger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ], meta: true, msg: 'HTTP {{req.method}} {{req.url}}', expressFormat: true, colorStatus: true }); var errorLogger = expressWinston.errorLogger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ] }); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ timestamp: function() { return Date.now(); }, formatter: function(options) { // Return string will be passed to logger. return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' ); } }) ] }); module.exports = { request: requestLogger, error: errorLogger, logger: logger };
Use random port in PID file test
package run_test import ( "io/ioutil" "os" "path/filepath" "testing" "time" "github.com/influxdata/influxdb/cmd/influxd/run" ) func TestCommand_PIDFile(t *testing.T) { tmpdir, err := ioutil.TempDir(os.TempDir(), "influxd-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) pidFile := filepath.Join(tmpdir, "influxdb.pid") cmd := run.NewCommand() cmd.Getenv = func(key string) string { switch key { case "INFLUXDB_BIND_ADDRESS", "INFLUXDB_HTTP_BIND_ADDRESS": return "127.0.0.1:0" default: return os.Getenv(key) } } if err := cmd.Run("-pidfile", pidFile); err != nil { t.Fatalf("unexpected error: %s", err) } if _, err := os.Stat(pidFile); err != nil { t.Fatalf("could not stat pid file: %s", err) } go cmd.Close() timeout := time.NewTimer(100 * time.Millisecond) select { case <-timeout.C: t.Fatal("unexpected timeout") case <-cmd.Closed: timeout.Stop() } if _, err := os.Stat(pidFile); err == nil { t.Fatal("expected pid file to be removed") } }
package run_test import ( "io/ioutil" "os" "path/filepath" "testing" "time" "github.com/influxdata/influxdb/cmd/influxd/run" ) func TestCommand_PIDFile(t *testing.T) { tmpdir, err := ioutil.TempDir(os.TempDir(), "influxd-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) pidFile := filepath.Join(tmpdir, "influxdb.pid") cmd := run.NewCommand() if err := cmd.Run("-pidfile", pidFile); err != nil { t.Fatalf("unexpected error: %s", err) } if _, err := os.Stat(pidFile); err != nil { t.Fatalf("could not stat pid file: %s", err) } go cmd.Close() timeout := time.NewTimer(100 * time.Millisecond) select { case <-timeout.C: t.Fatal("unexpected timeout") case <-cmd.Closed: timeout.Stop() } if _, err := os.Stat(pidFile); err == nil { t.Fatal("expected pid file to be removed") } }
Fix 'Template is not iterable' error
#From http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template from django.template import Context from django.template.loader_tags import BlockNode, ExtendsNode class BlockNotFound(Exception): pass def _get_node(template, context=Context(), name='subject', block_lookups={}): for node in template.template: if isinstance(node, BlockNode) and node.name == name: #Rudimentary handling of extended templates, for issue #3 for i in xrange(len(node.nodelist)): n = node.nodelist[i] if isinstance(n, BlockNode) and n.name in block_lookups: node.nodelist[i] = block_lookups[n.name] return node.render(context) elif isinstance(node, ExtendsNode): lookups = dict([(n.name, n) for n in node.nodelist if isinstance(n, BlockNode)]) lookups.update(block_lookups) return _get_node(node.get_parent(context), context, name, lookups) raise BlockNotFound("Node '%s' could not be found in template." % name)
#From http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template from django.template import Context from django.template.loader_tags import BlockNode, ExtendsNode class BlockNotFound(Exception): pass def _get_node(template, context=Context(), name='subject', block_lookups={}): for node in template: if isinstance(node, BlockNode) and node.name == name: #Rudimentary handling of extended templates, for issue #3 for i in xrange(len(node.nodelist)): n = node.nodelist[i] if isinstance(n, BlockNode) and n.name in block_lookups: node.nodelist[i] = block_lookups[n.name] return node.render(context) elif isinstance(node, ExtendsNode): lookups = dict([(n.name, n) for n in node.nodelist if isinstance(n, BlockNode)]) lookups.update(block_lookups) return _get_node(node.get_parent(context), context, name, lookups) raise BlockNotFound("Node '%s' could not be found in template." % name)
Replace magic numbers with constants
package com.alexstyl.specialdates.events; import com.alexstyl.specialdates.date.DateDisplayStringCreator; import com.alexstyl.specialdates.date.Date; import org.junit.BeforeClass; import org.junit.Test; import static com.alexstyl.specialdates.date.DateConstants.MAY; import static org.fest.assertions.api.Assertions.assertThat; public class DateDisplayStringCreatorTest { private static DateDisplayStringCreator creator; @BeforeClass public static void init() { creator = DateDisplayStringCreator.INSTANCE; } @Test public void givenDateWithYear_thenReturningStringIsCorrect() { Date date = Date.on(5, MAY, 1995); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo("1995-05-05"); } @Test public void givenDateWithNoYear_thenReturningStringIsCorrect() { Date date = Date.on(5, MAY); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo("--05-05"); } }
package com.alexstyl.specialdates.events; import com.alexstyl.specialdates.date.DateDisplayStringCreator; import com.alexstyl.specialdates.date.Date; import org.junit.BeforeClass; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; public class DateDisplayStringCreatorTest { private static final String EXPECTED_STRING = "1995-05-05"; private static final String EXPECTED_STRING_NO_YEAR = "--05-05"; private static DateDisplayStringCreator creator; @BeforeClass public static void init() { creator = DateDisplayStringCreator.INSTANCE; } @Test public void givenDateWithYear_thenReturningStringIsCorrect() { Date date = Date.on(5, 5, 1995); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo(EXPECTED_STRING); } @Test public void givenDateWithNoYear_thenReturningStringIsCorrect() { Date date = Date.on(5, 5); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo(EXPECTED_STRING_NO_YEAR); } }
Remove rank to default set. deoplete will set 100 Signed-off-by: Koichi Shiraishi <2e5bdfebde234ed3509bcfc18121c70b6631e207@gmail.com>
import deoplete.util from .base import Base class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'go' self.mark = '[go]' self.filetypes = ['go'] self.min_pattern_length = 0 self.is_bytepos = True def get_complete_api(self, findstart): complete_api = self.vim.vars['deoplete#sources#go'] if complete_api == 'gocode': return self.vim.call('gocomplete#Complete', findstart, 0) elif complete_api == 'vim-go': return self.vim.call('go#complete#Complete', findstart, 0) else: return deoplete.util.error(self.vim, "g:deoplete#sources#go must be 'gocode' or 'vim-go'") def get_complete_position(self, context): return self.get_complete_api(1) def gather_candidates(self, context): return self.get_complete_api(0)
import deoplete.util from .base import Base class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'go' self.mark = '[go]' self.filetypes = ['go'] self.rank = 100 self.min_pattern_length = 0 self.is_bytepos = True def get_complete_api(self, findstart): complete_api = self.vim.vars['deoplete#sources#go'] if complete_api == 'gocode': return self.vim.call('gocomplete#Complete', findstart, 0) elif complete_api == 'vim-go': return self.vim.call('go#complete#Complete', findstart, 0) else: return deoplete.util.error(self.vim, "g:deoplete#sources#go must be 'gocode' or 'vim-go'") def get_complete_position(self, context): return self.get_complete_api(1) def gather_candidates(self, context): return self.get_complete_api(0)
Remove kapruka link from online donation list
@extends('layouts.master') @section('content') <div class="container main-container"> <div class="online-donations"> <div class="col-md-12"> <div class="col-md-12"> <ul class="list-group"> <li class="list-group-item" style="padding: 2%; font-size: 40px"><a href="http://takas.lk/tag/product/list/tagId/196" target="_blank">takas.lk</a></li> <li class="list-group-item" style="padding: 2%; font-size: 40px"><a href="http://imcds.org/about-us" target="_blank">ICMD</a></li> </ul> <div> <div> </div> </div><!-- /.container --> @endsection
@extends('layouts.master') @section('content') <div class="container main-container"> <div class="online-donations"> <div class="col-md-12"> <div class="col-md-12"> <ul class="list-group"> <li class="list-group-item" style="padding: 2%; font-size: 40px"><a href="http://takas.lk/tag/product/list/tagId/196" target="_blank">takas.lk</a></li> <li class="list-group-item" style="padding: 2%; font-size: 40px"><a href="http://imcds.org/about-us" target="_blank">ICMD</a></li> <li class="list-group-item" style="padding: 2%;font-size: 40px"><a href="http://www.kapruka.com/contactUs/donate.jsp" target="_blank">kapruka.com</a></li> </ul> <div> <div> </div> </div><!-- /.container --> @endsection
Change the is_producttype template tag to return a boolean rather than a string. --HG-- extra : convert_revision : svn%3Aa38d40e9-c014-0410-b785-c606c0c8e7de/satchmo/trunk%401200
from django import template from django.conf import settings from django.core import urlresolvers from django.template import Context, Template from django.utils.translation import get_language, ugettext_lazy as _ from satchmo.configuration import config_value from satchmo.product.models import Category from satchmo.shop.templatetags import get_filter_args register = template.Library() def is_producttype(product, ptype): """Returns True if product is ptype""" if ptype in product.get_subtypes(): return True else: return False register.filter('is_producttype', is_producttype) def product_images(product, args=""): args, kwargs = get_filter_args(args, keywords=('include_main', 'maximum'), boolargs=('include_main'), intargs=('maximum'), stripquotes=True) q = product.productimage_set if kwargs.get('include_main', True): q = q.all() else: main = product.main_image q = q.exclude(id = main.id) maximum = kwargs.get('maximum', -1) if maximum>-1: q = list(q)[:maximum] return q register.filter('product_images', product_images) def smart_attr(product, key): """Run the smart_attr function on the spec'd product """ return product.smart_attr(key) register.filter('smart_attr', smart_attr)
from django import template from django.conf import settings from django.core import urlresolvers from django.template import Context, Template from django.utils.translation import get_language, ugettext_lazy as _ from satchmo.configuration import config_value from satchmo.product.models import Category from satchmo.shop.templatetags import get_filter_args register = template.Library() def is_producttype(product, ptype): """Returns True if product is ptype""" if ptype in product.get_subtypes(): return "true" else: return "" register.filter('is_producttype', is_producttype) def product_images(product, args=""): args, kwargs = get_filter_args(args, keywords=('include_main', 'maximum'), boolargs=('include_main'), intargs=('maximum'), stripquotes=True) q = product.productimage_set if kwargs.get('include_main', True): q = q.all() else: main = product.main_image q = q.exclude(id = main.id) maximum = kwargs.get('maximum', -1) if maximum>-1: q = list(q)[:maximum] return q register.filter('product_images', product_images) def smart_attr(product, key): """Run the smart_attr function on the spec'd product """ return product.smart_attr(key) register.filter('smart_attr', smart_attr)
Fix wrong description of rebuild-index command in help text
package main import ( "restic/repository" "github.com/spf13/cobra" ) var cmdRebuildIndex = &cobra.Command{ Use: "rebuild-index [flags]", Short: "build a new index file", Long: ` The "rebuild-index" command creates a new index based on the pack files in the repository. `, RunE: func(cmd *cobra.Command, args []string) error { return runRebuildIndex(globalOptions) }, } func init() { cmdRoot.AddCommand(cmdRebuildIndex) } func runRebuildIndex(gopts GlobalOptions) error { repo, err := OpenRepository(gopts) if err != nil { return err } lock, err := lockRepoExclusive(repo) defer unlockRepo(lock) if err != nil { return err } return repository.RebuildIndex(repo) }
package main import ( "restic/repository" "github.com/spf13/cobra" ) var cmdRebuildIndex = &cobra.Command{ Use: "rebuild-index [flags]", Short: "build a new index file", Long: ` The "rebuild-index" command creates a new index by combining the index files into a new one. `, RunE: func(cmd *cobra.Command, args []string) error { return runRebuildIndex(globalOptions) }, } func init() { cmdRoot.AddCommand(cmdRebuildIndex) } func runRebuildIndex(gopts GlobalOptions) error { repo, err := OpenRepository(gopts) if err != nil { return err } lock, err := lockRepoExclusive(repo) defer unlockRepo(lock) if err != nil { return err } return repository.RebuildIndex(repo) }
Return errors as json, instead of throwing an error about view engines.
'use strict'; var express = require('express'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routeBuilder = require('./routes'); var app = express(); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use('/', routeBuilder(require('./routes/home'))); app.use('/users', routeBuilder(require('./routes/users'))); // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.json({ message: err.message, error: err }); next = next; }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.json({ message: err.message, error: {} }); next = next; }); module.exports = app;
'use strict'; var express = require('express'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routeBuilder = require('./routes'); var app = express(); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use('/', routeBuilder(require('./routes/home'))); app.use('/users', routeBuilder(require('./routes/users'))); // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); next = next; }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); next = next; }); module.exports = app;
[Form] Remove "value" attribute on empty_value option Today we faced a very strange issue with the newest Blackberry 10 browser, it was not submitting our forms. Finally we found that in a ```select``` element, if you have a disabled option, it can't have a value or the HTML5 validator will crash and not submit the form. Of course, setting the ```novalidate``` option for the whole form also solved the issue. Although I know this must be an issue with the WebKit version the BB10 has it can easily be solved in symfony with this change. In fact, it does make sense since we already have a disabled option with no value if the ```preferred_choices``` are not empty and a ```separator``` is set
<select <?php echo $view['form']->block($form, 'widget_attributes') ?> <?php if ($multiple): ?> multiple="multiple"<?php endif ?> > <?php if (null !== $empty_value): ?><option <?php if ($required):?> disabled="disabled"<?php if (empty($value) && "0" !== $value): ?> selected="selected"<?php endif ?><?php else: ?> value=""<?php endif?>><?php echo $view->escape($view['translator']->trans($empty_value, array(), $translation_domain)) ?></option><?php endif; ?> <?php if (count($preferred_choices) > 0): ?> <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $preferred_choices)) ?> <?php if (count($choices) > 0 && null !== $separator): ?> <option disabled="disabled"><?php echo $separator ?></option> <?php endif ?> <?php endif ?> <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $choices)) ?> </select>
<select <?php echo $view['form']->block($form, 'widget_attributes') ?> <?php if ($multiple): ?> multiple="multiple"<?php endif ?> > <?php if (null !== $empty_value): ?><option value=""<?php if ($required):?> disabled="disabled"<?php if (empty($value) && "0" !== $value): ?> selected="selected"<?php endif ?><?php endif?>><?php echo $view->escape($view['translator']->trans($empty_value, array(), $translation_domain)) ?></option><?php endif; ?> <?php if (count($preferred_choices) > 0): ?> <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $preferred_choices)) ?> <?php if (count($choices) > 0 && null !== $separator): ?> <option disabled="disabled"><?php echo $separator ?></option> <?php endif ?> <?php endif ?> <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $choices)) ?> </select>
Fix executor builds on Windows
package executor import ( "os/exec" "time" cstructs "github.com/hashicorp/nomad/client/driver/structs" "golang.org/x/sys/windows" ) func (e *UniversalExecutor) LaunchSyslogServer(ctx *ExecutorContext) (*SyslogServerState, error) { return nil, nil } func (e *UniversalExecutor) wait() { defer close(e.processExited) err := e.cmd.Wait() ic := &cstructs.IsolationConfig{Cgroup: e.groups, CgroupPaths: e.cgPaths} if err == nil { e.exitState = &ProcessState{Pid: 0, ExitCode: 0, IsolationConfig: ic, Time: time.Now()} return } exitCode := 1 var signal int if exitErr, ok := err.(*exec.ExitError); ok { if status, ok := exitErr.Sys().(windows.WaitStatus); ok { exitCode = status.ExitStatus() if status.Signaled() { signal = int(status.Signal()) exitCode = 128 + signal } } } else { e.logger.Printf("[DEBUG] executor: unexpected Wait() error type: %v", err) } e.exitState = &ProcessState{Pid: 0, ExitCode: exitCode, Signal: signal, IsolationConfig: ic, Time: time.Now()} }
package executor import ( "os/exec" "time" "golang.org/x/sys/windows" ) func (e *UniversalExecutor) LaunchSyslogServer(ctx *ExecutorContext) (*SyslogServerState, error) { return nil, nil } func (e *UniversalExecutor) wait() { defer close(e.processExited) err := e.cmd.Wait() ic := &cstructs.IsolationConfig{Cgroup: e.groups, CgroupPaths: e.cgPaths} if err == nil { e.exitState = &ProcessState{Pid: 0, ExitCode: 0, IsolationConfig: ic, Time: time.Now()} return } exitCode := 1 var signal int if exitErr, ok := err.(*exec.ExitError); ok { if status, ok := exitErr.Sys().(windows.WaitStatus); ok { exitCode = status.ExitStatus() if status.Signaled() { signal = int(status.Signal()) exitCode = 128 + signal } } } else { e.logger.Printf("[DEBUG] executor: unexpected Wait() error type: %v", err) } e.exitState = &ProcessState{Pid: 0, ExitCode: exitCode, Signal: signal, IsolationConfig: ic, Time: time.Now()} }
Fix up the change to the singleton some more
"use strict"; const MongoClient = require("mongodb").MongoClient; const config = require("./config"); let singletonPromise = null; let singleton = null; function connect() { if (singletonPromise) { return singletonPromise; } else { singletonPromise = new Promise(function(resolve, reject) { const mongoURL = config.mongolab.uri; MongoClient.connect(mongoURL, function(err, db) { if (err) { reject(err); } else { singleton = db; resolve(db); } }); }); return singletonPromise; } } function disconnect() { if (singleton) { singleton.close(); singletonPromise = null; singletonPromise = null; } } module.exports = { connect, disconnect };
"use strict"; const MongoClient = require("mongodb").MongoClient; const config = require("./config"); let singleton = null; function connect() { if (singleton) { return singleton; } else { singleton = new Promise(function(resolve, reject) { const mongoURL = config.mongolab.uri; MongoClient.connect(mongoURL, function(err, db) { if (err) { reject(err); } else { resolve(db); } }); }); return singleton; } } function disconnect() { if (singleton) { singleton.close(); singleton = null; } } module.exports = { connect, disconnect };
Change the ray - plane intersection function
public class Plane extends Shape { public Vector Normal ; public Point3D P ; float t ; private float EPS = 0.00001f ; public Plane(){} ; public Plane ( Vector Normal , Point3D P , Material material ) { this.Normal = Normal ; this.P = P ; this.material = material ; }; @Override public boolean Intersect(Ray ray) { Vector v = new Vector ( ray.getPos() , this.P ) ; ray.normalize(); //v.norm() ; this.Normal.normalize(); float den = ray.getDir().dot(this.Normal) ; // Check if crossing the plane if ( den < EPS ) { this.t = v.dot(this.Normal ) / den ; return ( this.t >= 0 ) ; } return false ; }; @Override public Vector getNormal(Point3D p) { return this.Normal ; }; @Override public float getInter() { return this.t ; }; @Override public Material getMaterial() { return this.material; }; }
public class Plane extends Shape { public Vector Normal ; public Point3D P ; float t ; private float EPS = 0.00001f ; public Plane(){} ; public Plane ( Vector Normal , Point3D P , Material material ) { this.Normal = Normal ; this.P = P ; this.material = material ; }; @Override public boolean Intersect(Ray ray) { ray.normalize(); Vector v = new Vector ( this.P , ray.getPos() ) ; // Check if parallel if ( ray.getDir().dot(Normal) < EPS ) return false ; t = v.dot( Normal ) / ray.getDir().dot( Normal ) ; return true ; /* Vector v = new Vector ( this.P , ray.getPos() ) ; t = v.dot( Normal ) / ray.getDir().dot( Normal ) ; //System.out.println( t ); return ( ray.getDir().dot(this.Normal) < EPS ) ; */ }; @Override public Vector getNormal(Point3D p) { return this.Normal ; }; @Override public float getInter() { return this.t ; }; @Override public Material getMaterial() { return this.material; }; }
Upgrade libchromiumcontent to fix chromiumviews.
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '9006e277b20109de165d4a17827c9b2029bf3831' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
Allow module value in config to be optional.
/** * Basic engine support. */ require('../lib/setModuleDefaults'); var config = require('config'); var engineConfig = config.engines || {}; /** * Return a function that creates a plugin: */ module.exports = function(language){ return { attach: function (/* options */){ var languageConfig = engineConfig[language] || {}; /** * If there is a specified engine for this language then use it, * otherwise just use the provided name: */ this.engine = require(languageConfig.module || language); /** * Add key methods: */ this.__express = this.engine.__express || undefined; this.renderFile = this.engine.renderFile || undefined; } , name: 'adapter-' + language }; };
/** * Basic engine support. */ require('../lib/setModuleDefaults'); var config = require('config'); var engineConfig = config.engines ? config.engines : undefined; /** * Return a function that creates a plugin: */ module.exports = function(language){ return { attach: function (/* options */){ /** * If there is a specified engine for this language then use it, * otherwise just use the provided name: */ var module = (engineConfig && engineConfig[language]) ? engineConfig[language].module : language; this.engine = require(module); /** * Add key methods: */ this.__express = this.engine.__express || undefined; this.renderFile = this.engine.renderFile || undefined; } , name: 'adapter-' + language }; };
Reduce the size of the jamendo album cover images requested since we don't use them for anything larger than 160x160 at the moment
<?php function resolve_external_url($url) { if (substr($url, 0, 10) == "jamendo://") { return process_jamendo_url($url); } return $url; } function process_jamendo_url($url) { if (substr($url, 10, 13) == "track/stream/") { $id = substr($url, 23); return "http://api.jamendo.com/get2/stream/track/redirect/?id=" . $id . "&streamencoding=ogg2"; } if (substr($url, 10, 15) == "album/download/") { $id = substr($url, 25); return "http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=" . $id . "&type=archive&class=ogg3"; } if (substr($url, 10, 10) == "album/art/") { $id = substr($url, 20); return "http://api.jamendo.com/get2/image/album/redirect/?id=" . $id . "&imagesize=200"; } // We don't know what this is return $url; } ?>
<?php function resolve_external_url($url) { if (substr($url, 0, 10) == "jamendo://") { return process_jamendo_url($url); } return $url; } function process_jamendo_url($url) { if (substr($url, 10, 13) == "track/stream/") { $id = substr($url, 23); return "http://api.jamendo.com/get2/stream/track/redirect/?id=" . $id . "&streamencoding=ogg2"; } if (substr($url, 10, 15) == "album/download/") { $id = substr($url, 25); return "http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=" . $id . "&type=archive&class=ogg3"; } if (substr($url, 10, 10) == "album/art/") { $id = substr($url, 20); return "http://api.jamendo.com/get2/image/album/redirect/?id=" . $id . "&imagesize=400"; } // We don't know what this is return $url; } ?>
Fix youtube search input handlers binding
/** * * YoutubeSearchInput * */ import React, { Component, PropTypes } from 'react'; import classNames from 'classnames'; class YoutubeSearchInput extends Component { handleChange = e => this.props.onChange(e.target.value); handleEnter = e => { if (e.key === 'Enter') { const { value, onSearch } = this.props; if (value) { onSearch(value); } } }; render() { const { isSearching, value } = this.props; const cn = classNames('ui fluid left icon input', { loading: isSearching }); return ( <div className={cn}> <input type="text" value={value} onKeyPress={this.handleEnter} onChange={this.handleChange} placeholder="Press enter to search..." /> <i className="search icon"></i> </div> ); } } YoutubeSearchInput.propTypes = { isSearching: PropTypes.bool.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, onSearch: PropTypes.func.isRequired, }; export default YoutubeSearchInput;
/** * * YoutubeSearchInput * */ import React, { Component, PropTypes } from 'react'; import classNames from 'classnames'; class YoutubeSearchInput extends Component { handleChange(e) { this.props.onChange(e.target.value); } handleEnter(e) { if (e.key === 'Enter') { const { value, onSearch } = this.props; if (value) { onSearch(value); } } } render() { const { isSearching, value } = this.props; const cn = classNames('ui fluid left icon input', { loading: isSearching }); return ( <div className={cn}> <input type="text" value={value} onKeyPress={this.handleEnter} onChange={this.handleChange} placeholder="Press enter to search..." /> <i className="search icon"></i> </div> ); } } YoutubeSearchInput.propTypes = { isSearching: PropTypes.bool.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, onSearch: PropTypes.func.isRequired, }; export default YoutubeSearchInput;
Fix for matrixmultiply != dot on Numeric < 23.4 git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@857 94b884b6-d6fd-0310-90d3-974f1d3f35e1
from info_scipy_base import __doc__ from scipy_base_version import scipy_base_version as __version__ from ppimport import ppimport, ppimport_attr # The following statement is equivalent to # # from Matrix import Matrix as mat # # but avoids expensive LinearAlgebra import when # Matrix is not used. mat = ppimport_attr(ppimport('Matrix'), 'Matrix') # Force Numeric to use scipy_base.fastumath instead of Numeric.umath. import fastumath # no need to use scipy_base.fastumath import sys as _sys _sys.modules['umath'] = fastumath import Numeric from Numeric import * import limits from type_check import * from index_tricks import * from function_base import * from shape_base import * from matrix_base import * from polynomial import * from scimath import * from machar import * from pexec import * if Numeric.__version__ < '23.5': matrixmultiply=dot Inf = inf = fastumath.PINF try: NAN = NaN = nan = fastumath.NAN except AttributeError: NaN = NAN = nan = fastumath.PINF/fastumath.PINF from scipy_test.testing import ScipyTest test = ScipyTest('scipy_base').test if _sys.modules.has_key('scipy_base.Matrix') \ and _sys.modules['scipy_base.Matrix'] is None: del _sys.modules['scipy_base.Matrix']
from info_scipy_base import __doc__ from scipy_base_version import scipy_base_version as __version__ from ppimport import ppimport, ppimport_attr # The following statement is equivalent to # # from Matrix import Matrix as mat # # but avoids expensive LinearAlgebra import when # Matrix is not used. mat = ppimport_attr(ppimport('Matrix'), 'Matrix') # Force Numeric to use scipy_base.fastumath instead of Numeric.umath. import fastumath # no need to use scipy_base.fastumath import sys as _sys _sys.modules['umath'] = fastumath import Numeric from Numeric import * import limits from type_check import * from index_tricks import * from function_base import * from shape_base import * from matrix_base import * from polynomial import * from scimath import * from machar import * from pexec import * Inf = inf = fastumath.PINF try: NAN = NaN = nan = fastumath.NAN except AttributeError: NaN = NAN = nan = fastumath.PINF/fastumath.PINF from scipy_test.testing import ScipyTest test = ScipyTest('scipy_base').test if _sys.modules.has_key('scipy_base.Matrix') \ and _sys.modules['scipy_base.Matrix'] is None: del _sys.modules['scipy_base.Matrix']
Add a little arrow to selected item in toctree
// We don't want the sidebar to include list of examples, that's just // much. This simple script tries to select those items and hide them. // "aside" selects sidebar elements, and "href" narrows it down to the // list of examples. This is a workaround, not a permanent fix. // The next lines work with furo theme // var examples = $('aside a[href*="examples.html"]') // var examples_clicked = $( ":contains('Examples')" ).filter($( ".current.reference.internal" )) // examples.nextAll().hide() // examples_clicked.nextAll().hide() // The next lines work with pydata theme if (location.protocol.startsWith("http") & location.protocol !== 'https:') { location.replace(`https:${location.href.substring(location.protocol.length)}`); } window.onload = function () { var examples_clicked = $( ".active a:contains(Examples)" ) if (examples_clicked.length == 1) { $(" nav.bd-links ").children().hide() } var selected = $("a.current") selected.html("&#8594; " + selected.text()) }; // window.onload = function() { // if (window.jQuery) { // // jQuery is loaded // alert("Yeah!"); // } else { // // jQuery is not loaded // alert("Doesn't Work"); // } // }
// We don't want the sidebar to include list of examples, that's just // much. This simple script tries to select those items and hide them. // "aside" selects sidebar elements, and "href" narrows it down to the // list of examples. This is a workaround, not a permanent fix. // The next lines work with furo theme // var examples = $('aside a[href*="examples.html"]') // var examples_clicked = $( ":contains('Examples')" ).filter($( ".current.reference.internal" )) // examples.nextAll().hide() // examples_clicked.nextAll().hide() // The next lines work with pydata theme if (location.protocol.startsWith("http") & location.protocol !== 'https:') { location.replace(`https:${location.href.substring(location.protocol.length)}`); } window.onload = function () { var examples_clicked = $( ".active a:contains(Examples)" ) if (examples_clicked.length == 1) { $(" nav.bd-links ").children().hide() } }; // window.onload = function() { // if (window.jQuery) { // // jQuery is loaded // alert("Yeah!"); // } else { // // jQuery is not loaded // alert("Doesn't Work"); // } // }
Remove duplicate mongoldb env setting
var all = { // define openshift runtime environment server: { port : process.env.OPENSHIFT_NODEJS_PORT || 8080, host : process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1' }, // Should we populate the DB with sample data? seedDB: false }; // default to a 'localhost' configuration: all.mongodb = { uri: 'mongodb://localhost/devnews-dev' }; // if OPENSHIFT env variables are present, use the available connection info: if (process.env.MONGOLAB_URI) { all.mongodb.uri = process.env.MONGOLAB_URI; } else if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) { all.mongodb.uri = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' + process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' + process.env.OPENSHIFT_MONGODB_DB_HOST + ':' + process.env.OPENSHIFT_MONGODB_DB_PORT + '/' + process.env.OPENSHIFT_APP_NAME; } module.exports = all;
var all = { // define openshift runtime environment server: { port : process.env.OPENSHIFT_NODEJS_PORT || 8080, host : process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1' }, // define mongodb runtime environment mongodb: { uri : process.env.MONGOLAB_URI || process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/devnews-dev' }, // Should we populate the DB with sample data? seedDB: false }; // default to a 'localhost' configuration: all.mongodb = { uri: 'mongodb://localhost/devnews-dev' }; // if OPENSHIFT env variables are present, use the available connection info: if (process.env.MONGOLAB_URI) { all.mongodb.uri = process.env.MONGOLAB_URI; } else if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) { all.mongodb.uri = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' + process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' + process.env.OPENSHIFT_MONGODB_DB_HOST + ':' + process.env.OPENSHIFT_MONGODB_DB_PORT + '/' + process.env.OPENSHIFT_APP_NAME; } module.exports = all;
Append menu to root menu if extensions is not available. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Story; use Orchestra\Contracts\Auth\Guard; use Orchestra\Contracts\Foundation\Foundation; class StoryMenuHandler { /** * ACL instance. * * @var \Orchestra\Contracts\Auth\Guard */ protected $auth; /** * Menu instance. * * @var \Orchestra\Widget\Handlers\Menu */ protected $menu; /** * Construct a new handler. * * @param \Orchestra\Contracts\Foundation\Foundation $foundation * @param \Orchestra\Contracts\Auth\Guard $auth */ public function __construct(Foundation $foundation, Guard $auth) { $this->menu = $foundation->menu(); $this->auth = $auth; } /** * Create a handler for `orchestra.ready: admin` event. * * @return void */ public function handle() { if ($this->auth->guest()) { return ; } $parent = $this->menu->has('extensions') ? '^:extensions' : '<:home'; $this->menu->add('storycms', $parent) ->title('Story CMS') ->link(handles('orchestra::storycms')); } }
<?php namespace Orchestra\Story; use Orchestra\Contracts\Auth\Guard; use Orchestra\Contracts\Foundation\Foundation; class StoryMenuHandler { /** * ACL instance. * * @var \Orchestra\Contracts\Auth\Guard */ protected $auth; /** * Menu instance. * * @var \Orchestra\Widget\Handlers\Menu */ protected $menu; /** * Construct a new handler. * * @param \Orchestra\Contracts\Foundation\Foundation $foundation * @param \Orchestra\Contracts\Auth\Guard $auth */ public function __construct(Foundation $foundation, Guard $auth) { $this->menu = $foundation->menu(); $this->auth = $auth; } /** * Create a handler for `orchestra.ready: admin` event. * * @return void */ public function handle() { if ($this->auth->guest()) { return ; } $this->menu->add('storycms', '^:extensions') ->title('Story CMS') ->link(handles('orchestra::storycms')); } }
Use players instead of todos
/* @flow */ // The types of actions that you can dispatch to modify the state of the store export const types = { ADD: 'ADD', REMOVE: 'REMOVE', } // Helper functions to dispatch actions, optionally with payloads export const actionCreators = { add: (item: string) => { return {type: types.ADD, payload: item} }, remove: (index: number) => { return {type: types.REMOVE, payload: index} } } // Initial state of the store const initialState = { players: ['Hannah', 'Markus', 'Tobi', 'Lo', 'Moritz'], } // Function to handle actions and update the state of the store. // Notes: // - The reducer must return a new state object. It must never modify // the state object. State objects should be treated as immutable. // - We set \`state\` to our \`initialState\` by default. Redux will // call reducer() with no state on startup, and we are expected to // return the initial state of the app in this case. export const reducer = (state: typeof initialState = initialState, action: {type: string, payload: any}) => { const {players} = state const {type, payload} = action switch (type) { case types.ADD: { return { ...state, todos: [payload, ...players], } } case types.REMOVE: { return { ...state, todos: players.filter((todo, i) => i !== payload), } } } return state }
// The types of actions that you can dispatch to modify the state of the store export const types = { ADD: 'ADD', REMOVE: 'REMOVE', } // Helper functions to dispatch actions, optionally with payloads export const actionCreators = { add: (item) => { return {type: types.ADD, payload: item} }, remove: (index) => { return {type: types.REMOVE, payload: index} } } // Initial state of the store const initialState = { todos: ['Click to remove', 'Learn React Native', 'Write Code', 'Ship App'], } // Function to handle actions and update the state of the store. // Notes: // - The reducer must return a new state object. It must never modify // the state object. State objects should be treated as immutable. // - We set \`state\` to our \`initialState\` by default. Redux will // call reducer() with no state on startup, and we are expected to // return the initial state of the app in this case. export const reducer = (state = initialState, action) => { const {todos} = state const {type, payload} = action switch (type) { case types.ADD: { return { ...state, todos: [payload, ...todos], } } case types.REMOVE: { return { ...state, todos: todos.filter((todo, i) => i !== payload), } } } return state }
Clarify meaning of --all option for packages command
# Copyright 2017-2020 TensorHub, 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. from __future__ import absolute_import from __future__ import division import click from guild import click_util @click.command("list, ls") @click.argument("terms", metavar="[TERM]...", nargs=-1) @click.option("-a", "--all", help="Show all installed Python packages.", is_flag=True) @click_util.use_args def list_packages(args): """List installed packages. Specify one or more `TERM` arguments to show packages matching any of the specified values. """ from . import packages_impl packages_impl.list_packages(args)
# Copyright 2017-2020 TensorHub, 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. from __future__ import absolute_import from __future__ import division import click from guild import click_util @click.command("list, ls") @click.argument("terms", metavar="[TERM]...", nargs=-1) @click.option("-a", "--all", help="Show all packages.", is_flag=True) @click_util.use_args def list_packages(args): """List installed packages. Specify one or more `TERM` arguments to show packages matching any of the specified values. """ from . import packages_impl packages_impl.list_packages(args)
Update repo URL to github.
# -*- coding: utf-8 -*- # # setup.py # colorific # """ Package information for colorific. """ import os from setuptools import setup readme = os.path.join(os.path.dirname(__file__), 'README.md') setup( name='colorific', version='0.2.0', description='Automatic color palette detection', long_description=open(readme).read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/99designs/colorific', py_modules=['colorific'], install_requires=[ 'PIL>=1.1.6', 'colormath>=1.0.8', 'numpy>=1.6.1', ], license='ISC', entry_points={ 'console_scripts': [ 'colorific = colorific:main', ], }, )
# -*- coding: utf-8 -*- # # setup.py # colorific # """ Package information for colorific. """ import os from setuptools import setup readme = os.path.join(os.path.dirname(__file__), 'README.md') setup( name='colorific', version='0.2.0', description='Automatic color palette detection', long_description=open(readme).read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://bitbucket.org/larsyencken/palette-detect', py_modules=['colorific'], install_requires=[ 'PIL>=1.1.6', 'colormath>=1.0.8', 'numpy>=1.6.1', ], license='ISC', entry_points={ 'console_scripts': [ 'colorific = colorific:main', ], }, )
Fix HasSlu slug autogeneration issue
<?php declare(strict_types=1); namespace Rinvex\Support\Traits; use Illuminate\Database\Eloquent\Model; use Spatie\Sluggable\HasSlug as BaseHasSlug; trait HasSlug { use BaseHasSlug; /** * Boot the trait. */ protected static function bootHasSlug() { // Auto generate slugs early before validation static::validating(function (Model $model) { if ($model->exists && $model->getSlugOptions()->generateSlugsOnUpdate) { $model->generateSlugOnUpdate(); } elseif (! $model->exists && $model->getSlugOptions()->generateSlugsOnCreate) { $model->generateSlugOnCreate(); } }); } }
<?php declare(strict_types=1); namespace Rinvex\Support\Traits; use Spatie\Sluggable\HasSlug as BaseHasSlug; trait HasSlug { use BaseHasSlug; /** * Boot the trait. */ protected static function bootHasSlug() { // Auto generate slugs early before validation static::validating(function (self $model) { if ($model->exists && $model->getSlugOptions()->generateSlugsOnUpdate) { $model->generateSlugOnUpdate(); } elseif (! $model->exists && $model->getSlugOptions()->generateSlugsOnCreate) { $model->generateSlugOnCreate(); } }); } }
Print out nicer error messages on connection errors
"""Command-line interface to pycat.""" import argparse import sys import socket from .talk import talk def argument_parser(): """Generate an `argparse` argument parser for pycat's arguments.""" parser = argparse.ArgumentParser(description='netcat, in Python') parser.add_argument('hostname', help='host to which to connect') parser.add_argument('port', help='port number to which to connect') return parser def main(args=sys.argv[1:]): """Run, as if from the command-line. args is a set of arguments to run with, defaulting to taking arguments from `sys.argv`. It should **not** include the name of the program as the first argument. """ parser = argument_parser() settings = parser.parse_args(args) try: sock = socket.create_connection((settings.hostname, settings.port)) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setblocking(False) talk(sock) except KeyboardInterrupt: sock.close() # Disregard Control-C, as this is probably how the user will exit. except ConnectionError as e: print(str(e), file=sys.stderr)
"""Command-line interface to pycat.""" import argparse import sys import socket from .talk import talk def argument_parser(): """Generate an `argparse` argument parser for pycat's arguments.""" parser = argparse.ArgumentParser(description='netcat, in Python') parser.add_argument('hostname', help='host to which to connect') parser.add_argument('port', help='port number to which to connect') return parser def main(args=sys.argv[1:]): """Run, as if from the command-line. args is a set of arguments to run with, defaulting to taking arguments from `sys.argv`. It should **not** include the name of the program as the first argument. """ parser = argument_parser() settings = parser.parse_args(args) try: sock = socket.create_connection((settings.hostname, settings.port)) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setblocking(False) talk(sock) except KeyboardInterrupt: sock.close() # Disregard Control-C, as this is probably how the user will exit.
Correct the rivets file name
var elixir = require('laravel-elixir'); elixir(function(mix) { mix.sass('app/assets/sass/main.scss') .styles([ 'app/assets/Bower_components/fontawesome/css/font-awesome.min.css', 'public/css/main.css', ], './') .scripts([ 'bower_components/jquery/dist/jquery.min.js', 'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js', 'bower_components/chartjs/Chart.min.js', 'bower_components/rivets/dist/rivets.bundle.js', 'js/app.js', 'js/**/*.js', ], './app/assets/') .version(['public/css/all.css', 'public/js/all.js']) .copy('app/assets/bower_components/fontawesome/fonts/', 'public/build/fonts'); });
var elixir = require('laravel-elixir'); elixir(function(mix) { mix.sass('app/assets/sass/main.scss') .styles([ 'app/assets/Bower_components/fontawesome/css/font-awesome.min.css', 'public/css/main.css', ], './') .scripts([ 'bower_components/jquery/dist/jquery.min.js', 'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js', 'bower_components/chartjs/Chart.min.js', 'bower_components/rivets/dist/riverts.bundle.js', 'js/app.js', 'js/**/*.js', ], './app/assets/') .version(['public/css/all.css', 'public/js/all.js']) .copy('app/assets/bower_components/fontawesome/fonts/', 'public/build/fonts'); });
Allow codec test to have more than just the one format
from .common import * from av.codec import Codec, Encoder, Decoder class TestCodecs(TestCase): def test_codec_mpeg4(self): for cls in (Encoder, Decoder): c = cls('mpeg4') self.assertEqual(c.name, 'mpeg4') self.assertEqual(c.long_name, 'MPEG-4 part 2') self.assertEqual(c.type, 'video') self.assertEqual(c.id, 13) formats = c.video_formats self.assertTrue(formats) self.assertTrue(any(f.name == 'yuv420p' for f in formats))
from .common import * from av.codec import Codec, Encoder, Decoder class TestCodecs(TestCase): def test_codec_mpeg4(self): for cls in (Encoder, Decoder): c = cls('mpeg4') self.assertEqual(c.name, 'mpeg4') self.assertEqual(c.long_name, 'MPEG-4 part 2') self.assertEqual(c.type, 'video') self.assertEqual(c.id, 13) formats = c.video_formats self.assertEqual(len(formats), 1) self.assertEqual(formats[0].name, 'yuv420p')
Use const for fakeResponse function
import queryString from 'query-string'; import pathMatch from 'path-match'; import parseUrl from 'parse-url'; const nativeFetch = window.fetch; //TODO: Handle response headers const fakeResponse = function(response = {}) { const responseStr = JSON.stringify(response); return new Response(responseStr); }; export const fakeFetch = (serverRoutes) => { return (url, options = {}) => { const body = options.body || ''; const method = options.method || 'GET'; const handlers = serverRoutes[method]; const pathname = parseUrl(url).pathname; const matchesPathname = path => pathMatch()(path)(pathname); const route = Object.keys(handlers).find(matchesPathname); if (!route) { return nativeFetch(url, options); } const handler = handlers[route]; const query = queryString.parse(parseUrl(url).search); const params = matchesPathname(route); return Promise.resolve(fakeResponse(handler({params, query, body}))); }; }; export const reset = () => { window.fetch = nativeFetch; };
import queryString from 'query-string'; import pathMatch from 'path-match'; import parseUrl from 'parse-url'; const nativeFetch = window.fetch; //TODO: Handle response headers let fakeResponse = function(response = {}) { const responseStr = JSON.stringify(response); return new Response(responseStr); }; export const fakeFetch = (serverRoutes) => { return (url, options = {}) => { const body = options.body || ''; const method = options.method || 'GET'; const handlers = serverRoutes[method]; const pathname = parseUrl(url).pathname; const matchesPathname = path => pathMatch()(path)(pathname); const route = Object.keys(handlers).find(matchesPathname); if (!route) { return nativeFetch(url, options); } const handler = handlers[route]; const query = queryString.parse(parseUrl(url).search); const params = matchesPathname(route); return Promise.resolve(fakeResponse(handler({params, query, body}))); }; }; export const reset = () => { window.fetch = nativeFetch; };
Add default case for switch (web)
import i18n from 'i18next'; const $app = document.getElementById('app'); class StoreSettings { data = {} defaultData = { lang: i18n.languages[0] || 'en', theme: 'light', view: 'map', debug: 0 } // Update setting, optionally save to localStorage. update(key, value, save) { if (save) { this.data[key] = value; localStorage.setItem('settings', JSON.stringify(this.data)); } // Handle setting side effects. switch (key) { case 'lang': i18n.changeLanguage(value); document.body.parentElement.setAttribute('lang', value); break; case 'theme': $app.setAttribute('data-theme', value); break; case 'debug': $app.className = 'is-debug-' + value; break; default: break; } } // Load and apply settings. constructor() { this.data = { ...this.defaultData, ...JSON.parse(localStorage.getItem('settings') || '{}') }; for (const key of Object.keys(this.data)) this.update(key, this.data[key]); } } export default new StoreSettings();
import i18n from 'i18next'; const $app = document.getElementById('app'); class StoreSettings { data = {} defaultData = { lang: i18n.languages[0] || 'en', theme: 'light', view: 'map', debug: 0 } // Update setting, optionally save to localStorage. update(key, value, save) { if (save) { this.data[key] = value; localStorage.setItem('settings', JSON.stringify(this.data)); } // Handle setting side effects. switch (key) { case 'lang': i18n.changeLanguage(value); document.body.parentElement.setAttribute('lang', value); break; case 'theme': $app.setAttribute('data-theme', value); break; case 'debug': $app.className = 'is-debug-' + value; break; } } // Load and apply settings. constructor() { this.data = { ...this.defaultData, ...JSON.parse(localStorage.getItem('settings') || '{}') }; for (const key of Object.keys(this.data)) this.update(key, this.data[key]); } } export default new StoreSettings();
Fix off-by-one for adjective list
var fs = require("fs"); var path = require("path"); var _ = require("lodash"); var animals; var adjectives; module.exports = function () { if (animals && adjectives) { return { animals : animals, adjectives : adjectives }; } adjectives = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "adjectives.json"))); animals = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "animals.json"))); _.each(adjectives, function (word, idx) { adjectives[idx] = word.toLowerCase(); }); _.each(animals, function (word, idx) { animals[idx] = word.toLowerCase(); }); return { adjectives : adjectives, animals : animals }; }; module.exports.NUM_ADJECTIVES = 1501; module.exports.NUM_ANIMALS = 1750;
var fs = require("fs"); var path = require("path"); var _ = require("lodash"); var animals; var adjectives; module.exports = function () { if (animals && adjectives) { return { animals : animals, adjectives : adjectives }; } adjectives = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "adjectives.json"))); animals = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "animals.json"))); _.each(adjectives, function (word, idx) { adjectives[idx] = word.toLowerCase(); }); _.each(animals, function (word, idx) { animals[idx] = word.toLowerCase(); }); return { adjectives : adjectives, animals : animals }; }; module.exports.NUM_ADJECTIVES = 1500; module.exports.NUM_ANIMALS = 1750;
Check for undo-ing delete commands of task without start or deadline
//@@author A0114395E package seedu.address.logic.parser; import java.util.List; import com.joestelmach.natty.DateGroup; public class NattyParser { private static NattyParser instance = null; private static String emptyValue = "-"; // Exists only to defeat instantiation. protected NattyParser() { } // Returns the singleton instance public static NattyParser getInstance() { if (instance == null) { instance = new NattyParser(); } return instance; } /** * Parses, analyses and converts 'rich text' into a timestamp * * @param String - e.g. 'Tomorrow' * @return String - Timestamp */ public String parseNLPDate(String argsString) { if (argsString.trim().equals(emptyValue)) { return emptyValue; } com.joestelmach.natty.Parser nParser = new com.joestelmach.natty.Parser(); List<DateGroup> groups = nParser.parse(argsString); String output = ""; for (DateGroup group : groups) { output = group.getDates().get(0).toString().replace("CST", ""); } return output; } }
//@@author A0114395E package seedu.address.logic.parser; import java.util.List; import com.joestelmach.natty.DateGroup; public class NattyParser { private static NattyParser instance = null; // Exists only to defeat instantiation. protected NattyParser() { } // Returns the singleton instance public static NattyParser getInstance() { if (instance == null) { instance = new NattyParser(); } return instance; } /** * Parses, analyses and converts 'rich text' into a timestamp * * @param String - e.g. 'Tomorrow' * @return String - Timestamp */ public String parseNLPDate(String argsString) { com.joestelmach.natty.Parser nParser = new com.joestelmach.natty.Parser(); List<DateGroup> groups = nParser.parse(argsString); String output = ""; for (DateGroup group : groups) { output = group.getDates().get(0).toString().replace("CST", ""); } return output; } }
Fix layout of dogs datatable
function renderThumbNail( data, type, row, meta ) { if(! window.dogList) { window.dogList = {}; window.dogList.snapshotUrl = '${SNAPSHOTURL}'; window.dogList.previewfileKey = '${PREVIEWKEY}'; window.dogList.renderSnapshotThumbnail = function(data, type, row, meta) { var html = ''; var colLength = 12 / $(data).length; $.each(data, function(index, value) { var cls = "thumbnail col-xs-" + colLength; html += '<div style="margin-bottom: 0" class="' + cls + '" ><a class="thumbNailLink" href="#" id="' + value + '" >'; html += '<img src="' + dogList.snapshotUrl +'?imageId=' + value + '" /></a></div>'; }); return html; }; $('#dogTable').on('click', '.thumbNailLink', function() { $('#image-file-key').val(window.dogList.previewfileKey + this.id); $('#image-preview-form').trigger('submit'); $('#image-preview').modal({keyboard:true, show:true}); }); } return window.dogList.renderSnapshotThumbnail(data, type, row, meta); }
function renderThumbNail( data, type, row, meta ) { if(! window.dogList) { window.dogList = {}; window.dogList.snapshotUrl = '${SNAPSHOTURL}'; window.dogList.previewfileKey = '${PREVIEWKEY}'; window.dogList.renderSnapshotThumbnail = function(data, type, row, meta) { var html = '<div class=\"row\">'; $.each(data, function(index, value) { html += '<div class="thumbnail col-xs-4"><a class="thumbNailLink" href="#" id="' + value + '" >'; html += '<img src="' + dogList.snapshotUrl +'?imageId=' + value + '" /></a></div>'; }); html += '</div>'; return html; }; $('#dogTable').on('click', '.thumbNailLink', function() { $('#image-file-key').val(window.dogList.previewfileKey + this.id); $('#image-preview-form').trigger('submit'); $('#image-preview').modal({keyboard:true, show:true}); }); } return window.dogList.renderSnapshotThumbnail(data, type, row, meta); }
Call export_card_data on batch save
from django.core.management import call_command from django.contrib import admin from refugeedata import models, forms class NumberAdmin(admin.ModelAdmin): list_display = ("number", "short_id", "active") class BatchAdmin(admin.ModelAdmin): list_display = ("registration_number_format", "data_file") def get_form(self, request, obj=None, **kwargs): if not obj: kwargs["form"] = forms.BatchAdminForm return super(BatchAdmin, self).get_form(request, obj=obj, **kwargs) def save_related(self, request, form, formsets, change): if not change: # create numbers = form.cleaned_data["registration_numbers"] models.RegistrationNumber.objects.bulk_create(numbers) form.cleaned_data["registration_numbers"] = ( models.RegistrationNumber.objects.filter( id__in=[n.id for n in numbers])) super(BatchAdmin, self).save_related(request, form, formsets, change) call_command("export_card_data", str(form.instance.id), "--save") class LanguageAdmin(admin.ModelAdmin): list_display = ("iso_code", "description", "example_text") admin.site.register(models.RegistrationNumber, NumberAdmin) admin.site.register(models.RegistrationCardBatch, BatchAdmin) admin.site.register(models.Language, LanguageAdmin)
from django.contrib import admin from refugeedata import models, forms class NumberAdmin(admin.ModelAdmin): list_display = ("number", "short_id", "active") class BatchAdmin(admin.ModelAdmin): list_display = ("registration_number_format", "data_file") def get_form(self, request, obj=None, **kwargs): if not obj: kwargs["form"] = forms.BatchAdminForm return super(BatchAdmin, self).get_form(request, obj=obj, **kwargs) def save_related(self, request, form, formsets, change): if not change: # create numbers = form.cleaned_data["registration_numbers"] models.RegistrationNumber.objects.bulk_create(numbers) form.cleaned_data["registration_numbers"] = ( models.RegistrationNumber.objects.filter( id__in=[n.id for n in numbers])) return super(BatchAdmin, self).save_related( request, form, formsets, change) class LanguageAdmin(admin.ModelAdmin): list_display = ("iso_code", "description", "example_text") admin.site.register(models.RegistrationNumber, NumberAdmin) admin.site.register(models.RegistrationCardBatch, BatchAdmin) admin.site.register(models.Language, LanguageAdmin)
Add e-mail for user profile edit form
$(document).ready(function() { showCurrentUserInfo(); setImageFormAction('profile'); populatePrefilled('interests'); populatePrefilled('skills'); }); /** * Populates inputs with current user information. */ async function showCurrentUserInfo() { const response = await fetch('/profile-update'); const userData = await response.json(); $('#name').val(userData['name']); $('#email').text(userData['email']); populateExisting('interests', userData); populateExisting('skills', userData); populateExistingImage('profile', '#profile-picture'); populateExistingImage('profile', '#profile-picture-main'); } /** * Populates inputs with labels that already exist */ function populateExisting(className, userData) { const existingLabels = userData[className]; for (const label of existingLabels) { $(`#${className}`).tagsinput('add', label); } } function removeAllExtraInputs() { removeExtraInputs('#interests'); removeExtraInputs('#skills'); } function getInterests() { return getLabels('interests'); } function getSkills() { return getLabels('skills'); } function getLabels(labelType) { let labels = []; for (const label of $(`#${labelType}`).children()) { labels.push(label.value); } return labels; }
$(document).ready(function() { showCurrentUserInfo(); setImageFormAction('profile'); populatePrefilled('interests'); populatePrefilled('skills'); }); /** * Populates inputs with current user information. */ async function showCurrentUserInfo() { const response = await fetch('/profile-update'); const userData = await response.json(); const userName = userData['name']; $('#name').val(userName); populateExisting('interests', userData); populateExisting('skills', userData); populateExistingImage('profile', '#profile-picture'); populateExistingImage('profile', '#profile-picture-main'); } /** * Populates inputs with labels that already exist */ function populateExisting(className, userData) { const existingLabels = userData[className]; for (const label of existingLabels) { $(`#${className}`).tagsinput('add', label); } } function removeAllExtraInputs() { removeExtraInputs('#interests'); removeExtraInputs('#skills'); } function getInterests() { return getLabels('interests'); } function getSkills() { return getLabels('skills'); } function getLabels(labelType) { let labels = []; for (const label of $(`#${labelType}`).children()) { labels.push(label.value); } return labels; }
Fix newlines in grunt log output.
/* * grunt-ember-handlebars * https://github.com/yaymukund/grunt-ember-handlebars * * Copyright (c) 2012 Mukund Lakshman * Licensed under the MIT license. * * A grunt task that precompiles Ember.js Handlebars templates into * separate .js files of the same name. This script expects the * following setup: * * tasks/ * ember-templates.js * lib/ * headless-ember.js * ember.js * * headless-ember and ember.js can both be found in the main Ember repo: * https://github.com/emberjs/ember.js/tree/master/lib */ var precompiler = require('./lib/precompiler'), path = require('path'); module.exports = function(grunt) { grunt.registerMultiTask('ember_handlebars', 'Precompile Ember Handlebars templates', function() { var files = grunt.file.expandFiles(this.file.src); grunt.utils._.each(files, function(file) { grunt.log.write('Precompiling "' + file + '" to "' + this.dest + '"\n'); var compiled = precompiler.precompile(file); out = path.join(this.dest, compiled.filename); grunt.file.write(out, compiled.src, 'utf8'); }, {dest: this.file.dest}); }); };
/* * grunt-ember-handlebars * https://github.com/yaymukund/grunt-ember-handlebars * * Copyright (c) 2012 Mukund Lakshman * Licensed under the MIT license. * * A grunt task that precompiles Ember.js Handlebars templates into * separate .js files of the same name. This script expects the * following setup: * * tasks/ * ember-templates.js * lib/ * headless-ember.js * ember.js * * headless-ember and ember.js can both be found in the main Ember repo: * https://github.com/emberjs/ember.js/tree/master/lib */ var precompiler = require('./lib/precompiler'), path = require('path'); module.exports = function(grunt) { grunt.registerMultiTask('ember_handlebars', 'Precompile Ember Handlebars templates', function() { var files = grunt.file.expandFiles(this.file.src); grunt.utils._.each(files, function(file) { grunt.log.write('Precompiling "' + file + '" to "' + this.dest + '"'); var compiled = precompiler.precompile(file); out = path.join(this.dest, compiled.filename); grunt.file.write(out, compiled.src, 'utf8'); }, {dest: this.file.dest}); }); };
Include license file in source distribution
#!/usr/bin/env python import setuptools from setuptools import setup with open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='cleanco', description='Python library to process company names', long_description=long_description, long_description_content_type='text/markdown', version='2.2-dev0', license="MIT", license_files=('LICENSE.txt',), classifiers = [ "Topic :: Office/Business", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3" ], url='https://github.com/psolin/cleanco', author='Paul Solin', author_email='paul@paulsolin.com', packages=["cleanco"], setup_requires=['pytest-runner'], tests_require=['pytest', 'tox'], )
#!/usr/bin/env python import setuptools from setuptools import setup with open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='cleanco', description='Python library to process company names', long_description=long_description, long_description_content_type='text/markdown', version='2.2-dev0', license="MIT", classifiers = [ "Topic :: Office/Business", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3" ], url='https://github.com/psolin/cleanco', author='Paul Solin', author_email='paul@paulsolin.com', packages=["cleanco"], setup_requires=['pytest-runner'], tests_require=['pytest', 'tox'], )
Fix requirejs with tooltipster depends problem
require.config({ baseUrl: 'app', paths: { jquery: 'lib/jquery-2.1.3', json: 'lib/json', d3: 'lib/d3.min', 'dagre-d3': 'lib/dagre-d3.min', text: 'lib/text', lettuce: 'lib/lettuce', 'underscore': 'lib/underscore-min', 'jquery.tooltipster': 'lib/jquery.tooltipster.min' }, 'shim': { 'jquery.tooltipster': { deps: ['jquery'] }, 'dagre-d3': { deps: ['d3'] } } }); require(['lib/knockout', 'scripts/render', 'json!../data/example.json'], function (ko, render, example) { 'use strict'; render.renderPage(example); });
require.config({ baseUrl: 'app', paths: { jquery: 'lib/jquery-2.1.3', json: 'lib/json', d3: 'lib/d3.min', 'dagre-d3': 'lib/dagre-d3.min', text: 'lib/text', lettuce: 'lib/lettuce', 'underscore': 'lib/underscore-min', 'jquery.tooltipster': 'lib/jquery.tooltipster.min' }, 'shim': { 'jquery.tipsy': { deps: ['jquery'] }, 'dagre-d3': { deps: ['d3'] } } }); require(['lib/knockout', 'scripts/render', 'json!../data/example.json'], function (ko, render, example) { 'use strict'; render.renderPage(example); });
Add scripts to generated package json
const fs = require('fs-extra'); const path = require('path'); const chalk = require('chalk'); function copyTemplate(appDir, templatePath) { fs.copySync(templatePath, appDir); fs.removeSync('.gitignore'); fs.moveSync( path.join(appDir, 'gitignore'), path.join(appDir, '.gitignore'), ); } function addPackageScripts(appDir) { const scripts = { start: 'landing-scripts start', build: 'landing-scripts build', serve: 'landing-scripts serve', audit: 'landing-scripts audit', }; const packageJson = require(`${appDir}/package.json`); packageJson.scripts = scripts; fs.writeFileSync( path.join(appDir, 'package.json'), JSON.stringify(packageJson, null, 2), ); } function init(appDir, appName, templatePath) { const isUsingYarn = fs.existsSync(path.join(appDir, 'yarn.lock')); const command = isUsingYarn ? 'yarn' : 'npm'; copyTemplate(appDir, templatePath); addPackageScripts(appDir); console.log(chalk.green('Project ready!')); console.log(); console.log('To start the project typing:'); console.log(); console.log(chalk.cyan('cd'), appName); console.log(chalk.cyan(command), 'start'); } module.exports = init;
const fs = require('fs-extra'); const path = require('path'); const chalk = require('chalk'); function copyTemplate(appDir, templatePath) { fs.copySync(templatePath, appDir); fs.removeSync('.gitignore'); fs.moveSync( path.join(appDir, 'gitignore'), path.join(appDir, '.gitignore'), ); } function addPackageScripts(appDir) { const scripts = { start: 'landing-scripts start', build: 'landing-scripts build', serve: 'landing-scripts serve', }; const packageJson = require(`${appDir}/package.json`); packageJson.scripts = scripts; fs.writeFileSync( path.join(appDir, 'package.json'), JSON.stringify(packageJson, null, 2), ); } function init(appDir, appName, templatePath) { const isUsingYarn = fs.existsSync(path.join(appDir, 'yarn.lock')); const command = isUsingYarn ? 'yarn' : 'npm'; copyTemplate(appDir, templatePath); addPackageScripts(appDir); console.log(chalk.green('Project ready!')); console.log(); console.log('To start the project typing:'); console.log(); console.log(chalk.cyan('cd'), appName); console.log(chalk.cyan(command), 'start'); } module.exports = init;
Add is_valid method for file sanitizer classes
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass from .error import ValidationError @add_metaclass(abc.ABCMeta) class NameSanitizer(object): @abc.abstractproperty def reserved_keywords(self): # pragma: no cover pass @abc.abstractmethod def validate(self, value): # pragma: no cover pass def is_valid(self, value): try: self.validate(value) except (TypeError, ValidationError): return False return True @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass def _is_reserved_keyword(self, value): return value in self.reserved_keywords @staticmethod def _validate_null_string(text): validate_null_string(text, error_msg="null name")
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass @add_metaclass(abc.ABCMeta) class NameSanitizer(object): @abc.abstractproperty def reserved_keywords(self): # pragma: no cover pass @abc.abstractmethod def validate(self, value): # pragma: no cover pass @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass def _is_reserved_keyword(self, value): return value in self.reserved_keywords @staticmethod def _validate_null_string(text): validate_null_string(text, error_msg="null name")
Add to console support provider.
<?php namespace Illuminate\Foundation\Providers; class ConsoleSupportProvider extends ServiceProvider { /** * The provider class names. * * @var array */ protected $providers = array( 'Illuminate\Foundation\Providers\CommandCreatorServiceProvider', 'Illuminate\Foundation\Providers\ComposerServiceProvider', 'Illuminate\Foundation\Providers\KeyGeneratorServiceProvider', 'Illuminate\Foundation\Providers\MaintenanceServiceProvider', 'Illuminate\Foundation\Providers\OptimizeServiceProvider', 'Illuminate\Foundation\Providers\PublisherServiceProvider', 'Illuminate\Foundation\Providers\RouteListServiceProvider', 'Illuminate\Foundation\Providers\ServerServiceProvider', 'Illuminate\Foundation\Providers\TinkerServiceProvider', ); /** * An array of the service provider instances. * * @var array */ protected $instances = array(); /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->instances = array(); foreach ($this->providers as $provider) { $this->instances[] = $this->app->register($provider); } } /** * Get the services provided by the provider. * * @return array */ public function provides() { $provides = array(); foreach ($this->instances as $instance) { $provides = array_merge($provides, $instance->provides()); } return $provides; } }
<?php namespace Illuminate\Foundation\Providers; class ConsoleSupportProvider extends ServiceProvider { /** * The provider class names. * * @var array */ protected $providers = array( 'Illuminate\Foundation\Providers\CommandCreatorServiceProvider', 'Illuminate\Foundation\Providers\KeyGeneratorServiceProvider', 'Illuminate\Foundation\Providers\MaintenanceServiceProvider', 'Illuminate\Foundation\Providers\OptimizeServiceProvider', 'Illuminate\Foundation\Providers\PublisherServiceProvider', 'Illuminate\Foundation\Providers\RouteListServiceProvider', 'Illuminate\Foundation\Providers\ServerServiceProvider', 'Illuminate\Foundation\Providers\TinkerServiceProvider', ); /** * An array of the service provider instances. * * @var array */ protected $instances = array(); /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->instances = array(); foreach ($this->providers as $provider) { $this->instances[] = $this->app->register($provider); } } /** * Get the services provided by the provider. * * @return array */ public function provides() { $provides = array(); foreach ($this->instances as $instance) { $provides = array_merge($provides, $instance->provides()); } return $provides; } }
Bump version number to 0.5
#!/usr/bin/env python from setuptools import setup setup(name='programmabletuple', version='0.5.0', description='Python metaclass for making named tuples with programmability', long_description=open('README.rst').read(), author='Tschijnmo TSCHAU', author_email='tschijnmotschau@gmail.com', url='https://github.com/tschijnmo/programmabletuple', license='MIT', packages=['programmabletuple', ], classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
#!/usr/bin/env python from setuptools import setup setup(name='programmabletuple', version='0.4.0', description='Python metaclass for making named tuples with programmability', long_description=open('README.rst').read(), author='Tschijnmo TSCHAU', author_email='tschijnmotschau@gmail.com', url='https://github.com/tschijnmo/programmabletuple', license='MIT', packages=['programmabletuple', ], classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Add test for string being null in hostutil
const HostUtil = { stringToHostname: function (string) { const HOSTNAME_MAX_LENGTH = 63; if (string == null) { return string; } // Strip or convert illegal characters let host = string.toLowerCase().replace(/[_\.]/g, '-').replace(/[^a-z0-9-]/g, ''); // Strip symbols from beginning while (host.startsWith('-')) { host = host.slice(1); } // Strip symbols from middle if greater than max length while (host.length > HOSTNAME_MAX_LENGTH && host.charAt(HOSTNAME_MAX_LENGTH - 1) === '-') { host = host.slice(0, HOSTNAME_MAX_LENGTH - 1).concat(host.slice(HOSTNAME_MAX_LENGTH)); } host = host.slice(0, HOSTNAME_MAX_LENGTH); // Strip symbols from end while (host.endsWith('-')) { host = host.slice(0, host.length - 1); } return host.slice(0, HOSTNAME_MAX_LENGTH); } }; module.exports = HostUtil;
const HostUtil = { stringToHostname: function (string) { const HOSTNAME_MAX_LENGTH = 63; // Strip or convert illegal characters let host = string.toLowerCase().replace(/[_\.]/g, '-').replace(/[^a-z0-9-]/g, ''); // Strip symbols from beginning while (host.startsWith('-')) { host = host.slice(1); } // Strip symbols from middle if greater than max length while (host.length > HOSTNAME_MAX_LENGTH && host.charAt(HOSTNAME_MAX_LENGTH - 1) === '-') { host = host.slice(0, HOSTNAME_MAX_LENGTH - 1).concat(host.slice(HOSTNAME_MAX_LENGTH)); } host = host.slice(0, HOSTNAME_MAX_LENGTH); // Strip symbols from end while (host.endsWith('-')) { host = host.slice(0, host.length - 1); } return host.slice(0, HOSTNAME_MAX_LENGTH); } }; module.exports = HostUtil;
Add patch for Processing 2.0-2.0.1 TAB keyboard input
package com.haxademic.core.system; import processing.core.PApplet; import processing.opengl.PGL; import com.haxademic.core.app.P; public class SystemUtil { public static String getJavaVersion() { return System.getProperty("java.version"); } public static String getTimestamp( PApplet p ) { // use P.nf to pad date components to 2 digits for more consistent ordering across systems return String.valueOf( P.year() ) + "-" + P.nf( P.month(), 2 ) + "-" + P.nf( P.day(), 2 ) + "-" + P.nf( P.hour(), 2 ) + "-" + P.nf( P.minute(), 2 ) + "-" + P.nf( P.second(), 2 ); } public static String getTimestampFine( PApplet p ) { return SystemUtil.getTimestamp(p) + "-" + P.nf( p.frameCount, 8 ); } // monkey-patch TAB capture ability - Processing 2.0 broke this in 3D rendering contexts public static void p2TabKeyInputPatch() { if(PGL.canvas != null) { PGL.canvas.setFocusTraversalKeysEnabled(false); } } }
package com.haxademic.core.system; import processing.core.PApplet; import com.haxademic.core.app.P; public class SystemUtil { public static String getJavaVersion() { return System.getProperty("java.version"); } public static String getTimestamp( PApplet p ) { // use P.nf to pad date components to 2 digits for more consistent ordering across systems return String.valueOf( P.year() ) + "-" + P.nf( P.month(), 2 ) + "-" + P.nf( P.day(), 2 ) + "-" + P.nf( P.hour(), 2 ) + "-" + P.nf( P.minute(), 2 ) + "-" + P.nf( P.second(), 2 ); } public static String getTimestampFine( PApplet p ) { return SystemUtil.getTimestamp(p) + "-" + P.nf( p.frameCount, 8 ); } }
Convert Nullable string into flat one, also add Fucnction as acceptable argument
/* @flow */ const hasFunctionNature = (maybe: any) => typeof maybe === 'function' const hasStringNature = (maybe: any) => typeof maybe === 'string' type Reducer = (state: any, action: Object) => any export default function reswitch (...args: Array<string | Function | Reducer | Object>): Reducer { const defaultReducer = (state: any) => state const hasDefaultReducer = ( (args.length % 2) && hasFunctionNature(args[args.length - 1]) ) if (args.length % 2 === 1) { if (hasStringNature(args[0]) && !hasDefaultReducer) { return defaultReducer } } if (!hasDefaultReducer) { args.push(defaultReducer) } return (state, action: Object) => { const argIndex = args.findIndex(arg => arg === action) + 1 || args.length - 1 if (hasFunctionNature(args[argIndex])) { return args[argIndex](state, action) } return args[argIndex] } }
/* @flow */ const hasFunctionNature = (maybe: any) => typeof maybe === 'function' const hasStringNature = (maybe: any) => typeof maybe === 'string' type Reducer = (state: any, action: Object) => any export default function reswitch(...args: Array<?string | Reducer | Object>): Reducer { const defaultReducer = (state: any) => state const hasDefaultReducer = ( (args.length % 2) && hasFunctionNature(args[args.length - 1]) ) if (args.length % 2 === 1) { if (hasStringNature(args[0]) && !hasDefaultReducer) { return defaultReducer } } if (!hasDefaultReducer) { args.push(defaultReducer) } return (state, action: Object) => { const argIndex = args.findIndex(arg => arg === action) + 1 || args.length - 1 if (hasFunctionNature(args[argIndex])) { return args[argIndex](state, action) } return args[argIndex] } }
Add more details in the test docstring.
r""" Tests for QtAwesome. """ # Standard library imports import sys import subprocess # Test Library imports import pytest # Local imports import qtawesome as qta from qtawesome.iconic_font import IconicFont from PyQt5.QtWidgets import QApplication def test_segfault_import(): output_number = subprocess.call('python -c "import qtawesome ' '; qtawesome.icon()"', shell=True) assert output_number == 0 def test_unique_font_family_name(): """ Test that each font used by qtawesome has a unique name. If this test fails, this probably means that you need to rename the family name of some fonts. Please see PR #98 for more details on why it is necessary and on how to do this. Regression test for Issue #107 """ app = QApplication(sys.argv) resource = qta._instance() assert isinstance(resource, IconicFont) prefixes = list(resource.fontname.keys()) assert prefixes fontnames = set(resource.fontname.values()) assert fontnames assert len(prefixes) == len(fontnames) sys.exit(app.exec_()) if __name__ == "__main__": pytest.main()
r""" Tests for QtAwesome. """ # Standard library imports import sys import subprocess # Test Library imports import pytest # Local imports import qtawesome as qta from qtawesome.iconic_font import IconicFont from PyQt5.QtWidgets import QApplication def test_segfault_import(): output_number = subprocess.call('python -c "import qtawesome ' '; qtawesome.icon()"', shell=True) assert output_number == 0 def test_unique_font_family_name(): """ Test that each font used by qtawesome has a unique name. Regression test for Issue #107 """ app = QApplication(sys.argv) resource = qta._instance() assert isinstance(resource, IconicFont) prefixes = list(resource.fontname.keys()) assert prefixes fontnames = set(resource.fontname.values()) assert fontnames assert len(prefixes) == len(fontnames) sys.exit(app.exec_()) if __name__ == "__main__": pytest.main()
Make error message more helpful by providing name
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); for (var i = 0; i < this._factories.length; i++) { if (this._factories[i].name === name) { throw new Error('A factory named ' + name + ' already exists'); } } FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { var factory = _.findWhere(FactoryBoy._factories, {name: name}); if (! factory) { throw new Error('Could not find the factory named ' + name); } return factory; }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; // Allow to overwrite the attribute definitions var attr = _.merge({}, factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, newAttr) { var factory = this._getFactory(name); var doc = _.merge({}, factory.attributes, newAttr); return doc; };
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); for (var i = 0; i < this._factories.length; i++) { if (this._factories[i].name === name) { throw new Error('A factory named ' + name + ' already exists'); } } FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { var factory = _.findWhere(FactoryBoy._factories, {name: name}); if (! factory) { throw new Error('Could not find the factory by that name'); } return factory; }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; // Allow to overwrite the attribute definitions var attr = _.merge({}, factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, newAttr) { var factory = this._getFactory(name); var doc = _.merge({}, factory.attributes, newAttr); return doc; };
Fix incorrect path in linked packages instructions
/** * Copy this file to `config/linked-packages.js` and uncomment any modules as desired to link them * for local development. * * These will be resolved as aliases in the webpack config. Note that you will need to ensure that * the packages are installed (via `yarn install`) in each respective folder * * It's recommended to use the `yarn startLocal` script to run the app, as it will automatically * start the webpack development server for the `viz` repo when needed. * * You may add as other modules to this list as well. */ var packages = { // '@tidepool/viz': process.env.TIDEPOOL_DOCKER_VIZ_DIR || '../viz', // 'tideline': process.env.TIDEPOOL_DOCKER_TIDELINE_DIR || '../tideline', // 'tidepool-platform-client': process.env.TIDEPOOL_DOCKER_PLATFORM_CLIENT_DIR || '../platform-client', }; module.exports = { list: () => console.log(Object.keys(packages).join(',')), packages: packages, }
/** * Copy this file to `local/linked-packages.js` and uncomment any modules as desired to link them * for local development. * * These will be resolved as aliases in the webpack config. Note that you will need to ensure that * the packages are installed (via `yarn install`) in each respective folder * * It's recommended to use the `yarn startLocal` script to run the app, as it will automatically * start the webpack development server for the `viz` repo when needed. * * You may add as other modules to this list as well. */ var packages = { // '@tidepool/viz': process.env.TIDEPOOL_DOCKER_VIZ_DIR || '../viz', // 'tideline': process.env.TIDEPOOL_DOCKER_TIDELINE_DIR || '../tideline', // 'tidepool-platform-client': process.env.TIDEPOOL_DOCKER_PLATFORM_CLIENT_DIR || '../platform-client', }; module.exports = { list: () => console.log(Object.keys(packages).join(',')), packages: packages, }
Return types in routing and news bundle
<?php /* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <adam@wellcommerce.org> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace WellCommerce\Bundle\ProductBundle\Entity; use WellCommerce\Bundle\RoutingBundle\Entity\Route; use WellCommerce\Bundle\RoutingBundle\Entity\RouteInterface; /** * Class ProductRoute * * @author Adam Piotrowski <adam@wellcommerce.org> */ class ProductRoute extends Route implements RouteInterface { /** * @var ProductInterface */ protected $identifier; /** * @return string */ public function getType() : string { return 'product'; } }
<?php /* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <adam@wellcommerce.org> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace WellCommerce\Bundle\ProductBundle\Entity; use WellCommerce\Bundle\RoutingBundle\Entity\Route; use WellCommerce\Bundle\RoutingBundle\Entity\RouteInterface; /** * Class ProductRoute * * @author Adam Piotrowski <adam@wellcommerce.org> */ class ProductRoute extends Route implements RouteInterface { /** * @var ProductInterface */ protected $identifier; /** * @return string */ public function getType() { return 'product'; } }
Change the from to not be a noreply
<?php declare(strict_types=1); namespace App\Mail\Attendance; use App\AttendanceExport; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Swift_Mime_SimpleMimeEntity as SimpleMimeEntity; class Report extends Mailable { use Queueable; use SerializesModels; /** * The AttendanceExport for the email. * * @var AttendanceExport */ public $export; /** * Create a new message instance. */ public function __construct(AttendanceExport $export) { $this->export = $export; } /** * Build the message. * * @return $this */ public function build() { return $this ->from('attendancereports@my.robojackets.org', 'RoboJackets') ->withSwiftMessage(static function (SimpleMimeEntity $message): void { $message->getHeaders()->addTextHeader('Reply-To', 'RoboJackets <officers@robojackets.org>'); })->subject('RoboJackets Attendance Report Ending '.$this->export->end_time->format('n/j/Y')) ->markdown('mail.attendance.report'); } }
<?php declare(strict_types=1); namespace App\Mail\Attendance; use App\AttendanceExport; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Swift_Mime_SimpleMimeEntity as SimpleMimeEntity; class Report extends Mailable { use Queueable; use SerializesModels; /** * The AttendanceExport for the email. * * @var AttendanceExport */ public $export; /** * Create a new message instance. */ public function __construct(AttendanceExport $export) { $this->export = $export; } /** * Build the message. * * @return $this */ public function build() { return $this ->from('noreply@my.robojackets.org', 'RoboJackets') ->withSwiftMessage(static function (SimpleMimeEntity $message): void { $message->getHeaders()->addTextHeader('Reply-To', 'RoboJackets <officers@robojackets.org>'); })->subject('RoboJackets Attendance Report Ending '.$this->export->end_time->format('n/j/Y')) ->markdown('mail.attendance.report'); } }
Add id in the result in the command bandwidth-pools
"""Displays information about the accounts bandwidth pools""" # :license: MIT, see LICENSE for more details. import click from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.managers.account import AccountManager as AccountManager from SoftLayer import utils @click.command() @environment.pass_env def cli(env): """Displays bandwidth pool information Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr """ manager = AccountManager(env.client) items = manager.get_bandwidth_pools() table = formatting.Table([ "Id", "Pool Name", "Region", "Servers", "Allocation", "Current Usage", "Projected Usage" ], title="Bandwidth Pools") table.align = 'l' for item in items: id = item.get('id') name = item.get('name') region = utils.lookup(item, 'locationGroup', 'name') servers = manager.get_bandwidth_pool_counts(identifier=item.get('id')) allocation = "{} GB".format(item.get('totalBandwidthAllocated', 0)) current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut')) projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0)) table.add_row([id, name, region, servers, allocation, current, projected]) env.fout(table)
"""Displays information about the accounts bandwidth pools""" # :license: MIT, see LICENSE for more details. import click from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.managers.account import AccountManager as AccountManager from SoftLayer import utils @click.command() @environment.pass_env def cli(env): """Displays bandwidth pool information Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr """ manager = AccountManager(env.client) items = manager.get_bandwidth_pools() table = formatting.Table([ "Pool Name", "Region", "Servers", "Allocation", "Current Usage", "Projected Usage" ], title="Bandwidth Pools") table.align = 'l' for item in items: name = item.get('name') region = utils.lookup(item, 'locationGroup', 'name') servers = manager.get_bandwidth_pool_counts(identifier=item.get('id')) allocation = "{} GB".format(item.get('totalBandwidthAllocated', 0)) current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut')) projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0)) table.add_row([name, region, servers, allocation, current, projected]) env.fout(table)
Change requested by pull request reviewers 2.
const net = require('net'); const JsonSocket = require('json-socket'); // Object containing clients list and relative sockets const clients = {}; // Server eventEmitter const server = net.createServer(); server.on('connection', initSocket); server.on('result', sendResult); // Init newly created socket function initSocket(connection) { const socket = new JsonSocket(connection); const parseMessage = (message) => { const clientId = message.clientId; const fileName = message.fileName; const code = message.code; const timeLimit = message.timeLimit; if (!(clientId && fileName && code && timeLimit)) { sendResult({}); } clients[message.clientId] = socket; server.emit('runJava', clientId, fileName, code); }; socket.on('message', parseMessage); }; function sendResult(feedback) { const socket = clients[feedback.clientId]; socket.sendEndMessage(feedback); } module.exports = server;
const net = require('net'); const JsonSocket = require('json-socket'); // Object containing clients list and relative sockets const clients = {}; // Server eventEmitter const server = net.createServer(); server.on('connection', initSocket); server.on('result', sendResult); // Init newly created socket function initSocket(connection) { let socket = new JsonSocket(connection); let parseMessage = (message) => { let clientId = message.clientId; let fileName = message.fileName; let code = message.code; let timeLimit = message.timeLimit; if (!(clientId && fileName && code && timeLimit)) { sendResult({}); } clients[message.clientId] = socket; server.emit('runJava', clientId, fileName, code); }; socket.on('message', parseMessage); }; function sendResult(feedback) { let socket = clients[feedback.clientId]; socket.sendEndMessage(feedback); } module.exports = server;
Add one more index file for solver
import argparse import os import shutil from astroplan import download_IERS_A from astropy.utils import data def download_all_files(data_folder=None): download_IERS_A() if data_folder is None: data_folder = "{}/astrometry/data".format(os.getenv('PANDIR')) for i in range(4214, 4220): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, fn) if not os.path.exists(dest): url = "http://data.astrometry.net/4200/{}".format(fn) df = data.download_file(url) try: shutil.move(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--folder', help='Folder to place astrometry data') args = parser.parse_args() if args.folder and not os.path.exists(args.folder): print("{} does not exist.".format(args.folder)) download_all_files(data_folder=args.folder)
import argparse import os import shutil from astroplan import download_IERS_A from astropy.utils import data def download_all_files(data_folder=None): download_IERS_A() if data_folder is None: data_folder = "{}/astrometry/data".format(os.getenv('PANDIR')) for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, fn) if not os.path.exists(dest): url = "http://data.astrometry.net/4200/{}".format(fn) df = data.download_file(url) try: shutil.move(df, dest) except OSError as e: print("Problem saving. (Maybe permissions?): {}".format(e)) if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--folder', help='Folder to place astrometry data') args = parser.parse_args() if args.folder and not os.path.exists(args.folder): print("{} does not exist.".format(args.folder)) download_all_files(data_folder=args.folder)
Add enhanced version of last test.
var promise = require('when'); describe('setup', function() { it('test env works', function() { expect(true).toBe(true); }); }); function promiseThatResolves() { return promise.promise(function(resolve) { resolve(); }); } function promiseThatRejects() { return promise.promise(function(_, reject) { reject('A rejected promise'); }); } describe('promises and jasmine', function() { it('the simplest passing promise test', function(done) { promiseThatResolves().then(success).done(); function success() { expect(true).toBe(true); done(); } // Issues here: // - missing `done();` on the last line makes the tests run looong (5s) until the timeout catches // that would be acceptable, since it kinda gives a hint where to look // - to have the function success at all makes the flow of the test just a bit harder to read }); it('a bit better passing promise test', function(done) { var success = jasmine.createSpy('success'); promiseThatResolves().then(success).done(); success.andCallFake(function() { expect(success).toHaveBeenCalled(); done(); }); // Pro // - removes the little meaningful `expect(true).toBe(true);` and replaces it by something // that shows a meaning when failing. // // Contra: // - the spy+callFake construct is not easy to understand on first sight }); });
var promise = require('when'); describe('setup', function() { it('test env works', function() { expect(true).toBe(true); }); }); function promiseThatResolves() { return promise.promise(function(resolve) { resolve(); }); } function promiseThatRejects() { return promise.promise(function(_, reject) { reject('A rejected promise'); }); } describe('promises and jasmine', function() { it('the simplest passing promise test', function(done) { promiseThatResolves().then(success).done(); function success() { expect(true).toBe(true); done(); } // Issues here: // - missing `done();` on the last line makes the tests run looong (5s) until the timeout catches // that would be acceptable, since it kinda gives a hint where to look // - to have the function success at all makes the flow of the test just a bit harder to read }); });
Add dummy Let's Encrypt email
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain) env.update(LETSENCRYPT_HOST=domain, LETSENCRYPT_EMAIL="pub@loomchild.net") env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out)
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain, LETSENCRYPT_HOST=domain) env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out)
Handle Ping result in ResultIqProtocolEntity refs #402
from yowsup.layers import YowProtocolLayer from yowsup.common import YowConstants from .protocolentities import * class YowIqProtocolLayer(YowProtocolLayer): def __init__(self): handleMap = { "iq": (self.recvIq, self.sendIq) } super(YowIqProtocolLayer, self).__init__(handleMap) def __str__(self): return "Iq Layer" def sendIq(self, entity): if entity.getXmlns() == "w:p": self.toLower(entity.toProtocolTreeNode()) def recvIq(self, node): if node["xmlns"] == "urn:xmpp:ping": entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"]) self.toLower(entity.toProtocolTreeNode()) elif node["type"] == "error": self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node)) elif node["type"] == "result" and not len(node.getAllChildren()): #allowing only unidentifiable result (has no children) iq through this layer. (ex: ping result) self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(node))
from yowsup.layers import YowProtocolLayer from yowsup.common import YowConstants from .protocolentities import * class YowIqProtocolLayer(YowProtocolLayer): def __init__(self): handleMap = { "iq": (self.recvIq, self.sendIq) } super(YowIqProtocolLayer, self).__init__(handleMap) def __str__(self): return "Iq Layer" def sendIq(self, entity): if entity.getXmlns() == "w:p": self.toLower(entity.toProtocolTreeNode()) def recvIq(self, node): if node["xmlns"] == "urn:xmpp:ping": entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"]) self.toLower(entity.toProtocolTreeNode()) elif node["type"] == "error": self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
Fix codestyle and use stripos to check starting with vowel
<?php namespace Codeception\Lib\Actor\Shared; trait Comment { public function expectTo($prediction) { return $this->comment('I expect to ' . $prediction); } public function expect($prediction) { return $this->comment('I expect ' . $prediction); } public function amGoingTo($argumentation) { return $this->comment('I am going to ' . $argumentation); } public function am($role) { $role = trim($role); if (stripos('aeiou', $role[0]) !== false) { return $this->comment('As an ' . $role); } return $this->comment('As a ' . $role); } public function lookForwardTo($achieveValue) { return $this->comment('So that I ' . $achieveValue); } }
<?php namespace Codeception\Lib\Actor\Shared; trait Comment { public function expectTo($prediction) { return $this->comment('I expect to ' . $prediction); } public function expect($prediction) { return $this->comment('I expect ' . $prediction); } public function amGoingTo($argumentation) { return $this->comment('I am going to ' . $argumentation); } public function am($role) { $role = (string) trim($role); $firstLetter = $role[0]; if(preg_match('/[aeiouAEIOU]/i', $firstLetter)) { return $this->comment('As an ' . $role); } return $this->comment('As a ' . $role); } public function lookForwardTo($achieveValue) { return $this->comment('So that I ' . $achieveValue); } public function comment($description) { $this->scenario->comment($description); return $this; } }
Make count of words default 0
from django.db import models class DataIngredient(models.Model): """"Class used to Store Ingredients of the recipes found in the crawling process""" ingredient = models.CharField(max_length=1000) recipe = models.CharField(max_length=500) group = models.CharField(max_length=500, default='Ingredientes') def __str__(self): return self.ingredient class DataWayCooking(models.Model): """Class used to Store steps of the recipes found in the crawling process""" description = models.CharField(max_length=500) recipe = models.CharField(max_length=500) group = models.CharField(max_length=500, default='Modo de Fazer') def __str__(self): return self.description class IngredientSpec(models.Model): """Class used to manipulate Ingredients found and change data to data mining and found patterns of ingredients""" word = models.CharField(max_length=500) count = models.IntegerField(default=0) type = models.CharField(max_length=1) class IgnoredWords(models.Model): """Model to store words to ignore from Ingredient Spec""" word = models.CharField(max_length=500)
from django.db import models class DataIngredient(models.Model): """"Class used to Store Ingredients of the recipes found in the crawling process""" ingredient = models.CharField(max_length=1000) recipe = models.CharField(max_length=500) group = models.CharField(max_length=500, default='Ingredientes') def __str__(self): return self.ingredient class DataWayCooking(models.Model): """Class used to Store steps of the recipes found in the crawling process""" description = models.CharField(max_length=500) recipe = models.CharField(max_length=500) group = models.CharField(max_length=500, default='Modo de Fazer') def __str__(self): return self.description class IngredientSpec(models.Model): """Class used to manipulate Ingredients found and change data to data mining and found patterns of ingredients""" word = models.CharField(max_length=500) count = models.IntegerField() type = models.CharField(max_length=1) class IgnoredWords(models.Model): """Model to store words to ignore from Ingredient Spec""" word = models.CharField(max_length=500)
Set scheduler to run every hour on the 25th minute Fixes ‘InvalidArgumentException : 5 is not a valid position’ when doing ‘artisan schedule:run’
<?php return [ /** * The storage config */ "storage" => [ /** * Returns the folder name of the chunks. The location is in storage/app/{folder_name} */ "chunks" => "chunks", "disk" => "local" ], "clear" => [ /** * How old chunks we should delete */ "timestamp" => "-3 HOURS", "schedule" => [ "enabled" => true, "cron" => "25 * * * *" // run every hour on the 25th minute ] ], "chunk" => [ // setup for the chunk naming setup to ensure same name upload at same time "name" => [ "use" => [ "session" => true, // should the chunk name use the session id? The uploader must send cookie!, "browser" => false // instead of session we can use the ip and browser? ] ] ] ];
<?php return [ /** * The storage config */ "storage" => [ /** * Returns the folder name of the chunks. The location is in storage/app/{folder_name} */ "chunks" => "chunks", "disk" => "local" ], "clear" => [ /** * How old chunks we should delete */ "timestamp" => "-3 HOURS", "schedule" => [ "enabled" => true, "cron" => "0 */1 * * * *" // run every hour ] ], "chunk" => [ // setup for the chunk naming setup to ensure same name upload at same time "name" => [ "use" => [ "session" => true, // should the chunk name use the session id? The uploader must send cookie!, "browser" => false // instead of session we can use the ip and browser? ] ] ] ];
Add `adaptTimeout` helper that changes timeouts during Travis test.
/*! resol-vbus | Copyright (c) 2013-2014, Daniel Wippermann | MIT license */ 'use strict'; var _ = require('lodash'); var Q = require('q'); var testUtils = { performAsyncTest: function(done, callback) { return Q.fcall(callback).then(function() { done(); }).fail(function(reason) { done(reason); }); }, expectPromise: function(promise) { expect(promise).to.be.an('object'); expect(promise).to.have.a.property('then').that.is.a('function'); return promise; }, expectRanges: function(ranges) { expect(ranges).a('array'); var comparableRanges = _.map(ranges, function(range) { return { minTimestamp: range.minTimestamp.toISOString(), maxTimestamp: range.maxTimestamp.toISOString(), }; }); return expect(comparableRanges); }, adaptTimeout: function(timeout) { var factor = process.env.TRAVIS ? 1000 : 1; return timeout * factor; }, }; module.exports = testUtils;
/*! resol-vbus | Copyright (c) 2013-2014, Daniel Wippermann | MIT license */ 'use strict'; var _ = require('lodash'); var Q = require('q'); var testUtils = { performAsyncTest: function(done, callback) { return Q.fcall(callback).then(function() { done(); }).fail(function(reason) { done(reason); }); }, expectPromise: function(promise) { expect(promise).to.be.an('object'); expect(promise).to.have.a.property('then').that.is.a('function'); return promise; }, expectRanges: function(ranges) { expect(ranges).a('array'); var comparableRanges = _.map(ranges, function(range) { return { minTimestamp: range.minTimestamp.toISOString(), maxTimestamp: range.maxTimestamp.toISOString(), }; }); return expect(comparableRanges); }, }; module.exports = testUtils;
Add dependency on wagtailcore migration 0002 (necessary to cleanly merge the other migration 0005 being added in 0.9)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0002_initial_data'), ('tests', '0004_auto_20141008_0420'), ] operations = [ migrations.AlterField( model_name='formfield', name='choices', field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True), preserve_default=True, ), migrations.AlterField( model_name='formfield', name='default_value', field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True), preserve_default=True, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('tests', '0004_auto_20141008_0420'), ] operations = [ migrations.AlterField( model_name='formfield', name='choices', field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True), preserve_default=True, ), migrations.AlterField( model_name='formfield', name='default_value', field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True), preserve_default=True, ), ]
Use https to gravatar url
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,))
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,))
Add simple attributes test case
/* * Copyright 2011 Rackspace * * 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. * */ var et = require('elementtree'); exports['test_simplest'] = function(test, assert) { /* Ported from <https://github.com/lxml/lxml/blob/master/src/lxml/tests/test_elementtree.py> */ var Element = et.Element var root = Element('root'); root.append(Element('one')); root.append(Element('two')); root.append(Element('three')); assert.equal(3, root.len()) assert.equal('one', root.getItem(0).tag) assert.equal('two', root.getItem(1).tag) assert.equal('three', root.getItem(2).tag) test.finish(); }; exports['test_attribute_values'] = function(test, assert) { var XML = et.XML; var root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>'); assert.equal('Alpha', root.attrib['alpha']); assert.equal('Beta', root.attrib['beta']); assert.equal('Gamma', root.attrib['gamma']); test.finish(); };
/* * Copyright 2011 Rackspace * * 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. * */ var et = require('elementtree'); exports['test_error_type'] = function(test, assert) { /* Ported from <https://github.com/lxml/lxml/blob/master/src/lxml/tests/test_elementtree.py> */ var Element = et.Element var root = Element('root'); root.append(Element('one')); root.append(Element('two')); root.append(Element('three')); assert.equal(3, root.len()) assert.equal('one', root.getItem(0).tag) assert.equal('two', root.getItem(1).tag) assert.equal('three', root.getItem(2).tag) test.finish(); };
Increase time before exit in TestMultipleAttachRestart Sometimes third attacher attaching to already stopped container. Also I've changed prefix to attach and fixed cleanup on Fatal. Docker-DCO-1.1-Signed-off-by: Alexandr Morozov <lk4d4math@gmail.com> (github: LK4D4)
package main import ( "os/exec" "strings" "sync" "testing" "time" ) func TestMultipleAttachRestart(t *testing.T) { cmd := exec.Command(dockerBinary, "run", "--name", "attacher", "-d", "busybox", "/bin/sh", "-c", "sleep 2 && echo hello") group := sync.WaitGroup{} group.Add(4) defer func() { cmd = exec.Command(dockerBinary, "kill", "attacher") if _, err := runCommand(cmd); err != nil { t.Fatal(err) } deleteAllContainers() }() go func() { defer group.Done() out, _, err := runCommandWithOutput(cmd) if err != nil { t.Fatal(err, out) } }() time.Sleep(500 * time.Millisecond) for i := 0; i < 3; i++ { go func() { defer group.Done() c := exec.Command(dockerBinary, "attach", "attacher") out, _, err := runCommandWithOutput(c) if err != nil { t.Fatal(err, out) } if actual := strings.Trim(out, "\r\n"); actual != "hello" { t.Fatalf("unexpected output %s expected hello", actual) } }() } group.Wait() logDone("attach - multiple attach") }
package main import ( "os/exec" "strings" "sync" "testing" "time" ) func TestMultipleAttachRestart(t *testing.T) { cmd := exec.Command(dockerBinary, "run", "--name", "attacher", "-d", "busybox", "/bin/sh", "-c", "sleep 1 && echo hello") group := sync.WaitGroup{} group.Add(4) go func() { defer group.Done() out, _, err := runCommandWithOutput(cmd) if err != nil { t.Fatal(err, out) } }() time.Sleep(500 * time.Millisecond) for i := 0; i < 3; i++ { go func() { defer group.Done() c := exec.Command(dockerBinary, "attach", "attacher") out, _, err := runCommandWithOutput(c) if err != nil { t.Fatal(err, out) } if actual := strings.Trim(out, "\r\n"); actual != "hello" { t.Fatalf("unexpected output %s expected hello", actual) } }() } group.Wait() cmd = exec.Command(dockerBinary, "kill", "attacher") if _, err := runCommand(cmd); err != nil { t.Fatal(err) } deleteAllContainers() logDone("run - multiple attach") }
Add HIDE_DYE item meta flag
package com.laytonsmith.abstraction.enums; import com.laytonsmith.annotations.MEnum; /** * A MCItemFlag can hide some Attributes from MCItemStacks, through MCItemMeta. */ @MEnum("com.commandhelper.ItemFlag") public enum MCItemFlag { /** * Setting to show/hide enchants */ HIDE_ENCHANTS, /** * Setting to show/hide Attributes like Damage */ HIDE_ATTRIBUTES, /** * Setting to show/hide the unbreakable State */ HIDE_UNBREAKABLE, /** * Setting to show/hide what the ItemStack can break/destroy */ HIDE_DESTROYS, /** * Setting to show/hide where this ItemStack can be build/placed on */ HIDE_PLACED_ON, /** * Setting to show/hide potion effects on this ItemStack */ HIDE_POTION_EFFECTS, /** * Setting to show/hide dyes from coloured leather armour */ HIDE_DYE; }
package com.laytonsmith.abstraction.enums; import com.laytonsmith.annotations.MEnum; /** * A MCItemFlag can hide some Attributes from MCItemStacks, through MCItemMeta. */ @MEnum("com.commandhelper.ItemFlag") public enum MCItemFlag { /** * Setting to show/hide enchants */ HIDE_ENCHANTS, /** * Setting to show/hide Attributes like Damage */ HIDE_ATTRIBUTES, /** * Setting to show/hide the unbreakable State */ HIDE_UNBREAKABLE, /** * Setting to show/hide what the ItemStack can break/destroy */ HIDE_DESTROYS, /** * Setting to show/hide where this ItemStack can be build/placed on */ HIDE_PLACED_ON, /** * Setting to show/hide potion effects on this ItemStack */ HIDE_POTION_EFFECTS; }
Add missing close parenthesis on track dict
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number']) d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({}))'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main()
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] d['short_label'] = '{}_{} binding sites'.format(metadata['protein'], metadata['serial_number']) d['long_label'] = 'Predicted {} binding sites (site width = {}, model identifier {}({})'.format(metadata['protein'], metadata['width'], metadata['serial_number'], metadata['author_identifier']) return d def render_tracks(assembly, metadata_file): obj = yaml.load(metadata_file) # Just pull out the assembly ones tracks = [generate_track_dict(x) for x in obj if x['assembly'] == assembly] trackdb = {'tracks': tracks} render_template(trackdb, 'trackDb') def main(): parser = argparse.ArgumentParser(description='Render trackDb.txt') parser.add_argument('--assembly') parser.add_argument('metadata_file', type=argparse.FileType('r')) args = parser.parse_args() render_tracks(args.assembly, args.metadata_file) if __name__ == '__main__': main()
Update Test according sad reality
<?php class GiphyTest extends TestCaseBase { public function testOne() { $this->assertEmbed( 'http://giphy.com/gifs/puppies-cute-animals-asdfghjkl-6UZFwMYqCeXi8', [ 'title' => 'Puppies GIF - Find & Share on GIPHY', 'type' => 'video', 'providerName' => 'Giphy', 'code' => '<iframe src="https://giphy.com/embed/6UZFwMYqCeXi8?html5=true" frameborder="0" allowTransparency="true" style="border:none;overflow:hidden;width:500px;height:280px;"></iframe>', 'width' => 500, 'height' => 280, ] ); } }
<?php class GiphyTest extends TestCaseBase { public function testOne() { $this->assertEmbed( 'http://giphy.com/gifs/puppies-cute-animals-asdfghjkl-6UZFwMYqCeXi8', [ 'title' => 'Puppies Animated GIF', 'type' => 'video', 'providerName' => 'Giphy', 'code' => '<iframe src="https://giphy.com/embed/6UZFwMYqCeXi8?html5=true" frameborder="0" allowTransparency="true" style="border:none;overflow:hidden;width:500px;height:280px;"></iframe>', 'width' => 500, 'height' => 280, ] ); } }
Rename rpc test queue and change rpc message
var assert = require('assert'); var producer = require('../index')().producer; var consumer = require('../index')().consumer; var uuid = require('node-uuid'); var fixtures = { queues: ['rpc-queue-0'] }; describe('Producer/Consumer RPC messaging:', function() { before(function (done) { return consumer.connect() .then(function (_channel) { assert(_channel !== undefined); assert(_channel !== null); }) .then(function () { return producer.connect(); }) .then(function (_channel) { assert(_channel !== undefined); assert(_channel !== null); }) .then(done); }); it('should be able to create a consumer that returns a message if called as RPC [rpc-queue-0]', function (done) { consumer.consume(fixtures.queues[0], function () { return 'Power Ranger Red'; }) .then(function(created) { assert.equal(created, true); }) .then(done); }); it('should be able to produce a RPC message and get a response [rpc-queue-0]', function (done) { producer.produce(fixtures.queues[0], { msg: uuid.v4() }) .then(function (response) { assert.equal(response, 'Power Ranger Red'); }) .then(done); }); });
var assert = require('assert'); var producer = require('../index')().producer; var consumer = require('../index')().consumer; var uuid = require('node-uuid'); var fixtures = { queues: ['test-queue-0'] }; describe('Producer/Consumer RPC messaging:', function() { before(function (done) { return consumer.connect() .then(function (_channel) { assert(_channel !== undefined); assert(_channel !== null); }) .then(function () { return producer.connect(); }) .then(function (_channel) { assert(_channel !== undefined); assert(_channel !== null); }) .then(done); }); it('should be able to create a consumer that returns true if called as RPC [test-queue-0]', function (done) { consumer.consume(fixtures.queues[0], function () { return true; }) .then(function(created) { assert(created, true); }) .then(done); }); it('should be able to produce a RPC message and get a response [test-queue-0]', function (done) { producer.produce(fixtures.queues[0], { msg: uuid.v4() }) .then(function (response) { assert(response, true); }) .then(done); }); });
Revert "Intentional fail to make Jenkins Fail if it is checking tests" This reverts commit 8483e760b4eb5568735f40fe3773c48cb320ce7e.
package hiteware.com.halfwaythere; import android.widget.TextView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; /** * Created by jasonhite on 4/29/15. */ @RunWith(CustomRobolectricRunner.class) @Config(constants = BuildConfig.class) public class SensorIntegrationTest { public MainActivity CreatedActivity; public TestInjectableApplication application; StepSensorChange stepSensorChange; @Before public void setUp() { application = (TestInjectableApplication) RuntimeEnvironment.application; CreatedActivity = Robolectric.buildActivity(MainActivity.class).create().postResume().get(); stepSensorChange = application.stepSensorChangeModule.provideStepSensorChange(); } @Test public void whenAStepCounterValueIsInjectedTheDisplayIsUpdated() { stepSensorChange.onSensorChanged(SensorValue.CreateSensorEvent(23)); assertThat(((TextView) CreatedActivity.findViewById(R.id.step_value)).getText().toString(), equalTo("23")); } }
package hiteware.com.halfwaythere; import android.widget.TextView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; /** * Created by jasonhite on 4/29/15. */ @RunWith(CustomRobolectricRunner.class) @Config(constants = BuildConfig.class) public class SensorIntegrationTest { public MainActivity CreatedActivity; public TestInjectableApplication application; StepSensorChange stepSensorChange; @Before public void setUp() { application = (TestInjectableApplication) RuntimeEnvironment.application; CreatedActivity = Robolectric.buildActivity(MainActivity.class).create().postResume().get(); stepSensorChange = application.stepSensorChangeModule.provideStepSensorChange(); } @Test public void whenAStepCounterValueIsInjectedTheDisplayIsUpdated() { stepSensorChange.onSensorChanged(SensorValue.CreateSensorEvent(24)); assertThat(((TextView) CreatedActivity.findViewById(R.id.step_value)).getText().toString(), equalTo("23")); } }
Update usage of `migrate` subcommand.
package main import ( "errors" "fmt" ) var cmdMigrate = &Command{ Run: runMigrate, UsageLine: "migrate NEW_KEY_FILE", Short: "Regenerate data file", Long: `Regenerate data file with new key file.`, } // MigrateFileName is file name that created with migrate subcommand. const MigrateFileName = "spwd-migrated.dat" func runMigrate(ctx context, args []string) error { if len(args) == 0 { return errors.New("new key file is required") } cfg, err := GetConfig() if err != nil { return err } Initialize(cfg) key, err := GetKey(cfg.KeyFile) if err != nil { return err } is, err := LoadItems(key, cfg.DataFile) if err != nil { return err } if len(is) == 0 { fmt.Fprintln(ctx.out, "no password.") return nil } nkey, err := GetKey(args[0]) if err != nil { return err } err = is.Save(nkey, MigrateFileName) if err != nil { return err } PrintSuccess(ctx.out, "new data file saved as %s successfully", MigrateFileName) return nil }
package main import ( "errors" "fmt" ) var cmdMigrate = &Command{ Run: runMigrate, UsageLine: "migrate", Short: "Regenerate data file", Long: `Regenerate data file with new key file.`, } // MigrateFileName is file name that created with migrate subcommand. const MigrateFileName = "spwd-migrated.dat" func runMigrate(ctx context, args []string) error { if len(args) == 0 { return errors.New("new key file is required") } cfg, err := GetConfig() if err != nil { return err } Initialize(cfg) key, err := GetKey(cfg.KeyFile) if err != nil { return err } is, err := LoadItems(key, cfg.DataFile) if err != nil { return err } if len(is) == 0 { fmt.Fprintln(ctx.out, "no password.") return nil } nkey, err := GetKey(args[0]) if err != nil { return err } err = is.Save(nkey, MigrateFileName) if err != nil { return err } PrintSuccess(ctx.out, "new data file saved as %s successfully", MigrateFileName) return nil }
Add reminder to myself to to importlib fallback.
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
Fix typo in acme_challenge view (str.join() takes a single iterable, not *args)
from __future__ import absolute_import, unicode_literals from django.http import HttpResponse from django.views.generic import TemplateView from manifestos.models import Manifesto, Collection LETSENCRYPT_SECRET = 'RoqK1ZHN6384upsmMKbrJuxqaGNKcmJc5JApOy8qi8Y' def acme_challenge(request, key): resp = '.'.join((key, LETSENCRYPT_SECRET)) return HttpResponse(resp) class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['collection'] = Collection.objects.get(featured=True) return context class AboutTemplateView(TemplateView): template_name = 'about.html' class ContactTemplateView(TemplateView): template_name = 'contact.html' class NewsTemplateView(TemplateView): template_name = 'news.html' class ProjectsTemplateView(TemplateView): template_name = 'projects_we_like.html' class ResourcesTemplateView(TemplateView): template_name = 'resources.html'
from __future__ import absolute_import, unicode_literals from django.http import HttpResponse from django.views.generic import TemplateView from manifestos.models import Manifesto, Collection LETSENCRYPT_SECRET = 'RoqK1ZHN6384upsmMKbrJuxqaGNKcmJc5JApOy8qi8Y' def acme_challenge(request, key): resp = '.'.join(key, LETSENCRYPT_SECRET) return HttpResponse(resp) class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['collection'] = Collection.objects.get(featured=True) return context class AboutTemplateView(TemplateView): template_name = 'about.html' class ContactTemplateView(TemplateView): template_name = 'contact.html' class NewsTemplateView(TemplateView): template_name = 'news.html' class ProjectsTemplateView(TemplateView): template_name = 'projects_we_like.html' class ResourcesTemplateView(TemplateView): template_name = 'resources.html'
Simplify server start in main method
import com.sun.jersey.api.container.grizzly.GrizzlyServerFactory; import com.sun.jersey.api.core.PackagesResourceConfig; import javax.ws.rs.core.UriBuilder; import java.io.IOException; import java.net.URI; public class Main { private static final int DEFAULT_PORT = 9998; public static void main(String[] args) throws IOException { GrizzlyServerFactory.create(getBaseUri(), getResourceConfig()); } private static URI getBaseUri() { final int port = System.getenv("PORT") != null ? Integer.parseInt(System.getenv("PORT")) : DEFAULT_PORT; return UriBuilder.fromUri("http://localhost/").port(port).build(); } private static PackagesResourceConfig getResourceConfig() { return new PackagesResourceConfig("resources"); } }
import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.sun.grizzly.http.SelectorThread; import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory; public class Main { public static void main(String[] args) throws IOException { final String baseUri = "http://localhost:"+(System.getenv("PORT")!=null?System.getenv("PORT"):"9998")+"/"; final Map<String, String> initParams = new HashMap<String, String>(); initParams.put("com.sun.jersey.config.property.packages","resources"); System.out.println("Starting grizzly..."); SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams); System.out.println(String.format("Jersey started with WADL available at %sapplication.wadl.",baseUri, baseUri)); } }
Update magic constants test to use new test case.
<?php namespace Psy\Test\CodeCleaner; use Psy\CodeCleaner; use Psy\CodeCleaner\MagicConstantsPass; use PHPParser_Node_Name as Name; use PHPParser_Node_Scalar_DirConst as DirConstant; use PHPParser_Node_Scalar_FileConst as FileConstant; use PHPParser_Node_Expr_FuncCall as FunctionCall; use PHPParser_Node_Scalar_String as StringNode; class MagicConstantsPassTest extends CodeCleanerTestCase { private $pass; public function setUp() { $this->pass = new MagicConstantsPass; } /** * @dataProvider magicConstants */ public function testProcess($from, $to) { $stmts = $this->parse($from); $this->pass->process($stmts); $this->assertEquals($to, $this->prettyPrint($stmts)); } public function magicConstants() { return array( array('__DIR__;', 'getcwd();'), array('__FILE__;', "'';"), array('___FILE___;', "___FILE___;"), ); } }
<?php namespace Psy\Test\CodeCleaner; use Psy\CodeCleaner; use Psy\CodeCleaner\MagicConstantsPass; use PHPParser_Node_Name as Name; use PHPParser_Node_Scalar_DirConst as DirConstant; use PHPParser_Node_Scalar_FileConst as FileConstant; use PHPParser_Node_Expr_FuncCall as FunctionCall; use PHPParser_Node_Scalar_String as StringNode; class MagicConstantsPassTest extends \PHPUnit_Framework_TestCase { private $pass; public function setUp() { $this->pass = new MagicConstantsPass; } public function testProcess() { $stmts = array(new DirConstant); $this->pass->process($stmts); $this->assertEquals(array(new FunctionCall(new Name('getcwd'))), $stmts); $stmts = array(new FileConstant); $this->pass->process($stmts); $this->assertEquals(array(new StringNode('')), $stmts); } }
refactor: Add a new HTTP header managed by the gateway
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.common.http; /** * Gravitee specific HTTP header enumeration. * * @author Aurélien Bourdon (aurelien.bourdon at gmail.com) */ public enum GraviteeHttpHeader { /** * Response time used to compute the entire Policy chain, in ms. */ X_GRAVITEE_RESPONSE_TIME("X-Gravitee-ResponseTime"), /** * Key to access to an API through the Gravitee gateway. */ X_GRAVITEE_API_KEY("X-Gravitee-Api-Key"), /** * The name of the API handle by Gravitee gateway. * This header must always be set by the gateway. */ X_GRAVITEE_API_NAME("X-Gravitee-Api-Name"); private String headerKey; GraviteeHttpHeader(String headerKey) { this.headerKey = headerKey; } @Override public String toString() { return headerKey; } }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.common.http; /** * Gravitee specific HTTP header enumeration. * * @author Aurélien Bourdon (aurelien.bourdon at gmail.com) */ public enum GraviteeHttpHeader { /** * Response time used to compute the entire Policy chain, in ms. */ X_GRAVITEE_RESPONSE_TIME("X-Gravitee-ResponseTime"), /** * Key to access to an API through the Gravitee gateway. */ X_GRAVITEE_API_KEY("X-Gravitee-Api-Key"); private String headerKey; GraviteeHttpHeader(String headerKey) { this.headerKey = headerKey; } @Override public String toString() { return headerKey; } }
Check DB adapter before allowing it to be used.
function Store(options) { var Adapter = require('./db/' + options.adapter); this.adapter = new Adapter(options[options.adapter]); check(this.adapter, methods); } var check = function (adapter, methods) { methods.forEach(function (method) { if (!adapter[method]) throw new Error("DB adapter missing method: " + method); }); }; // Methods that should be supported by adaptors. var methods = [ 'connect', 'disconnect', 'setBin', 'setBinOwner', 'setBinPanel', 'getBin', 'getLatestBin', 'getLatestBinForUser', 'getBinsByUser', 'generateBinId', 'getUser', 'getUserByEmail', 'setUser', 'touchLogin', 'touchOwners', 'updateOwners', 'updateUserEmail', 'updateUserKey', 'upgradeUserKey', 'getUserByForgotToken', 'setForgotToken', 'expireForgotToken', 'expireForgotTokenByUser', 'reportBin', 'getAllOwners', 'getOwnersBlock', 'populateOwners' ]; // Proxy the methods through the store. methods.forEach(function (method) { Store.prototype[method] = function () { this.adapter[method].apply(this.adapter, arguments); }; }); module.exports = function createStore(options) { return new Store(options); }; module.exports.Store = Store;
function Store(options) { var Adapter = require('./db/' + options.adapter); this.adapter = new Adapter(options[options.adapter]); } // Methods that should be supported by adaptors. var methods = [ 'connect', 'disconnect', 'setBin', 'setBinOwner', 'setBinPanel', 'getBin', 'getLatestBin', 'getLatestBinForUser', 'getBinsByUser', 'generateBinId', 'getUser', 'getUserByEmail', 'setUser', 'touchLogin', 'touchOwners', 'updateOwners', 'updateUserEmail', 'updateUserKey', 'upgradeUserKey', 'getUserByForgotToken', 'setForgotToken', 'expireForgotToken', 'expireForgotTokenByUser', 'reportBin', 'getAllOwners', 'getOwnersBlock', 'populateOwners' ]; // Proxy the methods through the store. methods.forEach(function (method) { Store.prototype[method] = function () { this.adapter[method].apply(this.adapter, arguments); }; }); module.exports = function createStore(options) { return new Store(options); }; module.exports.Store = Store;
Update copy to clipboard style
import React, { Component } from 'react' import PropTypes from 'prop-types' import copy from 'copy-to-clipboard' import Text from 'v2/components/UI/Text' export default class CopyToClipboard extends Component { static propTypes = { value: PropTypes.string.isRequired, label: PropTypes.string.isRequired, copiedLabel: PropTypes.string, onClick: PropTypes.func, } static defaultProps = { onClick: () => {}, copiedLabel: 'Copied!', } constructor(props) { super(props) this.state = { currentLabel: props.label, } } copyToClipboard = () => { const { value, onClick, label, copiedLabel } = this.props copy(value) this.setState({ currentLabel: copiedLabel, }) setTimeout(() => { this.setState({ currentLabel: label, }) }, 2000) return onClick() } render() { const { currentLabel } = this.state return ( <a role="button" tabIndex={0} onClick={this.copyToClipboard} style={{ cursor: 'pointer' }} > <Text {...this.props}>{currentLabel}</Text> </a> ) } }
import React, { Component } from 'react' import PropTypes from 'prop-types' import copy from 'copy-to-clipboard' export default class CopyToClipboard extends Component { static propTypes = { value: PropTypes.string.isRequired, label: PropTypes.string.isRequired, copiedLabel: PropTypes.string, onClick: PropTypes.func, } static defaultProps = { onClick: () => {}, copiedLabel: 'Copied!', } constructor(props) { super(props) this.state = { currentLabel: props.label, } } copyToClipboard = () => { const { value, onClick, label, copiedLabel } = this.props copy(value) this.setState({ currentLabel: copiedLabel, }) setTimeout(() => { this.setState({ currentLabel: label, }) }, 2000) return onClick() } render() { const { currentLabel } = this.state return ( <a role="button" tabIndex={0} onClick={this.copyToClipboard}> {currentLabel} </a> ) } }
Move inspect function outside of constructor
'use strict'; var v8StyleErrors = require('./lib/v8-style')() var reformat = require('./lib/reformat') function defaultInspect() { return this.message ? '[' + this.name + ': ' + this.message + ']' : '[' + this.name + ']' } function ErrorMaker(name, ParentError) { function NewError(message) { if (!(this instanceof NewError)) return new NewError(message) // Use a try/catch block to capture the stack trace. Capturing the stack trace here is // necessary, otherwise we will get the stack trace at the time the new error class was created, // rather than when it is instantiated. We add `message` and `name` so that the stack trace // string will match our current error class. try { throw new Error(message) } catch (err) { err.name = name this.stack = err.stack } // if we have v8-styled stack messages and this.stack is defined, then reformat if (v8StyleErrors && this.stack) { this.stack = reformat(this.stack, name, message) } this.message = message || '' this.name = name } NewError.prototype = new (ParentError || Error)() NewError.prototype.constructor = NewError NewError.prototype.inspect = defaultInspect; NewError.prototype.name = name return NewError } module.exports = ErrorMaker
'use strict'; var v8StyleErrors = require('./lib/v8-style')() var reformat = require('./lib/reformat') function ErrorMaker(name, ParentError) { function NewError(message) { if (!(this instanceof NewError)) return new NewError(message) // Use a try/catch block to capture the stack trace. Capturing the stack trace here is // necessary, otherwise we will get the stack trace at the time the new error class was created, // rather than when it is instantiated. We add `message` and `name` so that the stack trace // string will match our current error class. try { throw new Error(message) } catch (err) { err.name = name this.stack = err.stack } // if we have v8-styled stack messages, then reformat if (v8StyleErrors) { if (this.stack) this.stack = reformat(this.stack, name, message) } this.message = message || '' this.name = name } NewError.prototype = new (ParentError || Error)() NewError.prototype.constructor = NewError NewError.prototype.inspect = function() { return this.message ? '[' + name + ': ' + this.message + ']' : '[' + name + ']' } NewError.prototype.name = name return NewError } module.exports = ErrorMaker
Add the ability for the mock model to have it's cast array updated
<?php class MockJsonModel extends Illuminate\Database\Eloquent\Model { use \ModelJsonColumn\JsonColumnTrait; protected $json_columns; public function __construct(array $attributes = []) { static::$booted[get_class($this)] = true; parent::__construct($attributes); } public function setJsonColumns(array $columns) { $this->json_columns = $columns; } public function setCastsColumns(array $columns) { $this->casts = $columns; } public function getCustomGetAttribute() { return 'custom getter result'; } public function setCustomSetAttribute($value) { $this->setJsonAttribute($this->jsonAttributes['custom_set'], 'custom_set', "custom {$value}"); } }
<?php class MockJsonModel extends Illuminate\Database\Eloquent\Model { use \ModelJsonColumn\JsonColumnTrait; protected $json_columns; public function __construct(array $attributes = []) { static::$booted[get_class($this)] = true; parent::__construct($attributes); } public function setJsonColumns(array $columns) { $this->json_columns = $columns; } public function getCustomGetAttribute() { return 'custom getter result'; } public function setCustomSetAttribute($value) { $this->setJsonAttribute($this->jsonAttributes['custom_set'], 'custom_set', "custom {$value}"); } }
Print container logs only in case of failed scenario
import time from itest_utils import wait_for_marathon from itest_utils import print_container_logs def before_all(context): wait_for_marathon() def after_scenario(context, scenario): """If a marathon client object exists in our context, delete any apps in Marathon and wait until they die.""" if scenario.status != 'passed': print "Zookeeper container logs:" print_container_logs('zookeeper') print "Marathon container logs:" print_container_logs('marathon') if context.client: while True: apps = context.client.list_apps() if not apps: break for app in apps: context.client.delete_app(app.id, force=True) time.sleep(0.5) while context.client.list_deployments(): time.sleep(0.5)
import time from itest_utils import wait_for_marathon from itest_utils import print_container_logs def before_all(context): wait_for_marathon() def after_scenario(context, scenario): """If a marathon client object exists in our context, delete any apps in Marathon and wait until they die.""" print_container_logs('zookeeper') print_container_logs('marathon') if context.client: while True: apps = context.client.list_apps() if not apps: break for app in apps: context.client.delete_app(app.id, force=True) time.sleep(0.5) while context.client.list_deployments(): time.sleep(0.5)
Update query for new trash handling
#!/usr/bin/env python # -*- coding: utf-8 -*- from pynux import utils from os.path import expanduser import collections import pprint pp = pprint.PrettyPrinter(indent=4) CHILD_NXQL = "SELECT * FROM Document WHERE ecm:parentId = '{}' AND " \ "ecm:isTrashed = 0 ORDER BY ecm:pos" nx = utils.Nuxeo(rcfile=open(expanduser('~/.pynuxrc'), 'r')) query = CHILD_NXQL.format('afa37e7d-051f-4fbc-a5b4-e83aa6171aef') uids = [] for child in nx.nxql(query): uids.append(child['uid']) #pp.pprint(uids) count = len(uids) dups = [item for item, count in collections.Counter(uids).items() if count > 1] #pp.pprint(dups) print len(uids) print len(dups)
#!/usr/bin/env python # -*- coding: utf-8 -*- from pynux import utils from os.path import expanduser import collections import pprint pp = pprint.PrettyPrinter(indent=4) CHILD_NXQL = "SELECT * FROM Document WHERE ecm:parentId = '{}' AND " \ "ecm:currentLifeCycleState != 'deleted' ORDER BY ecm:pos" nx = utils.Nuxeo(rcfile=open(expanduser('~/.pynuxrc'), 'r')) query = CHILD_NXQL.format('afa37e7d-051f-4fbc-a5b4-e83aa6171aef') uids = [] for child in nx.nxql(query): uids.append(child['uid']) #pp.pprint(uids) count = len(uids) dups = [item for item, count in collections.Counter(uids).items() if count > 1] #pp.pprint(dups) print len(uids) print len(dups)
Add missing usage and permissions assignments.
package com.campmongoose.serversaturday.spigot.command.sscommand.submit; import com.campmongoose.serversaturday.common.Reference.Commands; import com.campmongoose.serversaturday.common.Reference.Messages; import com.campmongoose.serversaturday.common.Reference.Permissions; import com.campmongoose.serversaturday.spigot.command.AbstractSpigotCommand; import com.campmongoose.serversaturday.spigot.command.SpigotCommandArgument; import com.campmongoose.serversaturday.spigot.command.SpigotCommandPermissions; import com.campmongoose.serversaturday.spigot.command.SpigotCommandUsage; import java.util.Collections; import org.bukkit.ChatColor; import org.bukkit.entity.Player; public class SSGetRewards extends AbstractSpigotCommand { public SSGetRewards() { super(Commands.GET_REWARDS_NAME, Commands.GET_REWARDS_DESC); usage = new SpigotCommandUsage(Collections.singletonList(new SpigotCommandArgument(Commands.SS_CMD + Commands.GOTO_NAME))); permissions = new SpigotCommandPermissions(Permissions.VIEW_GOTO, false); executor = (sender, args) -> { getPluginInstance().getRewardGiver().givePlayerReward((Player) sender); sender.sendMessage(ChatColor.GOLD + Messages.REWARDS_GIVEN); return true; }; } }
package com.campmongoose.serversaturday.spigot.command.sscommand.submit; import com.campmongoose.serversaturday.common.Reference.Commands; import com.campmongoose.serversaturday.common.Reference.Messages; import com.campmongoose.serversaturday.spigot.command.AbstractSpigotCommand; import org.bukkit.ChatColor; import org.bukkit.entity.Player; public class SSGetRewards extends AbstractSpigotCommand { public SSGetRewards() { super(Commands.GET_REWARDS_NAME, Commands.GET_REWARDS_DESC); executor = (sender, args) -> { getPluginInstance().getRewardGiver().givePlayerReward((Player) sender); sender.sendMessage(ChatColor.GOLD + Messages.REWARDS_GIVEN); return true; }; } }
Fix comment to make more sense
package com.haxademic.core.system; import processing.core.PApplet; import processing.opengl.PGL; import com.haxademic.core.app.P; public class SystemUtil { public static String getJavaVersion() { return System.getProperty("java.version"); } public static String getTimestamp( PApplet p ) { // use P.nf to pad date components to 2 digits for more consistent ordering across systems return String.valueOf( P.year() ) + "-" + P.nf( P.month(), 2 ) + "-" + P.nf( P.day(), 2 ) + "-" + P.nf( P.hour(), 2 ) + "-" + P.nf( P.minute(), 2 ) + "-" + P.nf( P.second(), 2 ); } public static String getTimestampFine( PApplet p ) { return SystemUtil.getTimestamp(p) + "-" + P.nf( p.frameCount, 8 ); } // Patch TAB capture ability - Processing 2.0 broke this in 3D rendering contexts public static void p2TabKeyInputPatch() { if(PGL.canvas != null) { PGL.canvas.setFocusTraversalKeysEnabled(false); } } }
package com.haxademic.core.system; import processing.core.PApplet; import processing.opengl.PGL; import com.haxademic.core.app.P; public class SystemUtil { public static String getJavaVersion() { return System.getProperty("java.version"); } public static String getTimestamp( PApplet p ) { // use P.nf to pad date components to 2 digits for more consistent ordering across systems return String.valueOf( P.year() ) + "-" + P.nf( P.month(), 2 ) + "-" + P.nf( P.day(), 2 ) + "-" + P.nf( P.hour(), 2 ) + "-" + P.nf( P.minute(), 2 ) + "-" + P.nf( P.second(), 2 ); } public static String getTimestampFine( PApplet p ) { return SystemUtil.getTimestamp(p) + "-" + P.nf( p.frameCount, 8 ); } // monkey-patch TAB capture ability - Processing 2.0 broke this in 3D rendering contexts public static void p2TabKeyInputPatch() { if(PGL.canvas != null) { PGL.canvas.setFocusTraversalKeysEnabled(false); } } }
Make invokeProcess() available to children AbstractInvokable Middleware will be able to more easily use composition of middleware within their process() methods if we allow invokeProcess() to be ran.
<?php namespace Lstr\Sprintf\Middleware; abstract class AbstractInvokable { /** * @var AbstractInvokable|null */ private $invokable; /** * @param AbstractInvokable|null $invokable */ public function __construct(AbstractInvokable $invokable = null) { $this->invokable = $invokable; } /** * @param string $name * @param callable $values * @param array $options * @return mixed */ public function __invoke($name, callable $values, array $options) { $params = new InvokableParams($name, $values, $options); $this->invokeProcess($params); $values_callback = $params->getValuesCallback(); return $values_callback($params->getName()); } /** * @param InvokableParams $params */ abstract protected function process(InvokableParams $params); /** * @param InvokableParams $params */ protected function invokeProcess(InvokableParams $params) { if ($this->invokable) { call_user_func([$this->invokable, 'invokeProcess'], $params); } $this->process($params); } }
<?php namespace Lstr\Sprintf\Middleware; abstract class AbstractInvokable { /** * @var AbstractInvokable|null */ private $invokable; /** * @param AbstractInvokable|null $invokable */ public function __construct(AbstractInvokable $invokable = null) { $this->invokable = $invokable; } /** * @param string $name * @param callable $values * @param array $options * @return mixed */ public function __invoke($name, callable $values, array $options) { $params = new InvokableParams($name, $values, $options); $this->invokeProcess($params); $values_callback = $params->getValuesCallback(); return $values_callback($params->getName()); } /** * @param InvokableParams $params */ abstract protected function process(InvokableParams $params); /** * @param InvokableParams $params */ private function invokeProcess(InvokableParams $params) { if ($this->invokable) { call_user_func([$this->invokable, 'invokeProcess'], $params); } $this->process($params); } }
Use `kebabeCase` instead of lowerCase * Because lowerCase converts `null piece` from `NullPiece`, but kebabCase converts `null-piece` from `NullPiece`. * this method is called for css class name, so more recommendable kebabeCase.
import React from 'react'; import { movePiece } from '../actions'; import { connect } from 'react-redux'; import _ from 'lodash'; const mapStateToProps = (state) => { return { board: state.board, turn: state.turn }; }; const mapDispatchToProps = (dispatch) => { return { onPieceClick: (board, piece) => { dispatch(movePiece(board, piece)); } }; }; export default class ShogiPiece extends React.Component { render() { var className = _.kebabCase(this.props.piece.constructor.name); return( <div className={className} onClick={() => this.props.onPieceClick(this.props.board, this.props.piece)}> <span>{this.props.piece.type}</span> </div> ); } } const Piece = connect( mapStateToProps, mapDispatchToProps )(ShogiPiece); export default Piece;
import React from 'react'; import { movePiece } from '../actions'; import { connect } from 'react-redux'; import _ from 'lodash'; const mapStateToProps = (state) => { return { board: state.board, turn: state.turn }; }; const mapDispatchToProps = (dispatch) => { return { onPieceClick: (board, piece) => { dispatch(movePiece(board, piece)); } }; }; export default class ShogiPiece extends React.Component { render() { var className = _.lowerCase(this.props.piece.constructor.name); return( <div className={className} onClick={() => this.props.onPieceClick(this.props.board, this.props.piece)}> <span>{this.props.piece.type}</span> </div> ); } } const Piece = connect( mapStateToProps, mapDispatchToProps )(ShogiPiece); export default Piece;
Remove uwsgi support, add support for simple alternative responses
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import flask RESPONSE_CODE = 200 app = flask.Flask(__name__) @app.route('/') def hello(): global RESPONSE_CODE if RESPONSE_CODE == 200: return 'Hi!\n' else: flask.abort(RESPONSE_CODE) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-b', '--bind-address', dest='bind', default='127.0.0.1') parser.add_argument('-p', '--port', dest='port', default=4000, type=int) parser.add_argument('-c', '--response_code', dest='code', default=200, type=int) return parser.parse_args() def main(): global RESPONSE_CODE opts = parse_args() RESPONSE_CODE = opts.code app.run(host=opts.bind, port=opts.port) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hi!\n' def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-b', '--bind-address', dest='bind', default='127.0.0.1') parser.add_argument('-p', '--port', dest='port', default=4000, type=int) return parser.parse_args() def main(): opts = parse_args() app.run(host=opts.bind, port=opts.port) # Support for uWSGI def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Hi!\n'] if __name__ == "__main__": main()
Set homepage to first semester fysmat
"""kokekunster URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from semesterpage.views import semester urlpatterns = [ url(r'^$', semester, {'program_code': 'mtfyma', 'semester_number': 1}), url(r'^admin/', include(admin.site.urls)), url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester), ]
"""kokekunster URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from semesterpage.views import semester urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^(\w{3,6})/semester/([1-9]|10)/$', semester), ]