text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix IllegalArgumentException in Random.nextInt (thanks to Prabakar)
/* * Copyright 2012 JBoss 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. */ package org.drools.planner.core.heuristic.selector.common.iterator; import java.util.Iterator; import java.util.List; import java.util.Random; /** * This {@link Iterator} does not shuffle and is never ending. * @param <S> */ public class CachedListRandomIterator<S> implements Iterator<S> { protected final List<S> cachedList; protected final Random workingRandom; protected final boolean notEmpty; public CachedListRandomIterator(List<S> cachedList, Random workingRandom) { this.cachedList = cachedList; this.workingRandom = workingRandom; notEmpty = !cachedList.isEmpty(); } public boolean hasNext() { return notEmpty; } public S next() { int index = workingRandom.nextInt(cachedList.size()); return cachedList.get(index); } public void remove() { throw new UnsupportedOperationException("Remove is not supported."); } }
/* * Copyright 2012 JBoss 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. */ package org.drools.planner.core.heuristic.selector.common.iterator; import java.util.Iterator; import java.util.List; import java.util.Random; /** * This {@link Iterator} does not shuffle and is never ending. * @param <S> */ public class CachedListRandomIterator<S> implements Iterator<S> { protected final List<S> cachedList; protected final Random workingRandom; public CachedListRandomIterator(List<S> cachedList, Random workingRandom) { this.cachedList = cachedList; this.workingRandom = workingRandom; } public boolean hasNext() { return true; } public S next() { int index = workingRandom.nextInt(cachedList.size()); return cachedList.get(index); } public void remove() { throw new UnsupportedOperationException("Remove is not supported."); } }
Revert back to FontAwesome 4.6.3 Test to show how to use GitHub
<?php // Register Style function sherpa_styles() { // We are going to defer loading our styles until after WooCommerce has loaded its styles IF WooCommerce exists if(function_exists('is_woocommerce')) { $main_css_deps = array('woocommerce-layout'); } else { $main_css_deps = FALSE; } wp_register_style( 'main_css', get_stylesheet_directory_uri() . '/css/style.css', $main_css_deps, '1.0', 'all' ); wp_enqueue_style( 'main_css' ); wp_register_style( 'font_awesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css', false, '4.6.3', 'all' ); wp_enqueue_style( 'font_awesome' ); } // Hook into the 'wp_enqueue_scripts' action add_action( 'wp_enqueue_scripts', 'sherpa_styles' ); ?>
<?php // Register Style function sherpa_styles() { // We are going to defer loading our styles until after WooCommerce has loaded its styles IF WooCommerce exists if(function_exists('is_woocommerce')) { $main_css_deps = array('woocommerce-layout'); } else { $main_css_deps = FALSE; } wp_register_style( 'main_css', get_stylesheet_directory_uri() . '/css/style.css', $main_css_deps, '1.0', 'all' ); wp_enqueue_style( 'main_css' ); wp_register_style( 'font_awesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css', false, '4.6.2', 'all' ); wp_enqueue_style( 'font_awesome' ); } // Hook into the 'wp_enqueue_scripts' action add_action( 'wp_enqueue_scripts', 'sherpa_styles' ); ?>
Add ability to force reload the pulls
import React from 'react'; import _ from 'lodash'; import Icon from './Icon'; class AccountBar extends React.Component { handleClick = (e) => { var currentTarget = e.currentTarget; this.props.setDisplayView(currentTarget.dataset.displayType); } render() { var props = this.props; var buttons = 'compact cozy comfortable'.split(' ').map( (item, index) => { var btnClassName = `btn btn-default ${props.config.view === item ? 'active' : ''}`; var iconClassName = `icon-monospaced display-${item}-icon`; return <a className={btnClassName} href="javascript:;" data-display-type={item} key={index} onClick={this.handleClick} title={_.capitalize(item)}> <Icon className={iconClassName} name="list-ul" /> </a>; } ); return <div className="management-bar management-bar-default"> <div className="container-fluid-1280 app-column"> <ul className="management-bar-nav nav"> <li> <a href="javascript:;" onClick={(e) => {props.loadPulls();}}> <Icon className="icon-monospaced" name="reload" /> Reload Pulls </a> </li> </ul> <div className="management-bar-header-right"> {buttons} </div> </div> </div>; } } export default AccountBar;
import React from 'react'; import _ from 'lodash'; import Icon from './Icon'; class AccountBar extends React.Component { handleClick = (e) => { var currentTarget = e.currentTarget; this.props.setDisplayView(currentTarget.dataset.displayType); } render() { var props = this.props; var buttons = 'compact cozy comfortable'.split(' ').map( (item, index) => { var btnClassName = `btn btn-default ${props.config.view === item ? 'active' : ''}`; var iconClassName = `icon-monospaced display-${item}-icon`; return <a className={btnClassName} href="javascript:;" data-display-type={item} key={index} onClick={this.handleClick} title={_.capitalize(item)}> <Icon className={iconClassName} name="list-ul" /> </a>; } ); // console.log(this.props); return <div className="management-bar management-bar-default"> <div className="container-fluid-1280 app-column"> <div className="management-bar-header-right"> {buttons} </div> </div> </div>; } } export default AccountBar;
Update the number of components listed in the model.
import os import unittest import opensim as osim test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)), 'tests') # Silence warning messages if mesh (.vtp) files cannot be found. osim.Model.setDebugLevel(0) class TestComponentInterface(unittest.TestCase): def test_printComponentsMatching(self): model = osim.Model(os.path.join(test_dir, "gait10dof18musc_subject01.osim")) model.finalizeFromProperties(); num_matches = model.printComponentsMatching("_r") self.assertEquals(num_matches, 126) def test_attachGeometry_memory_management(self): model = osim.Model() model.getGround().attachGeometry(osim.Sphere(1.5))
import os import unittest import opensim as osim test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)), 'tests') # Silence warning messages if mesh (.vtp) files cannot be found. osim.Model.setDebugLevel(0) class TestComponentInterface(unittest.TestCase): def test_printComponentsMatching(self): model = osim.Model(os.path.join(test_dir, "gait10dof18musc_subject01.osim")) model.finalizeFromProperties(); num_matches = model.printComponentsMatching("_r") self.assertEquals(num_matches, 98) def test_attachGeometry_memory_management(self): model = osim.Model() model.getGround().attachGeometry(osim.Sphere(1.5))
Change str() of Category for easier form handling
from django.db import models from django.conf import settings class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) name = models.CharField(max_length=21) row_number = models.IntegerField(default=0) column_number = models.IntegerField(default=0) progress_bar_color = models.CharField(max_length=6, default="335544") # hidden = models.BooleanField(default=False) # trash = models.BooleanField(default=False) def __str__(self): return str(self.name) class Bookmark(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=50) link = models.TextField() row_number = models.IntegerField(default=0) glyphicon = models.CharField(max_length=30, default="asterisk") def __str__(self): return str(self.category) + ' ' + str(self.name) class Trash(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=50) link = models.TextField() glyphicon = models.CharField(max_length=30) def __str__(self): return str(self.category) + ' ' + str(self.name)
from django.db import models from django.conf import settings class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) name = models.CharField(max_length=21) row_number = models.IntegerField(default=0) column_number = models.IntegerField(default=0) progress_bar_color = models.CharField(max_length=6, default="335544") # hidden = models.BooleanField(default=False) # trash = models.BooleanField(default=False) def __str__(self): return str(self.user) + ' ' + str(self.name) class Bookmark(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=50) link = models.TextField() row_number = models.IntegerField(default=0) glyphicon = models.CharField(max_length=30, default="asterisk") def __str__(self): return str(self.category) + ' ' + str(self.name) class Trash(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=50) link = models.TextField() glyphicon = models.CharField(max_length=30) def __str__(self): return str(self.category) + ' ' + str(self.name)
Add lang to `html` tag h/t shivampaw
<!doctype html> <html amp <?php language_attributes(); ?>> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"> <?php do_action( 'amp_post_template_head', $this ); ?> <style amp-custom> <?php $this->load_parts( array( 'style' ) ); ?> <?php do_action( 'amp_post_template_css', $this ); ?> </style> </head> <body> <?php $this->load_parts( array( 'header-bar' ) ); ?> <div class="amp-wp-content"> <h1 class="amp-wp-title"><?php echo wp_kses_data( $this->get( 'post_title' ) ); ?></h1> <ul class="amp-wp-meta"> <?php $this->load_parts( apply_filters( 'amp_post_template_meta_parts', array( 'meta-author', 'meta-time', 'meta-taxonomy' ) ) ); ?> </ul> <?php echo $this->get( 'post_amp_content' ); // amphtml content; no kses ?> </div> <?php do_action( 'amp_post_template_footer', $this ); ?> </body> </html>
<!doctype html> <html amp> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"> <?php do_action( 'amp_post_template_head', $this ); ?> <style amp-custom> <?php $this->load_parts( array( 'style' ) ); ?> <?php do_action( 'amp_post_template_css', $this ); ?> </style> </head> <body> <?php $this->load_parts( array( 'header-bar' ) ); ?> <div class="amp-wp-content"> <h1 class="amp-wp-title"><?php echo wp_kses_data( $this->get( 'post_title' ) ); ?></h1> <ul class="amp-wp-meta"> <?php $this->load_parts( apply_filters( 'amp_post_template_meta_parts', array( 'meta-author', 'meta-time', 'meta-taxonomy' ) ) ); ?> </ul> <?php echo $this->get( 'post_amp_content' ); // amphtml content; no kses ?> </div> <?php do_action( 'amp_post_template_footer', $this ); ?> </body> </html>
Fix make plugin global after API change
export {Utilities} from './validation/utilities'; export {ValidationConfig} from './validation/validation-config'; export {ValidationLocale} from './validation/validation-locale'; export * from './validation/validation-result'; export * from './validation/validation-rules'; export {Validation} from './validation/validation'; export {ValidateCustomAttribute} from './validation/validate-custom-attribute'; export {ValidateCustomAttributeViewStrategy} from './validation/validate-custom-attribute-view-strategy'; export {ValidateCustomAttributeViewStrategyBase} from './validation/validate-custom-attribute-view-strategy'; export {ensure} from './validation/decorators'; import {ValidationConfig} from './validation/validation-config'; import {Validation} from './validation/validation'; export function configure(aurelia, configCallback) { aurelia.globalResources('./validation/validate-custom-attribute'); if(configCallback !== undefined && typeof(configCallback) === 'function') { configCallback(Validation.defaults); } aurelia.singleton(ValidationConfig, Validation.defaults); return Validation.defaults.locale(); }
export {Utilities} from './validation/utilities'; export {ValidationConfig} from './validation/validation-config'; export {ValidationLocale} from './validation/validation-locale'; export * from './validation/validation-result'; export * from './validation/validation-rules'; export {Validation} from './validation/validation'; export {ValidateCustomAttribute} from './validation/validate-custom-attribute'; export {ValidateCustomAttributeViewStrategy} from './validation/validate-custom-attribute-view-strategy'; export {ValidateCustomAttributeViewStrategyBase} from './validation/validate-custom-attribute-view-strategy'; export {ensure} from './validation/decorators'; import {ValidationConfig} from './validation/validation-config'; import {Validation} from './validation/validation'; export function configure(aurelia, configCallback) { aurelia.globalizeResources('./validation/validate-custom-attribute'); if(configCallback !== undefined && typeof(configCallback) === 'function') { configCallback(Validation.defaults); } aurelia.withSingleton(ValidationConfig, Validation.defaults); return Validation.defaults.locale(); }
Work around NaN, Infinity and -Infinity.
/* * ASCII sparklines. */ (function(root) { var ticks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']; var spark = function (ints) { // Ignore impossible numbers when making graphs var pureNumbers = ints.filter(function (num) { return (!isNaN(num)) && (!(num === Infinity || num === -Infinity)); }); // Find min and max var max = Math.max.apply(null, pureNumbers), min = Math.min.apply(null, pureNumbers); // Convert to chars var steps = ints.map(function (tick) { if (isNaN(tick)) { return " "; } if (tick === Infinity || tick === -Infinity) { return "∞"; } var index = Math.round((tick - min) / max * (ticks.length -1)); return ticks[index]; }); return steps.join(""); } if(typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { module.exports = spark; } exports.spark = spark; } else { root.spark = spark; } })(this || window);
/* * ASCII sparklines. */ (function(root) { var ticks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']; var spark = function (ints) { var max = Math.max.apply(null, ints), min = Math.min.apply(null, ints); var steps = ints.map(function (tick) { var index = Math.round((tick - min) / max * (ticks.length -1)); return ticks[index]; }); return steps.join(""); } if(typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { module.exports = spark; } exports.spark = spark; } else { root.spark = spark; } })(this || window);
Allow quality to be configurable In images with few colors (such as a 4-color palette), a high value would remove most of the detail, resulting in a nearly flat/blank image.
var GifEncoder = require("gif-encoder") var concat = require("terminus").concat module.exports = writegif // something with GifEncoder isn't correctly resetting the // state of backpressure it seems like? var hwm = 128 * 100 * 1024 // HUGE function writegif(image, opts, callback) { if (!callback) { callback = opts; opts = {}; } var out = concat(function (buffer) { callback(null, buffer) }) var gif = new GifEncoder(image.width, image.height, {highWaterMark: hwm}) gif.pipe(out) gif.writeHeader() // default = 10, 200 is maybe a bit smaller sometimes gif.setQuality(opts.quality || 200) if (image.frames.length > 1) { gif.setRepeat(0) } image.frames.forEach(function (frame) { if (frame.delay) { gif.setDelay(frame.delay) } gif.addFrame(frame.data) }) gif.finish() }
var GifEncoder = require("gif-encoder") var concat = require("terminus").concat module.exports = writegif // something with GifEncoder isn't correctly resetting the // state of backpressure it seems like? var hwm = 128 * 100 * 1024 // HUGE // default = 10, 200 is maybe a bit smaller sometimes var quality = 200 function writegif(image, callback) { var out = concat(function (buffer) { callback(null, buffer) }) var gif = new GifEncoder(image.width, image.height, {highWaterMark: hwm}) gif.pipe(out) gif.writeHeader() gif.setQuality(quality) if (image.frames.length > 1) { gif.setRepeat(0) } image.frames.forEach(function (frame) { if (frame.delay) { gif.setDelay(frame.delay) } gif.addFrame(frame.data) }) gif.finish() }
Fix previous commit for IE7-8
/* jshint loopfunc: true*/ var has = require('has'); var classic = require('classic'); var spipe = require('./index'); var slice = Array.prototype.slice; module.exports = function createChainable(functionMap) { function Chainable() { var tgt = this; if (!(tgt instanceof Chainable)) tgt = new Chainable(); tgt._pipeline = spipe.apply(null, slice.call(arguments)); return tgt; } for (var k in functionMap) { if (!has(functionMap, k)) continue; Chainable.prototype[k] = (function(name, fn) { return function() { this._pipeline.apply(null, [fn].concat(slice.call(arguments))); return this; }; })(k, functionMap[k]); } Chainable.prototype.end = function(eager) { return this._pipeline(eager); }; return Chainable; };
/* jshint loopfunc: true*/ var has = require('has'); var classic = require('classic'); var spipe = require('./index'); var slice = Array.prototype.slice; module.exports = function createChainable(functionMap) { return classic(function() { this.constructor = function Chainable() { var tgt = this; if (!(tgt instanceof Chainable)) tgt = new Chainable(); tgt._pipeline = spipe.apply(null, slice.call(arguments)); return tgt; }; for (var k in functionMap) { if (!has(functionMap, k)) continue; this[k] = (function(name, fn) { return function() { this._pipeline.apply(null, [fn].concat(slice.call(arguments))); return this; }; })(k, functionMap[k]); } this.end = function(eager) { return this._pipeline(eager); }; }); };
Use README.rst and CHANGES.rst for description
from setuptools import setup, find_packages long_description = open('README.rst').read() + open('CHANGES.rst').read() setup( name='django-simple-history', version='1.1.3.post1', description='Store model history and view/revert changes from admin site.', long_description=long_description, author='Corey Bertram', author_email='corey@qr7.com', mantainer='Trey Hunner', url='https://github.com/treyhunner/django-simple-history', packages=find_packages(), classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: Django", "Environment :: Web Environment", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "License :: OSI Approved :: BSD License", ], tests_require=["Django>=1.3", "webtest", "django-webtest"], test_suite='runtests.main', )
from setuptools import setup, find_packages setup( name='django-simple-history', version='1.1.3.post1', description='Store model history and view/revert changes from admin site.', author='Corey Bertram', author_email='corey@qr7.com', mantainer='Trey Hunner', url='https://github.com/treyhunner/django-simple-history', packages=find_packages(), classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: Django", "Environment :: Web Environment", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "License :: OSI Approved :: BSD License", ], tests_require=["Django>=1.3", "webtest", "django-webtest"], test_suite='runtests.main', )
Fix Query does not exist Fix "Class PackageClass\Property\Search\Query does not exist" does not exist from custom SavedSearch
<?php namespace Concrete\Core\Entity\Search; use Doctrine\ORM\Mapping as ORM; /** * @ORM\MappedSuperClass */ abstract class SavedSearch { /** @ORM\Embedded(class = "\Concrete\Core\Entity\Search\Query") */ protected $query = null; /** * @ORM\Column(type="string") */ protected $presetName; /** * @return mixed */ public function getID() { return $this->id; } /** * @return mixed */ public function getPresetName() { return $this->presetName; } /** * @param mixed $presetName */ public function setPresetName($presetName) { $this->presetName = $presetName; } /** * @return mixed */ public function getQuery() { return $this->query; } /** * @param mixed $query */ public function setQuery($query) { $this->query = $query; } }
<?php namespace Concrete\Core\Entity\Search; use Doctrine\ORM\Mapping as ORM; /** * @ORM\MappedSuperClass */ abstract class SavedSearch { /** @ORM\Embedded(class = "Query") */ protected $query = null; /** * @ORM\Column(type="string") */ protected $presetName; /** * @return mixed */ public function getID() { return $this->id; } /** * @return mixed */ public function getPresetName() { return $this->presetName; } /** * @param mixed $presetName */ public function setPresetName($presetName) { $this->presetName = $presetName; } /** * @return mixed */ public function getQuery() { return $this->query; } /** * @param mixed $query */ public function setQuery($query) { $this->query = $query; } }
Replace local copy of TimerMixin with module from npm. Reviewed By: spicyj, davidaurelio Differential Revision: D3819543 fbshipit-source-id: 69d68a7653fce05a31cbfd61e48878b7a0a2ab51
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LazyRenderer */ 'use strict'; var React = require('React'); var TimerMixin = require('react-timer-mixin'); var LazyRenderer = React.createClass({ mixin: [TimerMixin], propTypes: { render: React.PropTypes.func.isRequired, }, componentWillMount: function(): void { this.setState({ _lazyRender : true, }); }, componentDidMount: function(): void { requestAnimationFrame(() => { this.setState({ _lazyRender : false, }); }); }, render: function(): ?ReactElement { return this.state._lazyRender ? null : this.props.render(); }, }); module.exports = LazyRenderer;
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LazyRenderer */ 'use strict'; var React = require('React'); var TimerMixin = require('TimerMixin'); var LazyRenderer = React.createClass({ mixin: [TimerMixin], propTypes: { render: React.PropTypes.func.isRequired, }, componentWillMount: function(): void { this.setState({ _lazyRender : true, }); }, componentDidMount: function(): void { requestAnimationFrame(() => { this.setState({ _lazyRender : false, }); }); }, render: function(): ?ReactElement { return this.state._lazyRender ? null : this.props.render(); }, }); module.exports = LazyRenderer;
Remove line breaks after each mod response
<?php $modResponses = "data/modResponses.js"; $jsonData = $_POST['data']; if (is_writable($modResponses)) { if (!$handle = fopen($modResponses, 'a')) { echo 'Cannot open file ($modResponses).'; exit; } if (isset($_POST['data'])) { if (fwrite($handle, $jsonData) === FALSE) { echo 'Cannot write to file ($modResponses).'; exit; } else { fwrite($handle, ","); } } echo 'Success! Wrote ($jsonData) to file ($modResponses).'; fclose($handle); } else { echo 'The file $modResponses is not writable.'; } ?>
<?php $modResponses = "data/modResponses.js"; $jsonData = $_POST['data']; if (is_writable($modResponses)) { if (!$handle = fopen($modResponses, 'a')) { echo 'Cannot open file ($modResponses).'; exit; } if (isset($_POST['data'])) { if (fwrite($handle, $jsonData) === FALSE) { echo 'Cannot write to file ($modResponses).'; exit; } else { fwrite($handle, ",\n"); } } echo 'Success! Wrote ($jsonData) to file ($modResponses).'; fclose($handle); } else { echo 'The file $modResponses is not writable.'; } ?>
Add comments to getApp for autocomplete
<?php class Infusionsoft_AppPool{ static protected $apps = array(); public function __construct(){ } /** * @param string $appHostname * @return Infusionsoft_App */ public static function getApp($appHostname = ''){ $appKey = strtolower($appHostname); if($appKey == '') $appKey = 'default'; if(array_key_exists($appKey, self::$apps)){ return self::$apps[$appKey]; } else{ return null; } } public static function addApp($app, $appKey = null){ if(count(self::$apps) == 0){ self::$apps['default'] = $app; } if($appKey == null){ $appKey = $app->getHostname(); } self::$apps[$appKey] = $app; return $app; } public static function clearApps(){ self::$apps = array(); } }
<?php class Infusionsoft_AppPool{ static protected $apps = array(); public function __construct(){ } public static function getApp($appHostname = ''){ $appKey = strtolower($appHostname); if($appKey == '') $appKey = 'default'; if(array_key_exists($appKey, self::$apps)){ return self::$apps[$appKey]; } else{ return null; } } public static function addApp($app, $appKey = null){ if(count(self::$apps) == 0){ self::$apps['default'] = $app; } if($appKey == null){ $appKey = $app->getHostname(); } self::$apps[$appKey] = $app; return $app; } public static function clearApps(){ self::$apps = array(); } }
Convert class based template compilation plugin to functional style
'use strict'; /* eslint-env node */ let TEST_SELECTOR_PREFIX = /data-test-.*/; function isTestSelector(attribute) { return TEST_SELECTOR_PREFIX.test(attribute); } function stripTestSelectors(node) { node.params = node.params.filter(function(param) { return !isTestSelector(param.original); }); node.hash.pairs = node.hash.pairs.filter(function(pair) { return !isTestSelector(pair.key); }); } function transform() { return { name: 'strip-test-selectors', visitor: { ElementNode(node) { node.attributes = node.attributes.filter(function(attribute) { return !isTestSelector(attribute.name); }); }, MustacheStatement(node) { stripTestSelectors(node); }, BlockStatement(node) { stripTestSelectors(node); }, } }; } module.exports = transform;
'use strict'; /* eslint-env node */ let TEST_SELECTOR_PREFIX = /data-test-.*/; function isTestSelector(attribute) { return TEST_SELECTOR_PREFIX.test(attribute); } function stripTestSelectors(node) { node.params = node.params.filter(function(param) { return !isTestSelector(param.original); }); node.hash.pairs = node.hash.pairs.filter(function(pair) { return !isTestSelector(pair.key); }); } function StripTestSelectorsTransform() { this.syntax = null; } StripTestSelectorsTransform.prototype.transform = function(ast) { let { traverse } = this.syntax; traverse(ast, { ElementNode(node) { node.attributes = node.attributes.filter(function(attribute) { return !isTestSelector(attribute.name); }); }, MustacheStatement(node) { stripTestSelectors(node); }, BlockStatement(node) { stripTestSelectors(node); }, }); return ast; }; module.exports = StripTestSelectorsTransform;
Add support for mingw-linux toolchains
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. """ Builder for Windows x86 """ from SCons.Script import AlwaysBuild, Default, DefaultEnvironment from platformio.util import get_systype env = DefaultEnvironment() env.Replace( AR="$_MINGWPREFIX-ar", AS="$_MINGWPREFIX-as", CC="$_MINGWPREFIX-gcc", CXX="$_MINGWPREFIX-g++", OBJCOPY="$_MINGWPREFIX-objcopy", RANLIB="$_MINGWPREFIX-ranlib", SIZETOOL="$_MINGWPREFIX-size", SIZEPRINTCMD='"$SIZETOOL" $SOURCES', PROGSUFFIX=".exe" ) if get_systype() == "darwin_x86_64": env.Replace( _MINGWPREFIX="i586-mingw32" ) elif get_systype() in ("linux_x86_64", "linux_i686"): env.Replace( _MINGWPREFIX="i686-w64-mingw32" ) # # Target: Build executable program # target_bin = env.BuildProgram() # # Target: Print binary size # target_size = env.Alias("size", target_bin, "$SIZEPRINTCMD") AlwaysBuild(target_size) # # Target: Define targets # Default([target_bin])
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. """ Builder for Windows x86 """ from SCons.Script import AlwaysBuild, Default, DefaultEnvironment from platformio.util import get_systype env = DefaultEnvironment() env.Replace( SIZEPRINTCMD="size $SOURCES", PROGSUFFIX=".exe" ) if get_systype() == "darwin_x86_64": env.Replace( AR="i586-mingw32-ar", AS="i586-mingw32-as", CC="i586-mingw32-gcc", CXX="i586-mingw32-g++", OBJCOPY="i586-mingw32-objcopy", RANLIB="i586-mingw32-ranlib", SIZETOOL="i586-mingw32-size", SIZEPRINTCMD='"$SIZETOOL" $SOURCES' ) # # Target: Build executable program # target_bin = env.BuildProgram() # # Target: Print binary size # target_size = env.Alias("size", target_bin, "$SIZEPRINTCMD") AlwaysBuild(target_size) # # Target: Define targets # Default([target_bin])
Add hints column in challenge model
# -*- coding: utf-8 -*- from hodor import db from sqlalchemy import inspect class Challenges(db.Model): __tablename__= 'challenges' #Data variables for each challenge chall_id=db.Column(db.String(32), primary_key=True,unique=True,nullable=False) name = db.Column(db.String(32), nullable=False) points = db.Column(db.Integer, nullable=False) description = db.Column(db.String(2048), nullable=False) hints=db.Column(db.String(512), nullable=False) @staticmethod def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def get_all(): return Challenges.query.all()
# -*- coding: utf-8 -*- from hodor import db from sqlalchemy import inspect class Challenges(db.Model): __tablename__= 'challenges' #Data variables for each Challenges chalid=db.Column(db.String(32), primary_key=True,unique=True,nullable=False) name = db.Column(db.String(32), nullable=False) points = db.Column(db.Integer, nullable=False) description = db.Column(db.String(2048), nullable=False) @staticmethod def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def get_all(): return Challenges.query.all()
Update the image helper to use drupal_get_path instead of path_to_theme().
<?php namespace AbleCore; class HTML { public static function image($source, $alt = '', $title = '', array $attributes = array(), array $options = array()) { $default_options = array( 'type' => 'theme', ); $options = array_replace_recursive($default_options, $options); $variables = array(); switch($options['type']) { case 'theme': global $theme; $variables['path'] = drupal_get_path('theme', $theme) . '/' . $source; break; default: $variables['path'] = $source; } if ($alt) { $variables['alt'] = $alt; } if ($title) { $variables['title'] = $title; } if (count($attributes) > 0) { if (array_key_exists('width', $attributes)) { $variables['width'] = $attributes['width']; unset($attributes['width']); } if (array_key_exists('height', $attributes)) { $variables['height'] = $attributes['height']; unset($attributes['height']); } $variables['attributes'] = $attributes; } return theme('image', $variables); } }
<?php namespace AbleCore; class HTML { public static function image($source, $alt = '', $title = '', array $attributes = array(), array $options = array()) { $default_options = array( 'type' => 'theme', ); $options = array_replace_recursive($default_options, $options); $variables = array(); switch($options['type']) { case 'theme': $variables['path'] = path_to_theme() . '/' . $source; break; default: $variables['path'] = $source; } if ($alt) { $variables['alt'] = $alt; } if ($title) { $variables['title'] = $title; } if (count($attributes) > 0) { if (array_key_exists('width', $attributes)) { $variables['width'] = $attributes['width']; unset($attributes['width']); } if (array_key_exists('height', $attributes)) { $variables['height'] = $attributes['height']; unset($attributes['height']); } $variables['attributes'] = $attributes; } return theme('image', $variables); } }
Make sure we do not try to convert None
from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 icon_file = "" if is_string(icon): # File path icon_file = icon elif icon: # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 if is_string(icon): # File path icon_file = icon else: icon_file = "" # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
Add new oedb data directory to package
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.2.0dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv'), os.path.join('oedb', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1, < 0.25', 'requests < 3.0'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.2.0dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1, < 0.25', 'requests < 3.0'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})
Use the precompiled css by default, allow an option to use scss
/* jshint node: true */ 'use strict'; var path = require('path'), path_join = function () { // fix path with windows back slash with path_join return path.join.apply(this, arguments).replace(/\\/g, '/'); }; module.exports = { name: 'ember-cli-chartist', included: function included(app) { this.app = app; var options = app.options['ember-cli-chartist'] || {}, modulePath = path.relative(app.project.root, __dirname), chartistPath = 'vendor/chartist'; if (options.useCustomCSS) { app.options.sassOptions = app.options.sassOptions || {}; app.options.sassOptions.includePaths = app.options.sassOptions.includePaths || []; app.options.sassOptions.includePaths.push(path_join(modulePath, chartistPath, 'scss')); app.options.sassOptions.includePaths.push(path_join(modulePath, chartistPath, 'scss/settings')); } else { app.import('vendor/chartist/chartist.css'); } app.import('vendor/chartist/chartist.js'); } };
/* jshint node: true */ 'use strict'; var path = require('path'), path_join = function () { // fix path with windows back slash with path_join return path.join.apply(this, arguments).replace(/\\/g, '/'); }; module.exports = { name: 'ember-cli-chartist', included: function included(app) { this.app = app; var options = app.options['ember-cli-chartist'] || {}, modulePath = path.relative(app.project.root, __dirname), chartistPath = 'vendor/chartist'; if (options.useDefaultCSS) { app.import('vendor/chartist/chartist.css'); } else { // NOTE: This is not working currently. apps are not recognizing the // includePaths set here. app.options.sassOptions = app.options.sassOptions || {}; app.options.sassOptions.includePaths = app.options.sassOptions.includePaths || []; app.options.sassOptions.includePaths.push(path_join(modulePath, chartistPath, 'scss')); app.options.sassOptions.includePaths.push(path_join(modulePath, chartistPath, 'scss/settings')); } app.import('vendor/chartist/chartist.js'); } };
Use nullary instead of arrow function This makes it more explicit that the function shouldn’t be called with an argument.
/* eslint-disable no-use-before-define */ const R = require('ramda'); const types = require('babel-types'); const nullary = R.nAry(0); function buildLiteral(value) { return R.cond([ [ R.is(Number), types.numericLiteral ], [ R.is(String), types.stringLiteral ], [ R.is(Boolean), types.booleanLiteral ], [ R.is(RegExp), (re) => types.regExpLiteral(re.source, re.flags) ], [ R.is(Array), buildArrayLiteral ], [ R.is(Object), buildObjectLiteral ], [ R.T, nullary(types.nullLiteral) ] ])(value); } function buildArrayLiteral(arr) { return types.arrayExpression(R.map(buildLiteral, arr)); } // Please note that we only support simple non-circular javascript constructs function buildObjectLiteral(obj) { const entries = R.toPairs(obj); const properties = R.map(function ([ key, value ]) { const keyLiteral = types.stringLiteral(key); const valueLiteral = buildLiteral(value); return types.objectProperty(keyLiteral, valueLiteral); }, entries); return types.objectExpression(properties); } module.exports = buildLiteral;
/* eslint-disable no-use-before-define */ const R = require('ramda'); const types = require('babel-types'); function buildLiteral(value) { return R.cond([ [ R.is(Number), types.numericLiteral ], [ R.is(String), types.stringLiteral ], [ R.is(Boolean), types.booleanLiteral ], [ R.is(RegExp), (re) => types.regExpLiteral(re.source, re.flags) ], [ R.is(Array), buildArrayLiteral ], [ R.is(Object), buildObjectLiteral ], [ R.T, () => types.nullLiteral() ] ])(value); } function buildArrayLiteral(arr) { return types.arrayExpression(R.map(buildLiteral, arr)); } // Please note that we only support simple non-circular javascript constructs function buildObjectLiteral(obj) { const entries = R.toPairs(obj); const properties = R.map(function ([ key, value ]) { const keyLiteral = types.stringLiteral(key); const valueLiteral = buildLiteral(value); return types.objectProperty(keyLiteral, valueLiteral); }, entries); return types.objectExpression(properties); } module.exports = buildLiteral;
Revert "Revert "I don't know what changed"" This reverts commit e36c6107647bed4008f46f0ae91fd747b47b29ea.
<?php get_template_part('templates/head'); ?> <body <?php body_class(); ?>> <!--[if lt IE 8]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'roots'); ?> </div> <![endif]--> <?php get_template_part('templates/header-top-navbar'); ?> <div class="body-wrap"> <div class="container"> <div class="row" role="document"> <main class="main <?php echo roots_main_class(); ?>" role="main"> <?php include roots_template_path(); ?> </main><!-- /.main --> <?php if (roots_display_sidebar()) : ?> <aside class="sidebar <?php echo roots_sidebar_class(); ?>" role="complementary"> <?php include roots_sidebar_path(); ?> </aside><!-- /.sidebar --> <?php endif; ?> </div><!-- /.content --> </div><!-- /.wrap --> <?php get_template_part('templates/footer'); ?> </body> </html>
<?php get_template_part('templates/head'); ?> <body <?php body_class(); ?>> <!--[if lt IE 8]> <div class="alert alert-warning"> <?php _e('You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.', 'roots'); ?> </div> <![endif]--> <?php get_template_part('templates/header-top-navbar'); ?> <div class="content-detail container"> <div class="row" role="document"> <?php if (roots_display_sidebar()) : ?> <aside class="sidebar <?php echo roots_sidebar_class(); ?>" role="complementary"> <?php include roots_sidebar_path(); ?> </aside> <!-- /.sidebar.<?php echo roots_sidebar_class(); ?> --> <?php endif; ?> <main class="main <?php echo roots_main_class(); ?>" role="main"> <div class="content-area"> <?php include roots_template_path(); ?> </div> <!-- /.content-area --> </main> <!-- /.main.<?php echo roots_main_class(); ?> --> </div> <!-- /.row --> </div> <!-- /.content-detail.container --> <?php get_template_part('templates/footer'); ?> </body> </html>
Clarify the type of response we're looking for.
<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ 'Symfony\Component\HttpKernel\Exception\HttpException' ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { return parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { if ($this->isHttpException($e)) { return $this->renderHttpException($e); } else { return parent::render($request, $e); } } }
<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ 'Symfony\Component\HttpKernel\Exception\HttpException' ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { return parent::report($e); } /** * Render an exception into a response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { if ($this->isHttpException($e)) { return $this->renderHttpException($e); } else { return parent::render($request, $e); } } }
Make tests more realistic by doing some “work” other than writing console output, moreso, moreso.
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); if (i % 20 == 0) { Thread.sleep(5); } } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); if (i % 20 == 0) { Thread.sleep(5); } } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); if (i % 20 == 0) { Thread.sleep(1); } } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); if (i % 20 == 0) { Thread.sleep(1); } } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
Support Django 1.4 in the test suite
#!/usr/bin/env python """ Logan ====== Logan is a toolkit for running standalone Django applications. It provides you with tools to create a CLI runner, manage settings, and the ability to bootstrap the process. :copyright: (c) 2012 David Cramer. :license: Apache License 2.0, see LICENSE for more details. """ from setuptools import setup, find_packages setup( name='logan', version='0.2.2', author='David Cramer', author_email='dcramer@gmail.com', url='http://github.com/dcramer/logan', description='Logan is a toolkit for building standalone Django applications.', packages=find_packages(exclude=["tests"]), long_description=__doc__, zip_safe=False, install_requires=[], tests_require=[ 'django>=1.2.5,<1.5', 'nose>=1.1.2', 'unittest2', ], test_suite='unittest2.collector', license='Apache License 2.0', include_package_data=True, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
#!/usr/bin/env python """ Logan ====== Logan is a toolkit for running standalone Django applications. It provides you with tools to create a CLI runner, manage settings, and the ability to bootstrap the process. :copyright: (c) 2012 David Cramer. :license: Apache License 2.0, see LICENSE for more details. """ from setuptools import setup, find_packages setup( name='logan', version='0.2.2', author='David Cramer', author_email='dcramer@gmail.com', url='http://github.com/dcramer/logan', description='Logan is a toolkit for building standalone Django applications.', packages=find_packages(exclude=["tests"]), long_description=__doc__, zip_safe=False, install_requires=[], tests_require=[ 'django>=1.2.5,<1.4', 'nose>=1.1.2', 'unittest2', ], test_suite='unittest2.collector', license='Apache License 2.0', include_package_data=True, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
Use __all__ for restricted exports
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings # import default models from djangoSHOP to materialize them from shop.models.defaults.address import ShippingAddress, BillingAddress from shop.models.defaults.cart import Cart from shop.models.defaults.cart_item import CartItem from shop.models.defaults.customer import Customer # models defined by the myshop instance itself if settings.SHOP_TUTORIAL == 'commodity' or settings.SHOP_TUTORIAL == 'i18n_commodity': from shop.models.defaults.order_item import OrderItem from shop.models.defaults.commodity import Commodity elif settings.SHOP_TUTORIAL == 'smartcard': from shop.models.defaults.order_item import OrderItem from .smartcard import SmartCard elif settings.SHOP_TUTORIAL == 'i18n_smartcard': from shop.models.defaults.order_item import OrderItem from .i18n_smartcard import SmartCard elif settings.SHOP_TUTORIAL == 'polymorphic': from .polymorphic.order import OrderItem from .polymorphic.smartcard import SmartCard from .polymorphic.smartphone import SmartPhoneModel, SmartPhone from shop.models.defaults.delivery import Delivery, DeliveryItem from shop.models.defaults.order import Order __all__ = ['ShippingAddress', 'BillingAddress', 'Cart', 'CartItem', 'Customer', 'Order', 'OrderItem', 'Commodity', 'SmartCard', 'SmartPhoneModel', 'SmartPhone', 'Delivery', 'DeliveryItem']
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings # import default models from djangoSHOP to materialize them from shop.models.defaults.address import ShippingAddress, BillingAddress from shop.models.defaults.cart import Cart from shop.models.defaults.cart_item import CartItem from shop.models.defaults.customer import Customer # models defined by the myshop instance itself if settings.SHOP_TUTORIAL == 'commodity' or settings.SHOP_TUTORIAL == 'i18n_commodity': from shop.models.defaults.order_item import OrderItem from shop.models.defaults.commodity import Commodity elif settings.SHOP_TUTORIAL == 'smartcard': from shop.models.defaults.order_item import OrderItem from .smartcard import SmartCard elif settings.SHOP_TUTORIAL == 'i18n_smartcard': from shop.models.defaults.order_item import OrderItem from .i18n_smartcard import SmartCard elif settings.SHOP_TUTORIAL == 'polymorphic': from .polymorphic.order import OrderItem from .polymorphic.smartcard import SmartCard from .polymorphic.smartphone import SmartPhoneModel, SmartPhone from shop.models.defaults.delivery import Delivery, DeliveryItem from shop.models.defaults.order import Order
Remove use call for ArrayCollection.
<?php namespace App\Repository\Framework; use App\Entity\Framework\LsDefFrameworkType; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Symfony\Bridge\Doctrine\RegistryInterface; /** * @method LsDefFrameworkType|null find($id, $lockMode = null, $lockVersion = null) * @method LsDefFrameworkType|null findOneBy(array $criteria, array $orderBy = null) * @method LsDefFrameworkType[] findAll() * @method LsDefFrameworkType[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class LsDefFrameworkTypeRepository extends ServiceEntityRepository { public function __construct(RegistryInterface $registry) { parent::__construct($registry, LsDefFrameworkType::class); } /** * @return array|LsDefFrameworkType[] */ public function getList() { $qBuilder = $this->createQueryBuilder('f', 'f.value') ->orderBy('f.value'); return $qBuilder->getQuery()->getResult(); } }
<?php namespace App\Repository\Framework; use App\Entity\Framework\LsDefFrameworkType; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Bridge\Doctrine\RegistryInterface; /** * @method LsDefFrameworkType|null find($id, $lockMode = null, $lockVersion = null) * @method LsDefFrameworkType|null findOneBy(array $criteria, array $orderBy = null) * @method LsDefFrameworkType[] findAll() * @method LsDefFrameworkType[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class LsDefFrameworkTypeRepository extends ServiceEntityRepository { public function __construct(RegistryInterface $registry) { parent::__construct($registry, LsDefFrameworkType::class); } /** * @return array|LsDefFrameworkType[] */ public function getList() { $qBuilder = $this->createQueryBuilder('f', 'f.value') ->orderBy('f.value'); return $qBuilder->getQuery()->getResult(); } }
CC-3841: Remove "airtime-show-recorder" initd script on upgrade -fixed
<?php /* Stuff not related to upgrading database + * config files goes here. */ class AirtimeMiscUpgrade{ public static function start($p_ini){ self::adjustAirtimeStorPermissions($p_ini); self::cleanupOldFiles(); } public static function adjustAirtimeStorPermissions($p_ini){ /* Make the read permission of Monit cfg files more strict */ $webUser = $p_ini["general"]["web_server_user"]; echo " * Updating /srv/airtime owner to root:$webUser".PHP_EOL; exec("chown -R root:$webUser /srv/airtime"); echo " * Updating /srv/airtime permissions to 02755".PHP_EOL; exec("chmod -R 2775 /srv/airtime"); } public static function cleanupOldFiles(){ exec("rm -f /usr/bin/airtime-user"); exec("rm -f /etc/init.d/airtime-show-recorder"); } }
<?php /* Stuff not related to upgrading database + * config files goes here. */ class AirtimeMiscUpgrade{ public static function start($p_ini){ self::adjustAirtimeStorPermissions($p_ini); } public static function adjustAirtimeStorPermissions($p_ini){ /* Make the read permission of Monit cfg files more strict */ $webUser = $p_ini["general"]["web_server_user"]; echo " * Updating /srv/airtime owner to root:$webUser".PHP_EOL; exec("chown -R root:$webUser /srv/airtime"); echo " * Updating /srv/airtime permissions to 02755".PHP_EOL; exec("chmod -R 2775 /srv/airtime"); } }
Add tabindex to the content landmark to make it focusable. Remove it from the previous landmark that we were trying to skip to.
<!DOCTYPE html> <html class="bg-white antialiased" lang="en"> <head> @include('components.meta') <title>@include('components.head-title')</title> <link rel="icon" type="image/x-icon" href="https://wayne.edu/favicon.ico"> <link rel="stylesheet" href="{{ mix('_resources/css/main.css') }}"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet" type="text/css"> @if(!empty($page['canonical']))<link rel="canonical" href="{{ $page['canonical'] }}">@endif @include('components.ga') </head> <body class="font-sans font-normal text-black leading-normal text-base"> @include('components.skip') @include('components.header') @if(!empty($site)) @include('components.menu-top', ['site' => $site]) @endif @if(!empty($banner)) @include('components.banner', ['banner' => $banner]) @endif <main id="panel"> @yield('content-area') </main> @if(!empty($social)) @include('components.footer-social', ['social' => $social]) @endif @if(!empty($contact)) @include('components.footer-contact', ['contact' => $contact]) @endif @include('components.footer') <script src="{{ mix('_resources/js/main.js') }}"></script> </body> </html>
<!DOCTYPE html> <html class="bg-white antialiased" lang="en"> <head> @include('components.meta') <title>@include('components.head-title')</title> <link rel="icon" type="image/x-icon" href="https://wayne.edu/favicon.ico"> <link rel="stylesheet" href="{{ mix('_resources/css/main.css') }}"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet" type="text/css"> @if(!empty($page['canonical']))<link rel="canonical" href="{{ $page['canonical'] }}">@endif @include('components.ga') </head> <body class="font-sans font-normal text-black leading-normal text-base"> @include('components.skip') @include('components.header') @if(!empty($site)) @include('components.menu-top', ['site' => $site]) @endif @if(!empty($banner)) @include('components.banner', ['banner' => $banner]) @endif <main id="panel" tabindex="-1"> @yield('content-area') </main> @if(!empty($social)) @include('components.footer-social', ['social' => $social]) @endif @if(!empty($contact)) @include('components.footer-contact', ['contact' => $contact]) @endif @include('components.footer') <script src="{{ mix('_resources/js/main.js') }}"></script> </body> </html>
maint(Build): Update path to the webpack module federation config.
/** * Module Federation support for Mockup. * * In this module federation setup Mockup is the main host, which loads other * "remote" bundles. * * Those remotes need to be registered via the Patternslib's Webpack Module * Federation helper, just like Mockup itself (See Mockup's webpack.config.js). * Patternslib' Module Federation helper registers the bundle under a prefix * (``MF_NAME_PREFIX``) in the global namespace. * * Here, we filter for all the globally registered bundles with this prefix and * load them. * * Note: loading in this context only means that the module federation * functionality for each bundle is initialized. * */ import "@patternslib/dev/webpack/module_federation"; // And now load this bundle's actual entry point. import("./patterns"); // Register Bootstrap and jQuery gloablly async function register_global_libraries() { // Register Bootstrap globally const bootstrap = await import("bootstrap"); window.bootstrap = bootstrap; // Register jQuery globally const jquery = (await import("jquery")).default; window.jQuery = jquery; window.$ = jquery; } register_global_libraries();
/** * Module Federation support for Mockup. * * In this module federation setup Mockup is the main host, which loads other * "remote" bundles. * * Those remotes need to be registered via the Patternslib's Webpack Module * Federation helper, just like Mockup itself (See Mockup's webpack.config.js). * Patternslib' Module Federation helper registers the bundle under a prefix * (``MF_NAME_PREFIX``) in the global namespace. * * Here, we filter for all the globally registered bundles with this prefix and * load them. * * Note: loading in this context only means that the module federation * functionality for each bundle is initialized. * */ import "@patternslib/patternslib/webpack/module_federation"; // And now load this bundle's actual entry point. import("./patterns"); // Register Bootstrap and jQuery gloablly async function register_global_libraries() { // Register Bootstrap globally const bootstrap = await import("bootstrap"); window.bootstrap = bootstrap; // Register jQuery globally const jquery = (await import("jquery")).default; window.jQuery = jquery; window.$ = jquery; } register_global_libraries();
Remove weird matplot lib defaults thing that did nothing
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(sort)) for user, streak in sorted_streaks if streak.get(sort) > 0][::-1]) title = 'Top Contributors by {} Streak'.format(sort.title()) figure = plt.figure() y_pos = np.arange(len(users)) # y-location of bars print('y_pos', y_pos) plt.barh(y_pos, streaks, facecolor='#ff9999', edgecolor='grey', align='center') plt.yticks(y_pos, users) plt.xlim([0, max(streaks) + 0.5]) # x-limits a bit wider at right plt.subplots_adjust(left=0.2) # Wider left margin plt.title(title) for format in ('png', 'svg'): figure.savefig('temp/top_{}.{}'.format(sort, format), format=format)
import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(sort)) for user, streak in sorted_streaks if streak.get(sort) > 0][::-1]) title = 'Top Contributors by {} Streak'.format(sort.title()) figure = plt.figure() y_pos = np.arange(len(users)) # y-location of bars print('y_pos', y_pos) plt.barh(y_pos, streaks, facecolor='#ff9999', edgecolor='grey', align='center') plt.yticks(y_pos, users) plt.xlim([0, max(streaks) + 0.5]) # x-limits a bit wider at right plt.subplots_adjust(left=0.2) # Wider left margin plt.title(title) for format in ('png', 'svg'): figure.savefig('temp/top_{}.{}'.format(sort, format), format=format)
Replace assertEqual(None, *) with assertIsNone Replace assertEqual(None, *) with assertIsNone in tests Change-Id: I257c479b7a23e39178d292c347d04ad979c48f0f Closes-bug: #1280522
# -*- coding: utf-8 -*- # 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. """ test_inventory ---------------------------------- Tests for `inventory` module. """ from bifrost import inventory from bifrost.tests import base class TestBifrostInventoryUnit(base.TestCase): def test_inventory_preparation(self): (groups, hostvars) = inventory._prepare_inventory() self.assertIn("baremetal", groups) self.assertIn("localhost", groups) self.assertDictEqual(hostvars, {}) localhost_value = dict(hosts=["127.0.0.1"]) self.assertDictEqual(localhost_value, groups['localhost']) def test__val_or_none(self): array = ['no', '', 'yes'] self.assertEqual('no', inventory._val_or_none(array, 0)) self.assertIsNone(inventory._val_or_none(array, 1)) self.assertEqual('yes', inventory._val_or_none(array, 2)) self.assertIsNone(inventory._val_or_none(array, 4))
# -*- coding: utf-8 -*- # 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. """ test_inventory ---------------------------------- Tests for `inventory` module. """ from bifrost import inventory from bifrost.tests import base class TestBifrostInventoryUnit(base.TestCase): def test_inventory_preparation(self): (groups, hostvars) = inventory._prepare_inventory() self.assertIn("baremetal", groups) self.assertIn("localhost", groups) self.assertDictEqual(hostvars, {}) localhost_value = dict(hosts=["127.0.0.1"]) self.assertDictEqual(localhost_value, groups['localhost']) def test__val_or_none(self): array = ['no', '', 'yes'] self.assertEqual('no', inventory._val_or_none(array, 0)) self.assertEqual(None, inventory._val_or_none(array, 1)) self.assertEqual('yes', inventory._val_or_none(array, 2)) self.assertEqual(None, inventory._val_or_none(array, 4))
Add more versions of Windows + environment
import os, sys from setuptools import setup setup( name='reddit_comment_scraper', version='2.0.0', description='A simple Reddit-scraping script', url='https://github.com/jfarmer/reddit_comment_scraper', author='Jesse Farmer', author_email='jesse@20bits.com', license='MIT', packages=['reddit_comment_scraper'], install_requires=[ 'unicodecsv==0.9.4', 'praw==2.1.19' ], entry_points={ 'console_scripts': [ 'scrape_comments=reddit_comment_scraper:main' ] }, classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Environment :: Console', 'Operating System :: POSIX', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows :: Windows 8.1', 'Operating System :: Microsoft :: Windows :: Windows 8', 'Operating System :: Microsoft :: Windows :: Windows 7', 'Operating System :: Microsoft :: Windows :: Windows Vista' ], )
import os, sys from setuptools import setup setup( name='reddit_comment_scraper', version='2.0.0', description='A simple Reddit-scraping script', url='https://github.com/jfarmer/reddit_comment_scraper', author='Jesse Farmer', author_email='jesse@20bits.com', license='MIT', packages=['reddit_comment_scraper'], install_requires=[ 'unicodecsv==0.9.4', 'praw==2.1.19' ], entry_points={ 'console_scripts': [ 'scrape_comments=reddit_comment_scraper:main' ] }, classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Operating System :: POSIX', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows :: Windows 7' ], )
Make the bundle compatible with Twig v2
<?php namespace Becklyn\RadBundle\Service; use Becklyn\RadBundle\Helper\Pagination; class PaginationTwigExtension extends AbstractTwigExtension { /** * Renders the pagination * * @param Pagination $pagination * * @param string $route * @param array $additionalRouteParameters * @param string $pageParameterName * * @return string */ public function pagination (Pagination $pagination, $route, array $additionalRouteParameters = array(), $pageParameterName = "page") { return $this->render( "@BecklynRad/Pagination/pagination.html.twig", array( "pagination" => $pagination, "route" => $route, "routeParameters" => $additionalRouteParameters, "pageParameterName" => $pageParameterName ) ); } /** * @return \Twig_Function[] */ public function getFunctions () { return array( "pagination" => new \Twig_SimpleFunction(array($this, "pagination"), array("is_safe" => array("html"))) ); } }
<?php namespace Becklyn\RadBundle\Service; use Becklyn\RadBundle\Helper\Pagination; class PaginationTwigExtension extends AbstractTwigExtension { /** * Renders the pagination * * @param Pagination $pagination * * @param string $route * @param array $additionalRouteParameters * @param string $pageParameterName * * @return string */ public function pagination (Pagination $pagination, $route, array $additionalRouteParameters = array(), $pageParameterName = "page") { return $this->render( "@BecklynRad/Pagination/pagination.html.twig", array( "pagination" => $pagination, "route" => $route, "routeParameters" => $additionalRouteParameters, "pageParameterName" => $pageParameterName ) ); } /** * @return \Twig_Function[] */ public function getFunctions () { return array( "pagination" => new \Twig_Function_Method($this, "pagination", array("is_safe" => array("html"))) ); } }
Set default path in EN/DE tests.
import pytest import os from ..en import English from ..de import German @pytest.fixture(scope="session") def EN(): return English() @pytest.fixture(scope="session") def DE(): return German() def pytest_addoption(parser): parser.addoption("--models", action="store_true", help="include tests that require full models") parser.addoption("--vectors", action="store_true", help="include word vectors tests") parser.addoption("--slow", action="store_true", help="include slow tests") def pytest_runtest_setup(item): for opt in ['models', 'vectors', 'slow']: if opt in item.keywords and not item.config.getoption("--%s" % opt): pytest.skip("need --%s option to run" % opt)
import pytest import os from ..en import English from ..de import German @pytest.fixture(scope="session") def EN(): return English(path=False) @pytest.fixture(scope="session") def DE(): return German(path=False) def pytest_addoption(parser): parser.addoption("--models", action="store_true", help="include tests that require full models") parser.addoption("--vectors", action="store_true", help="include word vectors tests") parser.addoption("--slow", action="store_true", help="include slow tests") def pytest_runtest_setup(item): for opt in ['models', 'vectors', 'slow']: if opt in item.keywords and not item.config.getoption("--%s" % opt): pytest.skip("need --%s option to run" % opt)
Add a function for commands to process parameters
# The purpose of this file is to provide base classes with the needed functions # already defined; this allows us to guarantee that any exceptions raised # during function calls are a problem with the module and not just that the # particular function isn't defined. class Module(object): def hook(self, base): self.ircd = base return self class Mode(object): def hook(self, base): self.ircd = base return self def prefixSymbol(self): return None def checkSet(self, channel, param): return True def checkUnset(self, channel, param): return True def onJoin(self, channel, user, params): return "pass" def onMessage(self, sender, target, message): return ["pass"] def onPart(self, channel, user, reason): pass def onTopicChange(self, channel, user, topic): pass def commandData(self, command, *args): pass def Command(object): def hook(self, base): self.ircd = base return self def onUse(self, user, params): pass def processParams(self, user, params): return { "user": user, "params": params }
# The purpose of this file is to provide base classes with the needed functions # already defined; this allows us to guarantee that any exceptions raised # during function calls are a problem with the module and not just that the # particular function isn't defined. class Module(object): def hook(self, base): self.ircd = base return self class Mode(object): def hook(self, base): self.ircd = base return self def prefixSymbol(self): return None def checkSet(self, channel, param): return True def checkUnset(self, channel, param): return True def onJoin(self, channel, user, params): return "pass" def onMessage(self, sender, target, message): return ["pass"] def onPart(self, channel, user, reason): pass def onTopicChange(self, channel, user, topic): pass def commandData(self, command, *args): pass def Command(object): def hook(self, base): self.ircd = base return self def onUse(self, user, params): pass
Make tests more realistic by doing some “work” other than writing console output.
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); if (i % 50 == 0) { Thread.sleep(1); } } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); if (i % 50 == 0) { Thread.sleep(1); } } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
package ${packageName}; import static org.junit.Assert.*; public class ${testClassName} { private final ${productionClassName} production = new ${productionClassName}("value"); @org.junit.Test public void testOne() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testOne - " + i); System.err.println("Some test error from ${testClassName}.testOne - " + i); } assertEquals(production.getProperty(), "value"); } @org.junit.Test public void testTwo() throws Exception { for (int i = 0; i < 500; i++) { System.out.println("Some test output from ${testClassName}.testTwo - " + i); System.err.println("Some test error from ${testClassName}.testTwo - " + i); } String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>; assertEquals(production.getProperty(), expected); } }
Fix babel config for babel 7
'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); const urls = require('./lib/prember-urls'); module.exports = function(defaults) { var includePolyfill = process.env.EMBER_ENV === 'production' || process.env.CI; var babelOptions = {}; if (includePolyfill) { babelOptions.includePolyfill = true; } else { babelOptions.exclude = ['@babel/plugin-transform-regenerator']; } var app = new EmberAddon(defaults, { minifyJS: { enabled: false }, snippetPaths: ['tests/dummy/snippets'], snippetSearchPaths: ['app', 'tests/dummy/app', 'addon'], emberCliFontAwesome: { useScss: true }, babel: babelOptions, prember: { urls, // GitHub Pages uses this filename to serve 404s emptyFile: '404.html' } }); /* This build file specifes the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ app.import('vendor/dummy-deps/rx.js'); return app.toTree(); };
'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); const urls = require('./lib/prember-urls'); module.exports = function(defaults) { var includePolyfill = process.env.EMBER_ENV === 'production' || process.env.CI; var babelOptions = {}; if (includePolyfill) { babelOptions.includePolyfill = true; } else { babelOptions.blacklist = ['regenerator']; } var app = new EmberAddon(defaults, { minifyJS: { enabled: false }, snippetPaths: ['tests/dummy/snippets'], snippetSearchPaths: ['app', 'tests/dummy/app', 'addon'], emberCliFontAwesome: { useScss: true }, babel: babelOptions, prember: { urls, // GitHub Pages uses this filename to serve 404s emptyFile: '404.html' } }); /* This build file specifes the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ app.import('vendor/dummy-deps/rx.js'); return app.toTree(); };
Allow env variable LOG_LEVEL to override the log level
const LEVELS = { NOTHING: 0, ERROR: 1, WARN: 2, INFO: 4, DEBUG: 5, } const createLevel = (label, level, currentLevel, loggerFunction) => (message, extra = {}) => { if (level > currentLevel) return const logData = Object.assign( { level: label, timestamp: new Date().toISOString(), message, }, extra ) loggerFunction(JSON.stringify(logData)) } const createLogger = ({ level = LEVELS.INFO } = {}) => { const logLevel = parseInt(process.env.LOG_LEVEL, 10) || level return { info: createLevel('INFO', LEVELS.INFO, logLevel, console.info), error: createLevel('ERROR', LEVELS.ERROR, logLevel, console.error), warn: createLevel('WARN', LEVELS.WARN, logLevel, console.warn), debug: createLevel('DEBUG', LEVELS.DEBUG, logLevel, console.log), } } module.exports = { LEVELS, createLogger, }
const LEVELS = { NOTHING: 0, ERROR: 1, WARN: 2, INFO: 4, DEBUG: 5, } const createLevel = (label, level, currentLevel, loggerFunction) => (message, extra = {}) => { if (level > currentLevel) return const logData = Object.assign( { level: label, timestamp: new Date().toISOString(), message, }, extra ) loggerFunction(JSON.stringify(logData)) } const createLogger = ({ level = parseInt(process.env.LOG_LEVEL, 10) || LEVELS.INFO } = {}) => ({ info: createLevel('INFO', LEVELS.INFO, level, console.info), error: createLevel('ERROR', LEVELS.ERROR, level, console.error), warn: createLevel('WARN', LEVELS.WARN, level, console.warn), debug: createLevel('DEBUG', LEVELS.DEBUG, level, console.log), }) module.exports = { LEVELS, createLogger, }
Revert "[TaPOS] link to the last irreversible block instead of headblock" This reverts commit 05cec8e450a09fd0d3fa2b40860760f7bff0c125.
from collections import OrderedDict from binascii import hexlify, unhexlify from calendar import timegm from datetime import datetime import json import struct import time from .account import PublicKey from .chains import known_chains from .signedtransactions import Signed_Transaction from .operations import Operation from .objects import GrapheneObject, isArgsThisClass timeformat = '%Y-%m-%dT%H:%M:%S%Z' def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["head_block_number"] & 0xFFFF ref_block_prefix = struct.unpack_from("<I", unhexlify(dynBCParams["head_block_id"]), 4)[0] return ref_block_num, ref_block_prefix def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs)).strftime(timeformat)
from collections import OrderedDict from binascii import hexlify, unhexlify from calendar import timegm from datetime import datetime import json import struct import time from .account import PublicKey from .chains import known_chains from .signedtransactions import Signed_Transaction from .operations import Operation from .objects import GrapheneObject, isArgsThisClass timeformat = '%Y-%m-%dT%H:%M:%S%Z' def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["last_irreversible_block_num"] & 0xFFFF ref_block_prefix = struct.unpack_from("<I", unhexlify(dynBCParams["head_block_id"]), 4)[0] return ref_block_num, ref_block_prefix def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs)).strftime(timeformat)
Fix shapemask_config import to handle copy.bara masking that allows cloud detection test to pass. PiperOrigin-RevId: 267404830
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Factory to provide model configs.""" from configs import retinanet_config from hyperparameters import params_dict def config_generator(model): """Model function generator.""" if model == 'retinanet': default_config = retinanet_config.RETINANET_CFG restrictions = retinanet_config.RETINANET_RESTRICTIONS elif model == 'shapemask': default_config = shapemask_config.SHAPEMASK_CFG restrictions = shapemask_config.SHAPEMASK_RESTRICTIONS else: raise ValueError('Model %s is not supported.' % model) return params_dict.ParamsDict(default_config, restrictions)
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Factory to provide model configs.""" from configs import retinanet_config from configs import shapemask_config from hyperparameters import params_dict def config_generator(model): """Model function generator.""" if model == 'retinanet': default_config = retinanet_config.RETINANET_CFG restrictions = retinanet_config.RETINANET_RESTRICTIONS elif model == 'shapemask': default_config = shapemask_config.SHAPEMASK_CFG restrictions = shapemask_config.SHAPEMASK_RESTRICTIONS else: raise ValueError('Model %s is not supported.' % model) return params_dict.ParamsDict(default_config, restrictions)
Remove '.wav' addition to all files uploaded
from flask import Flask, request, jsonify, send_from_directory import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): return send_from_directory('', 'index.html') @app.route("/sounds") def get_sounds_list(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) sounds = os.listdir(UPLOAD_FOLDER) return jsonify({'sounds': sounds}) @app.route("/sounds/<path:path>") def serve_static(path): return send_from_directory(UPLOAD_FOLDER, path) @app.route("/upload", methods=["POST"]) def upload_file(): file = request.files["sound"] if file: if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) filename = uuid.uuid4().__str__() file.save(os.path.join(UPLOAD_FOLDER, filename)) return filename + "\n" if __name__ == "__main__": app.run(host = "0.0.0.0", debug=True)
from flask import Flask, request, jsonify, send_from_directory import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): return send_from_directory('', 'index.html') @app.route("/sounds") def get_sounds_list(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) sounds = os.listdir(UPLOAD_FOLDER) return jsonify({'sounds': sounds}) @app.route("/sounds/<path:path>") def serve_static(path): return send_from_directory(UPLOAD_FOLDER, path) @app.route("/upload", methods=["POST"]) def upload_file(): file = request.files["sound"] if file: if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) filename = uuid.uuid4().__str__() + ".wav" file.save(os.path.join(UPLOAD_FOLDER, filename)) return filename + "\n" if __name__ == "__main__": app.run(host = "0.0.0.0", debug=True)
Update host changed time on content block save
<?php namespace Drupal\wmcontent\EventSubscriber; use Drupal\Core\Entity\EntityInterface; use Drupal\wmcontent\Event\ContentBlockChangedEvent; use Drupal\wmcontent\WmContentManager; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class ContentBlockSubscriber implements EventSubscriberInterface { /** @var WmContentManager */ private $manager; private $updatedHosts = []; public function __construct(WmContentManager $manager) { $this->manager = $manager; } public static function getSubscribedEvents() { $events[ContentBlockChangedEvent::NAME][] = ['updateHostEntity']; return $events; } /** * Trigger an update of the contentblock's host entity */ public function updateHostEntity(ContentBlockChangedEvent $event) { $host = $this->manager->getHost($event->getContentBlock()); if (!$host instanceof EntityInterface) { return; } $cid = sprintf('%s:%s', $host->getEntityTypeId(), $host->id()); if (array_key_exists($cid, $this->updatedHosts)) { return; } $host->set('changed', time()); $host->save(); $this->updatedHosts[$cid] = true; } }
<?php namespace Drupal\wmcontent\EventSubscriber; use Drupal\Core\Entity\EntityInterface; use Drupal\wmcontent\Event\ContentBlockChangedEvent; use Drupal\wmcontent\WmContentManager; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class ContentBlockSubscriber implements EventSubscriberInterface { /** @var WmContentManager */ private $manager; private $updatedHosts = []; public function __construct(WmContentManager $manager) { $this->manager = $manager; } public static function getSubscribedEvents() { $events[ContentBlockChangedEvent::NAME][] = ['updateHostEntity']; return $events; } /** * Trigger an update of the contentblock's host entity */ public function updateHostEntity(ContentBlockChangedEvent $event) { $host = $this->manager->getHost($event->getContentBlock()); if (!$host instanceof EntityInterface) { return; } $cid = sprintf('%s:%s', $host->getEntityTypeId(), $host->id()); if (array_key_exists($cid, $this->updatedHosts)) { return; } $host->save(); $this->updatedHosts[$cid] = true; } }
Remove some comments leftover from tutorial
var gulp = require('gulp'); var browserify = require('browserify'); var gutil = require('gulp-util'); var source = require('vinyl-source-stream'); // Babel - converts ES6 code to ES5 - however it doesn't handle imports. // Browserify - crawls your code for dependencies and packages them up // into one file. can have plugins. // Babelify - a babel plugin for browserify, to make browserify // handle es6 including imports. gulp.task('bundle', function() { browserify({ entries: './scripts/game.js', debug: true }) .transform('babelify',{presets: ['env']}) .on('error',gutil.log) .bundle() .on('error',gutil.log) .pipe(source('bundle.js')) .pipe(gulp.dest('')); }); gulp.task('watch',function() { gulp.watch('./scripts/*.js',['bundle']) }); gulp.task('default', ['watch']);
/** * Gulpfile to make my life easier. */ var gulp = require('gulp'); var browserify = require('browserify'); var gutil = require('gulp-util'); var source = require('vinyl-source-stream'); // Lets bring es6 to es5 with this. // Babel - converts ES6 code to ES5 - however it doesn't handle imports. // Browserify - crawls your code for dependencies and packages them up // into one file. can have plugins. // Babelify - a babel plugin for browserify, to make browserify // handle es6 including imports. gulp.task('bundle', function() { browserify({ entries: './scripts/game.js', debug: true }) .transform('babelify',{presets: ['env']}) .on('error',gutil.log) .bundle() .on('error',gutil.log) .pipe(source('bundle.js')) .pipe(gulp.dest('')); }); gulp.task('watch',function() { gulp.watch('./scripts/*.js',['bundle']) }); gulp.task('default', ['watch']);
Add globals to make eslint pass
module.exports = { "env": { "browser": true }, "extends": "eslint:recommended", "rules": { "indent": [ "error", 4 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "double" ], "semi": [ "error", "always" ] }, "globals": { "$": true, "it": true, "describe": true, "beforeEach": true, "chai": true, "jQuery": true, "chrome": true, "modal": true, "modalHTML": true, "Modal": true, "flashInterval": true } };
module.exports = { "env": { "browser": true }, "extends": "eslint:recommended", "rules": { "indent": [ "error", 4 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "double" ], "semi": [ "error", "always" ] } };
Handle amount not already being a number
function play(type) { var sounds = { 'yes' : 'Pop', 'no' : 'Basso', 'maybe' : 'Bottle', }; if (window.fluid) { window.fluid.playSound(sounds[type]); } } $.getFocusedElement = function() { var elem = document.activeElement; return $( elem && ( elem.type || elem.href ) ? elem : [] ); }; // http://stackoverflow.com/a/3109234 function round_to_even(num, decimalPlaces) { var d = decimalPlaces || 0; var m = Math.pow(10, d); var n = d ? num * m : num; var i = Math.floor(n), f = n - i; var r = (f == 0.5) ? ((i % 2 == 0) ? i : i + 1) : Math.round(n); return d ? r / m : r; } // format number as $3.00 or ($3.00) function amount(amount) { if (typeof(amount) == 'undefined' || amount == null) { return ''; } if (typeof(amount) == 'string') { amount= parseFloat(amount); } if (amount < 0.0) { return '($' + Math.abs(amount).toFixed(2) + ')'; } else { return '$' + amount.toFixed(2); } }
function play(type) { var sounds = { 'yes' : 'Pop', 'no' : 'Basso', 'maybe' : 'Bottle', }; if (window.fluid) { window.fluid.playSound(sounds[type]); } } $.getFocusedElement = function() { var elem = document.activeElement; return $( elem && ( elem.type || elem.href ) ? elem : [] ); }; // http://stackoverflow.com/a/3109234 function round_to_even(num, decimalPlaces) { var d = decimalPlaces || 0; var m = Math.pow(10, d); var n = d ? num * m : num; var i = Math.floor(n), f = n - i; var r = (f == 0.5) ? ((i % 2 == 0) ? i : i + 1) : Math.round(n); return d ? r / m : r; } // format number as $3.00 or ($3.00) function amount(amount) { if (typeof(amount) == 'undefined' || amount == null) { return ''; } if (amount < 0.0) { return '($' + Math.abs(amount).toFixed(2) + ')'; } else { return '$' + amount.toFixed(2); } }
Remove prefix and change from settings to mode
package com.uxxu.konashi.lib.stores; import com.uxxu.konashi.lib.dispatcher.CharacteristicDispatcher; import com.uxxu.konashi.lib.dispatcher.UartStoreUpdater; /** * Created by e10dokup on 9/20/15. */ public class UartStore implements Store { private byte mMode; private byte[] mBaudrate; public UartStore(CharacteristicDispatcher<UartStore, UartStoreUpdater> dispatcher) { dispatcher.setStore(this); } public byte getMode() { return mMode; } public void setMode(byte mode) { mMode = mode; } public byte[] getBaudrate() { return mBaudrate; } public void setBaudrate(byte[] baudrate) { mBaudrate = baudrate; } }
package com.uxxu.konashi.lib.stores; import com.uxxu.konashi.lib.dispatcher.CharacteristicDispatcher; import com.uxxu.konashi.lib.dispatcher.UartStoreUpdater; /** * Created by e10dokup on 9/20/15. */ public class UartStore implements Store { private byte mUartSetting; private byte[] mUartBaudrate; public UartStore(CharacteristicDispatcher<UartStore, UartStoreUpdater> dispatcher) { dispatcher.setStore(this); } public byte getUartSetting() { return mUartSetting; } public void setUartSetting(byte uartSetting) { mUartSetting = uartSetting; } public byte[] getUartBaudrate() { return mUartBaudrate; } public void setUartBaudrate(byte[] uartBaudrate) { mUartBaudrate = uartBaudrate; } }
Add test for dropped language name
const test = require('tap').test; const TextToSpeech = require('../../src/extensions/scratch3_text2speech/index.js'); const fakeStage = { textToSpeechLanguage: null }; const fakeRuntime = { getTargetForStage: () => fakeStage, on: () => {} // Stub out listener methods used in constructor. }; const ext = new TextToSpeech(fakeRuntime); test('if no language is saved in the project, use default', t => { t.strictEqual(ext.getCurrentLanguage(), 'en'); t.end(); }); test('if an unsupported language is dropped onto the set language block, use default', t => { ext.setLanguage({LANGUAGE: 'nope'}); t.strictEqual(ext.getCurrentLanguage(), 'en'); t.end(); }); test('if a supported language name is dropped onto the set language block, use it', t => { ext.setLanguage({LANGUAGE: 'español'}); t.strictEqual(ext.getCurrentLanguage(), 'es'); t.end(); }); test('get the extension locale for a supported locale that differs', t => { ext.setLanguage({LANGUAGE: 'ja-hira'}); t.strictEqual(ext.getCurrentLanguage(), 'ja'); t.end(); });
const test = require('tap').test; const TextToSpeech = require('../../src/extensions/scratch3_text2speech/index.js'); const fakeStage = { textToSpeechLanguage: null }; const fakeRuntime = { getTargetForStage: () => fakeStage, on: () => {} // Stub out listener methods used in constructor. }; const ext = new TextToSpeech(fakeRuntime); test('if no language is saved in the project, use default', t => { t.strictEqual(ext.getCurrentLanguage(), 'en'); t.end(); }); test('if an unsupported language is dropped onto the set language block, use default', t => { ext.setLanguage({LANGUAGE: 'nope'}); t.strictEqual(ext.getCurrentLanguage(), 'en'); t.end(); }); test('get the extension locale for a supported locale that differs', t => { ext.setLanguage({LANGUAGE: 'ja-hira'}); t.strictEqual(ext.getCurrentLanguage(), 'ja'); t.end(); });
Fix date and label calculation
var angular = require('angular'); angular.module('DashCtrl', ['chart.js']).controller('DashController', ['$scope', $scope => { const colorScheme = ['#2a9fd6']; // Calculate and format descending dates back one week const currentDate = new Date(); const oneDay = 1000 * 60 * 60 * 24; let dates = Array.from({length: 7}, (date, i) => new Date(currentDate - oneDay * (6 - i))); let labels = dates.map(date => date.toISOString().substr(5, 5)); $scope.uploadColors = colorScheme; $scope.uploadLabels = labels; $scope.uploadSeries = ['Uploads']; $scope.uploadData = [[10, 20, 30, 20, 15, 20, 45]]; $scope.uploadOptions = { title: { display: true, text: 'Historical Uploads' }, }; $scope.viewColors = colorScheme; $scope.viewLabels = labels; $scope.viewSeries = ['Views']; $scope.viewData = [[5, 11, 4, 3, 7, 9, 21]]; $scope.viewOptions = { title: { display: true, text: 'Historical Views' } }; }]); { }
var angular = require('angular'); angular.module('DashCtrl', ['chart.js']).controller('DashController', ['$scope', $scope => { const colorScheme = ['#2a9fd6']; let weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; for(let i = 0; i < 6 - (new Date()).getDay(); i++) { const back = weekDays.pop(); weekDays.unshift(back); } $scope.uploadColors = colorScheme; $scope.uploadLabels = weekDays; $scope.uploadSeries = ['Uploads']; $scope.uploadData = [[10, 20, 30, 20, 15, 20, 45]]; $scope.uploadOptions = { title: { display: true, text: 'Historical Uploads' }, }; $scope.viewColors = colorScheme; $scope.viewLabels = weekDays; $scope.viewSeries = ['Views']; $scope.viewData = [[5, 11, 4, 3, 7, 9, 21]]; $scope.viewOptions = { title: { display: true, text: 'Historical Views' } }; }]); { }
Fix bug in temporary directory generation.
from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ _FORMATS = ( archivers.TARBALL, archivers.TARBALL_GZ, archivers.TARBALL_BZ2, archivers.TARBALL_XZ, archivers.ZIP, ) @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: with self.settings(ARCHIVE_DIRECTORY=directory): yield None def test_archive(self): """ Test each format """ for fmt in self._FORMATS: with self.subTest(fmt=fmt): with self._wrap_in_temp_dir(): with self.settings(ARCHIVE_FORMAT=fmt): call_command('archive')
from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ _FORMATS = ( archivers.TARBALL, archivers.TARBALL_GZ, archivers.TARBALL_BZ2, archivers.TARBALL_XZ, archivers.ZIP, ) @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: yield self.settings(ARCHIVE_DIRECTORY=directory) def test_archive(self): """ Test each format """ for fmt in self._FORMATS: with self.subTest(fmt=fmt): with self._wrap_in_temp_dir(): with self.settings(ARCHIVE_FORMAT=fmt): call_command('archive')
Add cose() back as a deprecated method for backward compatibility
package org.bouncycastle.crypto.tls; import java.io.IOException; import java.io.OutputStream; /** * An OutputStream for an TLS connection. */ public class TlsOuputStream extends OutputStream { private TlsProtocolHandler handler; protected TlsOuputStream(TlsProtocolHandler handler) { this.handler = handler; } public void write(byte buf[], int offset, int len) throws IOException { this.handler.writeData(buf, offset, len); } public void write(int arg0) throws IOException { byte[] buf = new byte[1]; buf[0] = (byte)arg0; this.write(buf, 0, 1); } /** @deprecated Use 'close' instead */ public void cose() throws IOException { handler.close(); } public void close() throws IOException { handler.close(); } public void flush() throws IOException { handler.flush(); } }
package org.bouncycastle.crypto.tls; import java.io.IOException; import java.io.OutputStream; /** * An OutputStream for an TLS connection. */ public class TlsOuputStream extends OutputStream { private TlsProtocolHandler handler; protected TlsOuputStream(TlsProtocolHandler handler) { this.handler = handler; } public void write(byte buf[], int offset, int len) throws IOException { this.handler.writeData(buf, offset, len); } public void write(int arg0) throws IOException { byte[] buf = new byte[1]; buf[0] = (byte)arg0; this.write(buf, 0, 1); } public void close() throws IOException { handler.close(); } public void flush() throws IOException { handler.flush(); } }
Fix: Increase height of 'About' window
const about = module.exports = { init, win: null } const config = require('../../config') const electron = require('electron') function init () { if (about.win) { return about.win.show() } const win = about.win = new electron.BrowserWindow({ backgroundColor: '#ECECEC', center: true, fullscreen: false, height: 220, icon: getIconPath(), maximizable: false, minimizable: false, resizable: false, show: false, skipTaskbar: true, title: 'About ' + config.APP_WINDOW_TITLE, useContentSize: true, webPreferences: { nodeIntegration: true, enableBlinkFeatures: 'AudioVideoTracks' }, width: 300 }) win.loadURL(config.WINDOW_ABOUT) // No menu on the About window win.setMenu(null) win.once('ready-to-show', function () { win.show() }) win.once('closed', function () { about.win = null }) } function getIconPath () { return process.platform === 'win32' ? config.APP_ICON + '.ico' : config.APP_ICON + '.png' }
const about = module.exports = { init, win: null } const config = require('../../config') const electron = require('electron') function init () { if (about.win) { return about.win.show() } const win = about.win = new electron.BrowserWindow({ backgroundColor: '#ECECEC', center: true, fullscreen: false, height: 170, icon: getIconPath(), maximizable: false, minimizable: false, resizable: false, show: false, skipTaskbar: true, title: 'About ' + config.APP_WINDOW_TITLE, useContentSize: true, webPreferences: { nodeIntegration: true, enableBlinkFeatures: 'AudioVideoTracks' }, width: 300 }) win.loadURL(config.WINDOW_ABOUT) // No menu on the About window win.setMenu(null) win.once('ready-to-show', function () { win.show() }) win.once('closed', function () { about.win = null }) } function getIconPath () { return process.platform === 'win32' ? config.APP_ICON + '.ico' : config.APP_ICON + '.png' }
Revert "modified error controller to be cli sensitive" This reverts commit 979ba31da56aa2355294435f28698998d0a96574.
<?php namespace devmo\controllers; /** * Default base controller for creating the wrapper around errors * * @category Framework * @author Dan Wager * @copyright Copyright (c) 2007 Devmo * @version 1.0 */ class Error extends \devmo\controllers\Controller { public $exception; public function run (array $args=null) { // log it $message = "Error:"; foreach ($args as $k=>$v) $message .= " {$k}:{$v}"; // build wrapper $error = $this->getView("devmo.views.{$this->exception->name}Error",$args); $view = $this->getView('devmo.views.Error',array('body'=>$error,'trace'=>$this->exception->__toViewString())); $wrap = $this->runController('devmo.SiteWrapper',array('title'=>'Problems!','body'=>$view)); return $wrap; } public function setException ($exception) { $this->exception = $exception; } }
<?php namespace devmo\controllers; /** * Default base controller for creating the wrapper around errors * * @category Framework * @author Dan Wager * @copyright Copyright (c) 2007 Devmo * @version 1.0 */ class Error extends \devmo\controllers\Controller { public $exception; public function run (array $args=null) { // log it $message = "Error:"; foreach ($args as $k=>$v) $message .= " {$k}:{$v}"; // build wrapper $view = null; if (Config::isCli()) { $view = $this->getView('devmo.echo'); $view->string = $this->exception; } else { $error = $this->getView("devmo.views.{$this->exception->name}Error",$args); $view = $this->getView('devmo.views.Error',array('body'=>$error,'trace'=>$this->exception->__toViewString())); $view = $this->runController('devmo.SiteWrapper',array('title'=>'Problems!','body'=>$view)); } return $view; } public function setException ($exception) { $this->exception = $exception; } }
Increment minor version for :fire: HOTFIX release
# -*- coding: utf-8 -*- # # Author: Taylor Smith <taylor.smith@alkaline-ml.com> # # The pyramid module __version__ = "0.6.2" try: # this var is injected in the setup build to enable # the retrieval of the version number without actually # importing the un-built submodules. __PYRAMID_SETUP__ except NameError: __PYRAMID_SETUP__ = False if __PYRAMID_SETUP__: import sys import os sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep) else: # check that the build completed properly. This prints an informative # message in the case that any of the C code was not properly compiled. from . import __check_build __all__ = [ 'arima', 'compat', 'datasets', 'utils' ] def setup_module(module): import numpy as np import random _random_seed = int(np.random.uniform() * (2 ** 31 - 1)) np.random.seed(_random_seed) random.seed(_random_seed)
# -*- coding: utf-8 -*- # # Author: Taylor Smith <taylor.smith@alkaline-ml.com> # # The pyramid module __version__ = "0.6.1-dev0" try: # this var is injected in the setup build to enable # the retrieval of the version number without actually # importing the un-built submodules. __PYRAMID_SETUP__ except NameError: __PYRAMID_SETUP__ = False if __PYRAMID_SETUP__: import sys import os sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep) else: # check that the build completed properly. This prints an informative # message in the case that any of the C code was not properly compiled. from . import __check_build __all__ = [ 'arima', 'compat', 'datasets', 'utils' ] def setup_module(module): import numpy as np import random _random_seed = int(np.random.uniform() * (2 ** 31 - 1)) np.random.seed(_random_seed) random.seed(_random_seed)
Refactor the Configuration.Env function to be easier to understand
package main import ( "encoding/json" "fmt" "github.com/imdario/mergo" "io/ioutil" ) // Configuration is the configuration type type Configuration struct { Environment Environments map[string]Environment `json:"environments"` } // Load open, read and parse the given configuration file func Load(filename string) (Configuration, error) { var c Configuration raw, err := ioutil.ReadFile(filename) if err != nil { return c, err } err = json.Unmarshal(raw, &c) if err != nil { return c, err } return c, nil } // Env return the requested environment from the configuration func (c Configuration) Env(name string) (Environment, error) { if name == "default" { return c.Environment, nil } env, found := c.Environments[name] if !found { return Environment{}, fmt.Errorf("unknown environment %s", name) } _ = mergo.Merge(&env, c.Environment) // No error can possibly occur here return env, nil }
package main import ( "encoding/json" "fmt" "github.com/imdario/mergo" "io/ioutil" ) // Configuration is the configuration type type Configuration struct { Environment Environments map[string]Environment `json:"environments"` } // Load open, read and parse the given configuration file func Load(filename string) (Configuration, error) { var c Configuration raw, err := ioutil.ReadFile(filename) if err != nil { return c, err } err = json.Unmarshal(raw, &c) if err != nil { return c, err } return c, nil } // Env return the requested environment from the configuration func (c Configuration) Env(name string) (Environment, error) { if name == "default" { return c.Environment, nil } overrides, found := c.Environments[name] if !found { return Environment{}, fmt.Errorf("unknown environment %s", name) } _ = mergo.Merge(&overrides, c.Environment) // No error can possibly occur here return overrides, nil }
Fix weird logo size on Firefox
import React from 'react'; import SVGInline from 'react-svg-inline'; import svg from '../../static/logo.svg'; const Logo = (props) => { return ( <SVGInline svg={svg} desc={props.desc} width={props.width} height={props.height} cleanup={['width', 'height']} /> ); }; Logo.propTypes = { desc: React.PropTypes.string, width: React.PropTypes.string, height: React.PropTypes.string, }; Logo.defaultProps = { desc: 'devnews logo', width: 'auto', height: '20px', }; export default Logo;
import React from 'react'; import SVGInline from 'react-svg-inline'; import svg from '../../static/logo.svg'; const Logo = (props) => { return ( <SVGInline svg={svg} desc={props.desc} width={props.width} height={props.height} /> ); }; Logo.propTypes = { desc: React.PropTypes.string, width: React.PropTypes.string, height: React.PropTypes.string, }; Logo.defaultProps = { desc: 'devnews logo', width: 'auto', height: '20', }; export default Logo;
Use Parser.module instead of Parser.scope
import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.module.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.module.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.module.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
import jedi from jedi.parsing import Parser from . import base def test_explicit_absolute_imports(): """ Detect modules with ``from __future__ import absolute_import``. """ parser = Parser("from __future__ import absolute_import", "test.py") assert parser.scope.explicit_absolute_import def test_no_explicit_absolute_imports(): """ Detect modules without ``from __future__ import absolute_import``. """ parser = Parser("1", "test.py") assert not parser.scope.explicit_absolute_import def test_dont_break_imports_without_namespaces(): """ The code checking for ``from __future__ import absolute_import`` shouldn't assume that all imports have non-``None`` namespaces. """ src = "from __future__ import absolute_import\nimport xyzzy" parser = Parser(src, "test.py") assert parser.scope.explicit_absolute_import @base.cwd_at("test/absolute_import") def test_can_complete_when_shadowing(): filename = "unittest.py" with open(filename) as f: lines = f.readlines() src = "".join(lines) script = jedi.Script(src, len(lines), len(lines[1]), filename) assert script.completions()
Add Composer version in about command
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class AboutCommand extends BaseCommand { protected function configure() { $this ->setName('about') ->setDescription('Shows a short information about Composer.') ->setHelp( <<<EOT <info>php composer.phar about</info> EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $composerVersion = Composer::getVersion(); $this->getIO()->write( <<<EOT <info>Composer - Dependency Manager for PHP - version $composerVersion</info> <comment>Composer is a dependency manager tracking local dependencies of your projects and libraries. See https://getcomposer.org/ for more information.</comment> EOT ); return 0; } }
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class AboutCommand extends BaseCommand { protected function configure() { $this ->setName('about') ->setDescription('Shows the short information about Composer.') ->setHelp( <<<EOT <info>php composer.phar about</info> EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $this->getIO()->write( <<<EOT <info>Composer - Dependency Manager for PHP</info> <comment>Composer is a dependency manager tracking local dependencies of your projects and libraries. See https://getcomposer.org/ for more information.</comment> EOT ); return 0; } }
Fix the rows fetching for the enum
'use strict'; const Promise = require('bluebird'); const db = require('../shared/db'); const getSources = require('./sources'); const entries = require('./entries'); const insertEntries = entries.insert; const deleteEntries = entries.delete; module.exports = function() { return Promise.using(db(), function(client) { return client.queryAsync({ name: 'get_distributions', text: 'select enum_range(null::distribution)', values: [] }).get(0).get('rows').get(0).get('enum_range').then(function(range) { return range.match(/{(.+)}/)[1].split(','); }).map(function(distribution) { deleteEntries(distribution) .then(getSources) .then(insertEntries) .done(); }); }); };
'use strict'; const Promise = require('bluebird'); const db = require('../shared/db'); const getSources = require('./sources'); const entries = require('./entries'); const insertEntries = entries.insert; const deleteEntries = entries.delete; module.exports = function() { return Promise.using(db(), function(client) { return client.queryAsync({ name: 'get_distributions', text: 'select enum_range(null::distribution)', values: [] }).get('rows').get(0).get('enum_range').then(function(range) { return range.match(/{(.+)}/)[1].split(','); }).map(function(distribution) { deleteEntries(distribution) .then(getSources) .then(insertEntries) .done(); }); }); };
Convert public key string type in server This fixes a segmentation fault caused by an incorrect string encoding when run in Python 2.7.
import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(str(request.form['PUBLIC_KEY'])) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e)
import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(request.form['PUBLIC_KEY']) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e)
Change command name in hint
package com.carrot.carrotshop.listener; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import com.carrot.carrotshop.ShopsData; public class PlayerConnexionListener { @Listener(order=Order.LATE) public void onPlayerJoin(ClientConnectionEvent.Join event) { if (ShopsData.hasSoldSomethingOffline(event.getTargetEntity().getUniqueId()) && event.getTargetEntity().hasPermission("carrotshop.report.self")) { event.getTargetEntity().sendMessage(Text.of(TextColors.YELLOW, "Someone used your shop signs while you were away. Use ", Text.builder("/carrotreport") .color(TextColors.DARK_AQUA) .onClick(TextActions.runCommand("/carrotreport")).build(), TextColors.YELLOW, " for more details" )); } } }
package com.carrot.carrotshop.listener; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import com.carrot.carrotshop.ShopsData; public class PlayerConnexionListener { @Listener(order=Order.LATE) public void onPlayerJoin(ClientConnectionEvent.Join event) { if (ShopsData.hasSoldSomethingOffline(event.getTargetEntity().getUniqueId()) && event.getTargetEntity().hasPermission("carrotshop.report.self")) { event.getTargetEntity().sendMessage(Text.of(TextColors.YELLOW, "Someone used your shop signs while you were away. Use ", Text.builder("/cs report") .color(TextColors.DARK_AQUA) .onClick(TextActions.runCommand("/cs report")).build(), TextColors.YELLOW, " for more details" )); } } }
Move code content to center of view
@extends("layout.base") @section("title", "Wdi Paste - {$paste->name}") @section("container") <h1 class="display-1">{{ $paste->name }}<small>.{{$paste->extension}}</small></h1> <blockquote class="blockquote"> <p class="mb-0">{{ $paste->description }}</p> <footer class="blockquote-footer"> <span>Creato il {{ $paste->created_at }} Linguaggio:</span> <cite title="Linguaggio"><a href="{{ route("language.show", $paste->language->name) }}">{{ $paste->language->name }}</a></cite> </footer> </blockquote> <div class="card m-5"> <div class="card-body p-0"> <pre class="m-0" v-pre><code>{{ $paste->code }}</code></pre> </div> </div> @endsection @section("js") <script>window.HighlightJs.initHighlightingOnLoad();</script> @endsection
@extends("layout.base") @section("title", "Wdi Paste - {$paste->name}") @section("container") <h1 class="display-1">{{ $paste->name }}<small>.{{$paste->extension}}</small></h1> <blockquote class="blockquote"> <p class="mb-0">{{ $paste->description }}</p> <footer class="blockquote-footer"> <span>Creato il {{ $paste->created_at }} Linguaggio:</span> <cite title="Linguaggio"><a href="{{ route("language.show", $paste->language->name) }}">{{ $paste->language->name }}</a></cite> </footer> </blockquote> <div class="card"> <div class="card-body p-0"> <pre class="m-0" v-pre><code>{{ $paste->code }}</code></pre> </div> </div> @endsection @section("js") <script>window.HighlightJs.initHighlightingOnLoad();</script> @endsection
Add repeat support when reading ADC values. - There is a bug in the ADC driver which allows reads to return stale or otherwise incorrect readings. Though there doesn't appear to be a guaranteed minimum count, repeating the read a number of times will eventually yeild the correct value. - Object initializtion now takes a default repeat count, which can optionally be overridden in the read() call.
"""Access ADCs vias SysFS interface.""" import glob class ADC(object): def __init__(self, num, repeat=8, base_filename='/sys/devices/ocp.*/helper.*/AIN'): self.num = num # Need to read a glob here, since numbering is not consistent # TODO: Verify num is reasonable (0-6) self.sysfs = glob.glob(base_filename + str(num))[0] self.repeat = repeat def __str__(self): out = "ADC#%d (%s)" % (self.num, self.sysfs) return out def read(self, repeat=None): if not repeat: repeat = self.repeat for i in range(repeat): val = None while not val: try: with open(self.sysfs, 'r') as f: val = f.read() except: pass return int(val)
"""Access ADCs vias SysFS interface.""" import glob class ADC(object): def __init__(self, num, base_filename='/sys/devices/ocp.*/helper.*/AIN'): self.num = num # Need to read a glob here, since numbering is not consistent # TODO: Verify num is reasonable (0-6) self.sysfs = glob.glob(base_filename + str(num))[0] def __str__(self): out = "ADC#%d (%s)" % (self.num, self.sysfs) return out def read(self): with open(self.sysfs, 'r') as f: f.read() val = None # Read a second time to ensure current value (bug in ADC driver) while not val: try: with open(self.sysfs, 'r') as f: val = f.read() except: pass return int(val)
Disable code formatting in security configuration region
package sk.tuke.cloud.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; /** * @author Dominik Matta */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private final PublicKeyProvider publicKeyProvider; @Autowired public SecurityConfiguration(PublicKeyProvider publicKeyProvider) { this.publicKeyProvider = publicKeyProvider; } @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .anyRequest().authenticated() .and() .apply(new JWTConfigurer(publicKeyProvider)); // @formatter:on } }
package sk.tuke.cloud.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; /** * @author Dominik Matta */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private final PublicKeyProvider publicKeyProvider; @Autowired public SecurityConfiguration(PublicKeyProvider publicKeyProvider) { this.publicKeyProvider = publicKeyProvider; } @Override protected void configure(HttpSecurity http) throws Exception { http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .anyRequest().authenticated() .and() .apply(new JWTConfigurer(publicKeyProvider)); } }
Refactor where notifications look for messages.
@if ($message = Session::get('success')) <div class="alert alert-success alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Success:</strong> {{ $message['text'] }} </div> {{ Session::forget('success') }} @endif @if ($message = Session::get('error')) <div class="alert alert-danger alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Error:</strong> {{ $message['text'] }} </div> {{ Session::forget('error') }} @endif @if ($message = Session::get('warning')) <div class="alert alert-warning alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Warning:</strong> {{ $message['text'] }} </div> {{ Session::forget('warning') }} @endif @if ($message = Session::get('info')) <div class="alert alert-info alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>FYI:</strong> {{ $message['text'] }} </div> {{ Session::forget('info') }} @endif
@if ($message = Session::get('success')) <div class="alert alert-success alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Success:</strong> {{ $message }} </div> {{ Session::forget('success') }} @endif @if ($message = Session::get('error')) <div class="alert alert-danger alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Error:</strong> {{ $message }} </div> {{ Session::forget('error') }} @endif @if ($message = Session::get('warning')) <div class="alert alert-warning alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Warning:</strong> {{ $message }} </div> {{ Session::forget('warning') }} @endif @if ($message = Session::get('info')) <div class="alert alert-info alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>FYI:</strong> {{ $message }} </div> {{ Session::forget('info') }} @endif
Add ending doc block annotation for ignoring coding standards
<?php namespace Zend\I18n\View; use IntlDateFormatter; // @codingStandardsIgnoreStart /** * Trait HelperTrait * * The trait provides convenience methods for view helpers, * defined by the zend-i18n component. It is designed to be used * for type-hinting $this variable inside zend-view templates via doc blocks. * * The base class is PhpRenderer, followed by the helper trait from * the zend-i18n component. However, multiple helper traits from different * Zend components can be chained afterwards. * * @example @var \Zend\View\Renderer\PhpRenderer|\Zend\I18n\View\HelperTrait $this * * @method string currencyFormat($number, $currencyCode = null, $showDecimals = null, $locale = null, $pattern = null) * @method string dateFormat($date, $dateType = IntlDateFormatter::NONE, $timeType = IntlDateFormatter::NONE, $locale = null, $pattern = null) * @method string numberFormat($number, $formatStyle = null, $formatType = null, $locale = null, $decimals = null, array $textAttributes = null) * @method string plural($strings, $number) * @method string translate($message, $textDomain = null, $locale = null) * @method string translatePlural($singular, $plural, $number, $textDomain = null, $locale = null) */ trait HelperTrait { } // @codingStandardsIgnoreEnd
<?php namespace Zend\I18n\View; use IntlDateFormatter; // @codingStandardsIgnoreStart /** * Trait HelperTrait * * The trait provides convenience methods for view helpers, * defined by the zend-i18n component. It is designed to be used * for type-hinting $this variable inside zend-view templates via doc blocks. * * The base class is PhpRenderer, followed by the helper trait from * the zend-i18n component. However, multiple helper traits from different * Zend components can be chained afterwards. * * @example @var \Zend\View\Renderer\PhpRenderer|\Zend\I18n\View\HelperTrait $this * * @method string currencyFormat($number, $currencyCode = null, $showDecimals = null, $locale = null, $pattern = null) * @method string dateFormat($date, $dateType = IntlDateFormatter::NONE, $timeType = IntlDateFormatter::NONE, $locale = null, $pattern = null) * @method string numberFormat($number, $formatStyle = null, $formatType = null, $locale = null, $decimals = null, array $textAttributes = null) * @method string plural($strings, $number) * @method string translate($message, $textDomain = null, $locale = null) * @method string translatePlural($singular, $plural, $number, $textDomain = null, $locale = null) */ trait HelperTrait { }
Fix more of the test.
import json from jazzband.projects.tasks import update_project_by_hook from jazzband.tasks import JazzbandSpinach def post(client, hook, data, guid="abc"): headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid} return client.post( "/hooks", content_type="application/json", data=json.dumps(data), headers=headers, ) def test_ping(client): rv = post(client, "ping", {}) assert b"pong" in rv.data assert rv.status_code == 200 def test_repo_transferred_hook(client, datadir, mocker): contents = (datadir / "repository.json").read_text() mocked_schedule = mocker.patch.object(JazzbandSpinach, "schedule") response = post(client, "repository", json.loads(contents)) assert response.data response_string = response.data.decode("utf-8") assert response_string.startswith("Started updating the project using hook id repo-added-") mocked_schedule.assert_called_once()
import json from jazzband.projects.tasks import update_project_by_hook from jazzband.tasks import JazzbandSpinach def post(client, hook, data, guid="abc"): headers = {"X-GitHub-Event": hook, "X-GitHub-Delivery": guid} return client.post( "/hooks", content_type="application/json", data=json.dumps(data), headers=headers, ) def test_ping(client): rv = post(client, "ping", {}) assert b"pong" in rv.data assert rv.status_code == 200 def test_repo_transferred_hook(client, datadir, mocker): contents = (datadir / "repository.json").read_text() mocked_schedule = mocker.patch.object(JazzbandSpinach, "schedule") response = post(client, "repository", json.loads(contents)) assert response.data response_string = response.data.decode("utf-8") assert response_string.startswith("Started updating the project using hook id repo-added-") mocked_schedule.assert_called_once_with(update_project_by_hook, response_string)
Allow any ip in the get_span expected span since it's not deterministic
# -*- coding: utf-8 -*- import mock import pytest @pytest.fixture def default_trace_id_generator(dummy_request): return lambda dummy_request: '17133d482ba4f605' @pytest.fixture def settings(): return { 'zipkin.tracing_percent': 100, 'zipkin.trace_id_generator': default_trace_id_generator, } @pytest.fixture def get_span(): return { 'id': '1', 'tags': { 'http.uri': '/sample', 'http.uri.qs': '/sample', 'http.route': '/sample', 'response_status_code': '200', }, 'name': 'GET /sample', 'traceId': '17133d482ba4f605', 'localEndpoint': { 'ipv4': mock.ANY, 'port': 80, 'serviceName': 'acceptance_service', }, 'kind': 'SERVER', 'timestamp': mock.ANY, 'duration': mock.ANY, }
# -*- coding: utf-8 -*- import mock import pytest @pytest.fixture def default_trace_id_generator(dummy_request): return lambda dummy_request: '17133d482ba4f605' @pytest.fixture def settings(): return { 'zipkin.tracing_percent': 100, 'zipkin.trace_id_generator': default_trace_id_generator, } @pytest.fixture def get_span(): return { 'id': '1', 'tags': { 'http.uri': '/sample', 'http.uri.qs': '/sample', 'http.route': '/sample', 'response_status_code': '200', }, 'name': 'GET /sample', 'traceId': '17133d482ba4f605', 'localEndpoint': { 'ipv4': '127.0.0.1', 'port': 80, 'serviceName': 'acceptance_service', }, 'kind': 'SERVER', 'timestamp': mock.ANY, 'duration': mock.ANY, }
Add comment to amqp.worker.join call.
from r2.lib import amqp, websockets from reddit_liveupdate.models import ActiveVisitorsByLiveUpdateEvent def broadcast_update(): event_ids = ActiveVisitorsByLiveUpdateEvent._cf.get_range( column_count=1, filter_empty=False) for event_id, is_active in event_ids: if is_active: count, is_fuzzed = ActiveVisitorsByLiveUpdateEvent.get_count( event_id, cached=False) else: count, is_fuzzed = 0, False payload = { "count": count, "fuzzed": is_fuzzed, } websockets.send_broadcast( "/live/" + event_id, type="activity", payload=payload) # ensure that all the amqp messages we've put on the worker's queue are # sent before we allow this script to exit. amqp.worker.join()
from r2.lib import amqp, websockets from reddit_liveupdate.models import ActiveVisitorsByLiveUpdateEvent def broadcast_update(): event_ids = ActiveVisitorsByLiveUpdateEvent._cf.get_range( column_count=1, filter_empty=False) for event_id, is_active in event_ids: if is_active: count, is_fuzzed = ActiveVisitorsByLiveUpdateEvent.get_count( event_id, cached=False) else: count, is_fuzzed = 0, False payload = { "count": count, "fuzzed": is_fuzzed, } websockets.send_broadcast( "/live/" + event_id, type="activity", payload=payload) amqp.worker.join()
Add int to input statements Ref #23 #10
"""Creates the station class""" class Station: """ Each train station is an instance of the Station class. Methods: __init__: creates a new stations total_station_pop: calculates total station population """ def __init__(self): self.capacity = int(eval(input("Enter the max capacity of the station: "))) #testfuntion() self.escalators = int(eval(input("Enter the number of escalators in the station: "))) #testfuntion() self.train_wait = int(eval(input("Enter the wait time between trains in seconds: "))) #testfuntion() self.travelors_arriving = int(eval(input("How many people just exited the train? "))) #testfuntion() self.travelors_departing = int(eval(input("How many people are waiting for the train? "))) #testfuntion()
"""Creates the station class""" class Station: """ Each train station is an instance of the Station class. Methods: __init__: creates a new stations total_station_pop: calculates total station population """ def __init__(self): self.capacity = eval(input("Enter the max capacity of the station: ")) #testfuntion() self.escalators = eval(input("Enter the number of escalators in the station: ")) #testfuntion() self.train_wait = eval(input("Enter the wait time between trains: ")) #testfuntion() self.travelors_arriving = eval(input("How many people just exited the train? ")) #testfuntion() self.travelors_departing = eval(input("How many people are waiting for the train? ")) #testfuntion()
Check Leaflet version on init
/** * @api * @namespace carto * * @description * # Carto.js * All the library features are exposed through the `carto` namespace. * * * - **Client** : The api client. * - **source** : Source description * - **style** : Style description * - **layer** : Layer description * - **dataview** : Dataview description * - **filter** : Filter description * * - **events** : The events exposed. * - **operation** : The operations exposed. */ if (!window.L) { throw new Error('Leaflet is required'); } if (window.L.version < '1.0.0') { throw new Error('Leaflet +1.0 is required'); } var Client = require('./client'); var source = require('./source'); var style = require('./style'); var layer = require('./layer'); var dataview = require('./dataview'); var filter = require('./filter'); var events = require('./events'); var operation = require('./constants').operation; var carto = window.carto = { Client: Client, source: source, style: style, layer: layer, dataview: dataview, filter: filter, events: events, operation: operation }; module.exports = carto;
/** * @api * @namespace carto * * @description * # Carto.js * All the library features are exposed through the `carto` namespace. * * * - **Client** : The api client. * - **source** : Source description * - **style** : Style description * - **layer** : Layer description * - **dataview** : Dataview description * - **filter** : Filter description * * - **events** : The events exposed. * - **operation** : The operations exposed. */ var Client = require('./client'); var source = require('./source'); var style = require('./style'); var layer = require('./layer'); var dataview = require('./dataview'); var filter = require('./filter'); var events = require('./events'); var operation = require('./constants').operation; var carto = window.carto = { Client: Client, source: source, style: style, layer: layer, dataview: dataview, filter: filter, events: events, operation: operation }; module.exports = carto;
flake8: Fix all warnings in top-level urlconf
from __future__ import absolute_import from django.conf import settings from django.conf.urls import include, patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.base import TemplateView admin.autodiscover() urlpatterns = patterns( '', # Robots not welcome (r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), # User accounts management (r'^account/', include('comics.accounts.urls')), # API (r'^api/', include('comics.api.urls')), # Help, about and feedback (r'^help/', include('comics.help.urls')), # Comic crawler status (r'^status/', include('comics.status.urls')), # Django admin (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/', include(admin.site.urls)), # Comics browsing. Must be last one included. (r'^', include('comics.browser.urls')), ) # Let Django host media if doing local development on runserver if not settings.MEDIA_URL.startswith('http'): urlpatterns += patterns( '', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) urlpatterns += staticfiles_urlpatterns()
from __future__ import absolute_import from django.conf import settings from django.conf.urls import include, patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.base import TemplateView admin.autodiscover() urlpatterns = patterns('', # Robots not welcome (r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), # User accounts management (r'^account/', include('comics.accounts.urls')), # API (r'^api/', include('comics.api.urls')), # Help, about and feedback (r'^help/', include('comics.help.urls')), # Comic crawler status (r'^status/', include('comics.status.urls')), # Django admin (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/', include(admin.site.urls)), # Comics browsing. Must be last one included. (r'^', include('comics.browser.urls')), ) # Let Django host media if doing local development on runserver if not settings.MEDIA_URL.startswith('http'): urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) urlpatterns += staticfiles_urlpatterns()
Doc: Standardize Jsdoc style in Defiant.Plugin
'use strict'; /** * Base Plugin class that all subsequent Plugins should be based on. * @class * @memberOf Defiant */ class Plugin { /** * @constructor * @param {Defiant.Engine} engine * The app engine. * @returns {Defiant.Plugin} * The plugin that was instantiated. */ constructor(engine) { /** * @member {Defiant.Engine} Defiant.Plugin#engine * The app engine. */ this.engine = engine; /** * @member {String} Defiant.Plugin#id * A unique string identifier for this plugin. It defaults to the * constructor name. */ this.id = this.constructor.name; /** * @member {number} Defiant.Plugin#weight * The weight of the plugin as seen by the app engine's * [plugin registry]{@link Defiant.Engine#pluginRegistry}. */ this.weight = 0; return this; } /** * All plugins will be initialized in order of their weight by * {@link Defiant.Engine#init}. * @function * @async */ async init() { // Just a stub. } } module.exports = Plugin;
'use strict'; /** * Base Plugin class that all subsequent Plugins should be based on. * @class * @memberOf Defiant */ class Plugin { /** * @constructor * @param {Defiant.Engine} engine The app engine. * @returns {Defiant.Plugin} The plugin that was instantiated. */ constructor(engine) { /** * @member {Defiant.Engine} Defiant.Plugin#engine The app engine. */ this.engine = engine; /** * @member {String} Defiant.Plugin#id A unique string identifier for this * plugin. It defaults to the constructor name. */ this.id = this.constructor.name; /** * @member {number} Defiant.Plugin#weight * The weight of the plugin as seen by the app engine's * [plugin registry]{@link Defiant.Engine#pluginRegistry}. */ this.weight = 0; return this; } /** * All plugins will be initialized in order of their weight by * {@link Defiant.Engine#init}. * @function * @async */ async init() { // Just a stub. } } module.exports = Plugin;
Add Additional Dependencies To Setup
#!/usr/bin/env python from setuptools import setup, find_packages version = '1.3' long_desc = """ nose-perfdump is a Nose plugin that collects per-test performance metrics into an SQLite3 database and reports the slowest tests, test files, and total time spent in tests. It is designed to make profiling tests to improve their speed easier. [Github](https://github.com/etscrivner/nose-perfdump) """ setup( name='nose-perfdump', version=version, description='Dump per-test performance metrics to an SQLite database for querying.', long_description=long_desc, author='Eric Scrivner', keywords='nose,nose plugin,profiler,profiling,tests,unittest', install_requires=['nose', 'pyparsing'], author_email='eric.t.scrivner@gmail.com', url='https://github.com/etscrivner/nose-perfdump', license='BSD', packages=find_packages(), include_package_data=True, entry_points={ 'nose.plugins.0.10': [ 'perfdump = perfdump:PerfDumpPlugin' ], 'console_scripts': [ 'perfdump.console:main' ] } )
#!/usr/bin/env python from setuptools import setup, find_packages version = '1.3' long_desc = """ nose-perfdump is a Nose plugin that collects per-test performance metrics into an SQLite3 database and reports the slowest tests, test files, and total time spent in tests. It is designed to make profiling tests to improve their speed easier. [Github](https://github.com/etscrivner/nose-perfdump) """ setup( name='nose-perfdump', version=version, description='Dump per-test performance metrics to an SQLite database for querying.', long_description=long_desc, author='Eric Scrivner', keywords='nose,nose plugin,profiler,profiling,tests,unittest', install_requires=['nose'], author_email='eric.t.scrivner@gmail.com', url='https://github.com/etscrivner/nose-perfdump', license='BSD', packages=find_packages(), include_package_data=True, entry_points={ 'nose.plugins.0.10': [ 'perfdump = perfdump:PerfDumpPlugin' ], 'console_scripts': [ 'perfdump.console:main' ] } )
Use hasOwnProperty when setting defaults
/** * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var hasOwn = Object.prototype.hasOwnProperty; exports.guessTabWidth = function(source) { var counts = []; // Sparse array. var lastIndent = 0; source.split("\n").forEach(function(line) { var indent = /^\s*/.exec(line)[0].length; var diff = Math.abs(indent - lastIndent); counts[diff] = ~~counts[diff] + 1; lastIndent = indent; }); var maxCount = -1; var result = 2; for (var tabWidth = 1; tabWidth < counts.length; tabWidth += 1) { if (tabWidth in counts && counts[tabWidth] > maxCount) { maxCount = counts[tabWidth]; result = tabWidth; } } return result; }; exports.defaults = function(obj) { var len = arguments.length; var extension; for (var i = 1; i < len; ++i) { if ((extension = arguments[i])) { for (var key in extension) { if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) { obj[key] = extension[key]; } } } } return obj; };
/** * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ exports.guessTabWidth = function(source) { var counts = []; // Sparse array. var lastIndent = 0; source.split("\n").forEach(function(line) { var indent = /^\s*/.exec(line)[0].length; var diff = Math.abs(indent - lastIndent); counts[diff] = ~~counts[diff] + 1; lastIndent = indent; }); var maxCount = -1; var result = 2; for (var tabWidth = 1; tabWidth < counts.length; tabWidth += 1) { if (tabWidth in counts && counts[tabWidth] > maxCount) { maxCount = counts[tabWidth]; result = tabWidth; } } return result; }; exports.defaults = function(obj) { var len = arguments.length; var extension; for (var i = 1; i < len; ++i) { if ((extension = arguments[i])) { for (var key in extension) { if (obj[key] === undefined) { obj[key] = extension[key]; } } } } return obj; };
Include format when constructing moment.js object Constructing a new instance of `moment` without a format string will cause a deprecation warning: ``` Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info. ``` Specifically, the resolution is mentioned here: https://github.com/moment/moment/issues/1407#ref-issue-32451744 So, instead of this, `moment('2/19/2018 10:34 am MST')`, you need to to include the format that you passing in: ``` var endDate = moment('2/19/2018 10:34 am MST', 'M/DD/YYYY hh:mm a z'); ``` Or alse, 1) used ISO format, 2) you can wrap the string in a JS `Date` (cherry picked from commit 3d81065966f6dde3fd69a7c89bf1ca9bceebd0a6)
define(function (require) { var moment = require('moment'), AppDispatcher = require('dispatchers/AppDispatcher'), ImageConstants = require('constants/ImageConstants'); return { updateImageAttributes: function (image, newAttributes) { if(newAttributes.end_date != null) { var end_date; if (typeof newAttributes.end_date === "object") { end_date = newAttributes.end_date } else { end_date = moment(newAttributes.end_date, "M/DD/YYYY hh:mm a z"); } newAttributes.end_date = end_date; } image.set({ name: newAttributes.name, description: newAttributes.description, end_date: newAttributes.end_date, tags: newAttributes.tags }); AppDispatcher.handleRouteAction({ actionType: ImageConstants.IMAGE_UPDATE, payload: {image: image} }); } }; });
define(function (require) { var moment = require('moment'), AppDispatcher = require('dispatchers/AppDispatcher'), ImageConstants = require('constants/ImageConstants'); return { updateImageAttributes: function (image, newAttributes) { if(newAttributes.end_date != null) { var end_date; if (typeof newAttributes.end_date === "object") { end_date = newAttributes.end_date } else { end_date = moment(newAttributes.end_date); } newAttributes.end_date = end_date; } image.set({ name: newAttributes.name, description: newAttributes.description, end_date: newAttributes.end_date, tags: newAttributes.tags }); AppDispatcher.handleRouteAction({ actionType: ImageConstants.IMAGE_UPDATE, payload: {image: image} }); } }; });
Use pointers to be more efficient
package git import ( "errors" "regexp" ) type GitRemote struct { Name string URL string } func Remotes() ([]*GitRemote, error) { r := regexp.MustCompile("(.+)\t(.+github.com.+) \\(push\\)") output, err := execGitCmd("remote", "-v") if err != nil { return nil, errors.New("Can't load git remote") } remotes := make([]*GitRemote, 0) for _, o := range output { if r.MatchString(o) { match := r.FindStringSubmatch(o) remotes = append(remotes, &GitRemote{Name: match[1], URL: match[2]}) } } if len(remotes) == 0 { return nil, errors.New("Can't find git remote (push)") } return remotes, nil } func OriginRemote() (*GitRemote, error) { remotes, err := Remotes() if err != nil { return nil, err } for _, r := range remotes { if r.Name == "origin" { return r, nil } } return nil, errors.New("Can't find git remote orign (push)") }
package git import ( "errors" "regexp" ) type GitRemote struct { Name string URL string } func Remotes() ([]GitRemote, error) { r := regexp.MustCompile("(.+)\t(.+github.com.+) \\(push\\)") output, err := execGitCmd("remote", "-v") if err != nil { return nil, errors.New("Can't load git remote") } remotes := make([]GitRemote, 0) for _, o := range output { if r.MatchString(o) { match := r.FindStringSubmatch(o) remotes = append(remotes, GitRemote{Name: match[1], URL: match[2]}) } } if len(remotes) == 0 { return nil, errors.New("Can't find git remote (push)") } return remotes, nil } func OriginRemote() (*GitRemote, error) { remotes, err := Remotes() if err != nil { return nil, err } for _, r := range remotes { if r.Name == "origin" { return &r, nil } } return nil, errors.New("Can't find git remote orign (push)") }
Add tests for parse & serialize
package venom import ( "testing" "github.com/stretchr/testify/assert" ) type setup struct { s string m map[string]string } var ( table = map[string]setup{ "empty": { s: "", m: map[string]string{}, }, "single": { s: "foo=bar", m: map[string]string{ "foo": "bar", }, }, "multiple": { s: "foo=bar,goo=moo", m: map[string]string{ "foo": "bar", "goo": "moo", }, }, } ) func TestParse(t *testing.T) { for name, x := range table { t.Run(name, func(t *testing.T) { m, err := parseMapStringString(x.s, ",", "=") assert.Nil(t, err) assert.Equal(t, m, x.m) }) } } func TestSerialize(t *testing.T) { for name, x := range table { t.Run(name, func(t *testing.T) { s, err := serializeMapStringString(x.m, ",", "=") assert.Nil(t, err) assert.Equal(t, s, x.s) }) } } func TestFailNoSep(t *testing.T) { m, err := parseMapStringString("foo", ",", "=") assert.NotNil(t, err) assert.Nil(t, m) }
package venom import ( "testing" "github.com/stretchr/testify/assert" ) func TestParseEmpty(t *testing.T) { m, err := parseMapStringString("", ",", "=") assert.Nil(t, err) assert.Equal(t, m, map[string]string{}) } func TestParseSingle(t *testing.T) { m, err := parseMapStringString("foo=bar", ",", "=") assert.Nil(t, err) assert.Equal(t, m, map[string]string{ "foo": "bar", }) } func TestParseMultiple(t *testing.T) { m, err := parseMapStringString("foo=bar,moo=goo", ",", "=") assert.Nil(t, err) assert.Equal(t, m, map[string]string{ "foo": "bar", "moo": "goo", }) } func TestFailNoSep(t *testing.T) { m, err := parseMapStringString("foo", ",", "=") assert.NotNil(t, err) assert.Nil(t, m) }
Add serial version uid to users class
/******************************************************************************* ** Copyright (c) 2010 - 2013 Ushahidi Inc ** All rights reserved ** Contact: team@ushahidi.com ** Website: http://www.ushahidi.com ** ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: http://www.gnu.org/licenses/lgpl.html. ** ** ** If you have questions regarding the use of this file, please contact ** Ushahidi developers at team@ushahidi.com. ** ******************************************************************************/ package com.crowdmap.java.sdk.json; import com.crowdmap.java.sdk.model.User; import java.io.Serializable; import java.util.List; /** * Users resources */ public class Users extends Response implements Serializable { private static final long serialVersionUID = 8172708394083993131L; private List<User> users; public List<User> getUsers(){ return users; } }
/******************************************************************************* ** Copyright (c) 2010 - 2013 Ushahidi Inc ** All rights reserved ** Contact: team@ushahidi.com ** Website: http://www.ushahidi.com ** ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: http://www.gnu.org/licenses/lgpl.html. ** ** ** If you have questions regarding the use of this file, please contact ** Ushahidi developers at team@ushahidi.com. ** ******************************************************************************/ package com.crowdmap.java.sdk.json; import com.crowdmap.java.sdk.model.User; import java.io.Serializable; import java.util.List; /** * Users resources */ public class Users extends Response implements Serializable { private List<User> users; public List<User> getUsers(){ return users; } }
Rename default PHP log file `php_error.log` -> `php_errors.log`
<?php /** * @title All Environment File * @desc File for all environments. * * @author Pierre-Henry Soria <hello@ph7cms.com> * @link http://ph7cms.com * @copyright (c) 2012-2019, Pierre-Henry Soria. All Rights Reserved. * @license MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / Config / Environment */ namespace PH7; defined('PH7') or exit('Restricted access'); ini_set('log_errors', 'On'); ini_set('error_log', PH7_PATH_LOG . 'php_errors.log'); ini_set('ignore_repeated_errors', 'On'); // Do not log repeated errors that occur in same file on same line // For Security Session // ini_set('session.auto_start', 0); // The default configuration of PHP (php.ini) should already have this setting disabled ini_set('session.use_cookies', 1); ini_set('session.use_only_cookies', 1); ini_set('session.use_trans_sid', 0); ini_set('session.hash_function', 1); ini_set('session.hash_bits_per_character', 6);
<?php /** * @title All Environment File * @desc File for all environments. * * @author Pierre-Henry Soria <hello@ph7cms.com> * @link http://ph7cms.com * @copyright (c) 2012-2019, Pierre-Henry Soria. All Rights Reserved. * @license MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / Config / Environment */ namespace PH7; defined('PH7') or exit('Restricted access'); ini_set('log_errors', 'On'); ini_set('error_log', PH7_PATH_LOG . 'php_error.log'); ini_set('ignore_repeated_errors', 'On'); // Do not log repeated errors that occur in same file on same line // For Security Session // ini_set('session.auto_start', 0); // The default configuration of PHP (php.ini) should already have this setting disabled ini_set('session.use_cookies', 1); ini_set('session.use_only_cookies', 1); ini_set('session.use_trans_sid', 0); ini_set('session.hash_function', 1); ini_set('session.hash_bits_per_character', 6);
Fix URLs to the gh-pages
/** * @link https://github.com/datarhei/restreamer * @copyright 2015 datarhei.org * @license Apache-2.0 */ 'use strict'; // Global config for frontend const config = { 'urls': { // project 'issueTracker': 'https://github.com/datarhei/restreamer/issues/new', 'projectPage': 'https://github.com/datarhei/restreamer', 'updatePage': 'https://datarhei.github.io/restreamer/docs/guides-updates.html', // help 'embedPlayerHelp': 'https://datarhei.github.io/restreamer/docs/guides-embedding.html', 'portForwardingHelp': 'https://datarhei.github.io/restreamer/wiki/portforwarding.html', 'rtmpServerHelp': 'https://datarhei.github.io/restreamer/docs/guides-external-rtmp.html' } }; window.angular.module('app').constant('config', config);
/** * @link https://github.com/datarhei/restreamer * @copyright 2015 datarhei.org * @license Apache-2.0 */ 'use strict'; // Global config for frontend const config = { 'urls': { // project 'issueTracker': 'https://github.com/datarhei/restreamer/issues/new', 'projectPage': 'https://github.com/datarhei/restreamer', 'updatePage': 'https://datarhei.github.io/restreamer/docs/references-updates.html', // help 'embedPlayerHelp': 'https://datarhei.github.io/restreamer/docs/guides-embed-upon-your-website.html', 'portForwardingHelp': 'https://datarhei.github.io/restreamer/wiki/portforwarding.html', 'rtmpServerHelp': 'https://datarhei.github.io/restreamer/docs/references-external-rtmp-streaming-server.html' } }; window.angular.module('app').constant('config', config);
Fix a bug with normal execution mode If all of the messages of a CombinedFragment got processed and deleted from the queue during the execution, null pointer exceptions where thrown because the fragment itself wasn't deleted from the queue and the method tried to process the next message of the empty fragment.
package hu.elte.txtuml.api.model.execution.impl.seqdiag.fragments.execstrats; import java.util.Queue; import hu.elte.txtuml.api.model.seqdiag.BaseCombinedFragmentWrapper; import hu.elte.txtuml.api.model.seqdiag.BaseFragmentWrapper; import hu.elte.txtuml.api.model.seqdiag.BaseMessageWrapper; public class ExecutionStrategySeq implements ExecutionStrategy { @Override public boolean containsMessage(Queue<BaseFragmentWrapper> containedFragments, BaseMessageWrapper message) { BaseFragmentWrapper wrapper = containedFragments.peek(); if (wrapper instanceof BaseCombinedFragmentWrapper) { return ((BaseCombinedFragmentWrapper) wrapper).containsMessage(message); } else { return wrapper.equals(message); } } @Override public boolean checkMessageSendToPattern(Queue<BaseFragmentWrapper> containedFragments, BaseMessageWrapper message) { BaseFragmentWrapper fragment = containedFragments.peek(); if (fragment instanceof BaseCombinedFragmentWrapper) { boolean result = ((BaseCombinedFragmentWrapper) fragment).checkMessageSendToPattern(message); if (result && fragment.size() == 0) { containedFragments.remove(); } return result; } else { BaseMessageWrapper required = (BaseMessageWrapper) fragment; if (!required.equals(message)) { return false; } containedFragments.remove(); return true; } } }
package hu.elte.txtuml.api.model.execution.impl.seqdiag.fragments.execstrats; import java.util.Queue; import hu.elte.txtuml.api.model.seqdiag.BaseCombinedFragmentWrapper; import hu.elte.txtuml.api.model.seqdiag.BaseFragmentWrapper; import hu.elte.txtuml.api.model.seqdiag.BaseMessageWrapper; public class ExecutionStrategySeq implements ExecutionStrategy { @Override public boolean containsMessage(Queue<BaseFragmentWrapper> containedFragments, BaseMessageWrapper message) { BaseFragmentWrapper wrapper = containedFragments.peek(); if (wrapper instanceof BaseCombinedFragmentWrapper) { return ((BaseCombinedFragmentWrapper) wrapper).containsMessage(message); } else { return wrapper.equals(message); } } @Override public boolean checkMessageSendToPattern(Queue<BaseFragmentWrapper> containedFragments, BaseMessageWrapper message) { BaseFragmentWrapper fragment = containedFragments.peek(); if (fragment instanceof BaseCombinedFragmentWrapper) { return ((BaseCombinedFragmentWrapper) fragment).checkMessageSendToPattern(message); } else { BaseMessageWrapper required = (BaseMessageWrapper) fragment; if (!required.equals(message)) { return false; } containedFragments.remove(); return true; } } }
Fix quotation mark in docstring Change-Id: Ie9501a0bce8c43e0316d1b8bda7296e859b0c8fb
# Copyright (c) 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import six def get_dict_from_output(output): """Parse list of dictionaries, return a dictionary. :param output: list of dictionaries """ obj = {} for item in output: obj[item['Property']] = six.text_type(item['Value']) return obj def get_object(object_list, object_value): """Get Ironic object by value from list of Ironic objects. :param object_list: the output of the cmd :param object_value: value to get """ for obj in object_list: if object_value in obj.values(): return obj
# Copyright (c) 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import six def get_dict_from_output(output): """Parse list of dictionaries, return a dictionary. :param output: list of dictionaries """ obj = {} for item in output: obj[item['Property']] = six.text_type(item['Value']) return obj def get_object(object_list, object_value): """"Get Ironic object by value from list of Ironic objects. :param object_list: the output of the cmd :param object_value: value to get """ for obj in object_list: if object_value in obj.values(): return obj
Fix method signature clash with parent method
<?php declare(strict_types=1); namespace Helmich\Psr7Assert\Constraint; use PHPUnit\Framework\Assert; use PHPUnit\Framework\Constraint\Constraint; use Psr\Http\Message\ResponseInterface; class HasStatusConstraint extends Constraint { /** @var Constraint */ private $status; public function __construct($status) { parent::__construct(); if (!$status instanceof Constraint) { $status = Assert::equalTo($status); } $this->status = $status; } /** * Returns a string representation of the object. * * @return string */ public function toString(): string { return "response status {$this->status->toString()}"; } protected function matches($other): bool { if (!$other instanceof ResponseInterface) { return false; } return $this->status->evaluate($other->getStatusCode(), '', true); } protected function additionalFailureDescription($other): string { if ($other instanceof ResponseInterface) { return 'Actual status is ' . $other->getStatusCode() . ' and the body contains: ' . $other->getBody(); } return ''; } }
<?php declare(strict_types=1); namespace Helmich\Psr7Assert\Constraint; use PHPUnit\Framework\Assert; use PHPUnit\Framework\Constraint\Constraint; use Psr\Http\Message\ResponseInterface; class HasStatusConstraint extends Constraint { /** @var Constraint */ private $status; public function __construct($status) { parent::__construct(); if (!$status instanceof Constraint) { $status = Assert::equalTo($status); } $this->status = $status; } /** * Returns a string representation of the object. * * @return string */ public function toString(): string { return "response status {$this->status->toString()}"; } protected function matches($other): bool { if (!$other instanceof ResponseInterface) { return false; } return $this->status->evaluate($other->getStatusCode(), '', true); } protected function additionalFailureDescription($other) { if ($other instanceof ResponseInterface) { return 'Actual status is ' . $other->getStatusCode() . " and the body contains: " . $other->getBody(); } return ''; } }
Fix possibly breaking input args stringify (PHPStan Level 5)
<?php /** * @copyright 2019 * @author Stefan "eFrane" Graupner <stefan.graupner@gmail.com> */ namespace EFrane\ConsoleAdditions\Batch; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; class InstanceCommandAction extends CommandAction { public function __construct(Command $command, InputInterface $input = null) { $this->command = $command; $this->input = $input; if (is_null($input)) { $this->input = new ArrayInput([]); } } public function __toString(): string { $this->abortIfNoApplication(); $inputString = ''; if (method_exists($this->input, '__toString')) { $inputString = $this->input->__toString(); } return trim( sprintf( '%s %s %s', $this->application->getName(), $this->command->getName(), $inputString ) ); } }
<?php /** * @copyright 2019 * @author Stefan "eFrane" Graupner <stefan.graupner@gmail.com> */ namespace EFrane\ConsoleAdditions\Batch; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; class InstanceCommandAction extends CommandAction { public function __construct(Command $command, InputInterface $input = null) { $this->command = $command; $this->input = $input; if (is_null($input)) { $this->input = new ArrayInput([]); } } public function __toString(): string { $this->abortIfNoApplication(); return trim( sprintf( '%s %s %s', $this->application->getName(), $this->command->getName(), $this->input ) ); } }
REmove unnecessary methods from interface git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1222403 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.tribes; /** * * <p>Title: MessageListener</p> * * <p>Description: The listener to be registered with the ChannelReceiver, internal Tribes component</p> * * @author Filip Hanik * @version 1.0 */ public interface MessageListener { /** * Receive a message from the IO components in the Channel stack * @param msg ChannelMessage */ public void messageReceived(ChannelMessage msg); public boolean accept(ChannelMessage msg); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.tribes; /** * * <p>Title: MessageListener</p> * * <p>Description: The listener to be registered with the ChannelReceiver, internal Tribes component</p> * * @author Filip Hanik * @version 1.0 */ public interface MessageListener { /** * Receive a message from the IO components in the Channel stack * @param msg ChannelMessage */ public void messageReceived(ChannelMessage msg); public boolean accept(ChannelMessage msg); @Override public boolean equals(Object listener); @Override public int hashCode(); }
Add IE and Opera Mini
var GOVUK = GOVUK || {}; GOVUK.UserSatisfaction = GOVUK.UserSatisfaction || function () {}; GOVUK.UserSatisfaction.prototype = { cookieNameSeenBar: "seenSurveyBar", cookieNameTakenSurvey: "takenUserSatisfactionSurvey", return { cookieNameSeenBar: "seenSurveyBar", cookieNameTakenSurvey: "takenUserSatisfactionSurvey", setCookieSeenBar: function () { cookie.write(this.cookieNameSeenBar, true); }, setCookieTakenSurvey: function () { cookie.write(this.cookieNameTakenSurvey, true); }, showSurveyBar: function () { var survey = document.getElementById("user-satisfaction-survey"); var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Opera\ Mini)/); if (survey && survey.style.display === "none" && !isMobile) { survey.style.display = "block"; } }, randomlyShowSurveyBar: function () { var min = 0; var max = 100; var random = Math.floor(Math.random() * (max - min + 1)) + min; if (random === 0 || random === 100 || random % 15 === 0) { this.showSurveyBar(); } } }; })();
var GOVUK = GOVUK || {}; GOVUK.UserSatisfaction = GOVUK.UserSatisfaction || function () {}; GOVUK.UserSatisfaction.prototype = { cookieNameSeenBar: "seenSurveyBar", cookieNameTakenSurvey: "takenUserSatisfactionSurvey", return { cookieNameSeenBar: "seenSurveyBar", cookieNameTakenSurvey: "takenUserSatisfactionSurvey", setCookieSeenBar: function () { cookie.write(this.cookieNameSeenBar, true); }, setCookieTakenSurvey: function () { cookie.write(this.cookieNameTakenSurvey, true); }, showSurveyBar: function () { var survey = document.getElementById("user-satisfaction-survey"); var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/); if (survey && survey.style.display === "none" && !isMobile) { survey.style.display = "block"; } }, randomlyShowSurveyBar: function () { var min = 0; var max = 100; var random = Math.floor(Math.random() * (max - min + 1)) + min; if (random === 0 || random === 100 || random % 15 === 0) { this.showSurveyBar(); } } }; })();
Check if action is available
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import layout from '../templates/components/time-input'; export default Component.extend({ layout, moment: service(), tagName: 'span', actions: { changeTime(time){ const parsed = this.get('moment').moment(time, 'HH:mm'); const oldDate = this.get('moment').moment(this.get('currentDate')); let newDate = oldDate ? oldDate.clone() : this.get('moment').moment(); newDate.hours(parsed.hours()); newDate.minutes(parsed.minutes()); let moments = this.get('arrayDates'); if(moments){ // Update time in array if set moments.forEach(function(element, index) { if (element.diff(newDate, 'days') === 0){ moments[index] = newDate; } }, this); this.set('arrayDates', null); this.set('arrayDates', moments); } if(this.get('onChangedTime')){ this.get('onChangedTime')(newDate); } } }, });
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import layout from '../templates/components/time-input'; export default Component.extend({ layout, moment: service(), tagName: 'span', actions: { changeTime(time){ const parsed = this.get('moment').moment(time, 'HH:mm'); const oldDate = this.get('moment').moment(this.get('currentDate')); let newDate = oldDate ? oldDate.clone() : this.get('moment').moment(); newDate.hours(parsed.hours()); newDate.minutes(parsed.minutes()); let moments = this.get('arrayDates'); if(moments){ // Update time in array if set moments.forEach(function(element, index) { if (element.diff(newDate, 'days') === 0){ moments[index] = newDate; } }, this); this.set('arrayDates', null); this.set('arrayDates', moments); } this.get('onChangedTime')(newDate); } }, });
Update prices for all BlueprintInstances we currently have
import sqlite3 import urllib2 import xml.etree.ElementTree as ET MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s' def main(): conn = sqlite3.connect('everdi.db') cur = conn.cursor() # Get all items used in current BlueprintInstances cur.execute(""" SELECT DISTINCT c.item_id FROM blueprints_blueprintcomponent c INNER JOIN blueprints_blueprintinstance AS bi ON c.blueprint_id = bi.blueprint_id """) rows = cur.fetchall() for i in range(0, len(rows), 20): url = MARKET_URL % ('&'.join('typeid=%s' % item for item in rows[i:i+20])) f = urllib2.urlopen(url) data = f.read() f.close() #open('data.txt', 'w').write(data) #data = open('data.txt').read() root = ET.fromstring(data) for t in root.findall('marketstat/type'): typeid = t.get('id') sell_median = t.find('sell/median').text buy_median = t.find('buy/median').text cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid)) conn.commit() if __name__ == '__main__': main()
import sqlite3 import urllib2 import xml.etree.ElementTree as ET MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s' ITEMS = [ 34, # Tritanium 35, # Pyerite 36, # Mexallon 37, # Isogen 38, # Nocxium 39, # Zydrine 40, # Megacyte 11399, # Morphite ] def main(): conn = sqlite3.connect('everdi.db') cur = conn.cursor() url = MARKET_URL % ('&'.join('typeid=%s' % i for i in ITEMS)) f = urllib2.urlopen(url) data = f.read() f.close() #open('data.txt', 'w').write(data) #data = open('data.txt').read() root = ET.fromstring(data) for t in root.findall('marketstat/type'): typeid = t.get('id') sell_median = t.find('sell/median').text buy_median = t.find('buy/median').text cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid)) conn.commit() if __name__ == '__main__': main()
Remove non-orthogonal helper method from API
package libgodelbrot import ( "image" ) func Render(info *Info) (*image.NRGBA, error) { context, err := MakeRenderer(info) if err == nil { return context.Render() } else { return nil, err } } func AutoConf(req *Request) (*Info, error) { // Configure uses panic when it encounters an error condition. // Here we detect that panic and convert it to an error, // which is idiomatic for the API. anything, err := panic2err(func() interface{} { return configure(req) }) if err == nil { return anything.(*Info), nil } else { return nil, err } } func MakeRenderer(desc *Info) (Renderer, error) { // Renderer is a thin wrapper, we just pass on to the library internals return renderer(desc) }
package libgodelbrot import ( "image" ) // Draw the Mandelbrot set. This is the main entry point to libgodelbrot func AutoRender(req *Request) (*image.NRGBA, error) { info, configErr := AutoConf(req) if configErr == nil { return Render(info) } else { return nil, configErr } } func Render(info *Info) (*image.NRGBA, error) { context, err := MakeRenderer(info) if err == nil { return context.Render() } else { return nil, err } } func AutoConf(req *Request) (*Info, error) { // Configure uses panic when it encounters an error condition. // Here we detect that panic and convert it to an error, // which is idiomatic for the API. anything, err := panic2err(func() interface{} { return configure(req) }) if err == nil { return anything.(*Info), nil } else { return nil, err } } func MakeRenderer(desc *Info) (Renderer, error) { // Renderer is a thin wrapper, we just pass on to the library internals return renderer(desc) }
Make dummy change manager do nothing
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.core.change; import javax.time.Instant; import com.opengamma.id.UniqueId; /** * Implementation of {@link ChangeManager} to use when change notifications are not supported or never needed. */ public final class DummyChangeManager implements ChangeManager { /** * Singleton instance */ public static final DummyChangeManager INSTANCE = new DummyChangeManager(); /** * Hidden constructor. */ private DummyChangeManager() { } @Override public void addChangeListener(ChangeListener listener) { // dummy manager does nothing } @Override public void removeChangeListener(ChangeListener listener) { // dummy manager does nothing } @Override public void entityChanged(ChangeType type, UniqueId beforeId, UniqueId afterId, Instant versionInstant) { // dummy manager does nothing } }
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.core.change; import javax.time.Instant; import com.opengamma.id.UniqueId; /** * Implementation of {@link ChangeManager} to use when change notifications are not supported or never needed. */ public final class DummyChangeManager implements ChangeManager { /** * Singleton instance */ public static final DummyChangeManager INSTANCE = new DummyChangeManager(); /** * Hidden constructor. */ private DummyChangeManager() { } @Override public void addChangeListener(ChangeListener listener) { } @Override public void removeChangeListener(ChangeListener listener) { } @Override public void entityChanged(ChangeType type, UniqueId beforeId, UniqueId afterId, Instant versionInstant) { throw new UnsupportedOperationException(DummyChangeManager.class.getSimpleName() + " does not support change notifications"); } }
[FIX] Handle other date formats that may come out of MySQL/ElasticSearch git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@47066 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ class Search_Formatter_ValueFormatter_Datetime extends Search_Formatter_ValueFormatter_Abstract { protected $format; function __construct() { $tikilib = TikiLib::lib('tiki'); $this->format = $tikilib->get_short_datetime_format(); } function render($name, $value, array $entry) { if (preg_match('/^\d{14}$/', $value)) { // Facing a date formated as YYYYMMDDHHIISS as indexed in lucene // Always stored as UTC $value = date_create_from_format('YmdHise', $value . 'UTC')->getTimestamp(); } $tikilib = TikiLib::lib('tiki'); if (is_numeric($value)) { // expects a unix timestamp but might be getting the default value return $tikilib->date_format($this->format, $value); } elseif (false !== $time = strtotime($value)) { return $tikilib->date_format($this->format, $time); } else { return $value; } } }
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ class Search_Formatter_ValueFormatter_Datetime extends Search_Formatter_ValueFormatter_Abstract { protected $format; function __construct() { $tikilib = TikiLib::lib('tiki'); $this->format = $tikilib->get_short_datetime_format(); } function render($name, $value, array $entry) { if (preg_match('/^\d{14}$/', $value)) { // Facing a date formated as YYYYMMDDHHIISS as indexed in lucene // Always stored as UTC $value = date_create_from_format('YmdHise', $value . 'UTC')->getTimestamp(); } if (is_numeric($value)) { // expects a unix timestamp but might be getting the default value $tikilib = TikiLib::lib('tiki'); return $tikilib->date_format($this->format, $value); } else { return $value; } } }
Convert LocalDateTime expected output to ISO-8601, since there's no timezone in LocalDateTime
/* * ****************************************************************************** * Copyright 2016-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ****************************************************************************** */ package com.spectralogic.dsbrowser.gui.services; import org.junit.Test; import java.time.LocalDateTime; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; public class BuildInfoService_Test { @Test public void parseDateString() { final String buildDate = "Wed Mar 15 11:10:25 MDT 2017"; final LocalDateTime ldt = LocalDateTime.parse(buildDate, BuildInfoServiceImpl.dtf); assertThat(ldt.toString(), is("2017-03-15T11:10:25")); } }
/* * ****************************************************************************** * Copyright 2016-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ****************************************************************************** */ package com.spectralogic.dsbrowser.gui.services; import org.junit.Test; import java.time.LocalDateTime; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; public class BuildInfoService_Test { @Test public void parseDateString() { final String buildDate = "Wed Mar 15 11:10:25 MDT 2017"; final LocalDateTime ldt = LocalDateTime.parse(buildDate, BuildInfoServiceImpl.dtf); final String formattedDate = ldt.format(BuildInfoServiceImpl.dtf); //final String formattedDate = ldt.format(BuildInfoServiceImpl.dtf); assertThat(formattedDate, is(buildDate)); } }
Add support for noseasons extended flag. - Only works with sync watchedShows.
package com.uwetrottmann.trakt5.enums; /** * By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically * all you need to match locally cached items and includes the title, year, and ids. However, you can request different * extended levels of information. */ public enum Extended implements TraktEnum { /** Default. Returns enough info to match locally. */ DEFAULT_MIN("min"), /** Minimal info and all images. */ IMAGES("images"), /** Complete info for an item. */ FULL("full"), /** Complete info and all images. */ FULLIMAGES("full,images"), /** Only works with sync watchedShows. */ NOSEASONS("noseasons"), /** Only works with sync watchedShows. */ NOSEASONSIMAGES("noseasons,images"); private final String value; Extended(String value) { this.value = value; } @Override public String toString() { return value; } }
package com.uwetrottmann.trakt5.enums; /** * By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically * all you need to match locally cached items and includes the title, year, and ids. However, you can request different * extended levels of information. */ public enum Extended implements TraktEnum { /** Default. Returns enough info to match locally. */ DEFAULT_MIN("min"), /** Minimal info and all images. */ IMAGES("images"), /** Complete info for an item. */ FULL("full"), /** Complete info and all images. */ FULLIMAGES("full,images"); private final String value; private Extended(String value) { this.value = value; } @Override public String toString() { return value; } }
Add string check - 10142
/** * This plug-in will add automatic detection for currency columns to * DataTables. Note that only $ and £ symbols are detected with this code, * but it is trivial to add more or change the current ones. This is best used * in conjunction with the currency sorting plug-in. * @name Currency * @author <a href="http://sprymedia.co.uk">Allan Jardine</a> */ jQuery.fn.dataTableExt.aTypes.unshift( function ( sData ) { var sValidChars = "0123456789.-,"; var Char; if ( typeof sData !== 'string' ) { return null; } /* Check the numeric part */ for ( i=1 ; i<sData.length ; i++ ) { Char = sData.charAt(i); if (sValidChars.indexOf(Char) == -1) { return null; } } /* Check prefixed by currency */ if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' ) { return 'currency'; } return null; } );
/** * This plug-in will add automatic detection for currency columns to * DataTables. Note that only $ and £ symbols are detected with this code, * but it is trivial to add more or change the current ones. This is best used * in conjunction with the currency sorting plug-in. * @name Currency * @author <a href="http://sprymedia.co.uk">Allan Jardine</a> */ jQuery.fn.dataTableExt.aTypes.unshift( function ( sData ) { var sValidChars = "0123456789.-,"; var Char; /* Check the numeric part */ for ( i=1 ; i<sData.length ; i++ ) { Char = sData.charAt(i); if (sValidChars.indexOf(Char) == -1) { return null; } } /* Check prefixed by currency */ if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' ) { return 'currency'; } return null; } );
Clean up formatting, skip infinite loop of new tabs, avoid int.toString.
// This code is from Jorge Cardoso's blog at http://jorgecardoso.eu/htmlblog/2012-08-30-Listing%20a%20user%20directory%20with%20javascript%20in%20a%20Chrome%20extension.html function DirectoryList ( path ) { this.path = path; this.fileList = []; } DirectoryList.prototype.getFileList = function( fileListener ) { var $this = this; chrome.extension.onMessage.addListener( function(request, sender, sendResponse) { chrome.extension.onMessage.removeListener(arguments.callee); chrome.tabs.remove($this.directory_list_tab); $this.fileList = request; fileListener(request); }); chrome.tabs.onUpdated.addListener(function onTabUpdated(tabId, changeInfo, _tab) { if ( _tab.id == $this.directory_list_tab ) { chrome.tabs.executeScript(_tab.id, {file: "directorylister-tab.js"}); chrome.tabs.onUpdated.removeListener(arguments.callee); } }); chrome.tabs.create({url:"file://"+$this.path, selected:false}, function(_tab) { $this.directory_list_tab = _tab.id; }); };
// This code is from Jorge Cardoso's blog at http://jorgecardoso.eu/htmlblog/2012-08-30-Listing%20a%20user%20directory%20with%20javascript%20in%20a%20Chrome%20extension.html function DirectoryList ( path ) { this.path = path; this.fileList = []; } DirectoryList.prototype.getFileList = function( fileListener ) { var $this = this; chrome.extension.onMessage.addListener( function(request, sender, sendResponse) { chrome.extension.onMessage.removeListener(arguments.callee); chrome.tabs.remove($this.tabid); $this.fileList = request; fileListener(request); }); chrome.tabs.onUpdated.addListener(function onTabUpdated(tabId, changeInfo, _tab) { if ( _tab.id.toString() === $this.tabid.toString() ) { chrome.tabs.executeScript(_tab.id, {file: "directorylister-tab.js"}); chrome.tabs.onUpdated.removeListener(arguments.callee); } }); chrome.tabs.create({}, function(_tab) { $this.tabid = _tab.id; console.log("Creating listing tab (" + $this.tabid + ") for: " + $this.path); chrome.tabs.update(_tab.id, {url:"file://"+$this.path, selected:false}); }); };
Add additional invalid host detection
import socket def valid_hostname(hostname: str): """ :param hostname: The hostname requested in the scan :return: Hostname if it's valid, otherwise None """ # Block attempts to scan things like 'localhost' if '.' not in hostname or 'localhost' in hostname: return False # First, let's try to see if it's an IPv4 address try: socket.inet_aton(hostname) # inet_aton() will throw an exception if hostname is not a valid IP address return None # If we get this far, it's an IP address and therefore not a valid fqdn except: pass # And IPv6 try: socket.inet_pton(socket.AF_INET6, hostname) # same as inet_aton(), but for IPv6 return None except: pass # Then, try to do a lookup on the hostname; this should return at least one entry and should be the first time # that the validator is making a network connection -- the same that requests would make. try: hostname_ips = socket.getaddrinfo(hostname, 443) if len(hostname_ips) < 1: return None except: return None # If we've made it this far, then everything is good to go! Woohoo! return hostname
import socket def valid_hostname(hostname: str): """ :param hostname: The hostname requested in the scan :return: Hostname if it's valid, otherwise None """ # First, let's try to see if it's an IPv4 address try: socket.inet_aton(hostname) # inet_aton() will throw an exception if hostname is not a valid IP address return None # If we get this far, it's an IP address and therefore not a valid fqdn except: pass # And IPv6 try: socket.inet_pton(socket.AF_INET6, hostname) # same as inet_aton(), but for IPv6 return None except: pass # Then, try to do a lookup on the hostname; this should return at least one entry and should be the first time # that the validator is making a network connection -- the same that requests would make. try: hostname_ips = socket.getaddrinfo(hostname, 443) if len(hostname_ips) < 1: return None except: return None # If we've made it this far, then everything is good to go! Woohoo! return hostname
Change relative imports to absolute.
from django.contrib import admin from auditlog.filters import ResourceTypeFilter from auditlog.mixins import LogEntryAdminMixin from auditlog.models import LogEntry class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin): list_display = ["created", "resource_url", "action", "msg_short", "user_url"] search_fields = [ "timestamp", "object_repr", "changes", "actor__first_name", "actor__last_name", ] list_filter = ["action", ResourceTypeFilter] readonly_fields = ["created", "resource_url", "action", "user_url", "msg"] fieldsets = [ (None, {"fields": ["created", "user_url", "resource_url"]}), ("Changes", {"fields": ["action", "msg"]}), ] admin.site.register(LogEntry, LogEntryAdmin)
from django.contrib import admin from .filters import ResourceTypeFilter from .mixins import LogEntryAdminMixin from .models import LogEntry class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin): list_display = ["created", "resource_url", "action", "msg_short", "user_url"] search_fields = [ "timestamp", "object_repr", "changes", "actor__first_name", "actor__last_name", ] list_filter = ["action", ResourceTypeFilter] readonly_fields = ["created", "resource_url", "action", "user_url", "msg"] fieldsets = [ (None, {"fields": ["created", "user_url", "resource_url"]}), ("Changes", {"fields": ["action", "msg"]}), ] admin.site.register(LogEntry, LogEntryAdmin)