text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix widget url generation when missing apikey and authtoken
var _ = require('underscore'); var Model = require('../../core/model'); /** * This model is used for getting the total amount of values * from the category. * */ module.exports = Model.extend({ defaults: { url: '', totalCount: 0, categoriesCount: 0 }, url: function () { var url = this.get('url'); var queryOptions = []; if (this.get('apiKey')) { url += '?api_key=' + this.get('apiKey'); } else if (this.get('authToken')) { var authToken = this.get('authToken'); if (authToken instanceof Array) { _.each(authToken, function (token) { queryOptions.push('auth_token[]=' + token); }); } else { queryOptions.push('auth_token=' + authToken); } url += '?' + queryOptions.join('&'); } return url; }, initialize: function () { this.bind('change:url', function () { this.fetch(); }, this); }, setUrl: function (url) { this.set('url', url); }, parse: function (d) { // Calculating the total amount of all categories with the sum of all // values from this model included the aggregated (Other) return { categoriesCount: d.categoriesCount, totalCount: _.reduce( _.pluck(d.categories, 'value'), function (memo, value) { return memo + value; }, 0 ) }; } });
var _ = require('underscore'); var Model = require('../../core/model'); /** * This model is used for getting the total amount of values * from the category. * */ module.exports = Model.extend({ defaults: { url: '', totalCount: 0, categoriesCount: 0 }, url: function () { var url = this.get('url'); var queryOptions = []; if (this.get('apiKey')) { queryOptions.push('api_key=' + this.get('apiKey')); } else if (this.get('authToken')) { var authToken = this.get('authToken'); if (authToken instanceof Array) { _.each(authToken, function (token) { queryOptions.push('auth_token[]=' + token); }); } else { queryOptions.push('auth_token=' + authToken); } } url += '?' + queryOptions.join('&'); return url; }, initialize: function () { this.bind('change:url', function () { this.fetch(); }, this); }, setUrl: function (url) { this.set('url', url); }, parse: function (d) { // Calculating the total amount of all categories with the sum of all // values from this model included the aggregated (Other) return { categoriesCount: d.categoriesCount, totalCount: _.reduce( _.pluck(d.categories, 'value'), function (memo, value) { return memo + value; }, 0 ) }; } });
Make valid schema types and validator error type configurable
var util = require('util'); /** * @param {mongoose.Schema} schema * @param {?Object=} options */ module.exports = exports = function constantPlugin(schema, options) { options = options || {}; options.ValidSchemaTypes = options.ValidSchemaTypes || ['String', 'Number', 'Date', 'ObjectID']; options.ErrorType = options.ErrorType || constantPlugin.ERROR_TYPE; function validateSchemaType(path, schemaType) { if (!~options.ValidSchemaTypes.indexOf(schemaType.instance)) throw new Error(util.format(constantPlugin.ErrorMessages.ERRINVALIDTYPE, path, schemaType.instance, options.ValidSchemaTypes.join(', '))); } /* Register validations. */ schema.eachPath(function (path, schemaType) { if (!schemaType.options.constant) return; validateSchemaType(path, schemaType); (function (path) { schemaType.validators.push([ function () { if (this.isNew || !this.isSelected(path)) return; return !this.isModified(path); }, constantPlugin.ErrorMessages.ERRCONSTRESET, options.ErrorType ]); })(path); }); }; exports.ErrorMessages = { ERRCONSTRESET: 'Constant `{PATH}` cannot be changed.', ERRINVALIDTYPE: 'Cannot use constant in path `%s` with type `%s`.\nConstant can only be used with: %s' }; exports.ERROR_TYPE = 'constant plugin';
/** * @param {mongoose.Schema} schema * @param {?Object=} options */ module.exports = exports = function constantPlugin(schema, options) { var validSchemaTypes = ['String', 'Number', 'Date', 'ObjectID']; function validateSchemaType(path, schemaType) { if (!~validSchemaTypes.indexOf(schemaType.instance)) { throw new Error('Cannot use constant in path ' + path + '.\nConstant can only be used with: ' + validSchemaTypes.join(', ')); } } /* Register validations. */ schema.eachPath(function (path, schemaType) { if (!schemaType.options.constant) return; validateSchemaType(path, schemaType); (function (path) { schemaType.validators.push( [ function () { if (this.isNew || !this.isSelected(path)) return; return !this.isModified(path); }, constantPlugin.ErrorMessages.ERRRESETCONST, 'constant plugin' ] ); })(path); }); }; exports.ErrorMessages = { ERRRESETCONST: 'Constant `{PATH}` cannot be changed.' };
Comment out active round check in round:sStart
<?php namespace OpenDominion\Console\Commands; use Carbon\Carbon; use Illuminate\Console\Command; use OpenDominion\Models\Round; use OpenDominion\Models\RoundLeague; class RoundStartCommand extends Command { protected $signature = 'round:start'; protected $description = 'Starts a new round (dev only)'; public function __construct() { parent::__construct(); // } public function handle() { $this->output->writeln('<info>Attempting to start a new round</info>'); $standardRoundLeague = RoundLeague::where('key', 'standard') ->firstOrFail(); $lastRound = Round::where('round_league_id', $standardRoundLeague->id) ->orderBy('number', 'desc') ->firstOrFail(); // if ($lastRound->isActive()) { // $this->output->writeln("<error>Did not create a new round because round {$lastRound->number} in {$standardRoundLeague->description} is still active!</error>"); // return false; // } $newRound = Round::create([ 'round_league_id' => $standardRoundLeague->id, 'number' => ($lastRound->number + 1), 'name' => 'Development Round', 'start_date' => new Carbon('+5 days midnight'), 'end_date' => new Carbon('+55 days midnight'), ]); $this->output->writeln("<info>Round {$newRound->number} created successfully</info>"); } }
<?php namespace OpenDominion\Console\Commands; use Carbon\Carbon; use Illuminate\Console\Command; use OpenDominion\Models\Round; use OpenDominion\Models\RoundLeague; class RoundStartCommand extends Command { protected $signature = 'round:start'; protected $description = 'Starts a new round (dev only)'; public function __construct() { parent::__construct(); // } public function handle() { $this->output->writeln('<info>Attempting to start a new round</info>'); $standardRoundLeague = RoundLeague::where('key', 'standard') ->firstOrFail(); $lastRound = Round::where('round_league_id', $standardRoundLeague->id) ->orderBy('number', 'desc') ->firstOrFail(); if ($lastRound->isActive()) { $this->output->writeln("<error>Did not create a new round because round {$lastRound->number} in {$standardRoundLeague->description} is still active!</error>"); return false; } $newRound = Round::create([ 'round_league_id' => $standardRoundLeague->id, 'number' => ($lastRound->number + 1), 'name' => 'Development Round', 'start_date' => new Carbon('+5 days midnight'), 'end_date' => new Carbon('+55 days midnight'), ]); $this->output->writeln("<info>Round {$newRound->number} created successfully</info>"); } }
Check search text before submitting post search event.
import React from 'react'; import ReactDOM from 'react-dom'; import { Well, InputGroup, FormControl, Button, Glyphicon } from 'react-bootstrap'; class SearchPostsWell extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { e.preventDefault(); if (this.props.onSubmit) { const q = ReactDOM.findDOMNode(this.refs.q).value.trim(); if (q) { this.props.onSubmit(q); } } } render() { const {q, pending} = this.props; return ( <Well> <h4>Blog Search</h4> <form autoComplete="off" onSubmit={this.handleSubmit}> <InputGroup> <FormControl ref="q" defaultValue={q} /> <InputGroup.Button> <Button disabled={pending}> <Glyphicon glyph="search" /> </Button> </InputGroup.Button> </InputGroup> </form> </Well> ); } } SearchPostsWell.propTypes = { q: React.PropTypes.string, pending: React.PropTypes.bool, onSubmit: React.PropTypes.func }; export default SearchPostsWell;
import React from 'react'; import ReactDOM from 'react-dom'; import { Well, InputGroup, FormControl, Button, Glyphicon } from 'react-bootstrap'; class SearchPostsWell extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { e.preventDefault(); if (this.props.onSubmit) { const q = ReactDOM.findDOMNode(this.refs.q).value.trim(); this.props.onSubmit(q); } } render() { const {q, pending} = this.props; return ( <Well> <h4>Blog Search</h4> <form autoComplete="off" onSubmit={this.handleSubmit}> <InputGroup> <FormControl ref="q" defaultValue={q} /> <InputGroup.Button> <Button disabled={pending}> <Glyphicon glyph="search" /> </Button> </InputGroup.Button> </InputGroup> </form> </Well> ); } } SearchPostsWell.propTypes = { q: React.PropTypes.string, pending: React.PropTypes.bool, onSubmit: React.PropTypes.func }; export default SearchPostsWell;
Use logApplicationPackage so users might get a notification
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.content.cluster; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; import com.yahoo.vespa.model.content.ResourceLimits; import java.util.logging.Level; /** * Builder for feed block resource limits. * * @author geirst */ public class DomResourceLimitsBuilder { public static ResourceLimits.Builder createBuilder(ModelElement contentXml, boolean hostedVespa, DeployLogger deployLogger) { ResourceLimits.Builder builder = new ResourceLimits.Builder(); ModelElement resourceLimits = contentXml.child("resource-limits"); if (resourceLimits == null) { return builder; } if (hostedVespa) { deployLogger.logApplicationPackage(Level.WARNING, "Element " + resourceLimits + " is not allowed, default limits will be used"); // TODO: Throw exception when we are sure nobody is using this //throw new IllegalArgumentException("Element " + element + " is not allowed to be set, default limits will be used"); return builder; } if (resourceLimits.child("disk") != null) { builder.setDiskLimit(resourceLimits.childAsDouble("disk")); } if (resourceLimits.child("memory") != null) { builder.setMemoryLimit(resourceLimits.childAsDouble("memory")); } return builder; } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.content.cluster; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; import com.yahoo.vespa.model.content.ResourceLimits; import java.util.logging.Level; /** * Builder for feed block resource limits. * * @author geirst */ public class DomResourceLimitsBuilder { public static ResourceLimits.Builder createBuilder(ModelElement contentXml, boolean hostedVespa, DeployLogger deployLogger) { ResourceLimits.Builder builder = new ResourceLimits.Builder(); ModelElement resourceLimits = contentXml.child("resource-limits"); if (resourceLimits == null) { return builder; } if (hostedVespa) { deployLogger.log(Level.WARNING, "Element " + resourceLimits + " is not allowed, default limits will be used"); // TODO: Throw exception when we are sure nobody is using this //throw new IllegalArgumentException("Element " + element + " is not allowed to be set, default limits will be used"); return builder; } if (resourceLimits.child("disk") != null) { builder.setDiskLimit(resourceLimits.childAsDouble("disk")); } if (resourceLimits.child("memory") != null) { builder.setMemoryLimit(resourceLimits.childAsDouble("memory")); } return builder; } }
Fix bug in multiple input fields interaction for media section
define('media-input', ['jquery', 'z'], function($, z) { function createInput($section) { $section.append($('<input>', { type: 'url', placeholder: $section.data('placeholder'), pattern: 'https?://.*' })); } z.page.on('loaded', function() { $('.fallback').each(function() { var $this = $(this); if (!$this.closest('.icon').length || !$this.children().length) { // Do not create input field if icon section already has icon value (in edit page). createInput($this); } }); }).on('input', '.screenshots input[type=url], .videos input[type=url]', function(e) { var $input = $(e.target); var $allInputs = $input.parent().children('input[type=url]'); var $emptyInputs = $allInputs.filter(function() { return !$(this).val(); }); if ($input.val() && $emptyInputs.length === 0) { createInput($input.parent()); } else { // So that at any point in time, there will be exactly // ONE empty input field for user to enter more URLs. $emptyInputs.slice(1).remove(); } }); });
define('media-input', ['jquery', 'z'], function($, z) { function createInput($section) { $section.append($('<input>', { type: 'url', placeholder: $section.data('placeholder'), pattern: 'https?://.*' })); } z.page.on('loaded', function() { $('.fallback').each(function() { var $this = $(this); if (!$this.closest('.icon').length || !$this.children().length) { // Do not create input field if icon section already has icon value (in edit page). createInput($this); } }); }).on('input', '.screenshots input[type=text], .videos input[type=text]', function(e) { var $input = $(e.target); var $allInputs = $input.parent().children('input[type=text]'); var $emptyInputs = $allInputs.filter(function() { return !$(this).val(); }); if ($input.val() && $emptyInputs.length === 0) { createInput($input.parent()); } else { // So that at any point in time, there will be exactly // ONE empty input field for user to enter more URLs. $emptyInputs.slice(1).remove(); } }); });
Update OpenJDK version to support both 8 and 9.
import re from versions.software.utils import get_command_stderr, get_soup, \ get_text_between def name(): """Return the precise name for the software.""" return 'Zulu OpenJDK' def installed_version(): """Return the installed version of the jdk, or None if not installed.""" try: version_string = get_command_stderr(('java', '-version')) # "1.8.0_162" or "9.0.4.1" for example return get_text_between(version_string, '"', '"') except FileNotFoundError: pass def latest_version(): """Return the latest version of Zulu OpenJDK available for download.""" installed = installed_version() soup = get_soup('http://www.azul.com/downloads/zulu/zulu-windows/') if soup: zip_filename = re.compile('\.zip$') for tag in soup.find_all('a', class_='r-download', href=zip_filename): filename = tag.attrs['href'] zulu = get_text_between(filename, 'bin/zulu', '-') jdk = get_text_between(filename, 'jdk', '-') if (installed is None) or (installed[0] == '9' and zulu[0] == '9'): return zulu elif installed[0] == '1' and jdk[0] == installed[2]: version, update = jdk.rsplit('.', 1) return f'1.{version}_{update}' return 'Unknown'
import re from versions.software.utils import get_command_stderr, get_soup, \ get_text_between def name(): """Return the precise name for the software.""" return 'Zulu OpenJDK' def installed_version(): """Return the installed version of the jdk, or None if not installed.""" try: version_string = get_command_stderr(('java', '-version')) return get_text_between(version_string, '"', '"') except FileNotFoundError: pass def downloadable_version(url): """Strip the version out of the Zulu OpenJDK manual download link.""" # example: http://cdn.azul.com/.../zulu8.23.0.3-jdk8.0.144-win_x64.zip filename = url[url.rfind('/') + 1:] jdk_version = get_text_between(filename, '-jdk', '-') version, update = jdk_version.rsplit('.', 1) return f'1.{version}_{update}' def latest_version(): """Return the latest version of Zulu OpenJDK available for download.""" soup = get_soup('http://www.azul.com/downloads/zulu/zulu-windows/') if soup: div = soup.find('div', class_='latest_area') if div: zip_filename = re.compile('\.zip$') tag = div.find('a', class_='r-download', href=zip_filename) if tag: return downloadable_version(tag.attrs['href']) return 'Unknown'
Disable auto-update until next season
'use strict'; function config() { const periodFormat = '{0}-{1}'; const firstHandledYear = 2000; const lastHandledPeriod = 2021; const currentPeriod = periodFormat.replace('{0}', lastHandledPeriod).replace('{1}', lastHandledPeriod + 1); const availablesPeriod = []; for (let i = lastHandledPeriod; i >= firstHandledYear; i--) { availablesPeriod.push(periodFormat.replace('{0}', i).replace('{1}', i + 1)); } return { port: process.env.PORT || 5000, updateLeagues: false, updateCompetitionGroups: false, updateCompetitionTournaments: false, updateWithImagesDownload: false, updateWithFullResults: false, isSummerTime: true, paths: { tableData: './data/{0}/{1}/table.json', scorersData: './data/{0}/{1}/scorers.json', assistsData: './data/{0}/{1}/assists.json', resultsData: './data/{0}/{1}/results.json', tournamentData: './data/{0}/{1}/tournament.json', groupsData: './data/{0}/{1}/groups.json', logosData: './data/images/logos/{0}.gif', flagsData: './data/images/flags/{0}.gif' }, periods: { current: currentPeriod, availables: availablesPeriod } }; } module.exports = config();
'use strict'; function config() { const periodFormat = '{0}-{1}'; const firstHandledYear = 2000; const lastHandledPeriod = 2021; const currentPeriod = periodFormat.replace('{0}', lastHandledPeriod).replace('{1}', lastHandledPeriod + 1); const availablesPeriod = []; for (let i = lastHandledPeriod; i >= firstHandledYear; i--) { availablesPeriod.push(periodFormat.replace('{0}', i).replace('{1}', i + 1)); } return { port: process.env.PORT || 5000, updateLeagues: true, updateCompetitionGroups: false, updateCompetitionTournaments: true, updateWithImagesDownload: false, updateWithFullResults: false, isSummerTime: true, paths: { tableData: './data/{0}/{1}/table.json', scorersData: './data/{0}/{1}/scorers.json', assistsData: './data/{0}/{1}/assists.json', resultsData: './data/{0}/{1}/results.json', tournamentData: './data/{0}/{1}/tournament.json', groupsData: './data/{0}/{1}/groups.json', logosData: './data/images/logos/{0}.gif', flagsData: './data/images/flags/{0}.gif' }, periods: { current: currentPeriod, availables: availablesPeriod } }; } module.exports = config();
Remove unused defaultParams from state
import React from 'react'; import classnames from 'classnames'; import Store from './Store'; import ActionCreator from './ActionCreator'; import urlUtil from './urlUtil'; const Url = React.createClass({ propTypes: { pathname: React.PropTypes.string, query: React.PropTypes.object, children: React.PropTypes.node, isActiveClass: React.PropTypes.string, className: React.PropTypes.string }, getDefaultProps() { return { query: {}, isActiveClass: 'active', className: '' }; }, getInitialState() { return { query: Store.getQuery(), pathname: Store.getPathname() }; }, componentDidMount() { this.unsubscribe = Store.addChangeListener(this.onChange); }, componentWillUnmount() { this.unsubscribe(); }, onClick(event) { event.preventDefault(); ActionCreator.navigateTo(this.props); }, onChange() { this.setState({ query: Store.getQuery(), pathname: Store.getPathname() }); }, render() { const oldParams = this.state; const newParams = this.props; const {href} = urlUtil.merge(oldParams, newParams); const isActive = urlUtil.isActive(oldParams, newParams); const linkClasses = classnames(this.props.className, { [this.props.isActiveClass]: isActive }); return <a {...this.props} href={href} onClick={this.onClick} className={linkClasses} />; } }); export default Url;
import React from 'react'; import classnames from 'classnames'; import Store from './Store'; import ActionCreator from './ActionCreator'; import urlUtil from './urlUtil'; const Url = React.createClass({ propTypes: { pathname: React.PropTypes.string, query: React.PropTypes.object, children: React.PropTypes.node, isActiveClass: React.PropTypes.string, className: React.PropTypes.string }, getDefaultProps() { return { query: {}, isActiveClass: 'active', className: '' }; }, getInitialState() { return { query: Store.getQuery(), pathname: Store.getPathname(), defaultParams: Store.getDefaultParams() }; }, componentDidMount() { this.unsubscribe = Store.addChangeListener(this.onChange); }, componentWillUnmount() { this.unsubscribe(); }, onClick(event) { event.preventDefault(); ActionCreator.navigateTo(this.props); }, onChange() { this.setState({ query: Store.getQuery(), pathname: Store.getPathname(), defaultParams: Store.getDefaultParams() }); }, render() { const oldParams = this.state; const newParams = this.props; const {href} = urlUtil.merge(oldParams, newParams); const isActive = urlUtil.isActive(oldParams, newParams); const linkClasses = classnames(this.props.className, { [this.props.isActiveClass]: isActive }); return <a {...this.props} href={href} onClick={this.onClick} className={linkClasses} />; } }); export default Url;
Use partial for duplicated partial string
"""Leetcode 131. Palindrome Partitioning Medium URL: https://leetcode.com/problems/palindrome-partitioning/ Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example: Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] """ class Solution(object): def _backtrack(self, result, temps, s, start): if start == len(s): result.append(temps[:]) return None for i in range(start, len(s)): # Check if palindrome. partial = s[start:i+1] if partial == partial[::-1]: temps.append(s[start:i+1]) self._backtrack(result, temps, s, i + 1) temps.pop() def partition(self, s): """ :type s: str :rtype: List[List[str]] Time complexity: O(n * 2^n), where n is the length of s. Space complexity: O(n). """ # Apply backtracking. result = [] temps = [] start = 0 self._backtrack(result, temps, s, start) return result def main(): s = "aab" print Solution().partition(s) if __name__ == '__main__': main()
"""Leetcode 131. Palindrome Partitioning Medium URL: https://leetcode.com/problems/palindrome-partitioning/ Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example: Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] """ class Solution(object): def _backtrack(self, result, temps, s, start): if start == len(s): result.append(temps[:]) return None for i in range(start, len(s)): # Check if palindrome. if s[start:i+1] == s[start:i+1][::-1]: temps.append(s[start:i+1]) self._backtrack(result, temps, s, i + 1) temps.pop() def partition(self, s): """ :type s: str :rtype: List[List[str]] """ # Apply backtracking. result = [] temps = [] start = 0 self._backtrack(result, temps, s, start) return result def main(): s = "aab" print Solution().partition(s) if __name__ == '__main__': main()
Fix plugin import for astropy 2.x
# Licensed under a 3-clause BSD style license - see LICENSE.rst # this contains imports plugins that configure py.test for astropy tests. # by importing them here in conftest.py they are discoverable by py.test # no matter how it is invoked within the source tree. import os try: from astropy.tests.plugins.display import (pytest_report_header, PYTEST_HEADER_MODULES, TESTED_VERSIONS) except ImportError: # When using astropy 2.0 from astropy.tests.pytest_plugins import (pytest_report_header, PYTEST_HEADER_MODULES, TESTED_VERSIONS) try: # This is the way to get plugins in astropy 2.x from astropy.tests.pytest_plugins import * except ImportError: # Otherwise they are installed as separate packages that pytest # automagically finds. pass from .tests.pytest_fixtures import * # This is to figure out ccdproc version, rather than using Astropy's try: from .version import version except ImportError: version = 'dev' packagename = os.path.basename(os.path.dirname(__file__)) TESTED_VERSIONS[packagename] = version # Uncomment the following line to treat all DeprecationWarnings as # exceptions # enable_deprecations_as_exceptions() # Add astropy to test header information and remove unused packages. try: PYTEST_HEADER_MODULES['Astropy'] = 'astropy' PYTEST_HEADER_MODULES['astroscrappy'] = 'astroscrappy' PYTEST_HEADER_MODULES['reproject'] = 'reproject' del PYTEST_HEADER_MODULES['h5py'] except KeyError: pass
# Licensed under a 3-clause BSD style license - see LICENSE.rst # this contains imports plugins that configure py.test for astropy tests. # by importing them here in conftest.py they are discoverable by py.test # no matter how it is invoked within the source tree. import os try: from astropy.tests.plugins.display import (pytest_report_header, PYTEST_HEADER_MODULES, TESTED_VERSIONS) except ImportError: # When using astropy 2.0 from astropy.tests.pytest_plugins import (pytest_report_header, PYTEST_HEADER_MODULES, TESTED_VERSIONS) from .tests.pytest_fixtures import * # This is to figure out ccdproc version, rather than using Astropy's try: from .version import version except ImportError: version = 'dev' packagename = os.path.basename(os.path.dirname(__file__)) TESTED_VERSIONS[packagename] = version # Uncomment the following line to treat all DeprecationWarnings as # exceptions # enable_deprecations_as_exceptions() # Add astropy to test header information and remove unused packages. try: PYTEST_HEADER_MODULES['Astropy'] = 'astropy' PYTEST_HEADER_MODULES['astroscrappy'] = 'astroscrappy' PYTEST_HEADER_MODULES['reproject'] = 'reproject' del PYTEST_HEADER_MODULES['h5py'] except KeyError: pass
Stop using reserved JavaScript keyword `package`
'use babel'; export function loadFile(path) { return window.nvim.command(`e ${path}`); } export async function loadFileGetBufferContents(path) { await loadFile(path); const buffer = await window.nvim.getCurrentBuffer(); const lineCount = await buffer.lineCount(); return await buffer.getLineSlice(0, lineCount, true, true); } export function timeout(ms = 50) { return new Promise(resolve => jasmine.setTimeout(resolve, ms)); } export function waitsForTimeout(ms = 50) { return waitsForPromise(() => timeout(ms)); } export function getActivationPromise() { return atom.packages.activatePackage('neovimbed').then(async pack => { atom.workspace.destroyActivePaneItem(); await pack.mainModule.initialisationPromise; window.nvim = pack.mainModule.nvim; // TODO: This may be a bad idea and it's actually something that // should be handled and have test cases for await window.nvim.command('set noswapfile'); return pack.mainModule; }); } export async function getBufferContents(bufferNumber) { const buffers = await window.nvim.getBuffers(); for (const buffer of buffers) { const n = await buffer.getNumber(); if (n === bufferNumber) { const lineCount = await buffer.lineCount(); return await buffer.getLineSlice(0, lineCount, true, true); } } throw new Error(`Could not find buffer ${bufferNumber}`); }
'use babel'; export function loadFile(path) { return window.nvim.command(`e ${path}`); } export async function loadFileGetBufferContents(path) { await loadFile(path); const buffer = await window.nvim.getCurrentBuffer(); const lineCount = await buffer.lineCount(); return await buffer.getLineSlice(0, lineCount, true, true); } export function timeout(ms = 50) { return new Promise(resolve => jasmine.setTimeout(resolve, ms)); } export function waitsForTimeout(ms = 50) { return waitsForPromise(() => timeout(ms)); } export function getActivationPromise() { return atom.packages.activatePackage('neovimbed').then(async package => { atom.workspace.destroyActivePaneItem(); await package.mainModule.initialisationPromise; window.nvim = package.mainModule.nvim; // TODO: This may be a bad idea and it's actually something that // should be handled and have test cases for await window.nvim.command('set noswapfile'); return package.mainModule; }); } export async function getBufferContents(bufferNumber) { const buffers = await window.nvim.getBuffers(); for (const buffer of buffers) { const n = await buffer.getNumber(); if (n === bufferNumber) { const lineCount = await buffer.lineCount(); return await buffer.getLineSlice(0, lineCount, true, true); } } throw new Error(`Could not find buffer ${bufferNumber}`); }
Add user context to Raven client, if the user is logged in
<?php require_once 'Zend/Log/Writer/Abstract.php'; /** * Publish SilverStripe errors and warnings to Sentry using the Raven client. */ class SentryLogger extends Zend_Log_Writer_Abstract { private $sentry; private $logLevels = array( 'NOTICE' => Raven_Client::INFO, 'WARN' => Raven_Client::WARNING, 'ERR' => Raven_Client::ERROR ); /** * @config */ private static $sentry_dsn; public static function factory($config) { return new SentryLogger(); } public function __construct() { $DSN = Config::inst()->get('SentryLogger', 'sentry_dsn'); $this->sentry = new Raven_Client($DSN); $this->sentry->setEnvironment(Director::get_environment_type()); if(Member::currentUserID()) { $this->sentry->user_context(array( 'email' => Member::curentUser()->Email, 'id' => Member::currentUserID() )); } } /** * Send the error. * * @param array $event * @return void */ public function _write($event) { $data['level'] = $this->logLevels[$event['priorityName']]; $data['timestamp'] = strtotime($event['timestamp']); $backtrace = SS_Backtrace::filter_backtrace(debug_backtrace(), array("SentryLogger->_write")); $this->sentry->captureMessage($event['message']['errstr'], array(), $data, $backtrace); } }
<?php require_once 'Zend/Log/Writer/Abstract.php'; /** * Publish SilverStripe errors and warnings to Sentry using the Raven client. */ class SentryLogger extends Zend_Log_Writer_Abstract { private $sentry; private $logLevels = array( 'NOTICE' => Raven_Client::INFO, 'WARN' => Raven_Client::WARNING, 'ERR' => Raven_Client::ERROR ); /** * @config */ private static $sentry_dsn; public static function factory($config) { return new SentryLogger(); } public function __construct() { $DSN = Config::inst()->get('SentryLogger', 'sentry_dsn'); $this->sentry = new Raven_Client($DSN); $this->sentry->setEnvironment(Director::get_environment_type()); } /** * Send the error. * * @param array $event * @return void */ public function _write($event) { $data['level'] = $this->logLevels[$event['priorityName']]; $data['timestamp'] = strtotime($event['timestamp']); $backtrace = SS_Backtrace::filter_backtrace(debug_backtrace(), array("SentryLogger->_write")); $this->sentry->captureMessage($event['message']['errstr'], array(), $data, $backtrace); } }
Add allowed_system as a class variable
import platform class OSXDodger(object): allowed_version = "10.6.1" allowed_system = "darwin" def __init__(self, applications_dir): self.app_dir = applications_dir def load_applications(self): """ Read all applications in the `/Applications/` dir """ self.pc_is_macintosh() def select_applications(self): """ Allow user to select an application they want not to appear on the Dock """ pass def load_dodger_filer(self): """ Load the file to modify for the application chosen by the user in `select_applications` The file to be loaded for is `info.plist` """ pass def dodge_application(self): """ Remive the application from the Dock """ pass @classmethod def pc_is_macintosh(cls): """ Check if it is an `Apple Computer` i.e a Mac @return bool """ system = platform.system().lower() sys_version = int((platform.mac_ver())[0].replace(".", "")) allowed_version = int(cls.allowed_version.replace(".", "")) if (system == cls.allowed_system) and (sys_version >= allowed_version): return True else: print("\nSorry :(") print("FAILED. OsX-dock-dodger is only applicable to computers " + "running OS X {} or higher".format(cls.allowed_version)) return False dodge = OSXDodger("/Applications/") dodge.load_applications()
import platform class OSXDodger(object): allowed_version = "10.12.1" def __init__(self, applications_dir): self.app_dir = applications_dir def load_applications(self): """ Read all applications in the `/Applications/` dir """ self.pc_is_macintosh() def select_applications(self): """ Allow user to select an application they want not to appear on the Dock """ pass def load_dodger_filer(self): """ Load the file to modify for the application chosen by the user in `select_applications` The file to be loaded for is `info.plist` """ pass def dodge_application(self): """ Remive the application from the Dock """ pass @classmethod def pc_is_macintosh(cls): """ Check if it is an `Apple Computer` i.e a Mac @return bool """ system = platform.system().lower() sys_version = int((platform.mac_ver())[0].replace(".", "")) allowed_version = int(cls.allowed_version.replace(".", "")) if (system == "darwin") and (sys_version >= allowed_version): return True else: print("\nSorry :(") print("FAILED. OsX-dock-dodger is only applicable to computers " + "running OS X {} or higher".format(cls.allowed_version)) return False dodge = OSXDodger("/Applications/") dodge.load_applications()
Set up options structure, require dateSlug
/* * grunt-deploy * https://github.com/kevinschaul/strib-deploy * * Copyright (c) 2013 Kevin Schaul * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerTask('deploy', 'Deploy to apps.startribune.com', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ appsSvnPath: '../apps', branch: 'master' }); if (!options.dateSlug) { grunt.log.error('dateSlug option is required.'); return false; } /* // Iterate over all specified file groups. this.files.forEach(function(f) { // Concat specified files. var src = f.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function(filepath) { // Read file source. return grunt.file.read(filepath); }).join(grunt.util.normalizelf(options.separator)); // Handle options. src += options.punctuation; // Write the destination file. grunt.file.write(f.dest, src); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); }); */ }); };
/* * grunt-deploy * https://github.com/kevinschaul/strib-deploy * * Copyright (c) 2013 Kevin Schaul * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('deploy', 'Deploy to apps.startribune.com', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ punctuation: '.', separator: ', ' }); // Iterate over all specified file groups. this.files.forEach(function(f) { // Concat specified files. var src = f.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function(filepath) { // Read file source. return grunt.file.read(filepath); }).join(grunt.util.normalizelf(options.separator)); // Handle options. src += options.punctuation; // Write the destination file. grunt.file.write(f.dest, src); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
Update state when commands context changed
var Model = codebox.require("hr.model"); var Collection = codebox.require("hr.collection"); var _ = codebox.require("hr.utils"); var commands = codebox.require("core/commands"); var MenuItem = Model.extend({ defaults: { type: "entry", caption: "", command: "", items: [], args: {}, position: 0, enabled: true }, // Constructor initialize: function() { MenuItem.__super__.initialize.apply(this, arguments); this.items = new MenuItems(); this.listenTo(this, "change:items", function() { this.items.reset(this.get("items")); }); this.items.reset(this.get("items")); this.listenTo(commands, "add remove reset change:enabled change:context context", this.checkState); }, // Execute the command associated with the entry execute: function() { commands.run(this.get("command"), this.get("args")) }, // Check visibility checkState: function() { if (this.get("command")) { var cmd = commands.get(this.get("command")); var isEnabled = ( // Command exits cmd && // Command is runnable cmd.isRunnable() ); this.set("enabled", isEnabled); } return this.get("enabled"); } }); var MenuItems = Collection.extend({ model: MenuItem, comparator: "position" }); module.exports = MenuItems;
var Model = codebox.require("hr.model"); var Collection = codebox.require("hr.collection"); var _ = codebox.require("hr.utils"); var commands = codebox.require("core/commands"); var MenuItem = Model.extend({ defaults: { type: "entry", caption: "", command: "", items: [], args: {}, position: 0, enabled: true }, // Constructor initialize: function() { MenuItem.__super__.initialize.apply(this, arguments); this.items = new MenuItems(); this.listenTo(this, "change:items", function() { this.items.reset(this.get("items")); }); this.items.reset(this.get("items")); this.listenTo(commands, "add remove reset change:enabled change:context", this.checkState); }, // Execute the command associated with the entry execute: function() { commands.run(this.get("command"), this.get("args")) }, // Check visibility checkState: function() { if (this.get("command")) { var cmd = commands.get(this.get("command")); var isEnabled = ( // Command exits cmd && // Command is runnable cmd.isRunnable() ); this.set("enabled", isEnabled); } return this.get("enabled"); } }); var MenuItems = Collection.extend({ model: MenuItem, comparator: "position" }); module.exports = MenuItems;
Change to use logging and set log level to INFO
import os import logging from decouple import config FOLDER = 'public' FOLDER = FOLDER.strip('/') logging.basicConfig(level=logging.INFO) def deploy(): import boto from boto.s3.connection import S3Connection AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') BUCKET_NAME = config('AWS_BUCKET_NAME') conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(BUCKET_NAME) key = boto.s3.key.Key(bucket) for dirpath, dirnames, filenames in os.walk(FOLDER): # do not use the FOLDER prefix destpath = dirpath[len(FOLDER):] destpath = destpath.strip('/') logging.info("Uploading %s files from %s to %s", len(filenames), dirpath, BUCKET_NAME) for filename in filenames: key.name = os.path.relpath(os.path.join(destpath, filename) ).replace('\\', '/') key.set_contents_from_filename(os.path.join(dirpath, filename)) logging.debug("Sending %s", key.name) logging.info("done :)")
import os import logging from decouple import config FOLDER = 'public' FOLDER = FOLDER.strip('/') log = logging.getLogger('deploy') def deploy(): import boto from boto.s3.connection import S3Connection AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') BUCKET_NAME = config('AWS_BUCKET_NAME') conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(BUCKET_NAME) key = boto.s3.key.Key(bucket) for dirpath, dirnames, filenames in os.walk(FOLDER): # do not use the FOLDER prefix destpath = dirpath[len(FOLDER):] destpath = destpath.strip('/') log.info("Uploading {0} files from {1} to {2} ...".format(len(filenames), dirpath, BUCKET_NAME)) for filename in filenames: key.name = os.path.relpath(os.path.join(destpath, filename) ).replace('\\', '/') key.set_contents_from_filename(os.path.join(dirpath, filename))
Add 'rc' as prereleaseName in grunt bump
module.exports = function(grunt) { grunt.initConfig({ watch: { all: { options: { livereload: true }, files: [ '*.html', 'examples/**/*.html', 'test/*.js', 'test/*.html', 'test/**/*.html' ], // tasks: ['jshint'], }, }, // Mocha mocha: { all: { src: ['test/index.html'], }, options: { run: true } }, bump: { options: { files: ['package.json', 'starcounter-include.html'], commit: true, commitMessage: '%VERSION%', commitFiles: ['package.json', 'starcounter-include.html'], createTag: true, tagName: '%VERSION%', tagMessage: 'Version %VERSION%', push: false, // pushTo: 'origin', globalReplace: false, prereleaseName: 'rc', regExp: false } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha'); grunt.loadNpmTasks('grunt-bump'); grunt.registerTask('default', ['watch']); grunt.registerTask('test', ['mocha']); };
module.exports = function(grunt) { grunt.initConfig({ watch: { all: { options: { livereload: true }, files: [ '*.html', 'examples/**/*.html', 'test/*.js', 'test/*.html', 'test/**/*.html' ], // tasks: ['jshint'], }, }, // Mocha mocha: { all: { src: ['test/index.html'], }, options: { run: true } }, bump: { options: { files: ['package.json', 'starcounter-include.html'], commit: true, commitMessage: '%VERSION%', commitFiles: ['package.json', 'starcounter-include.html'], createTag: true, tagName: '%VERSION%', tagMessage: 'Version %VERSION%', push: false, // pushTo: 'origin', globalReplace: false, prereleaseName: false, regExp: false } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha'); grunt.loadNpmTasks('grunt-bump'); grunt.registerTask('default', ['watch']); grunt.registerTask('test', ['mocha']); };
Allow .js extension for JSX files
module.exports = { parser: 'babel-eslint', extends: [ 'airbnb', 'plugin:ava/recommended', ], plugins: [ 'import', 'ava', ], rules: { indent: ['error', 4, { SwitchCase: 1, MemberExpression: 1, VariableDeclarator: 1, outerIIFEBody: 1, FunctionDeclaration: { parameters: 1, body: 1, }, FunctionExpression: { parameters: 1, body: 1, }, }], 'valid-jsdoc': 'error', strict: 'error', 'no-sync': 'error', 'no-inline-comments': 'error', 'no-use-before-define': ['error', 'nofunc'], 'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'], 'max-len': ['error', 150, 4, { ignoreUrls: true, ignoreComments: false, ignoreRegExpLiterals: true, ignoreStrings: true, ignoreTemplateLiterals: true, }], 'react/jsx-filename-extension': ['error', { extensions: ['.js', '.jsx'] }], }, };
module.exports = { parser: 'babel-eslint', extends: [ 'airbnb', 'plugin:ava/recommended', ], plugins: [ 'import', 'ava', ], rules: { indent: ['error', 4, { SwitchCase: 1, MemberExpression: 1, VariableDeclarator: 1, outerIIFEBody: 1, FunctionDeclaration: { parameters: 1, body: 1, }, FunctionExpression: { parameters: 1, body: 1, }, }], 'valid-jsdoc': 'error', strict: 'error', 'no-sync': 'error', 'no-inline-comments': 'error', 'no-use-before-define': ['error', 'nofunc'], 'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'], 'max-len': ['error', 150, 4, { ignoreUrls: true, ignoreComments: false, ignoreRegExpLiterals: true, ignoreStrings: true, ignoreTemplateLiterals: true, }], }, };
Fix issue when use text search and count
/* ** Module dependencies */ var mongoose = require('mongoose'); var Record = mongoose.model('Record'); var async = require('async'); exports.search = function(req, res, next) { function buildQuery() { var query = Record.find().where('metadata.type').in(['dataset', 'series']); if (req.query.q && req.query.q.length) { query.where({ $text: { $search: req.query.q, $language: 'french' }}); } if (req.query.opendata === 'true') { query .where('metadata.keywords') .in(['donnée ouverte', 'données ouvertes', 'opendata']); } if (req.service) query.where('parentCatalog', req.service.id); return query; } async.parallel({ results: function(callback) { buildQuery() .select({ score: { $meta: 'textScore' } }) .sort({ score: { $meta: 'textScore' } }) .limit(20) .exec(callback); }, count: function(callback) { buildQuery().count().exec(callback); } }, function(err, out) { if (err) return next(err); res.json(out); }); };
/* ** Module dependencies */ var mongoose = require('mongoose'); var Record = mongoose.model('Record'); var async = require('async'); exports.search = function(req, res, next) { function buildQuery() { var query = Record.find().where('metadata.type').in(['dataset', 'series']); if (req.query.q && req.query.q.length) { query .where({ $text: { $search: req.query.q, $language: 'french' }}) .select({ score: { $meta: 'textScore' } }) .sort({ score: { $meta: 'textScore' } }); } if (req.query.opendata === 'true') { query .where('metadata.keywords') .in(['donnée ouverte', 'données ouvertes', 'opendata']); } if (req.service) query.where('parentCatalog', req.service.id); return query; } async.parallel({ results: function(callback) { buildQuery().limit(20).exec(callback); }, count: function(callback) { buildQuery().count().exec(callback); } }, function(err, out) { if (err) return next(err); res.json(out); }); };
Include phones in default org object
import React, { Component } from 'react' import { fetchOrganization } from '../../core/firebaseRestAPI' import { authenticate } from '../../lib/session' import { uuid } from '../../lib/uuid' import Layout from '../../components/Layout' import Loading from '../../components/Loading' import OrganizationEdit from '../../components/OrganizationEdit' const blankOrganization = () => ({ id: uuid(), longDescription: "", name: "", url: "", phones: [] }) class OrganizationAdminPage extends Component { constructor(props) { super(props) this.state = { organization: null, } } componentWillMount() { authenticate() } componentDidMount() { const match = this.props.route.pattern.exec(window.location.pathname) const organizationId = match[1] if (organizationId === 'new') { this.setState({ organization: blankOrganization() }) } else { fetchOrganization(organizationId) .then(organization => { this.setState({ organization }) }) } } componentDidUpdate() { const { organization } = this.state if (organization && organization.name) { document.title = organization.name } else { document.title = 'Create Organization' } } render() { const { organization } = this.state return ( <Layout admin> { organization ? <OrganizationEdit organization={organization} /> : <Loading /> } </Layout> ) } } export default OrganizationAdminPage
import React, { Component } from 'react' import { fetchOrganization } from '../../core/firebaseRestAPI' import { authenticate } from '../../lib/session' import { uuid } from '../../lib/uuid' import Layout from '../../components/Layout' import Loading from '../../components/Loading' import OrganizationEdit from '../../components/OrganizationEdit' const blankOrganization = () => ({ id: uuid(), longDescription: "", name: "", url: "" }) class OrganizationAdminPage extends Component { constructor(props) { super(props) this.state = { organization: null, } } componentWillMount() { authenticate() } componentDidMount() { const match = this.props.route.pattern.exec(window.location.pathname) const organizationId = match[1] if (organizationId === 'new') { this.setState({ organization: blankOrganization() }) } else { fetchOrganization(organizationId) .then(organization => { this.setState({ organization }) }) } } componentDidUpdate() { const { organization } = this.state if (organization && organization.name) { document.title = organization.name } else { document.title = 'Create Organization' } } render() { const { organization } = this.state return ( <Layout admin> { organization ? <OrganizationEdit organization={organization} /> : <Loading /> } </Layout> ) } } export default OrganizationAdminPage
Fix "Call to a member function close() on null" exception
<?php namespace VladimirYuldashev\LaravelQueueRabbitMQ; use Illuminate\Queue\QueueManager; use Illuminate\Support\ServiceProvider; use PhpAmqpLib\Connection\AMQPStreamConnection; use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnector; use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnectorSSL; class LaravelQueueRabbitMQServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom( __DIR__ . '/../config/rabbitmq.php', 'queue.connections.rabbitmq' ); } /** * Register the application's event listeners. * * @return void */ public function boot() { /** @var QueueManager $queue */ $queue = $this->app['queue']; if ($this->app['config']['rabbitmq']['ssl_params']['ssl_on'] === true) { $connector = new RabbitMQConnectorSSL(); } else { $connector = new RabbitMQConnector(); } $queue->stopping(function () use ($connector) { if ($connector->connection() instanceof AMQPStreamConnection) { $connector->connection()->close(); } }); $queue->addConnector('rabbitmq', function () use ($connector) { return $connector; }); } }
<?php namespace VladimirYuldashev\LaravelQueueRabbitMQ; use Illuminate\Queue\QueueManager; use Illuminate\Support\ServiceProvider; use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnector; use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnectorSSL; class LaravelQueueRabbitMQServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom( __DIR__ . '/../config/rabbitmq.php', 'queue.connections.rabbitmq' ); } /** * Register the application's event listeners. * * @return void */ public function boot() { /** @var QueueManager $queue */ $queue = $this->app['queue']; if ($this->app['config']['rabbitmq']['ssl_params']['ssl_on'] === true) { $connector = new RabbitMQConnectorSSL(); } else { $connector = new RabbitMQConnector(); } $queue->stopping(function () use ($connector) { $connector->connection()->close(); }); $queue->addConnector('rabbitmq', function () use ($connector) { return $connector; }); } }
Change error status with config problems to critical
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: [email protected] @license: The MIT license Copyright (C) 2015 """ from sheldon.adapter import * from sheldon.config import * from sheldon.exceptions import * from sheldon.manager import * from sheldon.storage import * from sheldon.utils import logger class Sheldon: """ Main class of the bot. Run script creating new instance of this class and run it. """ def __init__(self, command_line_arguments): """ Function for loading bot. :param command_line_arguments: dict, arguments for start script :return: """ self._load_config(command_line_arguments) def _load_config(self, command_line_arguments): """ Сreate and load bot config. :param command_line_arguments: dict, arguments for creating config: config-prefix - prefix of environment variables. Default - 'SHELDON_' :return: """ # Config class is imported from sheldon.config try: if 'config-prefix' in command_line_arguments: self.config = Config(prefix=command_line_arguments['config-prefix']) else: self.config = Config() except Exception as error: logger.critical_message('Error with loading config:') logger.critical_message(str(error.__traceback__))
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: [email protected] @license: The MIT license Copyright (C) 2015 """ from sheldon.adapter import * from sheldon.config import * from sheldon.exceptions import * from sheldon.manager import * from sheldon.storage import * from sheldon.utils import logger class Sheldon: """ Main class of the bot. Run script creating new instance of this class and run it. """ def __init__(self, command_line_arguments): """ Function for loading bot. :param command_line_arguments: dict, arguments for start script :return: """ self._load_config(command_line_arguments) def _load_config(self, command_line_arguments): """ Сreate and load bot config. :param command_line_arguments: dict, arguments for creating config: config-prefix - prefix of environment variables. Default - 'SHELDON_' :return: """ # Config class is imported from sheldon.config try: if 'config-prefix' in command_line_arguments: self.config = Config(prefix=command_line_arguments['config-prefix']) else: self.config = Config() except Exception as error: logger.error_message('Error with loading config:') logger.error_message(str(error.__traceback__))
Fix missing backslash on exception
<?php namespace Stevebauman\Maintenance\Services; use Stevebauman\Maintenance\Models\Note; /** * Class NoteService * @package Stevebauman\Maintenance\Services */ class NoteService extends BaseModelService { /** * @var SentryService */ protected $sentry; /** * Constructor. * * @param Note $note * @param SentryService $sentry */ public function __construct(Note $note, SentryService $sentry) { $this->model = $note; $this->sentry = $sentry; } /** * Creates a note. * * @return bool|static */ public function create() { $this->dbStartTransaction(); try { $insert = [ 'user_id' => $this->sentry->getCurrentUserId(), 'content' => $this->getInput('content', null, true), ]; $record = $this->model->create($insert); if($record) { $this->dbCommitTransaction(); return $record; } } catch(\Exception $e) { $this->dbRollbackTransaction(); } return false; } }
<?php namespace Stevebauman\Maintenance\Services; use Stevebauman\Maintenance\Models\Note; /** * Class NoteService * @package Stevebauman\Maintenance\Services */ class NoteService extends BaseModelService { /** * @var SentryService */ protected $sentry; /** * @param Note $note * @param SentryService $sentry */ public function __construct(Note $note, SentryService $sentry) { $this->model = $note; $this->sentry = $sentry; } /** * Creates a note * * @return bool|static */ public function create() { $this->dbStartTransaction(); try { $insert = [ 'user_id' => $this->sentry->getCurrentUserId(), 'content' => $this->getInput('content', null, true), ]; $record = $this->model->create($insert); if($record) { $this->dbCommitTransaction(); return $record; } } catch(Exception $e) { $this->dbRollbackTransaction(); } return false; } }
Use arrow functions whenver possible
(function () { function initTwinklingStars() { const devicePixelRatio = Math.min(window.devicePixelRatio, 3) || 1; particlesJS('stars', { particles: { number: { value: 180, density: { enable: true, value_area: 600 } }, color: { value: '#ffffff' }, shape: { type: 'circle' }, opacity: { value: 1, random: true, anim: { enable: true, speed: 3, opacity_min: 0 } }, size: { value: 1.5 / devicePixelRatio, random: true, anim: { enable: true, speed: 1, size_min: 0.5 / devicePixelRatio, sync: false } }, line_linked: { enable: false }, move: { enable: true, speed: 50, direction: 'none', random: true, straight: true, out_mode: 'bounce' } }, retina_detect: true }); } window.onload = () => { document.body.className = ''; initTwinklingStars(); } window.onresize = () => { clearTimeout(window.onResizeEnd); window.onResizeEnd = setTimeout(initTwinklingStars, 250); } window.ontouchmove = () => false; window.onorientationchange = () => { document.body.scrollTop = 0; }; }());
(function () { function initTwinklingStars() { const devicePixelRatio = Math.min(window.devicePixelRatio, 3) || 1; particlesJS('stars', { particles: { number: { value: 180, density: { enable: true, value_area: 600 } }, color: { value: '#ffffff' }, shape: { type: 'circle' }, opacity: { value: 1, random: true, anim: { enable: true, speed: 3, opacity_min: 0 } }, size: { value: 1.5 / devicePixelRatio, random: true, anim: { enable: true, speed: 1, size_min: 0.5 / devicePixelRatio, sync: false } }, line_linked: { enable: false }, move: { enable: true, speed: 50, direction: 'none', random: true, straight: true, out_mode: 'bounce' } }, retina_detect: true }); } window.onload = function () { document.body.className = ''; initTwinklingStars(); } window.onresize = function () { clearTimeout(window.onResizeEnd); window.onResizeEnd = setTimeout(initTwinklingStars, 250); } window.ontouchmove = function () { return false; } window.onorientationchange = function () { document.body.scrollTop = 0; } }());
Use Play's ok() for chunked responses
package controllers; import org.sagebionetworks.bridge.models.UserSession; import org.sagebionetworks.bridge.services.backfill.BackfillService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import play.mvc.Result; public class BackfillController extends BaseController implements ApplicationContextAware { private final Logger logger = LoggerFactory.getLogger(BackfillService.class); private ApplicationContext appContext; @Override public void setApplicationContext(ApplicationContext appContext) throws BeansException { this.appContext = appContext; } public Result backfill(final String name) throws Exception { final String user = checkUser(); final BackfillService backfillService = appContext.getBean(name, BackfillService.class); Chunks<String> chunks = new StringChunks() { @Override public void onReady(final Chunks.Out<String> out) { BackfillChunksAdapter chunksAdapter = new BackfillChunksAdapter(out); backfillService.backfill(user, name, chunksAdapter); } }; logger.info("Backfill " + name + " submitted."); return ok(chunks); } private String checkUser() throws Exception { UserSession session = getAuthenticatedAdminSession(); return session.getUser().getEmail(); } }
package controllers; import org.sagebionetworks.bridge.models.UserSession; import org.sagebionetworks.bridge.services.backfill.BackfillService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import play.mvc.Result; public class BackfillController extends BaseController implements ApplicationContextAware { private final Logger logger = LoggerFactory.getLogger(BackfillService.class); private ApplicationContext appContext; @Override public void setApplicationContext(ApplicationContext appContext) throws BeansException { this.appContext = appContext; } public Result backfill(final String name) throws Exception { final String user = checkUser(); final BackfillService backfillService = appContext.getBean(name, BackfillService.class); Chunks<String> chunks = new StringChunks() { @Override public void onReady(final Chunks.Out<String> out) { BackfillChunksAdapter chunksAdapter = new BackfillChunksAdapter(out); backfillService.backfill(user, name, chunksAdapter); } }; logger.info("Backfill " + name + " submitted."); return okResult(chunks); } private String checkUser() throws Exception { UserSession session = getAuthenticatedAdminSession(); return session.getUser().getEmail(); } }
Use new with gutil plugin error.
/* jshint node:true */ 'use strict'; var csso = require('csso'), gutil = require('gulp-util'), transform = require('stream').Transform, bufferstreams = require('bufferstreams'), PLUGIN_NAME = 'gulp-csso'; function cssoTransform(optimise) { // Returns a callback that handles the buffered content return function(err, buffer, cb) { if (err) { cb(new gutil.PluginError(PLUGIN_NAME, err)); } var optimised = csso.justDoIt(String(buffer), optimise); cb(null, new Buffer(optimised)); }; } function gulpcsso(optimise) { var stream = new transform({ objectMode: true }); stream._transform = function(file, unused, done) { // Pass through if null if (file.isNull()) { stream.push(file); done(); return; } if (file.isStream()) { file.contents = file.contents.pipe(new bufferstreams(cssoTransform(optimise))); stream.push(file); done(); } else { var optimised = csso.justDoIt(String(file.contents), optimise); file.contents = new Buffer(optimised); stream.push(file); done(); } }; return stream; } gulpcsso.cssoTransform = cssoTransform; module.exports = gulpcsso;
/* jshint node:true */ 'use strict'; var csso = require('csso'), gutil = require('gulp-util'), transform = require('stream').Transform, bufferstreams = require('bufferstreams'), PLUGIN_NAME = 'gulp-csso'; function cssoTransform(optimise) { // Returns a callback that handles the buffered content return function(err, buffer, cb) { if (err) { cb(gutil.PluginError(PLUGIN_NAME, err)); } var optimised = csso.justDoIt(String(buffer), optimise); cb(null, new Buffer(optimised)); }; } function gulpcsso(optimise) { var stream = new transform({ objectMode: true }); stream._transform = function(file, unused, done) { // Pass through if null if (file.isNull()) { stream.push(file); done(); return; } if (file.isStream()) { file.contents = file.contents.pipe(new bufferstreams(cssoTransform(optimise))); stream.push(file); done(); } else { var optimised = csso.justDoIt(String(file.contents), optimise); file.contents = new Buffer(optimised); stream.push(file); done(); } }; return stream; } gulpcsso.cssoTransform = cssoTransform; module.exports = gulpcsso;
Use unicode strings for 'no javascript' just so it's consistent with browser-retrieved values
class FingerprintAgent(object): def __init__(self, request): self.request = request def detect_server_whorls(self): vars = {} # get cookie enabled if self.request.cookies: vars['cookie_enabled'] = 'Yes' else: vars['cookie_enabled'] = 'No' # get user_agent vars['user_agent'] = self._get_header('User-Agent') # get http_accept vars['http_accept'] = " ".join([ self._get_header('Accept'), self._get_header('Accept-Charset'), self._get_header('Accept-Encoding'), self._get_header('Accept-Language') ]) vars['dnt_enabled'] = (self._get_header('DNT') != "") # these are dummies: vars['plugins'] = u"no javascript" vars['video'] = u"no javascript" vars['timezone'] = u"no javascript" vars['fonts'] = u"no javascript" vars['supercookies'] = u"no javascript" vars['canvas_hash'] = u"no javascript" vars['webgl_hash'] = u"no javascript" vars['language'] = u"no javascript" vars['platform'] = u"no javascript" vars['touch_support'] = u"no javascript" return vars def _get_header(self, header): return self.request.headers.get(header) or ""
class FingerprintAgent(object): def __init__(self, request): self.request = request def detect_server_whorls(self): vars = {} # get cookie enabled if self.request.cookies: vars['cookie_enabled'] = 'Yes' else: vars['cookie_enabled'] = 'No' # get user_agent vars['user_agent'] = self._get_header('User-Agent') # get http_accept vars['http_accept'] = " ".join([ self._get_header('Accept'), self._get_header('Accept-Charset'), self._get_header('Accept-Encoding'), self._get_header('Accept-Language') ]) vars['dnt_enabled'] = (self._get_header('DNT') != "") # these are dummies: vars['plugins'] = "no javascript" vars['video'] = "no javascript" vars['timezone'] = "no javascript" vars['fonts'] = "no javascript" vars['supercookies'] = "no javascript" vars['canvas_hash'] = "no javascript" vars['webgl_hash'] = "no javascript" vars['language'] = "no javascript" vars['platform'] = "no javascript" vars['touch_support'] = "no javascript" return vars def _get_header(self, header): return self.request.headers.get(header) or ""
Update status color based on response code
<?php /** * Class Sheep_Debug_Block_Controller * * @category Sheep * @package Sheep_Debug * @license Copyright: Pirate Sheep, 2016, All Rights reserved. * @link https://piratesheep.com */ class Sheep_Debug_Block_Controller extends Sheep_Debug_Block_Panel { public function getSubTitle() { $requestInfo = $this->getRequestInfo(); return $this->__('TIME: %ss MEM: %s', $this->formatNumber($requestInfo->getTime()), $this->helper->formatMemorySize($requestInfo->getPeakMemory()) ); } public function isVisible() { return $this->helper->isPanelVisible('controller'); } /** * @return Sheep_Debug_Model_Controller */ public function getController() { return $this->getRequestInfo()->getController(); } /** * Returns response code from request profile or from current response * * @return int */ public function getResponseCode() { return $this->getController()->getResponseCode() ?: $this->getAction()->getResponse()->getHttpResponseCode(); } /** * Returns status color prefix for CSS based on response status code * * @return string */ public function getStatusColor() { $responseCode = $this->getResponseCode(); return $responseCode > 399 ? 'red' : ( $responseCode > 299 ? 'yellow' : 'green'); } }
<?php /** * Class Sheep_Debug_Block_Controller * * @category Sheep * @package Sheep_Debug * @license Copyright: Pirate Sheep, 2016, All Rights reserved. * @link https://piratesheep.com */ class Sheep_Debug_Block_Controller extends Sheep_Debug_Block_Panel { public function getSubTitle() { $requestInfo = $this->getRequestInfo(); return $this->__('TIME: %ss MEM: %s', $this->formatNumber($requestInfo->getTime()), $this->helper->formatMemorySize($requestInfo->getPeakMemory()) ); } public function isVisible() { return $this->helper->isPanelVisible('controller'); } /** * @return Sheep_Debug_Model_Controller */ public function getController() { return $this->getRequestInfo()->getController(); } /** * Returns response code from request profile or from current response * * @return int */ public function getResponseCode() { return $this->getController()->getResponseCode() ?: $this->getAction()->getResponse()->getHttpResponseCode(); } /** * Returns status color prefix for CSS based on response status code * * @return string */ public function getStatusColor() { // TODO: also use yellow : return $this->getResponseCode() == 200 ?'green' : 'red'; } }
Add changes missing from commit a3a01cd
<?php require('ErrorsContainer.php'); class AddSegmentsErrors extends ErrorsContainer { public function __constructor() { $this->errors = [ 'missingCategory' => false, 'categoryInvalidFormat' => false, 'missingAlbum' => false, 'missingAuthor' => false, 'missingName' => false, 'missingAdNumber' => false, 'missingStartTime' => false, 'startTimeInvalidFormat' => false, 'outOfEpisodeBounds' => false ]; } public function markCategoryMissing() { $this->errors['misisngCategory'] = true; } public function markCategoryInvalidFormat() { $this->errors['categoryInvalidFormat'] = true; } public function markAlbumMissing() { $this->errors['missingAlbum'] = true; } public function markAuthorMissing() { $this->errors['missingAuthor'] = true; } public function markNameMissing() { $this->errors['missingName'] = true; } public function markAdNumberMissing() { $this->errors['missingAdNumber'] = true; } public function markStartTimeMissing() { $this->errors['missingStartTime'] = true; } public function markStartTimeInvalidFormat() { $this->errors['startTimeInvalidFormat'] = true; } public function markStartTimeOutOfEpisodeBounds() { $this->errors['outOfEpisodeBounds'] = true; } }
<?php require('ErrorsContainer.php'); class AddSegmentsErrors extends ErrorsContainer { public function __constructor() { $this->errors = [ 'missingAlbum' => false, 'missingAuthor' => false, 'missingName' => false, 'missingAdNumber' => false, 'missingStartTime' => false, 'startTimeInvalidFormat' => false, 'outOfEpisodeBounds' => false ]; } public function markAlbumMissing() { $this->errors['missingAlbum'] = true; } public function markAuthorMissing() { $this->errors['missingAuthor'] = true; } public function markNameMissing() { $this->errors['missingName'] = true; } public function markAdNumberMissing() { $this->errors['missingAdNumber'] = true; } public function markStartTimeMissing() { $this->errors['missingStartTime'] = true; } public function markStartTimeInvalidFormat() { $this->errors['startTimeInvalidFormat'] = true; } public function markStartTimeOutOfEpisodeBounds() { $this->errors['outOfEpisodeBounds'] = true; } }
Allow user to type :)
import React, {PropTypes} from 'react' const ENTER = 13 const ESCAPE = 27 const RawQueryEditor = React.createClass({ propTypes: { query: PropTypes.shape({ rawText: PropTypes.string.isRequired, id: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func.isRequired, }, getInitialState() { return { value: this.props.query.rawText, } }, componentWillReceiveProps(nextProps) { if (nextProps.query.rawText !== this.props.query.rawText) { this.setState({value: nextProps.query.rawText}) } }, handleKeyDown(e) { if (e.keyCode === ENTER) { e.preventDefault() this.handleUpdate(); } else if (e.keyCode === ESCAPE) { this.setState({value: this.props.query.rawText}, () => { this.editor.blur() }) } }, handleChange() { this.setState({ value: this.editor.value, }) }, handleUpdate() { this.props.onUpdate(this.state.value) }, render() { const {value} = this.state return ( <div className="raw-text"> <textarea className="raw-text--field" onChange={this.handleChange} onKeyDown={this.handleKeyDown} onBlur={this.handleUpdate} ref={(editor) => this.editor = editor} value={value} placeholder="Blank query" /> </div> ) }, }) export default RawQueryEditor
import React, {PropTypes} from 'react' const ENTER = 13 const ESCAPE = 27 const RawQueryEditor = React.createClass({ propTypes: { query: PropTypes.shape({ rawText: PropTypes.string.isRequired, id: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func.isRequired, }, getInitialState() { return { value: this.props.query.rawText, } }, componentWillReceiveProps(nextProps) { if (nextProps.query.rawText !== this.props.query.rawText) { this.setState({value: nextProps.query.rawText}) } }, handleKeyDown(e) { e.preventDefault() if (e.keyCode === ENTER) { this.handleUpdate(); } else if (e.keyCode === ESCAPE) { this.setState({value: this.props.query.rawText}, () => { this.editor.blur() }) } }, handleChange() { this.setState({ value: this.editor.value, }) }, handleUpdate() { this.props.onUpdate(this.state.value) }, render() { const {value} = this.state return ( <div className="raw-text"> <textarea className="raw-text--field" onChange={this.handleChange} onKeyDown={this.handleKeyDown} onBlur={this.handleUpdate} ref={(editor) => this.editor = editor} value={value} placeholder="Blank query" /> </div> ) }, }) export default RawQueryEditor
Add missing trailing commas in new webpack config
/* eslint-disable import/no-commonjs */ const webpack = require('webpack') const baseConfig = { entry: './src/index.js', module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/, }, ], }, output: { library: 'ReduxMost', libraryTarget: 'umd', }, externals: { most: { root: 'most', commonjs2: 'most', commonjs: 'most', amd: 'most', }, redux: { root: 'Redux', commonjs2: 'redux', commonjs: 'redux', amd: 'redux', }, }, resolve: { extensions: ['.js'], mainFields: ['module', 'main', 'jsnext:main'], }, } const devConfig = { ...baseConfig, output: { ...baseConfig.output, filename: './dist/redux-most.js', }, plugins: [ new webpack.EnvironmentPlugin({ 'NODE_ENV': 'development', }), ], } const prodConfig = { ...baseConfig, output: { ...baseConfig.output, filename: './dist/redux-most.min.js', }, plugins: [ new webpack.EnvironmentPlugin({ 'NODE_ENV': 'production', }), new webpack.optimize.UglifyJsPlugin({ compress: { screw_ie8: true, warnings: false, }, comments: false, }), ], } module.exports = [devConfig, prodConfig]
/* eslint-disable import/no-commonjs */ const webpack = require('webpack') const baseConfig = { entry: './src/index.js', module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/, }, ], }, output: { library: 'ReduxMost', libraryTarget: 'umd', }, externals: { most: { root: 'most', commonjs2: 'most', commonjs: 'most', amd: 'most', }, redux: { root: 'Redux', commonjs2: 'redux', commonjs: 'redux', amd: 'redux', }, }, resolve: { extensions: ['.js'], mainFields: ['module', 'main', 'jsnext:main'], }, } const devConfig = { ...baseConfig, output: { ...baseConfig.output, filename: './dist/redux-most.js', }, plugins: [ new webpack.EnvironmentPlugin({ 'NODE_ENV': 'development' }), ], } const prodConfig = { ...baseConfig, output: { ...baseConfig.output, filename: './dist/redux-most.min.js', }, plugins: [ new webpack.EnvironmentPlugin({ 'NODE_ENV': 'production' }), new webpack.optimize.UglifyJsPlugin({ compress: { screw_ie8: true, warnings: false, }, comments: false, }), ], } module.exports = [devConfig, prodConfig]
Move setting VCAP_SERVICES out of fixture This was inconsistent with the source data for the fixture being overidden in some of the tests. We only need to set it in the env once, so it makes sense to just put the code there.
import json import os import pytest from app.cloudfoundry_config import ( extract_cloudfoundry_config, set_config_env_vars, ) @pytest.fixture def cloudfoundry_config(): return { 'postgres': [{ 'credentials': { 'uri': 'postgres uri' } }], 'user-provided': [] } @pytest.fixture def vcap_application(os_environ): os.environ['VCAP_APPLICATION'] = '{"space_name": "🚀🌌"}' def test_extract_cloudfoundry_config_populates_other_vars(cloudfoundry_config, vcap_application): os.environ['VCAP_SERVICES'] = json.dumps(cloudfoundry_config) extract_cloudfoundry_config() assert os.environ['SQLALCHEMY_DATABASE_URI'] == 'postgresql uri' assert os.environ['NOTIFY_ENVIRONMENT'] == '🚀🌌' assert os.environ['NOTIFY_LOG_PATH'] == '/home/vcap/logs/app.log' def test_set_config_env_vars_ignores_unknown_configs(cloudfoundry_config, vcap_application): cloudfoundry_config['foo'] = {'credentials': {'foo': 'foo'}} cloudfoundry_config['user-provided'].append({ 'name': 'bar', 'credentials': {'bar': 'bar'} }) set_config_env_vars(cloudfoundry_config) assert 'foo' not in os.environ assert 'bar' not in os.environ
import json import os import pytest from app.cloudfoundry_config import ( extract_cloudfoundry_config, set_config_env_vars, ) @pytest.fixture def cloudfoundry_config(): return { 'postgres': [{ 'credentials': { 'uri': 'postgres uri' } }], 'user-provided': [] } @pytest.fixture def cloudfoundry_environ(os_environ, cloudfoundry_config): os.environ['VCAP_SERVICES'] = json.dumps(cloudfoundry_config) os.environ['VCAP_APPLICATION'] = '{"space_name": "🚀🌌"}' def test_extract_cloudfoundry_config_populates_other_vars(cloudfoundry_environ): extract_cloudfoundry_config() assert os.environ['SQLALCHEMY_DATABASE_URI'] == 'postgresql uri' assert os.environ['NOTIFY_ENVIRONMENT'] == '🚀🌌' assert os.environ['NOTIFY_LOG_PATH'] == '/home/vcap/logs/app.log' def test_set_config_env_vars_ignores_unknown_configs(cloudfoundry_config, cloudfoundry_environ): cloudfoundry_config['foo'] = {'credentials': {'foo': 'foo'}} cloudfoundry_config['user-provided'].append({ 'name': 'bar', 'credentials': {'bar': 'bar'} }) set_config_env_vars(cloudfoundry_config) assert 'foo' not in os.environ assert 'bar' not in os.environ
Disable echo of sql alchemy
import sqlalchemy as sa engine = None metadata = None task_table = None metadata_table = None def setup_db(db_url): global engine, metadata engine = sa.create_engine(db_url, echo=False) metadata = sa.MetaData(engine) make_task_table() metadata.create_all(engine) def make_task_table(): global task_table, metadata_table task_table = sa.Table('datastorer_tasks', metadata, sa.Column('job_id', sa.UnicodeText, primary_key=True), sa.Column('job_type', sa.UnicodeText), sa.Column('status', sa.UnicodeText, index=True), sa.Column('data', sa.UnicodeText), sa.Column('error', sa.UnicodeText), sa.Column('requested_timestamp', sa.DateTime), sa.Column('finished_timestamp', sa.DateTime), sa.Column('sent_data', sa.UnicodeText), sa.Column('result_url', sa.UnicodeText), sa.Column('api_key', sa.UnicodeText), ) metadata_table = sa.Table('metadata', metadata, sa.Column('job_id', sa.UnicodeText, primary_key=True), sa.Column('key', sa.UnicodeText, primary_key=True), sa.Column('value', sa.UnicodeText, index=True), sa.Column('type', sa.UnicodeText), )
import sqlalchemy as sa engine = None metadata = None task_table = None metadata_table = None def setup_db(db_url): global engine, metadata engine = sa.create_engine(db_url, echo=True) metadata = sa.MetaData(engine) make_task_table() metadata.create_all(engine) def make_task_table(): global task_table, metadata_table task_table = sa.Table('datastorer_tasks', metadata, sa.Column('job_id', sa.UnicodeText, primary_key=True), sa.Column('job_type', sa.UnicodeText), sa.Column('status', sa.UnicodeText, index=True), sa.Column('data', sa.UnicodeText), sa.Column('error', sa.UnicodeText), sa.Column('requested_timestamp', sa.DateTime), sa.Column('finished_timestamp', sa.DateTime), sa.Column('sent_data', sa.UnicodeText), sa.Column('result_url', sa.UnicodeText), sa.Column('api_key', sa.UnicodeText), ) metadata_table = sa.Table('metadata', metadata, sa.Column('job_id', sa.UnicodeText, primary_key=True), sa.Column('key', sa.UnicodeText, primary_key=True), sa.Column('value', sa.UnicodeText, index=True), sa.Column('type', sa.UnicodeText), )
Fix error when showing content app in media section
(function () { 'use strict'; function RelatedLinksAppController($scope) { var vm = this; vm.relations = $scope.model.viewModel; var currentVariant = _.find($scope.content.variants, function (v) { return v.active }); if (currentVariant && currentVariant.language) { vm.culture = currentVariant.language.culture; vm.cultureRelations = _.filter(vm.relations, function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() }); } else { vm.cultureRelations = vm.relations; } vm.ungrouped = []; for (var i = 0; i < vm.cultureRelations.length; i++) { var relation = vm.cultureRelations[i]; for (var j = 0; j < relation.Properties.length; j++) { vm.ungrouped.push({ id: relation.Id, name: relation.Name, propertyname: relation.Properties[j].PropertyName, tabname: relation.Properties[j].TabName, published: relation.IsPublished, trashed: relation.IsTrashed }); } } } angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController', [ '$scope', 'editorState', 'localizationService', RelatedLinksAppController ]); })();
(function () { 'use strict'; function RelatedLinksAppController($scope) { var vm = this; vm.relations = $scope.model.viewModel; var currentVariant = _.find($scope.content.variants, function (v) { return v.active }); if (currentVariant.language) { vm.culture = currentVariant.language.culture; vm.cultureRelations = _.filter(vm.relations, function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() }); } else { vm.cultureRelations = vm.relations; } vm.ungrouped = []; for (var i = 0; i < vm.cultureRelations.length; i++) { var relation = vm.cultureRelations[i]; for (var j = 0; j < relation.Properties.length; j++) { vm.ungrouped.push({ id: relation.Id, name: relation.Name, propertyname: relation.Properties[j].PropertyName, tabname: relation.Properties[j].TabName, published: relation.IsPublished, trashed: relation.IsTrashed }); } } } angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController', [ '$scope', 'editorState', 'localizationService', RelatedLinksAppController ]); })();
Add compare function to lang Field
<?php namespace Splash\Tests\Tools\Fields; /** * @abstract Language Field : ISO Language Code * * @example en_US, fr_FR, fr_BE * * @see ISO 639-1 : http://www.iso.org/iso/language_codes */ class Oolang extends Oovarchar { //============================================================================== // Structural Data //============================================================================== const FORMAT = 'Lang'; //============================================================================== // DATA VALIDATION //============================================================================== /** * Verify given Raw Data is Valid * * @param string $Data * * @return bool True if OK, Error String if KO */ public static function validate($Data) { if (!empty($Data) && !is_string($Data)) { return "Field Data is not a String."; } return true; } //============================================================================== // FAKE DATA GENERATOR //============================================================================== /** * Generate Fake Raw Field Data for Debugger Simulations * * @return mixed */ public static function fake($Settings) { //============================================================================== // Use Formater Settings if (!empty($Settings["Langs"])) { //============================================================================== // Select Random Language $index = rand(0, count($Settings["Langs"]) -1); //============================================================================== // Return Language Code return $Settings["Langs"][$index]; } //============================================================================== // Return Language Code return (mt_rand()%2)?"en_US":"fr_FR"; } }
<?php namespace Splash\Tests\Tools\Fields; /** * @abstract Language Field : ISO Language Code * * @example en_US, fr_FR, fr_BE * * @see ISO 639-1 : http://www.iso.org/iso/language_codes */ class Oolang { //============================================================================== // Structural Data //============================================================================== const FORMAT = 'Lang'; //============================================================================== // DATA VALIDATION //============================================================================== /** * Verify given Raw Data is Valid * * @param string $Data * * @return bool True if OK, Error String if KO */ public static function validate($Data) { if (!empty($Data) && !is_string($Data)) { return "Field Data is not a String."; } return true; } //============================================================================== // FAKE DATA GENERATOR //============================================================================== /** * Generate Fake Raw Field Data for Debugger Simulations * * @return mixed */ public static function fake($Settings) { //============================================================================== // Use Formater Settings if (!empty($Settings["Langs"])) { //============================================================================== // Select Random Language $index = rand(0, count($Settings["Langs"]) -1); //============================================================================== // Return Language Code return $Settings["Langs"][$index]; } //============================================================================== // Return Language Code return (mt_rand()%2)?"en_US":"fr_FR"; } }
Validate data, and use a different password creation method
<?php namespace Korobi\WebBundle\Security; use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface; use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider; use Symfony\Component\Security\Core\User\UserInterface; class UserProvider extends FOSUBUserProvider { public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $username = $response->getUsername(); $user = $this->userManager->findUserBy([$this->getProperty($response) => $username]); // no existing user, create one from response data if ($user == null) { /** @var $user \Korobi\WebBundle\Entity\User */ $user = $this->userManager->createUser(); $user->setGithubUserId($username); $user->setUsername($response->getNickname()); $user->setEmail($response->getEmail() ?: $response->getNickname() . '@users.noreply.github.com'); $user->setPlainPassword(hash('sha512', $username . '__meow')); $user->setEnabled(true); $this->userManager->updateUser($user); return $user; } /** @var $user \Korobi\WebBundle\Entity\User */ $user = parent::loadUserByOAuthUserResponse($response); return $user; } public function connect(UserInterface $user, UserResponseInterface $response) { parent::connect($user, $response); } }
<?php namespace Korobi\WebBundle\Security; use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface; use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider; use Symfony\Component\Security\Core\User\UserInterface; class UserProvider extends FOSUBUserProvider { public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $username = $response->getUsername(); $user = $this->userManager->findUserBy([$this->getProperty($response) => $username]); if ($user == null) { /** @var $user \Korobi\WebBundle\Entity\User */ $user = $this->userManager->createUser(); $user->setGithubUserId($username); $user->setUsername($response->getNickname()); $user->setEmail($response->getEmail()); $user->setPlainPassword($username . '__meow'); $user->setEnabled(true); $this->userManager->updateUser($user); return $user; } /** @var $user \Korobi\WebBundle\Entity\User */ $user = parent::loadUserByOAuthUserResponse($response); $user->setGithubUserId($username); return $user; } public function connect(UserInterface $user, UserResponseInterface $response) { parent::connect($user, $response); } }
Add image url to item model.
package com.uwetrottmann.shopr.algorithm.model; import java.math.BigDecimal; /** * Represents a item (e.g. clothing item), or one case in the case-base. */ public class Item { private int id; private String name; private BigDecimal price; private String image_url; private int shop_id; private Attributes attrs; private double querySimilarity; private double quality; public int id() { return id; } public Item id(int id) { this.id = id; return this; } public String name() { return name; } public Item name(String name) { this.name = name; return this; } public BigDecimal price() { return price; } public Item price(BigDecimal price) { this.price = price; return this; } public String image() { return image_url; } public Item image(String image_url) { this.image_url = image_url; return this; } public int shopId() { return shop_id; } public Item shopId(int shop_id) { this.shop_id = shop_id; return this; } public Attributes attributes() { return attrs; } public Item attributes(Attributes attrs) { this.attrs = attrs; return this; } public double querySimilarity() { return querySimilarity; } public Item querySimilarity(double querySimilarity) { this.querySimilarity = querySimilarity; return this; } public double quality() { return quality; } public Item quality(double quality) { this.quality = quality; return this; } }
package com.uwetrottmann.shopr.algorithm.model; import java.math.BigDecimal; /** * Represents a item (e.g. clothing item), or one case in the case-base. */ public class Item { private int id; private String name; private BigDecimal price; private int shop_id; private Attributes attrs; private double querySimilarity; private double quality; public int id() { return id; } public Item id(int id) { this.id = id; return this; } public String name() { return name; } public Item name(String name) { this.name = name; return this; } public BigDecimal price() { return price; } public Item price(BigDecimal price) { this.price = price; return this; } public int shopId() { return shop_id; } public Item shopId(int shop_id) { this.shop_id = shop_id; return this; } public Attributes attributes() { return attrs; } public Item attributes(Attributes attrs) { this.attrs = attrs; return this; } public double querySimilarity() { return querySimilarity; } public Item querySimilarity(double querySimilarity) { this.querySimilarity = querySimilarity; return this; } public double quality() { return quality; } public Item quality(double quality) { this.quality = quality; return this; } }
Stop disabling update button while updating
import React from 'react'; import { formatRelative } from 'date-fns'; import './Projects.css'; const Projects = ({ projects, toggle, update }) => { return ( <ul className="ToggleProjects__list list-unstyled" > {projects.map(project => ( <li key={project.id} className="ToggleProjects__project" > <label className="ToggleProjects__label"> <input checked={project.selected} className="ToggleProjects__checkbox" type="checkbox" onChange={toggle.bind(this, project.id)} /> {project.company} &mdash; {project.name} <small><a href={process.env.REACT_APP_CONNECTWISE_SERVER_URL + "/services/system_io/router/openrecord.rails?recordType=ProjectHeaderFV&recid=" + project.id} target="_blank" rel="noopener">(ID: {project.id})</a></small> <button className="btn-link btn-sm" onClick={update.bind(this, project.id)} type="button" > {!project.updating ? 'Update Tickets' : 'Updating Tickets...'} </button> {project.lastUpdated ? ( <span className="ToggleProjects__updated">Updated {formatRelative(project.lastUpdated, new Date())}</span> ) : null} </label> </li> ))} </ul> ); }; export default Projects;
import React from 'react'; import { formatRelative } from 'date-fns'; import './Projects.css'; const Projects = ({ projects, toggle, update }) => { return ( <ul className="ToggleProjects__list list-unstyled" > {projects.map(project => ( <li key={project.id} className="ToggleProjects__project" > <label className="ToggleProjects__label"> <input checked={project.selected} className="ToggleProjects__checkbox" type="checkbox" onChange={toggle.bind(this, project.id)} /> {project.company} &mdash; {project.name} <small><a href={process.env.REACT_APP_CONNECTWISE_SERVER_URL + "/services/system_io/router/openrecord.rails?recordType=ProjectHeaderFV&recid=" + project.id} target="_blank" rel="noopener">(ID: {project.id})</a></small> <button className="btn-link btn-sm" onClick={update.bind(this, project.id)} type="button" disabled={project.updating} > {!project.updating ? 'Update Tickets' : 'Updating Tickets...'} </button> {project.lastUpdated ? ( <span className="ToggleProjects__updated">Updated {formatRelative(project.lastUpdated, new Date())}</span> ) : null} </label> </li> ))} </ul> ); }; export default Projects;
Copy built package to QA Folder
module.exports = function(grunt) { grunt.initConfig({ copyPackageTo: "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package", movePackageTo: process.env["JOB_NAME"] ? "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package" : "build", jobName: process.env["JOB_NAME"] || "local", buildNumber: process.env["BUILD_NUMBER"] || "non-ci", destinationFolder: process.env["JOB_NAME"] ? "<%= movePackageTo %>\\<%= jobName %>\\<%= grunt.template.today('yyyy-mm-dd') %> #<%= buildNumber %>" : "<%= movePackageTo %>", compress: { main: { options: { archive: "<%= destinationFolder %>\\Telerik AppBuilder.zip" }, files: [ { src: ["**/*.{py,pyd,so}", "*.{sublime-keymap,sublime-menu,sublime-settings}", "LICENSE"] } ] } }, copy: { package_to_qa_drop_folder: { src: "*.zip", dest: "<%= copyPackageTo %>/<%= jobName %>/Telerik AppBuilder.zip" } }, clean: { src: ["**/*.pyc"] } }); grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.registerTask("default", "compress:main"); }
module.exports = function(grunt) { grunt.initConfig({ movePackageTo: process.env["JOB_NAME"] ? "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package" : "build", jobName: process.env["JOB_NAME"] || "local", buildNumber: process.env["BUILD_NUMBER"] || "non-ci", destinationFolder: process.env["JOB_NAME"] ? "<%= movePackageTo %>\\<%= jobName %>\\<%= grunt.template.today('yyyy-mm-dd') %> #<%= buildNumber %>" : "<%= movePackageTo %>", compress: { main: { options: { archive: "<%= destinationFolder %>\\Telerik AppBuilder.zip" }, files: [ { src: ["**/*.{py,pyd,so}", "*.{sublime-keymap,sublime-menu,sublime-settings}", "LICENSE"] } ] } }, clean: { src: ["**/*.pyc"] } }); grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.registerTask("default", "compress:main"); }
Set middleware function to be definable
'use strict'; module.exports = function(gulp, $, config, _) { var proxyTarget = _.get(config, 'proxy.url', config.consts.proxy.url); var proxyPrefixes = _.get(config, 'proxy.prefixes', config.consts.proxy.prefixes); var proxy = $.httpProxy.createProxyServer({ target: proxyTarget }); function isProxiedPrefix(url) { return _.some(proxyPrefixes, function (expression) { return expression.test(url); }); } function proxyMiddleware(req, res, next) { if (isProxiedPrefix(req.url)) { proxy.web(req, res, function (err) { next(err); }); } else { next(); } } function server(filesToWatch, filesToServe) { return $.browserSync({ files: filesToWatch, notify: false, server: { baseDir: filesToServe, middleware: config.consts.browserSync.middleware || proxyMiddlewares } }); } gulp.task('serve', function () { return server([ config.paths.app.base, config.paths.build.tmp.base, ], _.union([ config.paths.build.tmp.base, config.paths.base ], config.paths.app.base)); }); gulp.task('serve:dist', ['build'], function () { return server(config.paths.build.dist.base, config.paths.build.dist.base); }); };
'use strict'; module.exports = function(gulp, $, config, _) { var proxyTarget = _.get(config, 'proxy.url', config.consts.proxy.url); var proxyPrefixes = _.get(config, 'proxy.prefixes', config.consts.proxy.prefixes); var proxy = $.httpProxy.createProxyServer({ target: proxyTarget }); function isProxiedPrefix(url) { return _.some(proxyPrefixes, function (expression) { return expression.test(url); }); } function proxyMiddleware(req, res, next) { if (isProxiedPrefix(req.url)) { proxy.web(req, res, function (err) { next(err); }); } else { next(); } } function server(filesToWatch, filesToServe) { return $.browserSync({ files: filesToWatch, notify: false, server: { baseDir: filesToServe, middleware: proxyMiddleware } }); } gulp.task('serve', function () { return server([ config.paths.app.base, config.paths.build.tmp.base, ], _.union([ config.paths.build.tmp.base, config.paths.base ], config.paths.app.base)); }); gulp.task('serve:dist', ['build'], function () { return server(config.paths.build.dist.base, config.paths.build.dist.base); }); };
Make array lib that much more awesome
<?php namespace Lib; class Arr { public static function set(string $key, $value, array $container = []): array { list($keys, $valueKey) = static::breakKey($key); $end = &static::seekEnd($keys, $container); $end[$valueKey] = $value; return $container; } private static function breakKey(string $key): array { $keys = explode('.', $key); $valueKey = array_pop($keys); return [$keys, $valueKey]; } private static function &seekEnd(array $keys = [], array &$container = []) { $currentDepth = &$container; foreach ($keys as $key) { if (!is_array($currentDepth[$key] ?? null)) { $currentDepth[$key] = []; $currentDepth = &$currentDepth[$key]; } } return $currentDepth; } public static function append(string $key, $value, array $container = []): array { list($keys, $valueKey) = static::breakKey($key); $end = &static::seekEnd($keys, $container); if (is_array($end[$valueKey] ?? null)) { $end[$valueKey][] = $value; } else { $end[$valueKey] = [$value]; } return $container; } }
<?php namespace Lib; class Arr { public static function set(string $key, $value, array $container = []): array { $keys = explode('.', $key); $valueKey = array_pop($keys); return static::delve(function (array &$end, array &$container) use ($valueKey, $value) { $end[$valueKey] = $value; return $container; }, $keys, $container); } private static function delve(callable $cb, array $keys = [], array $container = []) { $currentDepth = &$container; foreach ($keys as $key) { if (!is_array($currentDepth[$key] ?? null)) { $currentDepth[$key] = []; $currentDepth = &$currentDepth[$key]; } } return $cb($currentDepth, $container); } public static function append(string $key, $value, array $container = []): array { $keys = explode('.', $key); $valueKey = array_pop($keys); return static::delve(function (&$end, &$container) use ($valueKey, $value) { if (is_array($end[$valueKey] ?? null)) { $end[$valueKey][] = $value; } else { $end[$valueKey] = [$value]; } return $container; }, $keys, $container); } }
Update setup to include new scripts
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License # setup for fsurfer-libs from distutils.core import setup setup(name='fsurfer-libs', version='PKG_VERSION', description='Python module to help create freesurfer workflows', author='Suchandra Thapa', author_email='[email protected]', url='https://github.com/OSGConnect/freesurfer_workflow', packages=['fsurfer'], data_files=[('/usr/share/fsurfer/scripts', ["bash/autorecon1.sh", "bash/autorecon2.sh", "bash/autorecon2-whole.sh", "bash/autorecon3.sh", "bash/autorecon1-options.sh", "bash/autorecon2-options.sh", "bash/autorecon3-options.sh", "bash/autorecon-all.sh", "bash/freesurfer-process.sh"])], license='Apache 2.0')
#!/usr/bin/env python # Copyright 2015 University of Chicago # Available under Apache 2.0 License # setup for fsurfer-libs from distutils.core import setup setup(name='fsurfer-libs', version='PKG_VERSION', description='Python module to help create freesurfer workflows', author='Suchandra Thapa', author_email='[email protected]', url='https://github.com/OSGConnect/freesurfer_workflow', packages=['fsurfer'], data_files=[('/usr/share/fsurfer/scripts', ["bash/autorecon1.sh", "bash/autorecon2.sh", "bash/autorecon2-whole.sh", "bash/autorecon3.sh", "bash/autorecon-all.sh", "bash/freesurfer-process.sh"])], license='Apache 2.0')
Add the missing return statement Simply return the 'X-RateLimit-Remaining' as expected.
<?php namespace Github\HttpClient\Message; use Guzzle\Http\Message\Response; use Github\Exception\ApiLimitExceedException; class ResponseMediator { public static function getContent(Response $response) { $body = $response->getBody(true); $content = json_decode($body, true); if (JSON_ERROR_NONE !== json_last_error()) { return $body; } return $content; } public static function getPagination(Response $response) { $header = $response->getHeader('Link'); if (empty($header)) { return null; } $pagination = array(); foreach (explode(',', $header) as $link) { preg_match('/<(.*)>; rel="(.*)"/i', trim($link, ','), $match); if (3 === count($match)) { $pagination[$match[2]] = $match[1]; } } return $pagination; } public static function getApiLimit(Response $response) { $remainingCalls = $response->getHeader('X-RateLimit-Remaining'); if (null !== $remainingCalls && 1 > $remainingCalls) { throw new ApiLimitExceedException($remainingCalls); } return $remainingCalls; } }
<?php namespace Github\HttpClient\Message; use Guzzle\Http\Message\Response; use Github\Exception\ApiLimitExceedException; class ResponseMediator { public static function getContent(Response $response) { $body = $response->getBody(true); $content = json_decode($body, true); if (JSON_ERROR_NONE !== json_last_error()) { return $body; } return $content; } public static function getPagination(Response $response) { $header = $response->getHeader('Link'); if (empty($header)) { return null; } $pagination = array(); foreach (explode(',', $header) as $link) { preg_match('/<(.*)>; rel="(.*)"/i', trim($link, ','), $match); if (3 === count($match)) { $pagination[$match[2]] = $match[1]; } } return $pagination; } public static function getApiLimit(Response $response) { $remainingCalls = $response->getHeader('X-RateLimit-Remaining'); if (null !== $remainingCalls && 1 > $remainingCalls) { throw new ApiLimitExceedException($remainingCalls); } } }
Make maximum number of words a parameter
import os from operator import itemgetter from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() def popular_words(max_entries=20, max_words=25): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] try: # Generate tag cloud from content of returned entries words = {} for entry in sqs[:max_entries]: text = entry.object.content for x in text.lower().split(): cleanx = x.replace(',', '').replace('.', '').replace('"', '').strip() if cleanx not in STOP_WORDS: # and not cleanx in hansard_words: words[cleanx] = 1 + words.get(cleanx, 0) for word in words: cloudlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:max_words] except: sortedlist = [] return sortedlist
import os from operator import itemgetter from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() def popular_words(max_entries=20): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] try: # Generate tag cloud from content of returned entries words = {} for entry in sqs[:max_entries]: text = entry.object.content for x in text.lower().split(): cleanx = x.replace(',', '').replace('.', '').replace('"', '').strip() if cleanx not in STOP_WORDS: # and not cleanx in hansard_words: words[cleanx] = 1 + words.get(cleanx, 0) for word in words: cloudlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:25] except: sortedlist = [] return sortedlist
Test failed because these was no expected-output file, but always printed to stdout. Repaired by not printing at all except in verbose mode. Made the test about 6x faster -- envelope analysis showed it took time proportional to the square of the # of tasks. Now it's linear.
# Very rudimentary test of threading module # Create a bunch of threads, let each do some work, wait until all are done from test_support import verbose import random import threading import time # This takes about n/3 seconds to run (about n/3 clumps of tasks, times # about 1 second per clump). numtasks = 10 # no more than 3 of the 10 can run at once sema = threading.BoundedSemaphore(value=3) mutex = threading.RLock() running = 0 class TestThread(threading.Thread): def run(self): global running delay = random.random() * 2 if verbose: print 'task', self.getName(), 'will run for', delay, 'sec' sema.acquire() mutex.acquire() running = running + 1 if verbose: print running, 'tasks are running' mutex.release() time.sleep(delay) if verbose: print 'task', self.getName(), 'done' mutex.acquire() running = running - 1 if verbose: print self.getName(), 'is finished.', running, 'tasks are running' mutex.release() sema.release() threads = [] def starttasks(): for i in range(numtasks): t = TestThread(name="<thread %d>"%i) threads.append(t) t.start() starttasks() if verbose: print 'waiting for all tasks to complete' for t in threads: t.join() if verbose: print 'all tasks done'
# Very rudimentary test of threading module # Create a bunch of threads, let each do some work, wait until all are done from test_support import verbose import random import threading import time numtasks = 10 # no more than 3 of the 10 can run at once sema = threading.BoundedSemaphore(value=3) mutex = threading.RLock() running = 0 class TestThread(threading.Thread): def run(self): global running delay = random.random() * numtasks if verbose: print 'task', self.getName(), 'will run for', round(delay, 1), 'sec' sema.acquire() mutex.acquire() running = running + 1 if verbose: print running, 'tasks are running' mutex.release() time.sleep(delay) if verbose: print 'task', self.getName(), 'done' mutex.acquire() running = running - 1 if verbose: print self.getName(), 'is finished.', running, 'tasks are running' mutex.release() sema.release() threads = [] def starttasks(): for i in range(numtasks): t = TestThread(name="<thread %d>"%i) threads.append(t) t.start() starttasks() print 'waiting for all tasks to complete' for t in threads: t.join() print 'all tasks done'
Use six.text_type for python3 compat
import decimal import msgpack from dateutil.parser import parse from django.utils.six import text_type from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % text_type(exc))
import decimal import msgpack from dateutil.parser import parse from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % unicode(exc))
Return migrations helper by reference
<?php /* * This file is part of the Active Collab DatabaseMigrations project. * * (c) A51 doo <[email protected]>. All rights reserved. */ namespace ActiveCollab\DatabaseMigrations\Command; use ActiveCollab\DatabaseMigrations\MigrationsInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @package ActiveCollab\DatabaseMigrations\Command */ trait All { /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $migrations = $this->getMigrations()->getMigrations(); if ($migrations_count = count($migrations)) { if ($migrations_count === 1) { $output->writeln('One migration found:'); } else { $output->writeln("{$migrations_count} migrations found:"); } $output->writeln(''); foreach ($migrations as $migration) { $output->writeln(' <comment>*</comment> ' . get_class($migration)); } } else { $output->writeln('No migrations found'); } return 0; } /** * @return MigrationsInterface */ abstract protected function &getMigrations(); }
<?php /* * This file is part of the Active Collab DatabaseMigrations project. * * (c) A51 doo <[email protected]>. All rights reserved. */ namespace ActiveCollab\DatabaseMigrations\Command; use ActiveCollab\DatabaseMigrations\MigrationsInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @package ActiveCollab\DatabaseMigrations\Command */ trait All { /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $migrations = $this->getMigrations()->getMigrations(); if ($migrations_count = count($migrations)) { if ($migrations_count === 1) { $output->writeln('One migration found:'); } else { $output->writeln("{$migrations_count} migrations found:"); } $output->writeln(''); foreach ($migrations as $migration) { $output->writeln(' <comment>*</comment> ' . get_class($migration)); } } else { $output->writeln('No migrations found'); } return 0; } /** * @return MigrationsInterface */ abstract protected function getMigrations(); }
Upgrade to a newer gevent for OSX Yosemity compat See https://github.com/gevent/gevent/issues/656
#!/usr/bin/python from setuptools import setup setup(name="catsnap", version="6.0.0", description="catalog and store images", author="Erin Call", author_email="[email protected]", url="https://github.com/ErinCall/", packages=['catsnap', 'catsnap.document', 'catsnap.config', 'catsnap.batch'], install_requires=[ "Flask==0.9", "gunicorn==0.14.6", "boto==2.5.2", "requests==0.13.2", "argparse==1.2.1", "psycopg2==2.4.6", "sqlalchemy==0.8.0b2", "yoyo-migrations==4.1.6", "wand==0.3.3", "celery==3.1.16", "redis==2.10.3", "gevent==1.1b5", "Flask-Sockets==0.1", "PyYAML==3.11", "mock==1.0.1", "nose==1.1.2", "splinter==0.5.3", "bcrypt==1.1.1", ], )
#!/usr/bin/python from setuptools import setup setup(name="catsnap", version="6.0.0", description="catalog and store images", author="Erin Call", author_email="[email protected]", url="https://github.com/ErinCall/", packages=['catsnap', 'catsnap.document', 'catsnap.config', 'catsnap.batch'], install_requires=[ "Flask==0.9", "gunicorn==0.14.6", "boto==2.5.2", "requests==0.13.2", "argparse==1.2.1", "psycopg2==2.4.6", "sqlalchemy==0.8.0b2", "yoyo-migrations==4.1.6", "wand==0.3.3", "celery==3.1.16", "redis==2.10.3", "gevent==1.0.2", "Flask-Sockets==0.1", "PyYAML==3.11", "mock==1.0.1", "nose==1.1.2", "splinter==0.5.3", "bcrypt==1.1.1", ], )
Fix forgotten ionic beta.2 changes
module.exports = { proxies: null, paths: { html : { src: ['app/**/*.html'], dest: "www/build" }, sass: { src: ['app/theme/app.+(ios|md).scss'], dest: 'www/build/css', include: [ 'node_modules/ionic-angular', 'node_modules/ionicons/dist/scss' ] }, fonts: { src: ['node_modules/ionic-angular/fonts/**/*.+(ttf|woff|woff2)'], dest: "www/build/fonts" }, watch: { sass: ['app/**/*.scss'], html: ['app/**/*.html'], livereload: [ 'www/build/**/*.html', 'www/build/**/*.js', 'www/build/**/*.css' ] } }, autoPrefixerOptions: { browsers: [ 'last 2 versions', 'iOS >= 7', 'Android >= 4', 'Explorer >= 10', 'ExplorerMobile >= 11' ], cascade: false }, // hooks execute before or after all project-related Ionic commands // (so not for start, docs, but serve, run, etc.) and take in the arguments // passed to the command as a parameter // // The format is 'before' or 'after' + commandName (uppercased) // ex: beforeServe, afterRun, beforePrepare, etc. hooks: { beforeServe: function(argv) { //console.log('beforeServe'); } } };
module.exports = { proxies: null, paths: { html : { src: ['app/**/*.html'], dest: "www/build" }, sass: { src: ['app/theme/app.+(ios|md).scss'], dest: 'www/build/css', include: [ 'node_modules/ionic-framework', 'node_modules/ionicons/dist/scss' ] }, fonts: { src: ['node_modules/ionic-framework/fonts/**/*.+(ttf|woff|woff2)'], dest: "www/build/fonts" }, watch: { sass: ['app/**/*.scss'], html: ['app/**/*.html'], livereload: [ 'www/build/**/*.html', 'www/build/**/*.js', 'www/build/**/*.css' ] } }, autoPrefixerOptions: { browsers: [ 'last 2 versions', 'iOS >= 7', 'Android >= 4', 'Explorer >= 10', 'ExplorerMobile >= 11' ], cascade: false }, // hooks execute before or after all project-related Ionic commands // (so not for start, docs, but serve, run, etc.) and take in the arguments // passed to the command as a parameter // // The format is 'before' or 'after' + commandName (uppercased) // ex: beforeServe, afterRun, beforePrepare, etc. hooks: { beforeServe: function(argv) { //console.log('beforeServe'); } } };
Use new scheme for npmcdn
var loaders = [ { test: /\.json$/, loader: "json-loader" }, ]; module.exports = [ {// Notebook extension entry: './src/extension.js', output: { filename: 'extension.js', path: '../pythreejs/static', libraryTarget: 'amd' } }, {// bqplot bundle for the notebook entry: './src/index.js', output: { filename: 'index.js', path: '../pythreejs/static', libraryTarget: 'amd' }, devtool: 'source-map', module: { loaders: loaders }, externals: ['jupyter-js-widgets'] }, {// embeddable bqplot bundle entry: './src/index.js', output: { filename: 'index.js', path: './dist/', libraryTarget: 'amd' }, devtool: 'source-map', module: { loaders: loaders }, externals: ['jupyter-js-widgets'] } ];
var loaders = [ { test: /\.json$/, loader: "json-loader" }, ]; module.exports = [ {// Notebook extension entry: './src/extension.js', output: { filename: 'extension.js', path: '../pythreejs/static', libraryTarget: 'amd' } }, {// bqplot bundle for the notebook entry: './src/index.js', output: { filename: 'index.js', path: '../pythreejs/static', libraryTarget: 'amd' }, devtool: 'source-map', module: { loaders: loaders }, externals: ['jupyter-js-widgets'] }, {// embeddable bqplot bundle entry: './src/index.js', output: { filename: 'embed.js', path: './dist/', libraryTarget: 'amd' }, devtool: 'source-map', module: { loaders: loaders }, externals: ['jupyter-js-widgets'] } ];
Use the correct server for the Hitbox.tv preview image
<?php class HitboxApi { private static $baseUrl = 'https://www.hitbox.tv/api/'; public function getStreamsByGame( $game ){ $channelList = array(); // This is a temporary solution until Hitbox enables filter by game $channels = $this->loadUrl( self::$baseUrl . 'media/live/list?liveonly=yes&showHidden=no&publicOnly=yes' ); foreach( $channels->livestream as $channel ) : if( $channel->category_name !== $game ) : continue; endif; $channelList[] = $this->streamFromData( $channel ); endforeach; return $channelList; } private function streamFromData( $data ){ $stream = new Stream(); $stream->setService( 'hitbox' ); // set quality $quality = json_decode( $data->media_profiles ); if( $quality !== null ) : $quality = end( $quality ); $stream->setQuality( $quality->height ); endif; $stream->setViewers( $data->media_views ); $stream->setPreviewImage( 'http://edge.sf.hitbox.tv' . $data->media_thumbnail_large ); $stream->setStatus( $data->media_status ); $stream->setName( $data->media_name ); $stream->setLink( $data->channel->channel_link ); return $stream; } private function loadUrl( $url ){ $kurl = new Kurl(); return json_decode( $kurl->loadData( $url ) ); } }
<?php class HitboxApi { private static $baseUrl = 'https://www.hitbox.tv/api/'; public function getStreamsByGame( $game ){ $channelList = array(); // This is a temporary solution until Hitbox enables filter by game $channels = $this->loadUrl( self::$baseUrl . 'media/live/list?liveonly=yes&showHidden=no&publicOnly=yes' ); foreach( $channels->livestream as $channel ) : if( $channel->category_name !== $game ) : continue; endif; $channelList[] = $this->streamFromData( $channel ); endforeach; return $channelList; } private function streamFromData( $data ){ $stream = new Stream(); $stream->setService( 'hitbox' ); // set quality $quality = json_decode( $data->media_profiles ); if( $quality !== null ) : $quality = end( $quality ); $stream->setQuality( $quality->height ); endif; $stream->setViewers( $data->media_views ); $stream->setPreviewImage( 'http://hitbox.tv' . $data->media_thumbnail_large ); $stream->setStatus( $data->media_status ); $stream->setName( $data->media_name ); $stream->setLink( $data->channel->channel_link ); return $stream; } private function loadUrl( $url ){ $kurl = new Kurl(); return json_decode( $kurl->loadData( $url ) ); } }
Add list of allowed elements to picture child def
<?php class HTMLPurifier_ChildDef_Picture extends HTMLPurifier_ChildDef { public $type = 'picture'; public $elements = array( 'img' => true, 'source' => true, ); /** * @param array $children * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return array */ public function validateChildren($children, $config, $context) { // if there are no tokens, delete parent node if (empty($children)) { return false; } if (!isset($config->getHTMLDefinition()->info['img'])) { trigger_error("Cannot allow picture without allowing img", E_USER_WARNING); return false; } $allowSource = isset($config->getHTMLDefinition()->info['source']); $hasImg = false; $result = array(); // Content model: // Zero or more source elements, followed by one img element, optionally intermixed with script-supporting elements. // https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element foreach ($children as $node) { if (($allowSource && $node->name === 'source') || $node->name === 'img') { $result[] = $node; } if ($node->name === 'img') { $hasImg = true; break; } } if (!$hasImg || empty($result)) { return false; } return $result; } }
<?php class HTMLPurifier_ChildDef_Picture extends HTMLPurifier_ChildDef { public $type = 'picture'; /** * @param array $children * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return array */ public function validateChildren($children, $config, $context) { // if there are no tokens, delete parent node if (empty($children)) { return false; } if (!isset($config->getHTMLDefinition()->info['img'])) { trigger_error("Cannot allow picture without allowing img", E_USER_WARNING); return false; } $allowSource = isset($config->getHTMLDefinition()->info['source']); $hasImg = false; $result = array(); // Content model: // Zero or more source elements, followed by one img element, optionally intermixed with script-supporting elements. // https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element foreach ($children as $node) { if (($allowSource && $node->name === 'source') || $node->name === 'img') { $result[] = $node; } if ($node->name === 'img') { $hasImg = true; break; } } if (!$hasImg || empty($result)) { return false; } return $result; } }
Throw ForbiddenException on unauthenticated request
<?php namespace AnduFratu\Jwt; \App::uses('BaseAuthenticate', 'Controller/Component/Auth'); class JwtAuthenticate extends \BaseAuthenticate { private $defaultSettings = array( 'param' => 'token', 'key' => 'EMPTY_KEY', ); public function __construct(\ComponentCollection $collection, $settings = array()) { $settings = \Hash::merge( $this->defaultSettings, $settings ); parent::__construct($collection, $settings); } public function authenticate(\CakeRequest $request, \CakeResponse $response) { return false; } public function getUser(\CakeRequest $request) { $token = $this->getToken($request); $user = false; if ($token) { try { $payload = (array) \JWT::decode($token, $this->settings['key']); $username = $this->_findUser($payload['sub']); $user = $this->_findUser($username); } catch (\UnexpectedValueException $e) { $user = false; } } return $user; } public function unauthenticated(\CakeRequest $request, \CakeResponse $response) { throw new \ForbiddenException(); return true; } private function getToken(\CakeRequest $request) { $headers = apache_request_headers(); if (isset($headers['Authorization'])) { $authHeader = $headers['Authorization']; $token = preg_replace('/Bearer (.+)$/', '$1', $authHeader); } else { $token = $request->param($this->settings['param']); } return $token; } }
<?php namespace AnduFratu\Jwt; \App::uses('BaseAuthenticate', 'Controller/Component/Auth'); class JwtAuthenticate extends \BaseAuthenticate { private $defaultSettings = array( 'param' => 'token', 'key' => 'EMPTY_KEY', ); public function __construct(\ComponentCollection $collection, $settings = array()) { $settings = \Hash::merge( $this->defaultSettings, $settings ); parent::__construct($collection, $settings); } public function authenticate(\CakeRequest $request, \CakeResponse $response) { return false; } public function getUser(\CakeRequest $request) { $token = $this->getToken($request); $user = false; if ($token) { try { $payload = (array) \JWT::decode($token, $this->settings['key']); $username = $this->_findUser($payload['sub']); $user = $this->_findUser($username); } catch (\UnexpectedValueException $e) { $user = false; } } return $user; } private function getToken(\CakeRequest $request) { $headers = apache_request_headers(); if (isset($headers['Authorization'])) { $authHeader = $headers['Authorization']; $token = preg_replace('/Bearer (.+)$/', '$1', $authHeader); } else { $token = $request->param($this->settings['param']); } return $token; } }
Return index.html in root and transform /status results
from flask import jsonify from . import app import mapper import utils from predict import predictor @app.route("/", methods=["GET"]) def index(): return app.send_static_file("index.html") @app.route("/build", methods=["POST"]) def build_model(): predictor.preprocess_airports() if not predictor.model: predictor.build_model() return jsonify({"message:" : "OK"}) @app.route("/predict", methods=["GET"]) def predict_all_delays(): results = None try: results = predictor.predict_all() except Exception as e: print "ERROR", e.message return jsonify({"message" : e.message}) return jsonify(results) @app.route("/predict/<airport_code>", methods=["GET"]) def predict_delay(airport_code): firebase_source = mapper.get_source_firebase() airport_status = firebase_source.get_airport(airport_code) cleaned_data = utils.get_clean_data(airport_status) res = predictor.predict(airport_code) cleaned_data["prediction"] = bool(res[0]) return jsonify(cleaned_data) @app.route("/status", methods=["GET"]) def get_airport_statuses(): firebase_source = mapper.get_source_firebase() airports = firebase_source.get_all() results = [] for airport_code, status in airports.items(): try: results.append(utils.get_clean_data(status)) except: pass results = {"items":results} return jsonify(results)
from flask import jsonify from . import app import mapper import utils from predict import predictor @app.route("/", methods=["GET"]) def index(): firebase_dump = mapper.get_dump_firebase() response = firebase_dump.get_all() response = response or {} return jsonify(response) @app.route("/build", methods=["POST"]) def build_model(): predictor.preprocess_airports() if not predictor.model: predictor.build_model() return jsonify({"message:" : "OK"}) @app.route("/predict", methods=["GET"]) def predict_all_delays(): results = None try: results = predictor.predict_all() except Exception as e: return jsonify({"message" : e.message}) return jsonify(results) @app.route("/predict/<airport_code>", methods=["GET"]) def predict_delay(airport_code): firebase_source = mapper.get_source_firebase() airport_status = firebase_source.get_airport(airport_code) cleaned_data = utils.get_clean_data(airport_status) res = predictor.predict(airport_code) cleaned_data["prediction"] = bool(res[0]) return jsonify(cleaned_data) @app.route("/status", methods=["GET"]) def get_airport_statuses(): firebase_source = mapper.get_source_firebase() airports = firebase_source.get_all() for airport_code, status in airports.items(): if "status" in status: del status["status"] return jsonify(airports)
Allow WebbitSocket.on{error,close,open} to be hooked up.
function WebbitSocket(path, target) { var self = this; var ws = new WebSocket('ws://' + document.location.host + path); ws.onclose = function() { target.onclose && target.onclose(); self.onclose && self.onclose(); }; ws.onerror = function() { target.onerror && target.onerror(); self.onerror && self.onerror(); }; ws.onmessage = function(e) { target.onmessage && target.onmessage(e); self.onmessage && self.onmessage(e); var msg = JSON.parse(e.data); if (msg.exports) { msg.exports.forEach(function(name) { self[name] = function() { var outgoing = { action: name, args: Array.prototype.slice.call(arguments) }; ws.send(JSON.stringify(outgoing)); }; }) target.onopen && target.onopen(); self.onopen && self.onopen(); } else { var action = target[msg.action]; if (typeof action === 'function') { action.apply(target, msg.args); } else { // TODO: ? } } }; }
function WebbitSocket(path, target) { var self = this; var ws = new WebSocket('ws://' + document.location.host + path); ws.onclose = function() { target.onclose && target.onclose(); }; ws.onmessage = function(e) { var msg = JSON.parse(e.data); if (msg.exports) { msg.exports.forEach(function(name) { self[name] = function() { var outgoing = { action: name, args: Array.prototype.slice.call(arguments) }; ws.send(JSON.stringify(outgoing)); }; }) target.onopen && target.onopen(); } else { var action = target[msg.action]; if (typeof action === 'function') { action.apply(target, msg.args); } else { // TODO: ? } } }; }
Change class definitions from old style to new style
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <[email protected]> """ from __future__ import print_function from __future__ import unicode_literals from pytablewriter._function import convert_idx_to_alphabet import pytest class Test_convert_idx_to_alphabet(object): @pytest.mark.parametrize(["value", "expected"], [ [ range(30), [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", ] ], [ range(0, 900, 30), [ "A", "AE", "BI", "CM", "DQ", "EU", "FY", "HC", "IG", "JK", "KO", "LS", "MW", "OA", "PE", "QI", "RM", "SQ", "TU", "UY", "WC", "XG", "YK", "ZO", "AAS", "ABW", "ADA", "AEE", "AFI", "AGM", ] ], ]) def test_normal(self, value, expected): assert [convert_idx_to_alphabet(v) for v in value] == expected
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <[email protected]> """ from __future__ import print_function from __future__ import unicode_literals from pytablewriter._function import convert_idx_to_alphabet import pytest class Test_convert_idx_to_alphabet: @pytest.mark.parametrize(["value", "expected"], [ [ range(30), [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", ] ], [ range(0, 900, 30), [ "A", "AE", "BI", "CM", "DQ", "EU", "FY", "HC", "IG", "JK", "KO", "LS", "MW", "OA", "PE", "QI", "RM", "SQ", "TU", "UY", "WC", "XG", "YK", "ZO", "AAS", "ABW", "ADA", "AEE", "AFI", "AGM", ] ], ]) def test_normal(self, value, expected): assert [convert_idx_to_alphabet(v) for v in value] == expected
Add correct response code for error 404 not 200 c:
<?php require $_SERVER['DOCUMENT_ROOT'] . '/../backend/outputObject.php'; require $_SERVER['DOCUMENT_ROOT'] . '/../backend/databaseOptions.php'; $id = $_GET['id']; $output = new JsonOutput('v2'); if ($id != '') { // Get dog by its ID $dog = getSpecificDog($id); $dogArray = array($dog); if ($dog->id != $id) { $dogArray = array(); $output = new JsonOutput('v2'); $output->error = 'ID not found'; $output->response_code = 404; } } else { // They want a random dog - check limits $dogArray = array(); // They specified a limit $limitStr = $_GET['limit']; if ($limitStr != '') { $limit = intval($limitStr); // Make sure it's between 20 and 1 if ($limit > 20) { $limit = 20; } else if ($limit < 1) { $limit = 1; } } else { // No limit specified - set default $limit = 1; } // For each i before limit, add to array. for ($i = 1; $i <= $limit; $i++) { $dog = getRandomDog(); array_push($dogArray, $dog); } } $output->fromDogList($dogArray); echo $output->jsonify(); ?>
<?php require $_SERVER['DOCUMENT_ROOT'] . '/../backend/outputObject.php'; require $_SERVER['DOCUMENT_ROOT'] . '/../backend/databaseOptions.php'; $id = $_GET['id']; $output = new JsonOutput('v2'); if ($id != '') { // Get dog by its ID $dog = getSpecificDog($id); $dogArray = array($dog); if ($dog->id != $id) { $dogArray = array(); $output = new JsonOutput('v2'); $output->error = 'ID not found'; } } else { // They want a random dog - check limits $dogArray = array(); // They specified a limit $limitStr = $_GET['limit']; if ($limitStr != '') { $limit = intval($limitStr); // Make sure it's between 20 and 1 if ($limit > 20) { $limit = 20; } else if ($limit < 1) { $limit = 1; } } else { // No limit specified - set default $limit = 1; } // For each i before limit, add to array. for ($i = 1; $i <= $limit; $i++) { $dog = getRandomDog(); array_push($dogArray, $dog); } } $output->fromDogList($dogArray); echo $output->jsonify(); ?>
Print detected content encoding info only if it's actually been detected
import re import requests from bs4 import BeautifulSoup as bs from jfr_playoff.logger import PlayoffLogger class RemoteUrl: url_cache = {} @classmethod def fetch_raw(cls, url): PlayoffLogger.get('remote').info( 'fetching content for: %s', url) if url not in cls.url_cache: request = requests.get(url) encoding_match = re.search( 'content=".*;( )?charset=(.*?)"', request.content, re.IGNORECASE) if encoding_match: PlayoffLogger.get('remote').debug( 'Content encoding: %s', encoding_match.group(2)) request.encoding = encoding_match.group(2) cls.url_cache[url] = request.text PlayoffLogger.get('remote').info( 'fetched %d bytes from remote location', len(cls.url_cache[url])) return cls.url_cache[url] @classmethod def fetch(cls, url): return bs(RemoteUrl.fetch_raw(url), 'lxml') @classmethod def clear_cache(cls): cls.url_cache = {}
import re import requests from bs4 import BeautifulSoup as bs from jfr_playoff.logger import PlayoffLogger class RemoteUrl: url_cache = {} @classmethod def fetch_raw(cls, url): PlayoffLogger.get('remote').info( 'fetching content for: %s', url) if url not in cls.url_cache: request = requests.get(url) encoding_match = re.search( 'content=".*;( )?charset=(.*?)"', request.content, re.IGNORECASE) PlayoffLogger.get('remote').debug( 'Content encoding: %s', encoding_match.group(2)) if encoding_match: request.encoding = encoding_match.group(2) cls.url_cache[url] = request.text PlayoffLogger.get('remote').info( 'fetched %d bytes from remote location', len(cls.url_cache[url])) return cls.url_cache[url] @classmethod def fetch(cls, url): return bs(RemoteUrl.fetch_raw(url), 'lxml') @classmethod def clear_cache(cls): cls.url_cache = {}
Make static js methods actually work.
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.core', name: 'Static', extends: 'foam.core.AbstractMethod', documentation: 'An Axiom for defining static methods.', methods: [ function isStatic() { return true; }, function installInClass(cls) { Object.defineProperty( cls, this.name, { value: this.code, configurable: false }); }, function installInProto(proto) { this.installInClass(proto); } ] }); foam.CLASS({ refines: 'foam.core.Model', properties: [ { class: 'AxiomArray', of: 'Static', name: 'static', adaptArrayElement: function(o) { if ( typeof o === 'function' ) { var name = foam.Function.getName(o); foam.assert(name, 'Static must be named'); return foam.core.Static.create({name: name, code: o}); } return foam.core.Static.isInstance(o) ? o : foam.core.Static.create(o) ; } } ] });
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.core', name: 'Static', extends: 'foam.core.AbstractMethod', documentation: 'An Axiom for defining static methods.', methods: [ function isStatic() { return true; }, function installInClass(cls) { Object.defineProperty( cls, this.name, { value: this.value, configurable: false }); }, function installInProto(proto) { this.installInClass(proto); } ] }); foam.CLASS({ refines: 'foam.core.Model', properties: [ { class: 'AxiomArray', of: 'Static', name: 'static', adaptArrayElement: function(o) { if ( typeof o === 'function' ) { var name = foam.Function.getName(o); foam.assert(name, 'Static must be named'); return foam.core.Static.create({name: name, code: o}); } return foam.core.Static.isInstance(o) ? o : foam.core.Static.create(o) ; } } ] });
Use shared_task instead of task.
from .models import FileImport from .importers import ImportFailure from django.db import transaction import celery assuming_failure_message = '{0} did not return True. Assuming failure.' processing_status = 'processing' processing_description = 'Processing the data in {filename}.' success_status = 'success' success_description = 'The import appears to have completed successfully.' # The description for failures is the contents of the exception message. failure_status = 'failure' @celery.shared_task @transaction.atomic def importer_asynchronous_task(import_pk, *args, **kwargs): logger = importer_asynchronous_task.get_logger() import_instance = FileImport.objects.get(pk=import_pk) ImportType = import_instance.get_related_importer(**kwargs) if ImportType is None: import_instance.status = 30 return False importer = ImportType() import_instance.status = processing_status import_instance.status_description = 'Currently processing file' import_instance.save() import_context = import_instance.get_context() try: if importer.process(import_context, logger) is True: import_instance.status = success_status import_instance.status_description = success_description import_instance.save() else: raise ImportFailure(assuming_failure_message.format( importer.__class__.__name__ )) except ImportFailure, e: import_instance.status = failure_status import_instance.status_description = e.message import_instance.save() return True
from .models import FileImport from .importers import ImportFailure from django.db import transaction import celery assuming_failure_message = '{0} did not return True. Assuming failure.' processing_status = 'processing' processing_description = 'Processing the data in {filename}.' success_status = 'success' success_description = 'The import appears to have completed successfully.' # The description for failures is the contents of the exception message. failure_status = 'failure' @celery.task @transaction.atomic def importer_asynchronous_task(import_pk, *args, **kwargs): logger = importer_asynchronous_task.get_logger() import_instance = FileImport.objects.get(pk=import_pk) ImportType = import_instance.get_related_importer(**kwargs) if ImportType is None: import_instance.status = 30 return False importer = ImportType() import_instance.status = processing_status import_instance.status_description = 'Currently processing file' import_instance.save() import_context = import_instance.get_context() try: if importer.process(import_context, logger) is True: import_instance.status = success_status import_instance.status_description = success_description import_instance.save() else: raise ImportFailure(assuming_failure_message.format( importer.__class__.__name__ )) except ImportFailure, e: import_instance.status = failure_status import_instance.status_description = e.message import_instance.save() return True
Fix query to exclude objects without relevant pages
from django.db.models import OuterRef, Subquery from official_documents.models import OfficialDocument from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand from sopn_parsing.helpers.extract_tables import extract_ballot_table from sopn_parsing.helpers.text_helpers import NoTextInDocumentError class Command(BaseSOPNParsingCommand): help = """ Parse tables out of PDFs in to ParsedSOPN models for later parsing. """ def handle(self, *args, **options): qs = self.get_queryset(options) filter_kwargs = {} if not options["ballot"] and not options["testing"]: if not options["reparse"]: filter_kwargs["officialdocument__parsedsopn"] = None qs = qs.filter(**filter_kwargs) # We can't extract tables when we don't know about the pages # It is possible for an a ballot to have more than one # OfficialDocument so we need to get the latest one to check # that we know which pages to parse tables from latest_sopns = OfficialDocument.objects.filter( ballot=OuterRef("pk") ).order_by("-created") qs = qs.annotate( sopn_relevant_pages=Subquery( latest_sopns.values("relevant_pages")[:1] ) ) qs = qs.exclude(sopn_relevant_pages="") for ballot in qs: try: extract_ballot_table(ballot) except NoTextInDocumentError: self.stdout.write( f"{ballot} raised a NoTextInDocumentError trying to extract tables" ) except ValueError: self.stdout.write( f"{ballot} raised a ValueError trying extract tables" )
from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand from sopn_parsing.helpers.extract_tables import extract_ballot_table from sopn_parsing.helpers.text_helpers import NoTextInDocumentError class Command(BaseSOPNParsingCommand): help = """ Parse tables out of PDFs in to ParsedSOPN models for later parsing. """ def handle(self, *args, **options): qs = self.get_queryset(options) filter_kwargs = {} if not options["ballot"] and not options["testing"]: if not options["reparse"]: filter_kwargs["officialdocument__parsedsopn"] = None qs = qs.filter(**filter_kwargs) # We can't extract tables when we don't know about the pages qs = qs.exclude(officialdocument__relevant_pages="") for ballot in qs: try: extract_ballot_table(ballot) except NoTextInDocumentError: self.stdout.write( f"{ballot} raised a NoTextInDocumentError trying to extract tables" ) except ValueError: self.stdout.write( f"{ballot} raised a ValueError trying extract tables" )
Send application/json instead of urlencoded for webhooks
<?php namespace CodeDay\Clear\Models\Application; use Illuminate\Database\Eloquent; class Webhook extends \Eloquent { protected $table = 'applications_webhooks'; public function application() { return $this->belongsTo('\CodeDay\Clear\Models\Application', 'application_id', 'public'); } public function Execute($data) { $opts = ['http' => ['method' => 'POST']]; $body = []; $body['data'] = $data; $body['private'] = $this->application->private; $body['event'] = $this->event; $opts['http']['header'] = 'Content-type: application/json'; $opts['http']['content'] = json_encode($body); $url = $this->url; try { \Queue::push(function ($job) use ($opts, $url) { $context = stream_context_create($opts); @file_get_contents($url, false, $context); $job->delete(); }); } catch (\Exception $ex) {} } public static function Fire($event, $data) { $all_hooks = self::where('event', '=', $event)->get(); foreach ($all_hooks as $hook) { $hook->Execute($data); } } protected static function boot() { parent::boot(); static::creating(function ($model) { $model->id = str_random(16); }); } }
<?php namespace CodeDay\Clear\Models\Application; use Illuminate\Database\Eloquent; class Webhook extends \Eloquent { protected $table = 'applications_webhooks'; public function application() { return $this->belongsTo('\CodeDay\Clear\Models\Application', 'application_id', 'public'); } public function Execute($data) { $opts = ['http' => ['method' => 'POST']]; $body = []; $body['data'] = $data; $body['private'] = $this->application->private; $body['event'] = $this->event; $opts['http']['header'] = 'Content-type: application/x-www-form-urlencoded'; $opts['http']['content'] = http_build_query($body); $url = $this->url; try { \Queue::push(function ($job) use ($opts, $url) { $context = stream_context_create($opts); @file_get_contents($url, false, $context); $job->delete(); }); } catch (\Exception $ex) {} } public static function Fire($event, $data) { $all_hooks = self::where('event', '=', $event)->get(); foreach ($all_hooks as $hook) { $hook->Execute($data); } } protected static function boot() { parent::boot(); static::creating(function ($model) { $model->id = str_random(16); }); } }
Remove defaultSource for shot image
'use strict'; var React = require('react-native'); var { Image, PixelRatio, StyleSheet, Text, TouchableHighlight, View } = React; var getImage = require('./helpers/getImage'), screen = require('Dimensions').get('window'); var ShotCell = React.createClass({ render: function() { return ( <View> <TouchableHighlight onPress={this.props.onSelect}> <View style={styles.row}> <Image source={getImage.shotImage(this.props.shot)} resizeMode="cover" style={styles.cellImage} accessible={true} /> </View> </TouchableHighlight> <View style={styles.cellBorder} /> </View> ); } }); var styles = StyleSheet.create({ textContainer: { flex: 1, }, row: { backgroundColor: 'white', flexDirection: 'column' }, cellImage: { backgroundColor: 'transparent', height: 300, width: screen.width }, cellBorder: { backgroundColor: 'rgba(0, 0, 0, 0.2)', // Trick to get the thinest line the device can display height: 1 / PixelRatio.get(), marginLeft: 4, }, }); module.exports = ShotCell;
'use strict'; var React = require('react-native'); var { Image, PixelRatio, StyleSheet, Text, TouchableHighlight, View } = React; var getImage = require('./helpers/getImage'), screen = require('Dimensions').get('window'); var ShotCell = React.createClass({ render: function() { return ( <View> <TouchableHighlight onPress={this.props.onSelect}> <View style={styles.row}> <Image source={getImage.shotImage(this.props.shot)} defaultSource={require('image!AuthorAvatar')} resizeMode="cover" style={styles.cellImage} accessible={true} /> </View> </TouchableHighlight> <View style={styles.cellBorder} /> </View> ); } }); var styles = StyleSheet.create({ textContainer: { flex: 1, }, row: { backgroundColor: 'white', flexDirection: 'column' }, cellImage: { backgroundColor: 'transparent', height: 300, width: screen.width }, cellBorder: { backgroundColor: 'rgba(0, 0, 0, 0.2)', // Trick to get the thinest line the device can display height: 1 / PixelRatio.get(), marginLeft: 4, }, }); module.exports = ShotCell;
Fix unicode support in ExecEngine
import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwargs) return instance.process(asset) engine.engine_class = cls engine.result_mimetype = cls.result_mimetype return engine def process(self, asset): raise NotImplementedError() class ExecEngine(BaseEngine): executable = None params = [] def __init__(self, executable=None): if executable is not None: self.executable = executable def process(self, asset): self.asset = asset p = subprocess.Popen( args=self.get_args(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = p.communicate(input=asset.processed_source.encode('utf-8')) if p.returncode != 0: raise EngineProcessFailed(errors) asset.processed_source = output.decode('utf-8') def get_args(self): return [self.executable] + self.params
import subprocess from functools import wraps class EngineProcessFailed(Exception): pass class BaseEngine(object): result_mimetype = None @classmethod def as_engine(cls, **initkwargs): @wraps(cls, updated=()) def engine(asset): instance = engine.engine_class(**initkwargs) return instance.process(asset) engine.engine_class = cls engine.result_mimetype = cls.result_mimetype return engine def process(self, asset): raise NotImplementedError() class ExecEngine(BaseEngine): executable = None params = [] def __init__(self, executable=None): if executable is not None: self.executable = executable def process(self, asset): self.asset = asset p = subprocess.Popen( args=self.get_args(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = p.communicate(input=asset.processed_source) if p.returncode != 0: raise EngineProcessFailed(errors) asset.processed_source = output def get_args(self): return [self.executable] + self.params
Create cookie on game first run
<?php include("/home/c0smic/secure/data_db_settings.php"); $body = file_get_contents('php://input'); setcookie('game_first-run', true, 5184000 + time(), '/'); $stime = ""; $etime = ""; $moves = ""; function parseData($body) { $splitter = substr($body, 0, 1); global $stime, $etime, $moves; $mark1 = strpos($body, $splitter, 1); $mark2 = strpos($body, $splitter, $mark1+1); $mark3 = strpos($body, $splitter, $mark2+1); $stime = substr($body, 1, $mark1-1); $etime = substr($body, $mark1+1, $mark2-$mark1-1); $moves = substr($body, $mark2+1, $mark3-$mark2-1); } parseData($body); $conn = mysql_connect('localhost:3036', $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } unset($dbuser, $dbpass); mysql_select_db('c0smic_maze-game'); $sql= "INSERT INTO data (stime, etime, moves) VALUES ('$stime','$etime','$moves')"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } mysql_close($conn); echo $str; ?>
<?php include("/home/c0smic/secure/data_db_settings.php"); $body = file_get_contents('php://input'); $stime = ""; $etime = ""; $moves = ""; function parseData($body) { $splitter = substr($body, 0, 1); global $stime, $etime, $moves; $mark1 = strpos($body, $splitter, 1); $mark2 = strpos($body, $splitter, $mark1+1); $mark3 = strpos($body, $splitter, $mark2+1); $stime = substr($body, 1, $mark1-1); $etime = substr($body, $mark1+1, $mark2-$mark1-1); $moves = substr($body, $mark2+1, $mark3-$mark2-1); } parseData($body); $conn = mysql_connect('localhost:3036', $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } unset($dbuser, $dbpass); mysql_select_db('c0smic_maze-game'); $sql= "INSERT INTO data (stime, etime, moves) VALUES ('$stime','$etime','$moves')"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } mysql_close($conn); echo $str; ?>
Use custom font for watermark Signed-off-by: Michal Čihař <[email protected]>
import os.path from django.conf import settings from versatileimagefield.datastructures.filteredimage import FilteredImage from versatileimagefield.registry import versatileimagefield_registry from PIL import Image, ImageDraw, ImageFont from io import BytesIO class Watermark(FilteredImage): def process_image(self, image, image_format, save_kwargs={}): """ Returns a BytesIO instance of `image` with inverted colors """ if image.mode != 'RGBA': image = image.convert('RGBA') txt = Image.new('RGBA', image.size, (255,255,255,0)) height = image.size[1] fontsize = int(image.size[1] * 0.1) # get a font fnt = ImageFont.truetype( os.path.join( os.path.dirname(os.path.dirname(__file__)), 'font', 'conthrax-sb.ttf' ), fontsize, ) # get a drawing context d = ImageDraw.Draw(txt) # draw text, half opacity d.text( (10 + fontsize * .2, height - 10 - fontsize - fontsize * .2), settings.WATERMARK_TEXT, font=fnt, fill=(255,255,255,30) ) out = Image.alpha_composite(image, txt) out = out.convert('RGB') imagefile = BytesIO() out.save( imagefile, **save_kwargs ) return imagefile versatileimagefield_registry.register_filter('watermark', Watermark)
from django.conf import settings from versatileimagefield.datastructures.filteredimage import FilteredImage from versatileimagefield.registry import versatileimagefield_registry from PIL import Image, ImageDraw, ImageFont from io import BytesIO class Watermark(FilteredImage): def process_image(self, image, image_format, save_kwargs={}): """ Returns a BytesIO instance of `image` with inverted colors """ if image.mode != 'RGBA': image = image.convert('RGBA') txt = Image.new('RGBA', image.size, (255,255,255,0)) fontsize = int(image.size[1] * 0.1) # get a font fnt = ImageFont.truetype( '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', fontsize, ) # get a drawing context d = ImageDraw.Draw(txt) # draw text, half opacity d.text( (10, image.size[1] - 10 - fontsize), settings.WATERMARK_TEXT, font=fnt, fill=(255,255,255,30) ) out = Image.alpha_composite(image, txt) out = out.convert('RGB') imagefile = BytesIO() out.save( imagefile, **save_kwargs ) return imagefile versatileimagefield_registry.register_filter('watermark', Watermark)
Update the arrows to font-awesome
<?php namespace LaravelFoundation\Pagination; trait FoundationFiveNextPreviousButtonRendererTrait { /** * Get the previous page pagination element. * * @param string $text * @return string */ public function getPreviousButton($text = '<i class="fa fa-caret-left fa-2x"></i>') { // If the current page is less than or equal to one, it means we can't go any // further back in the pages, so we will render a disabled previous button // when that is the case. Otherwise, we will give it an active "status". if ($this->paginator->currentPage() <= 1) { return $this->getDisabledTextWrapper($text); } $url = $this->paginator->url( $this->paginator->currentPage() - 1 ); return $this->getPageLinkWrapper($url, $text, 'prev'); } /** * Get the next page pagination element. * * @param string $text * @return string */ public function getNextButton($text = '<i class="fa fa-caret-right fa-2x"></i>') { // If the current page is greater than or equal to the last page, it means we // can't go any further into the pages, as we're already on this last page // that is available, so we will make it the "next" link style disabled. if (! $this->paginator->hasMorePages()) { return $this->getDisabledTextWrapper($text); } $url = $this->paginator->url($this->paginator->currentPage() + 1); return $this->getPageLinkWrapper($url, $text, 'next'); } }
<?php namespace LaravelFoundation\Pagination; trait FoundationFiveNextPreviousButtonRendererTrait { /** * Get the previous page pagination element. * * @param string $text * @return string */ public function getPreviousButton($text = '&laquo;') { // If the current page is less than or equal to one, it means we can't go any // further back in the pages, so we will render a disabled previous button // when that is the case. Otherwise, we will give it an active "status". if ($this->paginator->currentPage() <= 1) { return $this->getDisabledTextWrapper($text); } $url = $this->paginator->url( $this->paginator->currentPage() - 1 ); return $this->getPageLinkWrapper($url, $text, 'prev'); } /** * Get the next page pagination element. * * @param string $text * @return string */ public function getNextButton($text = '&raquo;') { // If the current page is greater than or equal to the last page, it means we // can't go any further into the pages, as we're already on this last page // that is available, so we will make it the "next" link style disabled. if (! $this->paginator->hasMorePages()) { return $this->getDisabledTextWrapper($text); } $url = $this->paginator->url($this->paginator->currentPage() + 1); return $this->getPageLinkWrapper($url, $text, 'next'); } }
Fix collection call in embedCheckins
<?php namespace App\Transformer; use Place; use League\Fractal\TransformerAbstract; class PlaceTransformer extends TransformerAbstract { protected $availableEmbeds = [ 'checkins' ]; /** * Turn this item object into a generic array * * @return array */ public function transform(Place $place) { return [ 'id' => (int) $place->id, 'name' => $place->name, 'lat' => (float) $place->lat, 'lon' => (float) $place->lon, 'address1' => $place->address1, 'address2' => $place->address2, 'city' => $place->city, 'state' => $place->state, 'zip' => (float) $place->zip, 'website' => $place->website, 'phone' => $place->phone, ]; } /** * Embed Checkins * * @return League\Fractal\Resource\Collection */ public function embedCheckins(Place $place) { $checkins = $place->checkins; return $this->collection($checkins, new CheckinTransformer); } }
<?php namespace App\Transformer; use Place; use League\Fractal\TransformerAbstract; class PlaceTransformer extends TransformerAbstract { protected $availableEmbeds = [ 'checkins' ]; /** * Turn this item object into a generic array * * @return array */ public function transform(Place $place) { return [ 'id' => (int) $place->id, 'name' => $place->name, 'lat' => (float) $place->lat, 'lon' => (float) $place->lon, 'address1' => $place->address1, 'address2' => $place->address2, 'city' => $place->city, 'state' => $place->state, 'zip' => (float) $place->zip, 'website' => $place->website, 'phone' => $place->phone, ]; } /** * Embed Checkins * * @return League\Fractal\Resource\Collection */ public function embedCheckins(Place $place) { $checkins = $place->checkins; return $this->collectionResource($checkins, new CheckinTransformer); } }
Fix osf clone test that was asking for a password
"""Test `osf clone` command.""" import os from mock import patch, mock_open, call from osfclient import OSF from osfclient.cli import clone from osfclient.tests.mocks import MockProject from osfclient.tests.mocks import MockArgs @patch.object(OSF, 'project', return_value=MockProject('1234')) def test_clone_project(OSF_project): # check that `osf clone` opens files with the right names and modes args = MockArgs(project='1234') mock_open_func = mock_open() with patch('osfclient.cli.open', mock_open_func): with patch('osfclient.cli.os.makedirs'): with patch('osfclient.cli.os.getenv', side_effect='SECRET'): clone(args) OSF_project.assert_called_once_with('1234') # check that the project and the files have been accessed for store in OSF_project.return_value.storages: assert store._name_mock.called for f in store.files: assert f._path_mock.called fname = f._path_mock.return_value if fname.startswith('/'): fname = fname[1:] full_path = os.path.join('1234', store._name_mock.return_value, fname) assert call(full_path, 'wb') in mock_open_func.mock_calls
"""Test `osf clone` command.""" import os from mock import patch, mock_open, call from osfclient import OSF from osfclient.cli import clone from osfclient.tests.mocks import MockProject from osfclient.tests.mocks import MockArgs @patch.object(OSF, 'project', return_value=MockProject('1234')) def test_clone_project(OSF_project): # check that `osf clone` opens files with the right names and modes args = MockArgs(project='1234') mock_open_func = mock_open() with patch('osfclient.cli.open', mock_open_func): with patch('osfclient.cli.os.makedirs'): clone(args) OSF_project.assert_called_once_with('1234') # check that the project and the files have been accessed for store in OSF_project.return_value.storages: assert store._name_mock.called for f in store.files: assert f._path_mock.called fname = f._path_mock.return_value if fname.startswith('/'): fname = fname[1:] full_path = os.path.join('1234', store._name_mock.return_value, fname) assert call(full_path, 'wb') in mock_open_func.mock_calls
Fix FindBugs warnings in Parser Test.
package core; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import static org.junit.Assert.*; /** * Created by user on 18-5-2016. */ public class ParserTest { public Parser p; /** * Initialize the Parser before testing it. */ @Before public void setUp() { p = new Parser(); } /** * Test the constructor. */ @Test public void testConstructor() { assertNotNull(p); } /** * Test the readGFA method. */ @SuppressFBWarnings("OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE") @Test public void readGFA() { HashMap<Integer, Node> map = new HashMap<Integer, Node>(); InputStream is = getClass().getResourceAsStream("/TBTestFile.gfa"); try { map = p.readGFA(is); is.close(); } catch (IOException e) { e.printStackTrace(); } assertEquals(4, map.size()); for (int i = 1; i <= 4; i++) { Node n = map.get(i); assertEquals(i, n.getId()); assertEquals(Character.toString((char) ('A' + i - 1)), n.getSequence()); assertEquals(i, n.getzIndex()); assertEquals("GENOME_1", n.getGenomes().get(0)); assertEquals(Integer.valueOf(i + 1), n.getLinks().get(0)); } } }
package core; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import static org.junit.Assert.*; /** * Created by user on 18-5-2016. */ public class ParserTest { public Parser p; /** * Initialize the Parser before testing it. */ @Before public void setUp() { p = new Parser(); } /** * Test the constructor. */ @Test public void testConstructor() { assertNotNull(p); } /** * Test the readGFA method. */ @Test public void readGFA() { HashMap<Integer, Node> map = new HashMap<Integer, Node>(); InputStream is = getClass().getResourceAsStream("/TBTestFile.gfa"); try { map = p.readGFA(is); is.close(); } catch (IOException e) { e.printStackTrace(); } assertEquals(4, map.size()); for (int i = 1; i <= 4; i++) { Node n = map.get(i); assertEquals(i, n.getId()); assertEquals(Character.toString((char) ('A' + i - 1)), n.getSequence()); assertEquals(i, n.getzIndex()); assertEquals("GENOME_1", n.getGenomes().get(0)); assertEquals(new Integer(i + 1), n.getLinks().get(0)); } } }
Add styleinjector task for live css injection
module.exports = function (grunt) { grunt.initConfig({ styleinjector: { files: { src : 'css/site.css' }, options: { watchTask: true } }, // watch changes to less files watch: { styles: { files: ["less/*"], tasks: ["less"] }, options: { spawn: false, }, }, // compile set less files less: { development: { options: { paths: ["less"], }, files: { "css/site.css": ["less/*.less", "!less/_*.less"] } } }, }); // Load tasks so we can use them grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-contrib-less"); grunt.loadNpmTasks('grunt-style-injector'); // the default task will show the usage grunt.registerTask("default", "Prints usage", function () { grunt.log.writeln(""); grunt.log.writeln("Using Base"); grunt.log.writeln("------------------------"); grunt.log.writeln(""); grunt.log.writeln("* run 'grunt --help' to get an overview of all commands."); grunt.log.writeln("* run 'grunt dev' to start watching and compiling LESS changes."); }); grunt.registerTask("dev", ["less:development", "styleinjector", "watch:styles"]); };
module.exports = function (grunt) { grunt.initConfig({ // watch changes to less files watch: { styles: { files: ["less/*"], tasks: ["less"] }, options: { spawn: false, }, }, // compile set less files less: { development: { options: { paths: ["less"], }, files: { "css/site.css": ["less/*.less", "!less/_*.less"] } } }, }); // Load tasks so we can use them grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-contrib-less"); // the default task will show the usage grunt.registerTask("default", "Prints usage", function () { grunt.log.writeln(""); grunt.log.writeln("Using Base"); grunt.log.writeln("------------------------"); grunt.log.writeln(""); grunt.log.writeln("* run 'grunt --help' to get an overview of all commands."); grunt.log.writeln("* run 'grunt dev' to start watching and compiling LESS changes."); }); grunt.registerTask("dev", ["less:development", "watch:styles"]); };
Sort imported properties by order_column.
<?php namespace Nonoesp\Folio\Commands; use Illuminate\Console\Command; use Symfony\Component\Process\Process; use Symfony\Component\Process\Exception\ProcessFailedException; class ItemPropertiesImport extends Command { protected $signature = 'folio:prop:import {id} {json}'; protected $description = 'Import item properties from a JSON string.'; public function __construct() { parent::__construct(); } public function handle() { try { // Item id $id = $this->argument('id'); // JSON string with properties $json = $this->argument('json'); // Find item by id $item = \Item::find($id); if ($item) { $this->info("Found item $id."); } else { $this->warn("Item $id doesn't exist."); return; } // Decode properties as JSON, create collection, sort by order_column $json_props = collect(json_decode($json)); $json_props = $json_props->sortBy('order_column'); foreach($json_props as $prop) { $property = new \Property(); $property->item_id = $id; $property->label = $prop->label; $property->name = $prop->name; $property->value = $prop->value; $property->order_column = $prop->order_column; $property->save(); } } catch (ProcessFailedException $exception) { return $this->error('Import item properties failed.'); } } }
<?php namespace Nonoesp\Folio\Commands; use Illuminate\Console\Command; use Symfony\Component\Process\Process; use Symfony\Component\Process\Exception\ProcessFailedException; // class ItemPropertiesImport extends Command { protected $signature = 'folio:prop:import {id} {json}'; protected $description = 'Import item properties from a JSON string.'; public function __construct() { parent::__construct(); } public function handle() { try { // Item id $id = $this->argument('id'); // JSON string with properties $json = $this->argument('json'); // Find item by id $item = \Item::find($id); if ($item) { $this->info("Found item $id."); } else { $this->warn("Item $id doesn't exist."); return; } // Decode properties as JSON foreach(json_decode($json) as $prop) { $property = new \Property(); $property->item_id = $id; $property->label = $prop->label; $property->name = $prop->name; $property->value = $prop->value; $property->save(); } } catch (ProcessFailedException $exception) { return $this->error('Import item properties failed.'); } } }
Add quiet mode support for Retry
import time from random import uniform from typing import Callable, Optional class Retry: def __init__( self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False ) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter self.__quiet = quiet if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method and not self.__quiet: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration
import time from random import uniform from typing import Callable, Optional class Retry: def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration
Fix slash escaping in renderer
var DOM = (function(){ var entityMap = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': '&quot;', "'": '&#39;' }; var entityRegex = /[&<>"']/g; return { /* * Returns a child element by its ID. Parent defaults to the entire document. */ id: function(id, parent){ return (parent || document).getElementById(id); }, /* * Returns an array of all child elements containing the specified class. Parent defaults to the entire document. */ cls: function(cls, parent){ return Array.prototype.slice.call((parent || document).getElementsByClassName(cls)); }, /* * Returns an array of all child elements that have the specified tag. Parent defaults to the entire document. */ tag: function(tag, parent){ return Array.prototype.slice.call((parent || document).getElementsByTagName(tag)); }, /* * Creates an element, adds it to the DOM, and returns it. */ createElement: function(tag, parent){ var ele = document.createElement(tag); parent.appendChild(ele); return ele; }, /* * Removes an element from the DOM. */ removeElement: function(ele){ ele.parentNode.removeChild(ele); }, /* * Converts characters to their HTML entity form. */ escapeHTML: function(html){ return String(html).replace(entityRegex, s => entityMap[s]); } }; })();
var DOM = (function(){ var entityMap = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': '&quot;', "'": '&#39;' }; var entityRegex = /[&<>"'\/]/g; return { /* * Returns a child element by its ID. Parent defaults to the entire document. */ id: function(id, parent){ return (parent || document).getElementById(id); }, /* * Returns an array of all child elements containing the specified class. Parent defaults to the entire document. */ cls: function(cls, parent){ return Array.prototype.slice.call((parent || document).getElementsByClassName(cls)); }, /* * Returns an array of all child elements that have the specified tag. Parent defaults to the entire document. */ tag: function(tag, parent){ return Array.prototype.slice.call((parent || document).getElementsByTagName(tag)); }, /* * Creates an element, adds it to the DOM, and returns it. */ createElement: function(tag, parent){ var ele = document.createElement(tag); parent.appendChild(ele); return ele; }, /* * Removes an element from the DOM. */ removeElement: function(ele){ ele.parentNode.removeChild(ele); }, /* * Converts characters to their HTML entity form. */ escapeHTML: function(html){ return String(html).replace(entityRegex, s => entityMap[s]); } }; })();
Rename alpha -> learning_rate and gamma -> discount_factor
from ..learner import Learner from ..policies import RandomPolicy from ..util import max_action_value from ..value_functions import TabularF from ...utils import check_random_state class QLearning(Learner): def __init__(self, env, policy=None, qf=None, learning_rate=0.1, discount_factor=0.99, n_episodes=1000, random_state=None, verbose=None): super(QLearning, self).__init__(env, n_episodes=n_episodes, verbose=verbose) self.learning_rate = learning_rate self.discount_factor = discount_factor self.random_state = check_random_state(random_state) self.policy = policy or RandomPolicy(env.actions, self.random_state) self.qf = qf or TabularF(self.random_state) def best_qvalue(self, state, actions): return max_action_value(self.qf, state, actions) ########### # Learner # ########### def episode(self): while not self.env.is_terminal(): state = self.env.cur_state() action = self.policy.action(state) reward, next_state = self.env.do_action(action) best_qvalue = self.best_qvalue(next_state, next_actions) target = reward + (self.discount_factor * best_qvalue) td_error = target - self.qf[state, action] self.qf[state, action] += self.learning_rate * td_error
from ..learner import Learner from ..policies import RandomPolicy from ..util import max_action_value from ..value_functions import TabularF from ...utils import check_random_state class QLearning(Learner): def __init__(self, env, policy=None, qf=None, alpha=0.1, gamma=0.99, n_episodes=1000, random_state=None, verbose=None): super(QLearning, self).__init__(env, n_episodes=n_episodes, verbose=verbose) self.alpha = alpha self.gamma = gamma self.random_state = check_random_state(random_state) self.policy = policy or RandomPolicy(env.actions, self.random_state) self.qf = qf or TabularF(self.random_state) def best_qvalue(self, state, actions): return max_action_value(self.qf, state, actions) ########### # Learner # ########### def episode(self): while not self.env.is_terminal(): state = self.env.cur_state() action = self.policy.action(state) reward, next_state = self.env.do_action(action) best_qvalue = self.best_qvalue(next_state, next_actions) target = reward + (self.gamma * best_qvalue) td_error = target - self.qf[state, action] self.qf[state, action] += self.alpha * td_error
Make sticky header react to resize events.
(function($) { // http://stackoverflow.com/a/6625189/199100 // http://css-tricks.com/persistent-headers/ function translate(element, x, y) { var translation = "translate(" + x + "px," + y + "px)"; element.css({ "transform": translation, "-ms-transform": translation, "-webkit-transform": translation, "-o-transform": translation, "-moz-transform": translation }); } function sticky_header() { $(".sticky-header").each(function() { var $header = $(this), $table = $header.parents('.sticky-area:first'), offsetTop = $table.offset().top, $nb = $('.navbar-fixed-top'), nb_height = 0; if ($nb.css('position') == 'fixed') { nb_height = $nb.height(); } var scrollTop = $(window).scrollTop() + nb_height, delta = scrollTop - offsetTop; if((scrollTop > offsetTop) && (scrollTop < (offsetTop + $table.height()))) { translate($header, 0, delta - 3); // correction for borders } else { translate($header, 0, 0); } }); } $(function() { $(window).scroll(sticky_header); $(window).resize(sticky_header); }); })(jQuery);
(function($) { // http://stackoverflow.com/a/6625189/199100 // http://css-tricks.com/persistent-headers/ function translate(element, x, y) { var translation = "translate(" + x + "px," + y + "px)"; element.css({ "transform": translation, "-ms-transform": translation, "-webkit-transform": translation, "-o-transform": translation, "-moz-transform": translation }); } $(function() { $(document).scroll(function() { $(".sticky-header").each(function() { var $header = $(this), $table = $header.parents('.sticky-area:first'), offsetTop = $table.offset().top, $nb = $('.navbar-fixed-top'), nb_height = 0; if ($nb.css('position') == 'fixed') { nb_height = $nb.height(); } var scrollTop = $(window).scrollTop() + nb_height, delta = scrollTop - offsetTop; if((scrollTop > offsetTop) && (scrollTop < (offsetTop + $table.height()))) { translate($header, 0, delta - 3); // correction for borders } else { translate($header, 0, 0); } }); }); }); })(jQuery);
Change download url for release 0.3.6
from distutils.core import setup setup( name = 'django-test-addons', packages = ['test_addons'], version = '0.3.6', description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.', author = 'Hakampreet Singh Pandher', author_email = '[email protected]', url = 'https://github.com/hspandher/django-test-utils', download_url = 'https://github.com/hspandher/django-test-utils/tarball/0.3.6', keywords = ['testing', 'django', 'mongo', 'redis', 'neo4j', 'TDD', 'python', 'memcache', 'django rest framework'], license = 'MIT', install_requires = [ 'django>1.6' ], extras_require = { 'mongo_testing': ['mongoengine>=0.8.7'], 'redis_testing': ['django-redis>=3.8.2'], 'neo4j_testing': ['py2neo>=2.0.6'], 'rest_framework_testing': ['djangorestframework>=3.0.5'], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Testing', 'Topic :: Database', ], )
from distutils.core import setup setup( name = 'django-test-addons', packages = ['test_addons'], version = '0.3.5', description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.', author = 'Hakampreet Singh Pandher', author_email = '[email protected]', url = 'https://github.com/hspandher/django-test-utils', download_url = 'https://github.com/hspandher/django-test-utils/tarball/0.1', keywords = ['testing', 'django', 'mongo', 'redis', 'neo4j', 'TDD', 'python', 'memcache', 'django rest framework'], license = 'MIT', install_requires = [ 'django>1.6' ], extras_require = { 'mongo_testing': ['mongoengine>=0.8.7'], 'redis_testing': ['django-redis>=3.8.2'], 'neo4j_testing': ['py2neo>=2.0.6'], 'rest_framework_testing': ['djangorestframework>=3.0.5'], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Testing', 'Topic :: Database', ], )
Verify overflow in words array into the learn module
import sys import os sys.path.append(os.path.dirname(__file__) + "/../../") from state import state from state.stateEnum import StateEnum from helpers import configHelper from helpers import processorHelper class Learn: current_word = 0 def __init__(self, level_number): self.number = level_number self.words = configHelper.get_level_config('learn', self.number)['words'] self.output = processorHelper.get_output_processor() print("Nivel " + str(self.number) + " de aprendizaje") self._print_word() def process_input(self, input_value): if input_value == "right": self.current_word += 1 if not self._verify_overflow(): self._print_word() else: print("Se termino el nivel " + str(self.number) + " de aprendizaje. Saliendo al menu principal ...") state.set_state(StateEnum.MENU.key) if input_value == "left": self.current_word -= 1 if not self._verify_overflow(): self._print_word() else: self.current_word = 0 if input_value == "back": print("Regresando a " + StateEnum.MENU.realName) state.set_state(StateEnum.MENU.key) def _verify_overflow(self): return self.current_word == -1 or self.current_word == len(self.words) def _print_word(self): word = self.words[self.current_word] print(word) self.output.write(word.upper())
import sys import os sys.path.append(os.path.dirname(__file__) + "/../../") from state import state from state.stateEnum import StateEnum from helpers import configHelper from helpers import processorHelper class Learn: current_word = 0 def __init__(self, level_number): self.number = level_number self.words = configHelper.get_level_config('learn', self.number)['words'] self.output = processorHelper.get_output_processor() print("Nivel " + str(self.number) + " de aprendizaje") self._print_word() def process_input(self, input_value): if input_value == "right": self.current_word += 1 self._verify_overflow() self._print_word() if input_value == "left": self.current_word -= 1 self._verify_overflow() self._print_word() if input_value == "back": print("Regresando a " + StateEnum.MENU.realName) state.set_state(StateEnum.MENU.key) def _verify_overflow(self): pass def _print_word(self): word = self.words[self.current_word] print(word) self.output.write(word.upper())
Increment the version to 0.2.
from setuptools import setup setup(name='tfr', version='0.2', description='Time-frequency reassigned spectrograms', url='http://github.com/bzamecnik/tfr', author='Bohumir Zamecnik', author_email='[email protected]', license='MIT', packages=['tfr'], zip_safe=False, install_requires=[ 'numpy', 'scikit-learn', 'scipy', 'soundfile', ], setup_requires=['setuptools-markdown'], long_description_markdown_filename='README.md', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Topic :: Multimedia :: Sound/Audio :: Analysis', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', ])
from setuptools import setup setup(name='tfr', version='0.1', description='Time-frequency reassigned spectrograms', url='http://github.com/bzamecnik/tfr', author='Bohumir Zamecnik', author_email='[email protected]', license='MIT', packages=['tfr'], zip_safe=False, install_requires=[ 'numpy', 'scikit-learn', 'scipy', 'soundfile', ], setup_requires=['setuptools-markdown'], long_description_markdown_filename='README.md', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Topic :: Multimedia :: Sound/Audio :: Analysis', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', ])
Make sql validators private static
package com.yahoo.squidb.data; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; /*package*/ class SqlValidatorFactory { interface SqlValidator { void compileStatement(SQLiteDatabase db, String sql); } private static final SqlValidator INSTANCE; static { int version = VERSION.SDK_INT; if (version >= VERSION_CODES.JELLY_BEAN) { INSTANCE = new DefaultSqlValidator(); } else if (version >= VERSION_CODES.ICE_CREAM_SANDWICH) { INSTANCE = new IcsSqlValidator(); } else { // included for forks that reduce minSdk below 14 INSTANCE = new DefaultSqlValidator(); } } private SqlValidatorFactory() { //no instance } static SqlValidator getValidator() { return INSTANCE; } private static class DefaultSqlValidator implements SqlValidator { @Override public void compileStatement(SQLiteDatabase db, String sql) { db.compileStatement(sql); } } private static class IcsSqlValidator implements SqlValidator { @Override public void compileStatement(SQLiteDatabase db, String sql) { Cursor c = db.rawQuery(sql, null); if (c != null) { c.close(); } } } }
package com.yahoo.squidb.data; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import com.yahoo.squidb.data.SqlValidatorFactory.SqlValidator; /*package*/ class SqlValidatorFactory { interface SqlValidator { void compileStatement(SQLiteDatabase db, String sql); } private static final SqlValidator INSTANCE; static { int version = VERSION.SDK_INT; if (version >= VERSION_CODES.JELLY_BEAN) { INSTANCE = new DefaultSqlValidator(); } else if (version >= VERSION_CODES.ICE_CREAM_SANDWICH) { INSTANCE = new IcsSqlValidator(); } else { // included for forks that reduce minSdk below 14 INSTANCE = new DefaultSqlValidator(); } } private SqlValidatorFactory() { //no instance } static SqlValidator getValidator() { return INSTANCE; } } /*package*/ class DefaultSqlValidator implements SqlValidator { @Override public void compileStatement(SQLiteDatabase db, String sql) { db.compileStatement(sql); } } /*package*/ class IcsSqlValidator implements SqlValidator { @Override public void compileStatement(SQLiteDatabase db, String sql) { Cursor c = db.rawQuery(sql, null); if (c != null) { c.close(); } } }
Set up list of needed pieces on init
import collections from stock import Stock # simple structure to keep track of a specific piece Piece = collections.namedtuple('Piece', 'id, length') class Planner(object): def __init__(self, sizes, needed, loss=0.25): self.stock = [] self.stock_sizes = sorted(sizes) self.pieces_needed = [Piece(i, s) for i, s in enumerate(needed)] self.pieces_needed.reverse() self.cut_loss = loss self.cur_stock = None @property def largest_stock(self): return self.stock_sizes[-1] def cut_piece(self, piece): """ Record the cut for the given piece """ self.cur_stock.cut(piece, self.cut_loss) def finalize_stock(self): """ Takes current stock out of use, attempts to shrink """ # shrink as much as possible for smaller in self.stock_sizes[-2::-1]: if self.cur_stock.shrink(smaller) is None: break self.stock.append(self.cur_stock) def apply_next_fit(self, piece): """ Cut from current stock until unable, then move to new stock """ if self.cur_stock.remaining_length < piece.length + self.cut_loss: # finalize current stock and get fresh stock self.finalize_stock() cur_stock = Stock(self.largest_stock) self.cur_stock.cut(piece, self.cut_loss)
import collections from stock import Stock # simple structure to keep track of a specific piece Piece = collections.namedtuple('Piece', 'id, length') class Planner(object): def __init__(self, sizes, needed, loss=0.25): self.stock = [] self.stock_sizes = sorted(sizes) self.pieces_needed = needed.reverse self.cut_loss = loss self.cur_stock = None @property def largest_stock(self): return self.stock_sizes[-1] def cut_piece(self, piece): """ Record the cut for the given piece """ self.cur_stock.cut(piece, self.cut_loss) def finalize_stock(self): """ Takes current stock out of use, attempts to shrink """ # shrink as much as possible for smaller in self.stock_sizes[-2::-1]: if self.cur_stock.shrink(smaller) is None: break self.stock.append(self.cur_stock) def apply_next_fit(self, piece): """ Cut from current stock until unable, then move to new stock """ if self.cur_stock.remaining_length < piece.length + self.cut_loss: # finalize current stock and get fresh stock self.finalize_stock() cur_stock = Stock(self.largest_stock) self.cur_stock.cut(piece, self.cut_loss)
Add new line character after output
/* * grunt-dredd * https://github.com/mfgea/grunt-dredd * * Copyright (c) 2014 Matias Gea * Licensed under the MIT license. */ 'use strict'; var Dredd = require('dredd'); module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerTask('dredd', 'Grunt wrapper for Dredd API Blueprint tester', function() { var done = grunt.task.current.async(); // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ server: 'http://localhost:3000', src: './api/api.apib' }); var dreddConfiguration = { 'blueprintPath': options.src, 'server': options.server, 'options': options }; var dreddInstance = new Dredd(dreddConfiguration); dreddInstance.run(function(error, stats){ if (error) { if (error.message) { grunt.log.error(error.message); } if (error.stack) { grunt.log.error(error.stack); } done(false); } if (stats.failures + stats.errors > 0) { done(false); } else { done(true); } }); grunt.log.write('Dredd test run at ' + dreddConfiguration.options.server + ', using ' + options.src + '\n'); }); };
/* * grunt-dredd * https://github.com/mfgea/grunt-dredd * * Copyright (c) 2014 Matias Gea * Licensed under the MIT license. */ 'use strict'; var Dredd = require('dredd'); module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerTask('dredd', 'Grunt wrapper for Dredd API Blueprint tester', function() { var done = grunt.task.current.async(); // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ server: 'http://localhost:3000', src: './api/api.apib' }); var dreddConfiguration = { 'blueprintPath': options.src, 'server': options.server, 'options': options }; var dreddInstance = new Dredd(dreddConfiguration); dreddInstance.run(function(error, stats){ if (error) { if (error.message) { grunt.log.error(error.message); } if (error.stack) { grunt.log.error(error.stack); } done(false); } if (stats.failures + stats.errors > 0) { done(false); } else { done(true); } }); grunt.log.write('Dredd test run at ' + dreddConfiguration.options.server + ', using ' + options.src); }); };
Add Wayland Backend.fake_click and Backend.get_all_windows methods These work by eval-ing in the test Qtile instance. It might be nicer to instead make these cmd_s on the `Core` if/when we expose cmd_ methods from the Core.
import contextlib import os import textwrap from libqtile.backend.wayland.core import Core from test.helpers import Backend wlr_env = { "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_RENDERER_ALLOW_SOFTWARE": "1", "WLR_RENDERER": "pixman", } @contextlib.contextmanager def wayland_environment(outputs): """This backend just needs some environmental variables set""" env = wlr_env.copy() env["WLR_HEADLESS_OUTPUTS"] = str(outputs) yield env class WaylandBackend(Backend): def __init__(self, env, args=()): self.env = env self.args = args self.core = Core self.manager = None def create(self): """This is used to instantiate the Core""" os.environ.update(self.env) return self.core(*self.args) def configure(self, manager): """This backend needs to get WAYLAND_DISPLAY variable.""" success, display = manager.c.eval("self.core.display_name") assert success self.env["WAYLAND_DISPLAY"] = display def fake_click(self, x, y): """Click at the specified coordinates""" self.manager.c.eval(textwrap.dedent(""" self.core._focus_by_click() self.core._process_cursor_button(1, True) """)) def get_all_windows(self): """Get a list of all windows in ascending order of Z position""" success, result = self.manager.c.eval(textwrap.dedent(""" [win.wid for win in self.core.mapped_windows] """)) assert success return eval(result)
import contextlib import os from libqtile.backend.wayland.core import Core from test.helpers import Backend wlr_env = { "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_RENDERER_ALLOW_SOFTWARE": "1", "WLR_RENDERER": "pixman", } @contextlib.contextmanager def wayland_environment(outputs): """This backend just needs some environmental variables set""" env = wlr_env.copy() env["WLR_HEADLESS_OUTPUTS"] = str(outputs) yield env class WaylandBackend(Backend): def __init__(self, env, args=()): self.env = env self.args = args self.core = Core self.manager = None def create(self): """This is used to instantiate the Core""" os.environ.update(self.env) return self.core(*self.args) def configure(self, manager): """This backend needs to get WAYLAND_DISPLAY variable.""" success, display = manager.c.eval("self.core.display_name") assert success self.env["WAYLAND_DISPLAY"] = display def fake_click(self, x, y): """Click at the specified coordinates""" raise NotImplementedError def get_all_windows(self): """Get a list of all windows in ascending order of Z position""" raise NotImplementedError
Update namespaces for beta 8 Refs flarum/core#1235.
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Auth\GitHub\Listener; use Flarum\Frontend\Event\Rendering; use Illuminate\Contracts\Events\Dispatcher; class AddClientAssets { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(Rendering::class, [$this, 'addAssets']); } /** * @param Rendering $event */ public function addAssets(Rendering $event) { if ($event->isForum()) { $event->addAssets([ __DIR__.'/../../js/forum/dist/extension.js', __DIR__.'/../../less/forum/extension.less' ]); $event->addBootstrapper('flarum/auth/github/main'); } if ($event->isAdmin()) { $event->addAssets([ __DIR__.'/../../js/admin/dist/extension.js' ]); $event->addBootstrapper('flarum/auth/github/main'); } } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Auth\GitHub\Listener; use Flarum\Event\ConfigureWebApp; use Illuminate\Contracts\Events\Dispatcher; class AddClientAssets { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(ConfigureWebApp::class, [$this, 'addAssets']); } /** * @param ConfigureClientView $event */ public function addAssets(ConfigureWebApp $event) { if ($event->isForum()) { $event->addAssets([ __DIR__.'/../../js/forum/dist/extension.js', __DIR__.'/../../less/forum/extension.less' ]); $event->addBootstrapper('flarum/auth/github/main'); } if ($event->isAdmin()) { $event->addAssets([ __DIR__.'/../../js/admin/dist/extension.js' ]); $event->addBootstrapper('flarum/auth/github/main'); } } }
Fix JavaScript Interaction with Forms
$(document).ready( function () { $('#signup').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#signup_modal').show(); }); $('#screen_block').click(function(event){ event.preventDefault(); clear_modals(); }); $('#login').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#login_modal').show(); }); $('.new_question_button').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#new_question_modal').show(); }); $('form#new_question').submit(function(event){ event.preventDefault(); $('form#new_question input[type="submit"').prop('disable', true); $.ajax({ url: '/questions', type: 'POST', data: $('form#new_question').serialize(), dataType: 'JSON', }).done(function(data){ $('ol.thumb-grid').load('/ .thumb-grid'); clear_modals(); reset_question_form(); }).fail(function(data){ reset_question_form(); }); }); }); function reset_question_form(){ $('form#new_question').trigger('reset'); $('form#new_question input[type="submit"').prop('disable', false); } function clear_modals(){ $('#screen_block').hide(); $('#login_modal').hide(); $('#signup_modal').hide(); $('#new_question_modal').hide(); }
$(document).ready( function () { $('#signup').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#signup_modal').show(); }); $('#screen_block').click(function(event){ event.preventDefault(); clear_modals(); }); $('#login').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#login_modal').show(); }); $('.new_question_button').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#new_question_modal').show(); }); $('form#new_question').submit(function(event){ event.preventDefault(); $('form#new_question input[type="submit"').prop('disable', true); $.ajax({ url: '/questions', type: 'POST', data: $('form#new_question').serialize(), dataType: 'JSON', }).done(function(data){ $('ol.thumb-grid').load('/ .thumb-grid'); // clear_modals(); reset_question_form() }).fail(function(data){ reset_question_form() }); }); }); function reset_question_form(){ $('form#new_question').trigger('reset'); $('form#new_question input[type="submit"').prop('disable', false); } function clear_modals(){ $('#screen_block').hide(); $('#login_modal').hide(); $('#signup_modal').hide(); $('#new_question_modal').hide(); }
Add test for exec_sql parameters This is testing the different ways the parameters of `exec_sql` can be defined.
<?php require_once("tests/util.php"); class PDOTest extends DatabasePDOTestCase { public function testLogin() { $username = "track"; $password = "password"; $this->assertGreaterThanOrEqual(0, $this->db->valid_login($username, $password)); $this->assertEquals(NO_USER, $this->db->valid_login("invalid$username", $password)); $this->assertEquals(INVALID_CREDENTIALS, $this->db->valid_login($username, "invalid$password")); } public function testCount() { $this->assertGreaterThanOrEqual(0, $this->db->get_count("trips")); } public function testAccountCreation() { $username = "track2"; $password = "password"; $this->db->exec_sql("DELETE FROM users WHERE username=?", $username); $this->assertEquals(NO_USER, $this->db->valid_login($username, $password)); $uid = $this->db->create_login($username, $password); $this->assertGreaterThanOrEqual(0, $uid); $this->assertEquals($uid, $this->db->valid_login($username, $password)); $this->db->exec_sql("DELETE FROM users WHERE username=?", $username); } public function testExecSqlParameters() { $no_parameters = $this->db->exec_sql("SELECT username FROM users WHERE username='track'")->fetchAll(); $this->assertEquals(array(array(0 => "track", "username" => "track")), $no_parameters); $as_parameters = $this->db->exec_sql("SELECT username FROM users WHERE username=?", "track")->fetchAll(); $this->assertEquals($no_parameters, $as_parameters); $as_list = $this->db->exec_sql("SELECT username FROM users WHERE username=?", array("track"))->fetchAll(); $this->assertEquals($as_parameters, $as_list); } } ?>
<?php require_once("tests/util.php"); class PDOTest extends DatabasePDOTestCase { public function testLogin() { $username = "track"; $password = "password"; $this->assertGreaterThanOrEqual(0, $this->db->valid_login($username, $password)); $this->assertEquals(NO_USER, $this->db->valid_login("invalid$username", $password)); $this->assertEquals(INVALID_CREDENTIALS, $this->db->valid_login($username, "invalid$password")); } public function testCount() { $this->assertGreaterThanOrEqual(0, $this->db->get_count("trips")); } public function testAccountCreation() { $username = "track2"; $password = "password"; $this->db->exec_sql("DELETE FROM users WHERE username=?", $username); $this->assertEquals(NO_USER, $this->db->valid_login($username, $password)); $uid = $this->db->create_login($username, $password); $this->assertGreaterThanOrEqual(0, $uid); $this->assertEquals($uid, $this->db->valid_login($username, $password)); $this->db->exec_sql("DELETE FROM users WHERE username=?", $username); } } ?>
Fix migration issue Fixed 'Course' object has no attribute 'history' issue in the migration
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-12-04 10:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): def add_created_modified_date(apps, schema_editor): Course = apps.get_model('courses', 'Course') HistoricalCourse = apps.get_model('courses', 'historicalcourse') courses = Course.objects.all() for course in courses: history = HistoricalCourse.objects.filter(id=course.id) course.created = history.earliest().history_date course.modified = history.latest().history_date course.save() dependencies = [ ('courses', '0005_auto_20170525_0131'), ] operations = [ migrations.AddField( model_name='course', name='created', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='course', name='modified', field=models.DateTimeField(auto_now=True, null=True), ), migrations.AddField( model_name='historicalcourse', name='created', field=models.DateTimeField(blank=True, editable=False, null=True), ), migrations.AddField( model_name='historicalcourse', name='modified', field=models.DateTimeField(blank=True, editable=False, null=True), ), migrations.RunPython(add_created_modified_date, migrations.RunPython.noop), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-12-04 10:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): def add_created_modified_date(apps, schema_editor): Course = apps.get_model('courses', 'Course') courses = Course.objects.all() for course in courses: course.created = course.history.earliest().history_date course.modified = course.history.latest().history_date course.save() dependencies = [ ('courses', '0005_auto_20170525_0131'), ] operations = [ migrations.AddField( model_name='course', name='created', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='course', name='modified', field=models.DateTimeField(auto_now=True, null=True), ), migrations.AddField( model_name='historicalcourse', name='created', field=models.DateTimeField(blank=True, editable=False, null=True), ), migrations.AddField( model_name='historicalcourse', name='modified', field=models.DateTimeField(blank=True, editable=False, null=True), ), migrations.RunPython(add_created_modified_date, migrations.RunPython.noop), ]
Fix given path order for Google App Engine
import os import hashlib from datetime import datetime VCS_NAMES = ['.svn', '.git', '.bzr', '.hg'] IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo'] def list_directory(path, include_directories=True): # Skip over any VCS directories. for root, dirs, files in os.walk(path): for dir in VCS_NAMES: try: dirs.remove(dir) except ValueError: pass # We are also interested in the directories. if include_directories: yield os.path.join(root) for file in files: _, ext = os.path.splitext(file) if ext in IGNORED_EXTENSIONS: continue yield os.path.join(root, file) def mtime(path): latest = 0 for path in list_directory(path): mtime = os.path.getmtime(path) latest = max(mtime, latest) return datetime.fromtimestamp(latest).isoformat()[:22] def md5(path): chcksm = hashlib.md5() for path in sorted(list(list_directory(path, include_directories=False))): chcksm.update(path) try: f = open(path, 'rb') while True: # 256kb chunks. # XXX how to optimize chunk size? chunk = f.read(0x40000) if not chunk: break chcksm.update(chunk) finally: f.close() return chcksm.hexdigest()
import os import hashlib from datetime import datetime VCS_NAMES = ['.svn', '.git', '.bzr', '.hg'] IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo'] def list_directory(path, include_directories=True): # Skip over any VCS directories. for root, dirs, files in os.walk(path): for dir in VCS_NAMES: try: dirs.remove(dir) except ValueError: pass # We are also interested in the directories. if include_directories: yield os.path.join(root) for file in files: _, ext = os.path.splitext(file) if ext in IGNORED_EXTENSIONS: continue yield os.path.join(root, file) def mtime(path): latest = 0 for path in list_directory(path): mtime = os.path.getmtime(path) latest = max(mtime, latest) return datetime.fromtimestamp(latest).isoformat()[:22] def md5(path): chcksm = hashlib.md5() for path in list_directory(path, include_directories=False): chcksm.update(path) try: f = open(path, 'rb') while True: # 256kb chunks. # XXX how to optimize chunk size? chunk = f.read(0x40000) if not chunk: break chcksm.update(chunk) finally: f.close() return chcksm.hexdigest()
Fix minor issue, no functions in loops
<?php namespace Stringizer\Transformers; /** * SwapCase - Swap the case of each character. * * @link https://github.com/jasonlam604/Stringizer * @copyright Copyright (c) 2016 Jason Lam * @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE.md (MIT License) */ class SwapCase extends Transformer implements TransformerInterface { public function __construct($value) { parent::__construct($value); } public function execute() { return $this->swap($this->getValue()); } /** * * @param string $str */ private function swap($str) { $arr = preg_split('//u', $this->getValue(), - 1, PREG_SPLIT_NO_EMPTY); $len = count($arr); for ($i = 0; $i < $len; $i ++) { if (ctype_alpha($arr[$i])) { if (ctype_upper($arr[$i])) { $arr[$i] = mb_strtolower($arr[$i]); } elseif (ctype_lower($arr[$i])) { $arr[$i] = mb_strtoupper($arr[$i]); } } } $str = implode("", $arr); return $str; } }
<?php namespace Stringizer\Transformers; /** * SwapCase - Swap the case of each character. * * @link https://github.com/jasonlam604/Stringizer * @copyright Copyright (c) 2016 Jason Lam * @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE.md (MIT License) */ class SwapCase extends Transformer implements TransformerInterface { public function __construct($value) { parent::__construct($value); } public function execute() { return $this->swap($this->getValue()); } /** * * @param string $str */ private function swap($str) { $arr = preg_split('//u', $this->getValue(), - 1, PREG_SPLIT_NO_EMPTY); for ($i = 0; $i < count($arr); $i ++) { if (ctype_alpha($arr[$i])) { if (ctype_upper($arr[$i])) { $arr[$i] = mb_strtolower($arr[$i]); } elseif (ctype_lower($arr[$i])) { $arr[$i] = mb_strtoupper($arr[$i]); } } } $str = implode("", $arr); return $str; } }
Add active() method to graph object model
// Copyright 2015, EMC, Inc. 'use strict'; module.exports = GraphModelFactory; GraphModelFactory.$provide = 'Models.GraphObject'; GraphModelFactory.$inject = [ 'Model', 'Constants' ]; function GraphModelFactory (Model, Constants) { return Model.extend({ connection: 'mongo', identity: 'graphobjects', attributes: { instanceId: { type: 'string', required: true, unique: true, uuidv4: true }, context: { type: 'json', required: true, json: true }, definition: { type: 'json', required: true, json: true }, tasks: { type: 'json', required: true, json: true }, node: { model: 'nodes' }, active: function() { var obj = this.toObject(); return obj._status === Constants.Task.States.Pending; } } }); }
// Copyright 2015, EMC, Inc. 'use strict'; module.exports = GraphModelFactory; GraphModelFactory.$provide = 'Models.GraphObject'; GraphModelFactory.$inject = [ 'Model' ]; function GraphModelFactory (Model) { return Model.extend({ connection: 'mongo', identity: 'graphobjects', attributes: { instanceId: { type: 'string', required: true, unique: true, uuidv4: true }, context: { type: 'json', required: true, json: true }, definition: { type: 'json', required: true, json: true }, tasks: { type: 'json', required: true, json: true }, node: { model: 'nodes' } } }); }
Remove route defenitions from controllers
<?php /** * @link https://github.com/sydes/framework * @copyright 2011-2017, ArtyGrand <artygrand.ru> * @license MIT license; see LICENSE */ namespace Sydes\Router; class Router { /** * Path to fast route cache file. */ protected $cacheFile = false; /** @var \FastRoute\Dispatcher */ protected $dispatcher; /** * @param string $file */ public function setCacheFile($file) { $this->cacheFile = $file; } /** * Dispatch router for request * * @param array $files * @param string $method * @param string $uri * @return array * @link https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php */ public function dispatch(array $files, $method, $uri) { $callback = function (Route $r) use ($files) { foreach ($files as $file) { if (file_exists($file)) { include $file; } } }; return $this->createDispatcher($callback)->dispatch($method, $uri); } /** * @return \FastRoute\Dispatcher */ protected function createDispatcher($callback) { $this->dispatcher = \FastRoute\cachedDispatcher($callback, [ 'cacheFile' => $this->cacheFile, 'cacheDisabled' => is_bool($this->cacheFile), 'routeCollector' => 'Sydes\Router\Route', ]); return $this->dispatcher; } }
<?php /** * @link https://github.com/sydes/framework * @copyright 2011-2017, ArtyGrand <artygrand.ru> * @license MIT license; see LICENSE */ namespace Sydes\Router; class Router { /** * Path to fast route cache file. */ protected $cacheFile = false; /** @var \FastRoute\Dispatcher */ protected $dispatcher; /** * @param string $file */ public function setCacheFile($file) { $this->cacheFile = $file; } /** * Dispatch router for request * * @param $method * @param $uri * @return array * @link https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php */ public function dispatch($modules, $method, $uri) { $callback = function (Route $r) use ($modules) { foreach ($modules as $module) { $class = 'Module\\'.$module.'\\Controller'; if (method_exists($class, 'routes')) { $class::routes($r); } } }; return $this->createDispatcher($callback)->dispatch($method, $uri); } /** * @return \FastRoute\Dispatcher */ protected function createDispatcher($callback) { $this->dispatcher = \FastRoute\cachedDispatcher($callback, [ 'cacheFile' => $this->cacheFile, 'cacheDisabled' => is_bool($this->cacheFile), 'routeCollector' => 'Sydes\Router\Route', ]); return $this->dispatcher; } }
Use facade for firing events
<?php namespace Adldap\Laravel\Traits; use Adldap\Models\User; use Adldap\Laravel\Events\AuthenticatedWithWindows; use Adldap\Laravel\Events\DiscoveredWithCredentials; use Adldap\Laravel\Events\AuthenticatedWithCredentials; use Illuminate\Support\Facades\Event; use Illuminate\Contracts\Auth\Authenticatable; trait DispatchesAuthEvents { /** * Dispatches an authentication event when users login by their credentials. * * @param User $user * @param Authenticatable|null $model * * @return void */ public function handleAuthenticatedWithCredentials(User $user, Authenticatable $model = null) { Event::fire(new AuthenticatedWithCredentials($user, $model)); } /** * Dispatches an event when a user has logged in via the WindowsAuthenticate middleware. * * @param User $user * @param Authenticatable|null $model * * @return void */ protected function handleAuthenticatedWithWindows(User $user, Authenticatable $model = null) { Event::fire(new AuthenticatedWithWindows($user, $model)); } /** * Dispatches an event when a user has been discovered by the their credentials. * * @param User $user */ protected function handleDiscoveredWithCredentials(User $user) { Event::fire(new DiscoveredWithCredentials($user)); } }
<?php namespace Adldap\Laravel\Traits; use Adldap\Models\User; use Adldap\Laravel\Events\AuthenticatedWithWindows; use Adldap\Laravel\Events\DiscoveredWithCredentials; use Adldap\Laravel\Events\AuthenticatedWithCredentials; use Illuminate\Contracts\Auth\Authenticatable; trait DispatchesAuthEvents { /** * Dispatches an authentication event when users login by their credentials. * * @param User $user * @param Authenticatable|null $model * * @return void */ public function handleAuthenticatedWithCredentials(User $user, Authenticatable $model = null) { event(new AuthenticatedWithCredentials($user, $model)); } /** * Dispatches an event when a user has logged in via the WindowsAuthenticate middleware. * * @param User $user * @param Authenticatable|null $model * * @return void */ protected function handleAuthenticatedWithWindows(User $user, Authenticatable $model = null) { event(new AuthenticatedWithWindows($user, $model)); } /** * Dispatches an event when a user has been discovered by the their credentials. * * @param User $user */ protected function handleDiscoveredWithCredentials(User $user) { event(new DiscoveredWithCredentials($user)); } }
Add missing config that caused test to fail
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: params = dict( LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'wagtailgeowidget': { 'handlers': ['console'], 'level': 'ERROR', 'propagate': True, }, }, }, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sites', 'wagtail.core', "wagtail.admin", 'wagtail.sites', 'wagtail.users', 'wagtail.images', 'taggit', 'wagtailgeowidget', "tests", ], MIDDLEWARE_CLASSES=[], ROOT_URLCONF='tests.urls', SECRET_KEY="secret key", ) settings.configure(**params) def runtests(): argv = sys.argv[:1] + ["test"] + sys.argv[1:] execute_from_command_line(argv) if __name__ == "__main__": runtests()
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: params = dict( LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'wagtailgeowidget': { 'handlers': ['console'], 'level': 'ERROR', 'propagate': True, }, }, }, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sites', 'wagtail.core', 'wagtail.sites', 'wagtail.users', 'wagtail.images', 'taggit', 'wagtailgeowidget', "tests", ], MIDDLEWARE_CLASSES=[], ROOT_URLCONF='tests.urls', ) settings.configure(**params) def runtests(): argv = sys.argv[:1] + ["test"] + sys.argv[1:] execute_from_command_line(argv) if __name__ == "__main__": runtests()
Test that the event manager is not replaced
<?php namespace UpCloo\App; class BootTest extends \PHPUnit_Framework_TestCase { public function testGetEmptyServiceManagerOnMissingConfiguration() { $boot = new Boot(new Config\ArrayProcessor()); $boot->bootstrap(); $this->assertInstanceOf("Zend\\ServiceManager\\ServiceManager", $boot->services()); $this->assertInstanceOf("Zend\\EventManager\\EventManager", $boot->events()); } public function testConfigurationOverwrite() { $processor = new Config\ArrayProcessor(); $myConf = [ "services" => [ "invokables" => [ "UpCloo\\Listener\\Renderer\\Json" => "UpCloo\\Listener\\Renderer\\Json" ], "aliases" => [ "renderer" => "UpCloo\\Listener\\Renderer\\Json", ] ] ]; $processor->appendConfig($myConf); $boot = new Boot($processor); $boot->bootstrap(); $renderer = $boot->services()->get("renderer"); $this->assertInstanceOf("UpCloo\\Listener\\Renderer\\Json", $renderer); } public function testServiceManagerIsNotReplaced() { $boot = new Boot(new Config\ArrayProcessor()); $serviceManager = new \Zend\ServiceManager\ServiceManager(); $boot->setServiceManager($serviceManager); $boot->bootstrap(); $this->assertSame($serviceManager, $boot->services()); } public function testEventManagerIsNotReplaced() { $boot = new Boot(new Config\ArrayProcessor()); $eventManager = new \Zend\EventManager\EventManager(); $boot->setEventManager($eventManager); $boot->bootstrap(); $this->assertSame($eventManager, $boot->events()); } }
<?php namespace UpCloo\App; class BootTest extends \PHPUnit_Framework_TestCase { public function testGetEmptyServiceManagerOnMissingConfiguration() { $boot = new Boot(new Config\ArrayProcessor()); $boot->bootstrap(); $this->assertInstanceOf("Zend\\ServiceManager\\ServiceManager", $boot->services()); $this->assertInstanceOf("Zend\\EventManager\\EventManager", $boot->events()); } public function testConfigurationOverwrite() { $processor = new Config\ArrayProcessor(); $myConf = [ "services" => [ "invokables" => [ "UpCloo\\Listener\\Renderer\\Json" => "UpCloo\\Listener\\Renderer\\Json" ], "aliases" => [ "renderer" => "UpCloo\\Listener\\Renderer\\Json", ] ] ]; $processor->appendConfig($myConf); $boot = new Boot($processor); $boot->bootstrap(); $renderer = $boot->services()->get("renderer"); $this->assertInstanceOf("UpCloo\\Listener\\Renderer\\Json", $renderer); } public function testServiceManagerIsNotReplaced() { $boot = new Boot(new Config\ArrayProcessor()); $serviceManager = new \Zend\ServiceManager\ServiceManager(); $boot->setServiceManager($serviceManager); $boot->bootstrap(); $this->assertSame($serviceManager, $boot->services()); } }
Fix build issue on OSX. Our script assumes the quest directory only has subdirectories of quests but OSX adds DS_STORE files to each directory and these were being picked up and causing the assemble quests script to fail.
""" Assembles the zone configurations for each quest into one file. Every quest that is in quest_dir and every zone that is in each quest will be included. Example output: { quest1: [ { zone: A, ... }, { zone: B, ... } ], quest2: [ { zone: X, ... } ] } """ import json import os quest_dir = 'src/quests' output_path = 'src/quests.json' output = {} for quest in os.listdir(quest_dir): questPath = os.path.join(quest_dir, quest) if os.path.isdir(questPath): output[quest] = { 'zones': [] } for zone in sorted(os.listdir(questPath)): if os.path.isdir(os.path.join(questPath, zone)): with open(os.path.join(questPath, zone, 'zone.json')) as f: data = json.load(f) output[quest]['zones'].append(data) with open(output_path, 'w') as output_file: json.dump(output, output_file, indent=4) print 'Generated ' + output_path
""" Assembles the zone configurations for each quest into one file. Every quest that is in quest_dir and every zone that is in each quest will be included. Example output: { quest1: [ { zone: A, ... }, { zone: B, ... } ], quest2: [ { zone: X, ... } ] } """ import json import os quest_dir = 'src/quests' output_path = 'src/quests.json' output = {} for quest in os.listdir(quest_dir): questPath = os.path.join(quest_dir, quest) if os.path.isdir(questPath): output[quest] = { 'zones': [] } for zone in sorted(os.listdir(questPath)): with open(os.path.join(questPath, zone, 'zone.json')) as f: data = json.load(f) output[quest]['zones'].append(data) with open(output_path, 'w') as output_file: json.dump(output, output_file, indent=4) print 'Generated ' + output_path
Fix exception test function for python3.
import sys import unittest #sys.path.insert(0, os.path.abspath('..')) import github3 class BaseTest(unittest.TestCase): api = 'https://api.github.com/' kr = 'kennethreitz' sigm = 'sigmavirus24' todo = 'Todo.txt-python' gh3py = 'github3py' def setUp(self): super(BaseTest, self).setUp() self.g = github3.GitHub() def assertIsInstance(self, obj, cls): """Assert that ``obj`` is an instance of ``cls``""" if not isinstance(obj, cls): self.fail() def assertRaisesError(self, func, *args, **kwargs): """Assert that func raises github3.Error""" try: func(*args, **kwargs) except github3.Error: pass except Exception as e: self.fail('{0}({1}, {2}) raises unexpected exception: {3}'.format( str(func), str(args), str(kwargs), str(e))) def assertIsNotNone(self, value, msg=None): if sys.version_info >= (2, 7): super(BaseTest, self).assertIsNotNone(value, msg) else: try: assert value is not None except AssertionError: self.fail('AssertionError: ' + msg)
import sys import unittest #sys.path.insert(0, os.path.abspath('..')) import github3 class BaseTest(unittest.TestCase): api = 'https://api.github.com/' kr = 'kennethreitz' sigm = 'sigmavirus24' todo = 'Todo.txt-python' gh3py = 'github3py' def setUp(self): super(BaseTest, self).setUp() self.g = github3.GitHub() def assertIsInstance(self, obj, cls): """Assert that ``obj`` is an instance of ``cls``""" if not isinstance(obj, cls): self.fail() def assertRaisesError(self, func, *args, **kwargs): """Assert that func raises github3.Error""" try: func(*args, **kwargs) except github3.Error: pass except Exception, e: self.fail('{0}({1}, {2}) raises unexpected exception: {3}'.format( str(func), str(args), str(kwargs), str(e))) def assertIsNotNone(self, value, msg=None): if sys.version_info >= (2, 7): super(BaseTest, self).assertIsNotNone(value, msg) else: try: assert value is not None except AssertionError: self.fail('AssertionError: ' + msg)
Fix editor dirty confirm leave. Use $window instead of window. Use the jQuery element of $window to bind listeners. Fix final location after modal confirm while properly retaining browser history.
'use strict'; angular.module('bitty') .directive('editorBox', function ($location, $modal, $window) { return { restrict: 'AE', link: function (scope, element) { var confirmMsg = 'You will lose any unsaved changes.'; var popping = false; var win = angular.element($window); element.addClass('editor-box'); scope.dirty = false; scope.aceChanged = function () { scope.dirty = true; }; scope.aceLoaded = function (editor) { editor.setShowPrintMargin(false); }; function beforeunloadListener() { if (scope.dirty) { return confirmMsg; } } function popstateListener() { popping = true; } win.bind('beforeunload', beforeunloadListener); win.bind('popstate', popstateListener); element.bind('$destroy', function () { win.unbind('beforeunload', beforeunloadListener); win.unbind('popstate', popstateListener); }); scope.$on('$locationChangeStart', function (event, next) { if (!scope.dirty) { return; } event.preventDefault(); $modal.open({ templateUrl: 'templates/modals/confirm.html', controller: 'ConfirmCtrl', resolve: { confirm: function () { return { title: 'Are you sure?', body: confirmMsg }; } } }).result.then(function () { // Confirmed scope.dirty = false; if (popping) { $window.history.back(); } else { $location.$$parse(next); } }, function () { popping = false; }); }); }, templateUrl: 'templates/directives/editorBox.html' }; });
'use strict'; angular.module('bitty').directive('editorBox', function ($location, $modal) { return { restrict: 'AE', link: function (scope, element) { var confirmMsg = 'You will lose any unsaved changes.'; element.addClass('editor-box'); scope.dirty = false; scope.aceChanged = function () { scope.dirty = true; }; scope.aceLoaded = function (editor) { editor.setShowPrintMargin(false); }; window.onbeforeunload = function () { if (scope.dirty) { return confirmMsg; } }; element.bind('$destroy', function () { window.onbeforeunload = null; }); scope.$on('$locationChangeStart', function (event, next) { if (!scope.dirty) { return; } event.preventDefault(); $modal.open({ templateUrl: 'templates/modals/confirm.html', controller: 'ConfirmCtrl', resolve: { confirm: function () { return { title: 'Are you sure?', body: confirmMsg }; } } }).result.then(function () { // Confirmed scope.dirty = false; $location.url(next); }); }); }, templateUrl: 'templates/directives/editorBox.html' }; });
Fix fibonacci sensor so it works under Python 3.
import os from st2reactor.sensor.base import PollingSensor class FibonacciSensor(PollingSensor): def __init__(self, sensor_service, config, poll_interval=5): super(FibonacciSensor, self).__init__( sensor_service=sensor_service, config=config, poll_interval=poll_interval ) self.a = None self.b = None self.count = None self.logger = None def setup(self): self.a = 0 self.b = 1 self.count = 2 self.logger = self.sensor_service.get_logger(name=self.__class__.__name__) def poll(self): fib = self.a + self.b self.logger.debug('Count: %d, a: %d, b: %d', self.count, self.a, self.b) payload = { "count": self.count, "fibonacci": fib, "pythonpath": os.environ.get("PYTHONPATH", None) } self.sensor_service.dispatch(trigger="examples.fibonacci", payload=payload) self.a = self.b self.b = fib self.count = self.count + 1 def cleanup(self): pass def add_trigger(self, trigger): # This method is called when trigger is created pass def update_trigger(self, trigger): # This method is called when trigger is updated pass def remove_trigger(self, trigger): # This method is called when trigger is deleted pass
from st2reactor.sensor.base import PollingSensor from environ import get_environ class FibonacciSensor(PollingSensor): def __init__(self, sensor_service, config, poll_interval=5): super(FibonacciSensor, self).__init__( sensor_service=sensor_service, config=config, poll_interval=poll_interval ) self.a = None self.b = None self.count = None self.logger = None def setup(self): self.a = 0 self.b = 1 self.count = 2 self.logger = self.sensor_service.get_logger(name=self.__class__.__name__) def poll(self): fib = self.a + self.b self.logger.debug('Count: %d, a: %d, b: %d', self.count, self.a, self.b) payload = { "count": self.count, "fibonacci": fib, "pythonpath": get_environ("PYTHONPATH") } self.sensor_service.dispatch(trigger="examples.fibonacci", payload=payload) self.a = self.b self.b = fib self.count = self.count + 1 def cleanup(self): pass def add_trigger(self, trigger): # This method is called when trigger is created pass def update_trigger(self, trigger): # This method is called when trigger is updated pass def remove_trigger(self, trigger): # This method is called when trigger is deleted pass
Correct comma spacing for Giuliano
var cheerio = require('cheerio'); require('./parserUtil'); module.exports.parse = function (html, callback) { var $ = cheerio.load(html); var menu = []; var todayStr = global.todaysDate.format("DD. MM. YYYY"); $('.menublock').each(function () { var leftCellText = $(this).children("div").first().text(); if (leftCellText.indexOf(todayStr) !== -1) { var match = /€(\d[\.,]\d{2})/.exec(leftCellText); var price = match ? parseFloat(match[1]) : NaN; var items = $(this).children("div").eq(1).text().match(/[^\r\n]+/g); menu = items.map(function(item, index){ var tmp = {isSoup: false, text: normalize(item), price: price }; if(index === 0) {//I think it is safe enough to assume that the first item in menu is the soup tmp.isSoup = true; tmp.price = NaN; } return tmp; }); return false; } }); function normalize(str) { return str.normalizeWhitespace() .removeMetrics() .correctCommaSpacing(); } callback(menu); };
var cheerio = require('cheerio'); require('./parserUtil'); module.exports.parse = function (html, callback) { var $ = cheerio.load(html); var menu = []; var todayStr = global.todaysDate.format("DD. MM. YYYY"); $('.menublock').each(function () { var leftCellText = $(this).children("div").first().text(); if (leftCellText.indexOf(todayStr) !== -1) { var match = /€(\d[\.,]\d{2})/.exec(leftCellText); var price = match ? parseFloat(match[1]) : NaN; var items = $(this).children("div").eq(1).text().match(/[^\r\n]+/g); menu = items.map(function(item, index){ var tmp = {isSoup: false, text: normalize(item), price: price }; if(index === 0) {//I think it is safe enough to assume that the first item in menu is the soup tmp.isSoup = true; tmp.price = NaN; } return tmp; }); return false; } }); function normalize(str) { return str.normalizeWhitespace() .removeMetrics(); } callback(menu); };