text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Increase decimal size to 5 Increase decimal size to 5 places
<?php /** * Adds automatic geocoding to a {@link Addressable} object. Uses the Google * Maps API to save latitude and longitude on write. * * @package silverstripe-addressable */ class Geocodable extends DataExtension { private static $db = array( 'Lat' => 'Decimal(9,5)', 'Lng' => 'Decimal(9,5)' ); public function onBeforeWrite() { if (!$this->owner->isAddressChanged()) return; $address = $this->owner->getFullAddress(); $region = strtolower($this->owner->Country); if(!$point = GoogleGeocoding::address_to_point($address, $region)) { return; } $this->owner->Lat = $point['lat']; $this->owner->Lng = $point['lng']; } public function updateCMSFields(FieldList $fields) { $fields->removeByName('Lat'); $fields->removeByName('Lng'); } public function updateFrontEndFields(FieldList $fields) { $this->updateCMSFields($fields); } }
<?php /** * Adds automatic geocoding to a {@link Addressable} object. Uses the Google * Maps API to save latitude and longitude on write. * * @package silverstripe-addressable */ class Geocodable extends DataExtension { private static $db = array( 'Lat' => 'Decimal', 'Lng' => 'Decimal' ); public function onBeforeWrite() { if (!$this->owner->isAddressChanged()) return; $address = $this->owner->getFullAddress(); $region = strtolower($this->owner->Country); if(!$point = GoogleGeocoding::address_to_point($address, $region)) { return; } $this->owner->Lat = $point['lat']; $this->owner->Lng = $point['lng']; } public function updateCMSFields(FieldList $fields) { $fields->removeByName('Lat'); $fields->removeByName('Lng'); } public function updateFrontEndFields(FieldList $fields) { $this->updateCMSFields($fields); } }
Hide simple view by default It is an example implementation, most actual applications would probably use something with more features.
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import SimpleView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "plugin": { "name": i18n_catalog.i18nc("@label", "Simple View"), "author": "Ultimaker", "version": "1.0", "decription": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."), "api": 2 }, "view": { "name": i18n_catalog.i18nc("@item:inmenu", "Simple"), "visible": False } } def register(app): return { "view": SimpleView.SimpleView() }
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import SimpleView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "plugin": { "name": i18n_catalog.i18nc("@label", "Simple View"), "author": "Ultimaker", "version": "1.0", "decription": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."), "api": 2 }, "view": { "name": i18n_catalog.i18nc("@item:inmenu", "Simple") } } def register(app): return { "view": SimpleView.SimpleView() }
Make settings test respect ES_INDEX_PREFIX.
from django.conf import settings # The test system uses this to override settings in settings.py and # settings_local.py with settings appropriate for testing. # Make sure Celery is EAGER. CELERY_ALWAYS_EAGER = True # Make sure the doctypes (the keys) match the doctypes in ES_INDEXES # in settings.py and settings_local.py. ES_INDEXES = {'default': 'sumo_test' + settings.ES_INDEX_PREFIX} ES_WRITE_INDEXES = ES_INDEXES # This makes sure we only turn on ES stuff when we're testing ES # stuff. ES_LIVE_INDEXING = False # Make sure we use port 6383 db 2 redis for tests. That's db 2 of the # redis test config. That shouldn't collide with anything else. REDIS_BACKENDS = { 'default': 'redis://localhost:6383?socket_timeout=0.5&db=2', 'karma': 'redis://localhost:6383?socket_timeout=0.5&db=2', 'helpfulvotes': 'redis://localhost:6383?socket_timeout=0.5&db=2', } # Use fake webtrends settings. WEBTRENDS_PROFILE_ID = 'ABC123'
# The test system uses this to override settings in settings.py and # settings_local.py with settings appropriate for testing. # Make sure Celery is EAGER. CELERY_ALWAYS_EAGER = True # Make sure the doctypes (the keys) match the doctypes in ES_INDEXES # in settings.py and settings_local.py. ES_INDEXES = {'default': 'sumo_test'} ES_WRITE_INDEXES = ES_INDEXES # This makes sure we only turn on ES stuff when we're testing ES # stuff. ES_LIVE_INDEXING = False # Make sure we use port 6383 db 2 redis for tests. That's db 2 of the # redis test config. That shouldn't collide with anything else. REDIS_BACKENDS = { 'default': 'redis://localhost:6383?socket_timeout=0.5&db=2', 'karma': 'redis://localhost:6383?socket_timeout=0.5&db=2', 'helpfulvotes': 'redis://localhost:6383?socket_timeout=0.5&db=2', } # Use fake webtrends settings. WEBTRENDS_PROFILE_ID = 'ABC123'
Use assert module for assertion
const assert = require('assert') const path = require('path') const Config = require('./models/config') const util = require('./util') function loadConfig (configPath) { const options = {} const base = options.base = path.dirname(configPath) const config = loadConfigFile(configPath) assert(config.taskFile, '"taskFile" must be specified in config file.') if (config.preset) { const presetPath = resolvePresetPath(config.preset, base) options.preset = loadConfig(presetPath) } const tasks = require(path.resolve(base, config.taskFile)) return new Config(config, tasks, options) } module.exports = loadConfig function loadConfigFile (configPath) { const ext = path.extname(configPath) assert( ext === '.js' || ext === '.json', path.basename(configPath) + ' is non-supported file format.' ) return require(path.resolve(configPath)) } function resolvePresetPath (preset, base) { if (!util.isLocalPath(preset)) { return require.resolve(preset) } return require.resolve(path.resolve(base, preset)) }
const assert = require('assert') const path = require('path') const Config = require('./models/config') const util = require('./util') function loadConfig (configPath) { const options = {} const base = options.base = path.dirname(configPath) const config = loadConfigFile(configPath) assert(config.taskFile, '"taskFile" must be specified in config file.') if (config.preset) { const presetPath = resolvePresetPath(config.preset, base) options.preset = loadConfig(presetPath) } const tasks = require(path.resolve(base, config.taskFile)) return new Config(config, tasks, options) } module.exports = loadConfig function loadConfigFile (configPath) { const ext = path.extname(configPath) if (ext !== '.js' && ext !== '.json') { throw new Error(path.basename(configPath) + ' is non-supported file format.') } return require(path.resolve(configPath)) } function resolvePresetPath (preset, base) { if (!util.isLocalPath(preset)) { return require.resolve(preset) } return require.resolve(path.resolve(base, preset)) }
Use UserPicture in contributors panel
import React from 'react'; import {creatorAttribute} from './util/ContributorsUtil'; import {contains} from './util/ContributorsUtil'; import UserPicture from '../../../common/UserPicture'; class ContributorItem extends React.Component { render() { return ( <div className="item"> <div className="image"> <UserPicture picture={ this.props.data.picture } username={ this.props.data.username } link={ false } private={ true } height={30} width={ 30 } centered={ true } size={ 'mini' }/> </div> <div className="content inline-div"> <div className="header"> <a href={'/user/' + this.props.data.id}>{this.props.data.username}</a> </div> <div className="description">{this.props.data.organization}</div> </div> </div> ); } } export default ContributorItem;
import React from 'react'; import {creatorAttribute} from './util/ContributorsUtil'; import {avatarPath} from './util/ContributorsUtil'; import {contains} from './util/ContributorsUtil'; class ContributorItem extends React.Component { render() { return ( <div className="item"> {/*<a className="avatar inline-div padding15"> {(this.props.data.username !== '') ? <img src={avatarPath(this.props.data.avatar)} height={30} width={30}></img> : <i className="ui icon user" />} </a>*/} <div className="content inline-div"> <div className="header"> <a href={'/user/' + this.props.data.id}>{this.props.data.username}</a> </div> <div className="description">{this.props.data.organization}</div> </div> </div> ); } } export default ContributorItem;
Increment the Java debugger minor version to 2.7 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=138825830
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.cdbg.debuglets.java; /** * Defines the version of the Java Cloud Debugger agent. */ public final class GcpDebugletVersion { /** * Major version of the debugger. * All agents of the same major version are compatible with each other. In other words an * application can mix different agents with the same major version within the same debuggee. */ public static final int MAJOR_VERSION = 2; /** * Minor version of the agent. */ public static final int MINOR_VERSION = 7; /** * Debugger agent version string in the format of MAJOR.MINOR. */ public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION); /** * Main function to print the version string. */ public static void main(String[] args) { System.out.println(VERSION); } }
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.cdbg.debuglets.java; /** * Defines the version of the Java Cloud Debugger agent. */ public final class GcpDebugletVersion { /** * Major version of the debugger. * All agents of the same major version are compatible with each other. In other words an * application can mix different agents with the same major version within the same debuggee. */ public static final int MAJOR_VERSION = 2; /** * Minor version of the agent. */ public static final int MINOR_VERSION = 6; /** * Debugger agent version string in the format of MAJOR.MINOR. */ public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION); /** * Main function to print the version string. */ public static void main(String[] args) { System.out.println(VERSION); } }
Revert last commit, to avoid vulnerabilities
<?php namespace App\Libs; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use App\Libs\ViewResolver; use Illuminate\Http\Request; abstract class Controller extends BaseController{ use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct(Request $request,ViewResolver $viewResolver){ $this->request = $request; $this->view = $viewResolver; if(app()->isInstalled()){ foreach(app()->plugins as $plugin){ foreach($plugin->getRegister('injectJs',[]) as $js){ $this->view->data['jsplugins'][] = $plugin->getPath().'/'.$js; } } } } public function redirect($location){ return redirect($location); } public function redirectToSelf(){ return redirect()->back(); } public function insideLink($location){ return redirect(\Config::get('horizontcms.backend_prefix')."/".$location); } }
<?php namespace App\Libs; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use App\Libs\ViewResolver; use Illuminate\Http\Request; abstract class Controller extends BaseController{ use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct(Request $request,ViewResolver $viewResolver){ $this->request = $request; $this->view = $viewResolver; if(app()->isInstalled()){ foreach(app()->plugins as $plugin){ foreach($plugin->getRegister('injectJs',[]) as $js){ $this->view->data['jsplugins'][] = str_contains($js,"http")? $js : $plugin->getPath().'/'.$js; } } } } public function redirect($location){ return redirect($location); } public function redirectToSelf(){ return redirect()->back(); } public function insideLink($location){ return redirect(\Config::get('horizontcms.backend_prefix')."/".$location); } }
Update regex and point to Jira
(() => { const $title = document.querySelector('.js-issue-title'); if (!$title) { return; } chrome.storage.local.get('inlineLinks', (options) => { let title = $title.innerHTML.replace(/(<a[^>]+>|⬆︎|<\/a>)/g, ''); // TODO: Bring back multiple matches for the new format // TODO: Format settings in options page? (Also, domain option?) let matches = title.match(/^\s*(\w+-\d+):?/); if (matches) { let tag = matches[1]; const url = `https://buildout.atlassian.net/browse/${tag}`; const attrs = `href="${url}" target="_blank"`; const replacement = options.inlineLinks === false ? `${tag}<a ${attrs}>⬆︎</a>` : `<a ${attrs}>${tag}</a>`; title = title.replace(tag, replacement); } $title.innerHTML = title; }); })();
(() => { const $title = document.querySelector('.js-issue-title'); if (!$title) { return; } chrome.storage.local.get('inlineLinks', (options) => { let title = $title.innerHTML.replace(/(<a[^>]+>|⬆︎|<\/a>)/g, ''); title.match(/[a-zA-Z0-9-]+(?=[\],\s\d#]*\])/g).forEach((tag) => { const url = `https://nextcapital.atlassian.net/browse/${tag}`; const attrs = `href="${url}" target="_blank"`; const replacement = options.inlineLinks === false ? `${tag}<a ${attrs}>⬆︎</a>` : `<a ${attrs}>${tag}</a>`; title = title.replace(tag, replacement); }); $title.innerHTML = title; }); })();
Add the .query() method to the Nock noop
/** * Copyright (c) 2015 IBM Cloudant, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ function noop() { return this; } function nock_noop() { // Return a completely inert nock-compatible object. return {head:noop, get:noop, post:noop, put:noop, 'delete':noop, reply:noop, filteringPath:noop, done:noop, query:noop}; } if (process.env.NOCK_OFF) { var nock = nock_noop; } else { var nock = require('nock'); } module.exports = nock;
/** * Copyright (c) 2015 IBM Cloudant, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ function noop() { return this; } function nock_noop() { // Return a completely inert nock-compatible object. return {head:noop, get:noop, post:noop, put:noop, 'delete':noop, reply:noop, filteringPath:noop, done:noop}; } if (process.env.NOCK_OFF) { var nock = nock_noop; } else { var nock = require('nock'); } module.exports = nock;
TEST: Reduce waiting time before retrying to click yes/no option
'use strict'; var util = require('util'); var common = require('../modules/common-functions'); exports.command = function(fields, value, callback) { var client = this; this.perform(function() { var attemptedOnce = false; function clickOption(field, value) { var el = util.format('input[name="%s"][value="%s"]', field, value); client.isVisible(el, function(result) { if(result.value === true) { client.click(el, function() { console.log(' • Setting ‘' + field + '’' + ' to ‘' + common.humaniseValue(value) + '’'); }); // Take into account transitions if element happens to be invisible straight away } else if(!attemptedOnce) { client.pause(200, function() { clickOption(field, value); attemptedOnce = true; }); } }); } if(fields.constructor === Array) { fields.forEach(function(field) { clickOption(field, value); }); } else { clickOption(fields, value); } }); if (typeof callback === 'function') { callback.call(client); } return client; };
'use strict'; var util = require('util'); var common = require('../modules/common-functions'); exports.command = function(fields, value, callback) { var client = this; this.perform(function() { var attemptedOnce = false; function clickOption(field, value) { var el = util.format('input[name="%s"][value="%s"]', field, value); client.isVisible(el, function(result) { if(result.value === true) { client.click(el, function() { console.log(' • Setting ‘' + field + '’' + ' to ‘' + common.humaniseValue(value) + '’'); }); // Take into account transitions if element happens to be invisible straight away } else if(!attemptedOnce) { client.pause(1000, function() { clickOption(field, value); attemptedOnce = true; }); } }); } if(fields.constructor === Array) { fields.forEach(function(field) { clickOption(field, value); }); } else { clickOption(fields, value); } }); if (typeof callback === 'function') { callback.call(client); } return client; };
Update the classifier for all the tested versions of python
from distutils.core import setup from setuptools import find_packages with open('README.md') as fp: long_description = fp.read() setup( name='sendwithus', version='1.6.6', author='sendwithus', author_email='us@sendwithus.com', packages=find_packages(), scripts=[], url='https://github.com/sendwithus/sendwithus_python', license='LICENSE.txt', description='Python API client for sendwithus.com', long_description=long_description, test_suite="sendwithus.test", install_requires=[ "requests >= 1.1.0", "six >= 1.9.0" ], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "License :: OSI Approved :: Apache Software License", "Development Status :: 5 - Production/Stable", "Topic :: Communications :: Email" ] )
from distutils.core import setup from setuptools import find_packages with open('README.md') as fp: long_description = fp.read() setup( name='sendwithus', version='1.6.6', author='sendwithus', author_email='us@sendwithus.com', packages=find_packages(), scripts=[], url='https://github.com/sendwithus/sendwithus_python', license='LICENSE.txt', description='Python API client for sendwithus.com', long_description=long_description, test_suite="sendwithus.test", install_requires=[ "requests >= 1.1.0", "six >= 1.9.0" ], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "License :: OSI Approved :: Apache Software License", "Development Status :: 5 - Production/Stable", "Topic :: Communications :: Email" ] )
Improve logic checking for `options.dest.root`
import { deepCollection } from './object'; // TODO NOPE import { resourcePath } from './shared'; import path from 'path'; import { pathSatisfies, is } from 'ramda'; function getBaseUrl (resource, drizzleData) { const options = drizzleData.options; const destRoot = options.dest.root; const destResource = options.dest[ Object.keys(options.keys).find( key => options.keys[key].singular === resource.resourceType ) ]; const baseurl = path.relative( path.dirname(resourcePath(resource.id, destResource)), destRoot ); return baseurl === '' ? `.${baseurl}` : baseurl; } function resourceContext (resource, drizzleData) { const context = Object.assign({}, resource); context.drizzle = drizzleData; if (pathSatisfies(is(String), ['dest', 'root'], drizzleData.options)) { context.baseurl = getBaseUrl(resource, drizzleData); } if (typeof resource.data === 'object') { Object.keys(resource.data).map(dataKey => context[dataKey] = resource.data[dataKey]); delete context.data; } return context; } /** */ function patternContext (pattern, drizzleData) { const context = resourceContext(pattern, drizzleData); // Get the collection for this pattern and add a reference to it context.collection = deepCollection(pattern.id, drizzleData.patterns); return context; } export { patternContext, resourceContext };
import { deepCollection } from './object'; // TODO NOPE import { resourcePath } from './shared'; import path from 'path'; function getBaseUrl (resource, drizzleData) { const options = drizzleData.options; const destRoot = options.dest.root; const destResource = options.dest[ Object.keys(options.keys).find( key => options.keys[key].singular === resource.resourceType ) ]; const baseurl = path.relative( path.dirname(resourcePath(resource.id, destResource)), destRoot ); return baseurl === '' ? `.${baseurl}` : baseurl; } function resourceContext (resource, drizzleData) { const context = Object.assign({}, resource); context.drizzle = drizzleData; if (drizzleData.options.dest) { context.baseurl = getBaseUrl(resource, drizzleData); } if (typeof resource.data === 'object') { Object.keys(resource.data).map(dataKey => context[dataKey] = resource.data[dataKey]); delete context.data; } return context; } /** */ function patternContext (pattern, drizzleData) { const context = resourceContext(pattern, drizzleData); // Get the collection for this pattern and add a reference to it context.collection = deepCollection(pattern.id, drizzleData.patterns); return context; } export { patternContext, resourceContext };
Change deprecated method for changing moment's locale Signed-off-by: Felipe Milani <6def120dcec8fcb28aed4723fac713cfff66d853@gmail.com>
// client entry point, imports all client code import { Meteor } from 'meteor/meteor'; import { render } from 'react-dom'; import { i18n } from 'meteor/universe:i18n'; import moment from 'moment'; // FIXME: importing this moment locale is causing a warning on browser's console // without this import, setting moment's locale doesn't work import 'moment/locale/pt-br'; import injectTapEventPlugin from 'react-tap-event-plugin'; import renderRoutes from '../imports/startup/client/routes.jsx'; Meteor.startup(() => { injectTapEventPlugin(); // for now, only pt-BR supported moment.updateLocale('pt-br', { calendar: { sameDay: '[Hoje]', nextDay: '[Amanhã]', nextWeek: 'ddd, DD [de] MMMM', lastDay: '[Ontem]', lastWeek: 'ddd, DD [de] MMMM', sameElse: 'ddd, DD [de] MMMM', }, }); i18n.setLocale('pt-BR'); // subscribe to how many reports the user has sent Meteor.subscribe('user.reportsSentCounter'); // wait for locale to be loaded to render the app i18n.onceChangeLocale(() => { Meteor.subscribe('user.settings', { // wait for user settings to be available. we need it to decide if we // redirect the user to settings page onReady() { render(renderRoutes(), document.getElementById('app')); }, }); }); });
// client entry point, imports all client code import { Meteor } from 'meteor/meteor'; import { render } from 'react-dom'; import { i18n } from 'meteor/universe:i18n'; import moment from 'moment'; // FIXME: importing this moment locale is causing a warning on browser's console // without this import, setting moment's locale doesn't work import 'moment/locale/pt-br'; import injectTapEventPlugin from 'react-tap-event-plugin'; import renderRoutes from '../imports/startup/client/routes.jsx'; Meteor.startup(() => { injectTapEventPlugin(); // for now, only pt-BR supported moment.locale('pt-br', { calendar: { sameDay: '[Hoje]', nextDay: '[Amanhã]', nextWeek: 'ddd, DD [de] MMMM', lastDay: '[Ontem]', lastWeek: 'ddd, DD [de] MMMM', sameElse: 'ddd, DD [de] MMMM', }, }); i18n.setLocale('pt-BR'); // subscribe to how many reports the user has sent Meteor.subscribe('user.reportsSentCounter'); // wait for locale to be loaded to render the app i18n.onceChangeLocale(() => { Meteor.subscribe('user.settings', { // wait for user settings to be available. we need it to decide if we // redirect the user to settings page onReady() { render(renderRoutes(), document.getElementById('app')); }, }); }); });
Reduce precision of floats in JSON Due to a https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue Fixes #161
<?php ini_set( 'serialize_precision', -1 ); // https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue require_once ('mysql.php'); $benchID = $_GET["bench"]; $format = $_GET["format"]; $latitude = $_GET["latitude"]; $longitude = $_GET["longitude"]; $radius = $_GET["radius"]; if (null != $latitude && null != $longitude && null != $radius) { $geojson = get_nearest_benches($latitude, $longitude, $radius); } else if (null != $benchID){ $geojson = get_bench($benchID); } else { $geojson = get_all_benches(); } if ("raw" == $format) { header('Content-Type: application/json; charset=utf-8'); echo json_encode($geojson, JSON_NUMERIC_CHECK); } else { header('Content-type: text/javascript; charset=utf-8'); echo "var benches = " . json_encode($geojson, JSON_NUMERIC_CHECK); } die();
<?php require_once ('mysql.php'); $benchID = $_GET["bench"]; $format = $_GET["format"]; $latitude = $_GET["latitude"]; $longitude = $_GET["longitude"]; $radius = $_GET["radius"]; if (null != $latitude && null != $longitude && null != $radius) { $geojson = get_nearest_benches($latitude, $longitude, $radius); } else if (null != $benchID){ $geojson = get_bench($benchID); } else { $geojson = get_all_benches(); } if ("raw" == $format) { header('Content-Type: application/json; charset=utf-8'); echo json_encode($geojson, JSON_NUMERIC_CHECK); } else { header('Content-type: text/javascript; charset=utf-8'); echo "var benches = " . json_encode($geojson, JSON_NUMERIC_CHECK); } die();
Set moderated false after editing
<?php namespace AppBundle\EventListener; use AppBundle\Event\AddUserEditEvent; use AppBundle\Model\UserManageableInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Doctrine\ORM\EntityManager; use AppBundle\Entity\Item; /** * Class AddUserEditListener * * @package AppBundle\Entity */ class AddUserEditListener { /** * @var EntityManager $entityManager */ private $entityManager; /** * @param EntityManager $em */ public function __construct(EntityManager $em) { $this->entityManager = $em; } /** * @param AddUserEditEvent $args * * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException */ public function onItemEdit(AddUserEditEvent $args) { $tokenStorage = $args->getTokenStorage(); $item = $args->getItem(); if ($item instanceof UserManageableInterface) { $user = $tokenStorage->getToken()->getUser(); $item->setCreatedBy($user); } $item->setModerated(false); } }
<?php namespace AppBundle\EventListener; use AppBundle\Event\AddUserEditEvent; use AppBundle\Model\UserManageableInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Doctrine\ORM\EntityManager; use AppBundle\Entity\Item; /** * Class AddUserEditListener * * @package AppBundle\Entity */ class AddUserEditListener { /** * @var EntityManager $entityManager */ private $entityManager; /** * @param EntityManager $em */ public function __construct(EntityManager $em) { $this->entityManager = $em; } /** * @param AddUserEditEvent $args * * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException */ public function onItemEdit(AddUserEditEvent $args) { $tokenStorage = $args->getTokenStorage(); $item = $args->getItem(); if ($item instanceof UserManageableInterface) { $user = $tokenStorage->getToken()->getUser(); $item->setCreatedBy($user); } } }
Support returning a promise from the transition handler so we can support delayed transitions
export const executeTransition = history => transitionData => { if (transitionData) { const method = transitionData.replace ? 'replace' : 'push'; history[method](transitionData); } }; export default (history, catchAllHandler) => next => (reducer, initialState) => { const store = next(reducer, initialState); const finalExecuteTransition = executeTransition(history); return { ...store, dispatch(action) { const { meta } = action; const transitionMetaFunc = meta ? (meta.transition || catchAllHandler) : catchAllHandler; const prevState = transitionMetaFunc && store.getState(); store.dispatch(action); const nextState = transitionMetaFunc && store.getState(); const transitionData = transitionMetaFunc && ( transitionMetaFunc(prevState, nextState, action) ); if (transitionData) { if (typeof transitionData.then === 'function') { transitionData .then(finalExecuteTransition) .catch(finalExecuteTransition); } else { finalExecuteTransition(transitionData); } } return action; }, }; };
export default (history, catchAllHandler) => { return next => (reducer, initialState) => { const store = next(reducer, initialState); return { ...store, dispatch(action) { const { type, meta } = action; const transitionMetaFunc = meta ? (meta.transition || catchAllHandler) : catchAllHandler; const prevState = transitionMetaFunc && store.getState(); store.dispatch(action); const nextState = transitionMetaFunc && store.getState(); let transitionData = transitionMetaFunc && ( transitionMetaFunc(prevState, nextState, action) ); if (transitionData) { const method = transitionData.replace ? 'replace' : 'push'; history[method](transitionData); } return action; } }; }; }
Trim whitespace on extracted role ARNs
package saml2aws import ( "fmt" "strings" ) // AWSRole aws role attributes type AWSRole struct { RoleARN string PrincipalARN string Name string } // ParseAWSRoles parses and splits the roles while also validating the contents func ParseAWSRoles(roles []string) ([]*AWSRole, error) { awsRoles := make([]*AWSRole, len(roles)) for i, role := range roles { awsRole, err := parseRole(role) if err != nil { return nil, err } awsRoles[i] = awsRole } return awsRoles, nil } func parseRole(role string) (*AWSRole, error) { tokens := strings.Split(role, ",") if len(tokens) != 2 { return nil, fmt.Errorf("Invalid role string only %d tokens", len(tokens)) } awsRole := &AWSRole{} for _, token := range tokens { if strings.Contains(token, ":saml-provider") { awsRole.PrincipalARN = strings.TrimSpace(token) } if strings.Contains(token, ":role") { awsRole.RoleARN = strings.TrimSpace(token) } } if awsRole.PrincipalARN == "" { return nil, fmt.Errorf("Unable to locate PrincipalARN in: %s", role) } if awsRole.RoleARN == "" { return nil, fmt.Errorf("Unable to locate RoleARN in: %s", role) } return awsRole, nil }
package saml2aws import ( "fmt" "strings" ) // AWSRole aws role attributes type AWSRole struct { RoleARN string PrincipalARN string Name string } // ParseAWSRoles parses and splits the roles while also validating the contents func ParseAWSRoles(roles []string) ([]*AWSRole, error) { awsRoles := make([]*AWSRole, len(roles)) for i, role := range roles { awsRole, err := parseRole(role) if err != nil { return nil, err } awsRoles[i] = awsRole } return awsRoles, nil } func parseRole(role string) (*AWSRole, error) { tokens := strings.Split(role, ",") if len(tokens) != 2 { return nil, fmt.Errorf("Invalid role string only %d tokens", len(tokens)) } awsRole := &AWSRole{} for _, token := range tokens { if strings.Contains(token, ":saml-provider") { awsRole.PrincipalARN = token } if strings.Contains(token, ":role") { awsRole.RoleARN = token } } if awsRole.PrincipalARN == "" { return nil, fmt.Errorf("Unable to locate PrincipalARN in: %s", role) } if awsRole.RoleARN == "" { return nil, fmt.Errorf("Unable to locate RoleARN in: %s", role) } return awsRole, nil }
Test average speed calculation by tracking sum and count separately
#!/usr/bin/python import sys import json # Count average speeds for links def main(locationdata_dictionary_file): locationdata = {} with open(locationdata_dictionary_file, "r") as dictionary_file: locationdata = json.load(dictionary_file) for input_line in sys.stdin: data = json.loads(input_line) for recognition in data['recognitions']: try: link_data = (item for item in locationdata['links'] if item['id'] == recognition['id']).next() average_speed = (link_data['dist'] / recognition['tt']) * 3.6 print "LongValueSum:" + str(recognition['id']) + "_speedsum\t" + str(int(average_speed)) print "LongValueSum:" + str(recognition['id']) + "_speedcount\t1" except: pass if __name__ == "__main__": main(sys.argv[1])
#!/usr/bin/python import sys import json # Count average speeds for links def main(locationdata_dictionary_file): locationdata = {} with open(locationdata_dictionary_file, "r") as dictionary_file: locationdata = json.load(dictionary_file) for input_line in sys.stdin: data = json.loads(input_line) for recognition in data['recognitions']: try: link_data = (item for item in locationdata['links'] if item['id'] == recognition['id']).next() average_speed = (link_data['dist'] / recognition['tt']) * 3.6 print "CountAverage: " + str(recognition['id']) + "\t" + str(int(average_speed)) except: pass if __name__ == "__main__": main(sys.argv[1])
Fix for LazyModel infinite recursion
class LazyModel(object): """ It's a helper class that is used in case you have model_class and object primary key. You might need to use only object id. If you try to access other fields of the model class then we will query the database to get that object and provide you with any field and method transparently proxying them. """ def __init__(self, model_class, pk): self._model_class = model_class self.pk = pk self._instance = None def __getattribute__(self, attr_name): # Hiding traces of decoration. if attr_name in ('__init__', '__getattribute__', '_model_class', 'pk', '_instance'): # Stopping recursion. return object.__getattribute__(self, attr_name) # All other attr_names, including auto-defined by system in self, are # searched in decorated self.instance, e.g.: __module__, __class__, etc. if self._instance is None: self._instance = self._model_class.objects.get(pk=self.pk) # Raises correct AttributeError if name is not found in decorated self.func. return getattr(self._instance, attr_name)
class LazyModel(object): """ It's a helper class that is used in case you have model_class and object primary key. You might need to use only object id. If you try to access other fields of the model class then we will query the database to get that object and provide you with any field and method transparently proxying them. """ def __init__(self, model_class, pk): self._model_class = model_class self.pk = pk self._instance = None def __getattribute__(self, attr_name): # Hiding traces of decoration. if attr_name in ('__init__', '__getattribute__', '_model_class', 'pk', '_instance'): # Stopping recursion. return object.__getattribute__(self, attr_name) # All other attr_names, including auto-defined by system in self, are # searched in decorated self.instance, e.g.: __module__, __class__, etc. if self._instance is None: self._instance = self._model_class.objects.get(pk=self.pk) # Raises correct AttributeError if name is not found in decorated self.func. return getattr(self.instance, attr_name)
Update requirements for correct mysql-connector name
from setuptools import setup datafiles = [('/etc', ['general_conf/bck.conf'])] setup( name='mysql-autoxtrabackup', version='1.1', packages=['general_conf', 'backup_prepare', 'partial_recovery', 'master_backup_script'], py_modules = ['autoxtrabackup'], url='https://github.com/ShahriyarR/MySQL-AutoXtraBackup', license='GPL', author='Shahriyar Rzayev', author_email='rzayev.shahriyar@yandex.com', description='Commandline tool written in Python 3 for using Percona Xtrabackup', install_requires=[ 'click>=3.3', 'mysql-connector>=2.0.2', ], dependency_links = ['https://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-2.1.3.tar.gz'], entry_points=''' [console_scripts] autoxtrabackup=autoxtrabackup:all_procedure ''', data_files = datafiles, )
from setuptools import setup datafiles = [('/etc', ['general_conf/bck.conf'])] setup( name='mysql-autoxtrabackup', version='1.1', packages=['general_conf', 'backup_prepare', 'partial_recovery', 'master_backup_script'], py_modules = ['autoxtrabackup'], url='https://github.com/ShahriyarR/MySQL-AutoXtraBackup', license='GPL', author='Shahriyar Rzayev', author_email='rzayev.shahriyar@yandex.com', description='Commandline tool written in Python 3 for using Percona Xtrabackup', install_requires=[ 'click>=3.3', 'mysql-connector-python>=2.0.2', ], dependency_links = ['https://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-2.1.3.tar.gz'], entry_points=''' [console_scripts] autoxtrabackup=autoxtrabackup:all_procedure ''', data_files = datafiles, )
Add script to reports views
<?php class show extends Controller { function __construct() { if( ! $this->authorized()) { redirect('auth/login'); } } function index() { $data = array(); $obj = new View(); $obj->view('dashboard/dashboard', $data); } function listing($which = '') { if($which) { $data['page'] = 'clients'; $data['scripts'] = array("clients/client_list.js"); $view = 'listing/'.$which; } else { $data = array('status_code' => 404); $view = 'error/client_error'; } $obj = new View(); $obj->view($view, $data); } function reports($which = 'default') { if($which) { $data['page'] = 'clients'; $data['scripts'] = array("clients/client_list.js"); $view = 'report/'.$which; } else { $data = array('status_code' => 404); $view = 'error/client_error'; } $obj = new View(); $obj->view($view, $data); } }
<?php class show extends Controller { function __construct() { if( ! $this->authorized()) { redirect('auth/login'); } } function index() { $data = array(); $obj = new View(); $obj->view('dashboard/dashboard', $data); } function listing($which = '') { if($which) { $data['page'] = 'clients'; $data['scripts'] = array("clients/client_list.js"); $view = 'listing/'.$which; } else { $data = array('status_code' => 404); $view = 'error/client_error'; } $obj = new View(); $obj->view($view, $data); } function reports($which = 'default') { if($which) { $data['page'] = 'clients'; $view = 'report/'.$which; } else { $data = array('status_code' => 404); $view = 'error/client_error'; } $obj = new View(); $obj->view($view, $data); } }
Add html plugin to production config
var webpack = require('webpack'); var loaders = require('./webpack.loaders'); var autoprefixer = require('autoprefixer'); var path = require('path'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var outpath = path.join(__dirname, "..", "app") var node_modules = path.join(outpath, "node_modules") module.exports = { target: "electron", entry: { app: `./src/client/index.jsx` }, output: { path: outpath, filename: '[name].bundle.js', sourceMapFilename: '[name].bundle.map' }, resolve: { extensions: ['', '.js', '.jsx', '.css', '.scss', '.sass', '.json'], root: node_modules }, module: { loaders: loaders }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new HtmlWebpackPlugin({ template: path.join(__dirname, '..', 'src', 'index.html') }) ], postcss: function () { return [autoprefixer]; } };
var webpack = require('webpack'); var loaders = require('./webpack.loaders'); var autoprefixer = require('autoprefixer'); var path = require('path'); var outpath = path.join(__dirname, "..", "app") var node_modules = path.join(outpath, "node_modules") module.exports = { target: "electron", entry: { app: `./src/client/index.jsx` }, output: { path: outpath, filename: '[name].bundle.js', sourceMapFilename: '[name].bundle.map' }, resolve: { extensions: ['', '.js', '.jsx', '.css', '.scss', '.sass', '.json'], root: node_modules }, module: { loaders: loaders }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }) ], postcss: function () { return [autoprefixer]; } };
Fix whitespace issue in matrix assertion
import unittest from matrix import Matrix class MatrixTest(unittest.TestCase): def test_extract_a_row(self): matrix = Matrix("1 2\n10 20") self.assertEqual([1, 2], matrix.rows[0]) def test_extract_same_row_again(self): matrix = Matrix("9 7\n8 6") self.assertEqual([9, 7], matrix.rows[0]) def test_extract_other_row(self): matrix = Matrix("9 8 7\n19 18 17") self.assertEqual([19, 18, 17], matrix.rows[1]) def test_extract_other_row_again(self): matrix = Matrix("1 4 9\n16 25 36") self.assertEqual([16, 25, 36], matrix.rows[1]) def test_extract_a_column(self): matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n8 7 6") self.assertEqual([1, 4, 7, 8], matrix.columns[0]) def test_extract_another_column(self): matrix = Matrix("89 1903 3\n18 3 1\n9 4 800") self.assertEqual([1903, 3, 4], matrix.columns[1]) if __name__ == '__main__': unittest.main()
import unittest from matrix import Matrix class MatrixTest(unittest.TestCase): def test_extract_a_row(self): matrix = Matrix("1 2\n10 20") self.assertEqual([1, 2], matrix.rows[0]) def test_extract_same_row_again(self): matrix = Matrix("9 7\n8 6") self.assertEqual([9, 7], matrix.rows[0]) def test_extract_other_row(self): matrix = Matrix("9 8 7\n19 18 17") self.assertEqual([19, 18, 17], matrix.rows[1]) def test_extract_other_row_again(self): matrix = Matrix("1 4 9\n16 25 36") self.assertEqual([16, 25, 36], matrix.rows[1]) def test_extract_a_column(self): matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n 8 7 6") self.assertEqual([1, 4, 7, 8], matrix.columns[0]) def test_extract_another_column(self): matrix = Matrix("89 1903 3\n18 3 1\n9 4 800") self.assertEqual([1903, 3, 4], matrix.columns[1]) if __name__ == '__main__': unittest.main()
Set development status to stable.
#!/usr/bin/env python from setuptools import setup from setuputils import find_version, read setup( name='astor', version=find_version('astor/__init__.py'), description='Read/rewrite/write Python ASTs', long_description=read('README.rst'), author='Patrick Maupin', author_email='pmaupin@gmail.com', platforms="Independent", url='https://github.com/pmaupin/astor.git', packages=['astor'], py_modules=['setuputils'], license="BSD", classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Code Generators', 'Topic :: Software Development :: Compilers', ], keywords='ast', )
#!/usr/bin/env python from setuptools import setup from setuputils import find_version, read setup( name='astor', version=find_version('astor/__init__.py'), description='Read/rewrite/write Python ASTs', long_description=read('README.rst'), author='Patrick Maupin', author_email='pmaupin@gmail.com', platforms="Independent", url='https://github.com/pmaupin/astor.git', packages=['astor'], py_modules=['setuputils'], license="BSD", classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Code Generators', 'Topic :: Software Development :: Compilers', ], keywords='ast', )
Stop getting videos every time script starts
import os from death_extractor import youtube as yt from death_extractor import set_interval from death_extractor import extract_and_upload def death_as_a_service(vid_path = 'vids', post_interval=3600*2, search_interval=3600*6, dl_interval=3600*3, max_downloads=4, to_imgur=True, to_tumblr=True): """Run periodic search/download/extract_and_upload operations""" print "Fetching new videos and consolidating queue..." yt.populate_queue() if len([file for file in os.listdir(vid_path) if not file.endswith('part') and not file.startswith('.')]) < 4: print "Downloading up to",max_downloads,"videos..." yt.dl(max_downloads) extract_and_upload(vid_path, to_imgur, to_tumblr) if search_interval: search_timer = set_interval(search_interval, yt.populate_queue) if dl_interval: dl_timer = set_interval(dl_interval, yt.dl, max_downloads) if post_interval: post_timer = set_interval(post_interval, extract_and_upload, vid_path, to_imgur, to_tumblr) if __name__ == '__main__': print "Running from console..." death_as_a_service()
from death_extractor import youtube as yt from death_extractor import set_interval from death_extractor import extract_and_upload def death_as_a_service(vid_path = 'vids', post_interval=3600*2, search_interval=3600*12, dl_interval=3600*6, max_downloads=5, to_imgur=True, to_tumblr=True): """Run periodic search/download/extract_and_upload operations""" #print "Fetching new videos and consolidating queue..." #yt.populate_queue() #print "Downloading up to",max_downloads,"videos..." #yt.dl(max_downloads) extract_and_upload(vid_path, to_imgur, to_tumblr) if search_interval: search_timer = set_interval(search_interval, yt.populate_queue) if dl_interval: dl_timer = set_interval(dl_interval, yt.dl, max_downloads) if post_interval: post_timer = set_interval(post_interval, extract_and_upload, vid_path, to_imgur, to_tumblr) if __name__ == '__main__': print "Running from console..." death_as_a_service()
Fix desktop version for crash in situation when no parameters are given.
package com.letscode.lcg; import java.util.Random; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; public class Main { public static void main(String[] args) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); String hostname = args.length > 0 ? args[0] : "localhost"; int port = args.length > 1 ? Integer.parseInt(args[1]) : 80; String nickname = args.length > 2 ? args[2] : null;//"Player " + (new Random().nextInt(12415124)); final String gameTitle = "Lambda Cipher Genesis"; cfg.title = nickname != null ? gameTitle + " - " + nickname : gameTitle; cfg.useGL20 = false; cfg.width = 1024; cfg.height = 600; new LwjglApplication(new LcgApp(hostname, port, nickname), cfg); } }
package com.letscode.lcg; import java.util.Random; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; public class Main { public static void main(String[] args) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); String hostname = args.length > 0 ? args[0] : "localhost"; int port = args.length > 1 ? Integer.parseInt(args[1]) : 80; String nickname = args.length > 2 ? args[2] : "Player " + (new Random().nextInt(12415124)); cfg.title = "Lambda Cipher Genesis - " + nickname; cfg.useGL20 = false; { cfg.width = 1024; cfg.height = 600; } new LwjglApplication(new LcgApp(hostname, port, nickname), cfg); } }
Update aiohttp version constraint to <3.5
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages __name__ == '__main__' and setup(name='aiohttp-json-rpc', version='0.11.1', author='Florian Scherf', url='https://github.com/pengutronix/aiohttp-json-rpc/', author_email='f.scherf@pengutronix.de', license='Apache 2.0', install_requires=['aiohttp>=3,<3.5'], python_requires='>=3.5', packages=find_packages(), zip_safe=False, entry_points={ 'pytest11': [ 'aiohttp-json-rpc = aiohttp_json_rpc.pytest', ] })
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages __name__ == '__main__' and setup(name='aiohttp-json-rpc', version='0.11.1', author='Florian Scherf', url='https://github.com/pengutronix/aiohttp-json-rpc/', author_email='f.scherf@pengutronix.de', license='Apache 2.0', install_requires=['aiohttp>=3,<3.4'], python_requires='>=3.5', packages=find_packages(), zip_safe=False, entry_points={ 'pytest11': [ 'aiohttp-json-rpc = aiohttp_json_rpc.pytest', ] })
Refactor some duplicate code into a checkSyntax function which isn't as noisy
<?php require_once('tests/php/base.php'); class SyntaxTests extends UnitTestCase { public function checkSyntax($file) { $output = exec("php -l $file", $array, $code); $this->assertTrue($code == 0, $output); } public function testFrameworkSyntax() { $test_files = glob("{framework/php/cashmusic.php,framework/php/*/*.php,framework/php/classes/*/*.php}", GLOB_BRACE); foreach ($test_files as $file){ $this->checkSyntax($file); } } public function testInstallerSyntax() { $test_files = glob("installers/php/*.php"); foreach ($test_files as $file){ $this->checkSyntax($file); } } public function testInterfaceSyntax() { $test_files = glob("{interfaces/php/*/*.php,interfaces/php/*/*/*.php,interfaces/php/*/*/*/*.php,interfaces/php/*/*/*/*/*.php}", GLOB_BRACE); foreach ($test_files as $file){ $this->checkSyntax($file); } } } ?>
<?php require_once('tests/php/base.php'); class SyntaxTests extends UnitTestCase { public function testFrameworkSyntax() { $test_files = glob("{framework/php/cashmusic.php,framework/php/*/*.php,framework/php/classes/*/*.php}", GLOB_BRACE); foreach ($test_files as $file){ system("php -l $file", $code); $this->assertTrue($code == 0); } } public function testInstallerSyntax() { $test_files = glob("installers/php/*.php"); foreach ($test_files as $file){ system("php -l $file", $code); $this->assertTrue($code == 0); } } public function testInterfaceSyntax() { $test_files = glob("{interfaces/php/*/*.php,interfaces/php/*/*/*.php,interfaces/php/*/*/*/*.php,interfaces/php/*/*/*/*/*.php}", GLOB_BRACE); foreach ($test_files as $file){ system("php -l $file", $code); $this->assertTrue($code == 0); } } } ?>
Fix bad dialect : mysql -> postgres
module.exports = { development: { username: "cyrilcanete", password: null, database: "cyrilcanete", host: "localhost", port: "5432", dialect: "postgres", }, test: { username: "root", password: null, database: "database_test", host: "127.0.0.1", dialect: "postgres", }, production: { url: process.env.DATABASE_URL || null, username: process.env.DATABASE_USER || "root", password: process.env.DATABASE_PASSWORD || null, database: process.env.DATABASE_NAME || "root", host: process.env.DATABASE_HOST || "localhost", port: process.env.DATABASE_PORT || "5432", dialect: "postgres", }, };
module.exports = { development: { username: "cyrilcanete", password: null, database: "cyrilcanete", host: "localhost", port: "5432", dialect: "postgres", }, test: { username: "root", password: null, database: "database_test", host: "127.0.0.1", dialect: "mysql", }, production: { url: process.env.DATABASE_URL || null, username: process.env.DATABASE_USER || "root", password: process.env.DATABASE_PASSWORD || null, database: process.env.DATABASE_NAME || "root", host: process.env.DATABASE_HOST || "localhost", port: process.env.DATABASE_PORT || "5432", dialect: "postgres", }, };
Add success message to clear-compiled command
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; class ClearCompiledCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'clear-compiled'; /** * The console command description. * * @var string */ protected $description = 'Remove the compiled class file'; /** * Execute the console command. * * @return void */ public function fire() { $compiledPath = $this->laravel->getCachedCompilePath(); $servicesPath = $this->laravel->getCachedServicesPath(); if (file_exists($compiledPath)) { @unlink($compiledPath); } if (file_exists($servicesPath)) { @unlink($servicesPath); } $this->info('Compiled class file removed!'); } }
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; class ClearCompiledCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'clear-compiled'; /** * The console command description. * * @var string */ protected $description = 'Remove the compiled class file'; /** * Execute the console command. * * @return void */ public function fire() { $compiledPath = $this->laravel->getCachedCompilePath(); $servicesPath = $this->laravel->getCachedServicesPath(); if (file_exists($compiledPath)) { @unlink($compiledPath); } if (file_exists($servicesPath)) { @unlink($servicesPath); } } }
Document that the test:features Gulp task also supports tags.
// Use the gulp-help plugin which defines a default gulp task // which lists what tasks are available. var gulp = require('gulp-help')(require('gulp')); // Sequential Gulp tasks var runSequence = require('run-sequence').use(gulp); var cucumber = require('gulp-cucumber'); // Parse any command line arguments ignoring // Node and the name of the calling script. // Extract tag arguments. var argv = require('minimist')(process.argv.slice(2)); var tags = argv.tags || false; // Run all the Cucumber features, doesn't start server // Hidden from gulp-help. gulp.task('cucumber', 'Run Cucumber directly without starting the server.', function() { var options = { support: 'features-support/**/*.js', // Tags are optional, falsey values are ignored. tags: tags } return gulp.src('features/**/*.feature').pipe(cucumber(options)); }, { options: {'tags': 'Supports optional tags argument e.g.\n\t\t\t--tags @parsing\n\t\t\t--tags @tag1,orTag2\n\t\t\t--tags @tag1 --tags @andTag2\n\t\t\t--tags @tag1 --tags ~@andNotTag2'} }); // Default Cucumber run requires server to be running. gulp.task('test:features', 'Test the features.', function(done) { runSequence('set-envs:test', 'server:start', 'cucumber', 'server:stop', done); }, { options: {'tags': 'Supports same optional tags arguments as \'Cucumber\' task.'} });
// Use the gulp-help plugin which defines a default gulp task // which lists what tasks are available. var gulp = require('gulp-help')(require('gulp')); // Sequential Gulp tasks var runSequence = require('run-sequence').use(gulp); var cucumber = require('gulp-cucumber'); // Parse any command line arguments ignoring // Node and the name of the calling script. // Extract tag arguments. var argv = require('minimist')(process.argv.slice(2)); var tags = argv.tags || false; // Run all the Cucumber features, doesn't start server // Hidden from gulp-help. gulp.task('cucumber', 'Run Cucumber directly without starting the server.', function() { var options = { support: 'features-support/**/*.js', // Tags are optional, falsey values are ignored. tags: tags } return gulp.src('features/**/*.feature').pipe(cucumber(options)); }, { options: {'tags': 'Supports optional tags argument e.g.\n\t\t\t--tags @parsing\n\t\t\t--tags @tag1,orTag2\n\t\t\t--tags @tag1 --tags @andTag2\n\t\t\t--tags @tag1 --tags ~@andNotTag2'} }); // Default Cucumber run requires server to be running. gulp.task('test:features', 'Test the features.', function(done) { runSequence('set-envs:test', 'server:start', 'cucumber', 'server:stop', done); });
Fix emptying empty deploymentBucket bug
'use strict'; const BbPromise = require('bluebird'); module.exports = { emptyDeploymentBucket() { return BbPromise.bind(this) .then(this.getObjectsToRemove) .then(this.removeObjects); }, getObjectsToRemove() { const params = { bucket: this.serverless.service.provider.deploymentBucketName, }; return this.provider.request('storage', 'objects', 'list', params) .then((response) => { if (!response.items || !response.items.length) return BbPromise.resolve([]); return BbPromise.resolve(response.items); }); }, removeObjects(objectsToRemove) { if (!objectsToRemove.length) return BbPromise.resolve(); this.serverless.cli.log('Removing artifacts in deployment bucket...'); const removePromises = []; objectsToRemove.forEach((object) => { const params = { bucket: object.bucket, object: encodeURIComponent(object.name), }; const request = this.provider.request('storage', 'objects', 'delete', params); removePromises.push(request); }); return BbPromise.all(removePromises); }, };
'use strict'; const BbPromise = require('bluebird'); module.exports = { emptyDeploymentBucket() { return BbPromise.bind(this) .then(this.getObjectsToRemove) .then(this.removeObjects); }, getObjectsToRemove() { const params = { bucket: this.serverless.service.provider.deploymentBucketName, }; return this.provider.request('storage', 'objects', 'list', params) .then((response) => { if (!response.items.length) return BbPromise.resolve([]); return BbPromise.resolve(response.items); }); }, removeObjects(objectsToRemove) { if (!objectsToRemove.length) return BbPromise.resolve(); this.serverless.cli.log('Removing artifacts in deployment bucket...'); const removePromises = []; objectsToRemove.forEach((object) => { const params = { bucket: object.bucket, object: encodeURIComponent(object.name), }; const request = this.provider.request('storage', 'objects', 'delete', params); removePromises.push(request); }); return BbPromise.all(removePromises); }, };
Format and update the secure ping url
angular.module('sample.home', [ 'auth0' ]) .controller('HomeCtrl', function HomeController($scope, auth, $http, $location, store) { $scope.auth = auth; $scope.callApi = function() { // Just call the API as you'd do using $http $http({ url: '/secured/ping', method: 'GET' }).then(function() { alert("We got the secured data successfully"); }, function(response) { if (response.status == -1) { alert("Please download the API seed so that you can call it."); } else { alert(response.data); } }); } $scope.logout = function() { auth.signout(); store.remove('profile'); store.remove('token'); $location.path('/login'); } });
angular.module( 'sample.home', [ 'auth0' ]) .controller( 'HomeCtrl', function HomeController( $scope, auth, $http, $location, store ) { $scope.auth = auth; $scope.callApi = function() { // Just call the API as you'd do using $http $http({ url: 'http://localhost:3001/secured/ping', method: 'GET' }).then(function() { alert("We got the secured data successfully"); }, function(response) { if (response.status == -1) { alert("Please download the API seed so that you can call it."); } else { alert(response.data); } }); } $scope.logout = function() { auth.signout(); store.remove('profile'); store.remove('token'); $location.path('/login'); } });
Remove unneeded shebang line that was triggering some linters.
# Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def destdir_join(d1, d2): # c:\destdir + c:\prefix must produce c:\destdir\prefix if len(d1) > 1 and d1[1] == ':' and \ len(d2) > 1 and d2[1] == ':': return d1 + d2[2:] return d1 + d2
#!/usr/bin/env python3 # Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def destdir_join(d1, d2): # c:\destdir + c:\prefix must produce c:\destdir\prefix if len(d1) > 1 and d1[1] == ':' and \ len(d2) > 1 and d2[1] == ':': return d1 + d2[2:] return d1 + d2
Add integration test for recording service form
(function() { window.shared || (window.shared = {}); var Simulate = React.addons.TestUtils.Simulate; /* Sugar for common test setup and interactions */ var SpecSugar = window.shared.SpecSugar = { withTestEl: function(description, testsFn) { return describe(description, function() { beforeEach(function() { this.testEl = $('<div id="test-el" />').get(0); $('body').append(this.testEl); }); afterEach(function() { $(this.testEl).remove(); }); testsFn.call(this); }); }, // Update the text value of an input or textarea, and simulate the React // change event. changeTextValue: function($el, value) { $el.val(value); Simulate.change($el.get(0)); return undefined; }, // Simulates opening the react-select dropdown and clicking the item // with `optionText`. changeReactSelect: function($selectEl, optionText) { React.addons.TestUtils.Simulate.mouseDown($selectEl.find('.Select-arrow-zone').get(0)); React.addons.TestUtils.Simulate.focus($selectEl.find('input:last').get(0)); $selectEl.find('.Select-option:contains(' + optionText + ')').click() return undefined; } }; })();
(function() { window.shared || (window.shared = {}); var Simulate = React.addons.TestUtils.Simulate; /* Sugar for common test setup and interactions */ var SpecSugar = window.shared.SpecSugar = { withTestEl: function(description, testsFn) { return describe(description, function() { beforeEach(function() { this.testEl = $('<div id="test-el" />').get(0); $('body').append(this.testEl); }); afterEach(function() { $(this.testEl).remove(); }); testsFn.call(this); }); }, // Update the text value of an input or textarea, and simulate the React // change event. changeTextValue: function($el, value) { $el.val(value); Simulate.change($el.get(0)); return undefined; }, // Simulates opening the react-select dropdown and clicking the item // with `optionText`. changeReactSelect: function($el, optionText) { React.addons.TestUtils.Simulate.mouseDown($selectEl.find('.Select-arrow-zone').get(0)); React.addons.TestUtils.Simulate.focus($selectEl.find('input:last').get(0)); $selectEl.find('.Select-option:contains(' + optionText + ')').click() return undefined; } }; })();
Set the fork-join pool globally to prevent DOS-vulnerability
package voot.oauth; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.stream.Collectors; import com.google.common.base.Preconditions; import voot.oauth.valueobject.Group; public class ExternalGroupsQuerier { private final List<GroupClient> groupClients; private final ForkJoinPool forkJoinPool; public ExternalGroupsQuerier(List<GroupClient> groupClients) { Preconditions.checkArgument(groupClients.size() > 0, "No clients configured"); this.groupClients = groupClients; forkJoinPool = new ForkJoinPool(groupClients.size() * 20); // we're I/O bound. } public List<Group> getMyGroups(String uid, String schacHomeOrganization) { try { return forkJoinPool.submit(() -> this.groupClients.parallelStream() .filter(client -> client.isAuthorative(schacHomeOrganization)) .map(client -> client.getMemberships(uid, schacHomeOrganization)) .flatMap(Collection::stream) .collect(Collectors.toList())).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Unable to schedule querying of external group providers.", e); } } }
package voot.oauth; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.stream.Collectors; import com.google.common.base.Preconditions; import voot.oauth.valueobject.Group; public class ExternalGroupsQuerier { private final List<GroupClient> groupClients; public ExternalGroupsQuerier(List<GroupClient> groupClients) { Preconditions.checkArgument(groupClients.size() > 0, "No clients configured"); this.groupClients = groupClients; } public List<Group> getMyGroups(String uid, String schacHomeOrganization) { // we're I/O bound and groupClients.size() will be < 5 ForkJoinPool forkJoinPool = new ForkJoinPool(groupClients.size()); try { return forkJoinPool.submit(() -> this.groupClients.parallelStream() .filter(client -> client.isAuthorative(schacHomeOrganization)) .map(client -> client.getMemberships(uid, schacHomeOrganization)) .flatMap(Collection::stream) .collect(Collectors.toList())).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Unable to schedule querying of external group providers.", e); } } }
Add error listener to test
var patch = require("../lib/patch") , net = require("net") , https = require("https") , fs = require("fs"); // This is probably THE most ugliest code I've ever written var responseRegExp = /^([0-9a-z-]{36}) (.*)$/i; var host = net.createServer(function(socket) { var i = 0; socket.setEncoding("utf8"); socket.on("data", function(data) { switch(i) { case 0: socket.write("SUCCESS"); break; default: socket.write(data.match(responseRegExp)[1] + " " + JSON.stringify({ peername: { address: "peer-address", port: 1234 }, sockname: { address: "sock-address", port: 1234 } })); } i++; }); }).listen(0).address().port; var ssl = { cert: fs.readFileSync(__dirname + "/ssl/cert.pem"), key: fs.readFileSync(__dirname + "/ssl/key.pem") }; // The utlimate test: HTTPS (and therefore SPDY too) var server = https.createServer(ssl, function(req, res) { console.log(req.socket.remoteAddress + ":" + req.socket.remotePort); res.end("Fuck yeah!"); }).on("error", console.log); patch(host, server, true).listen("address");
var patch = require("../lib/patch") , net = require("net") , https = require("https") , fs = require("fs"); // This is probably THE most ugliest code I've ever written var responseRegExp = /^([0-9a-z-]{36}) (.*)$/i; var host = net.createServer(function(socket) { var i = 0; socket.setEncoding("utf8"); socket.on("data", function(data) { switch(i) { case 0: socket.write("SUCCESS"); break; default: socket.write(data.match(responseRegExp)[1] + " " + JSON.stringify({ peername: { address: "peer-address", port: 1234 }, sockname: { address: "sock-address", port: 1234 } })); } i++; }); }).listen(0).address().port; var ssl = { cert: fs.readFileSync(__dirname + "/ssl/cert.pem"), key: fs.readFileSync(__dirname + "/ssl/key.pem") }; // The utlimate test: HTTPS (and therefore SPDY too) var server = https.createServer(ssl, function(req, res) { console.log(req.socket.remoteAddress + ":" + req.socket.remotePort); res.end("Fuck yeah!"); }); patch(host, server, true).listen("address");
Reduce the size of log_name so it fits within mysql's limit.
from database import db from conversions import datetime_from_str class LogEntry(db.Model): id = db.Column(db.Integer, primary_key=True) timestamp = db.Column(db.DateTime, index=True) server = db.Column(db.String(100), index=True) log_name = db.Column(db.String(255), index=True) message = db.Column(db.Text(), nullable=True) def __init__(self, timestamp, server, log_name, message): self.timestamp = datetime_from_str(timestamp) self.server = server self.log_name = log_name self.message = message def to_dict(self): return { 'timestamp': self.timestamp, 'server': self.server, 'log_name': self.log_name, 'message': self.message, }
from database import db from conversions import datetime_from_str class LogEntry(db.Model): id = db.Column(db.Integer, primary_key=True) timestamp = db.Column(db.DateTime, index=True) server = db.Column(db.String(100), index=True) log_name = db.Column(db.String(760), index=True) message = db.Column(db.Text(), nullable=True) def __init__(self, timestamp, server, log_name, message): self.timestamp = datetime_from_str(timestamp) self.server = server self.log_name = log_name self.message = message def to_dict(self): return { 'timestamp': self.timestamp, 'server': self.server, 'log_name': self.log_name, 'message': self.message, }
Convert HashSet to LinkedHashSet to maintain FindCommand keyword sequence
package seedu.tache.logic.parser; import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.tache.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Matcher; import seedu.tache.logic.commands.Command; import seedu.tache.logic.commands.FindCommand; import seedu.tache.logic.commands.IncorrectCommand; /** * Parses input arguments and creates a new FindCommand object */ public class FindCommandParser { /** * Parses the given {@code String} of arguments in the context of the FindCommand * and returns an FindCommand object for execution. */ public Command parse(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } //@@author A0139925U // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new LinkedHashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } }
package seedu.tache.logic.parser; import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.tache.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import seedu.tache.logic.commands.Command; import seedu.tache.logic.commands.FindCommand; import seedu.tache.logic.commands.IncorrectCommand; /** * Parses input arguments and creates a new FindCommand object */ public class FindCommandParser { /** * Parses the given {@code String} of arguments in the context of the FindCommand * and returns an FindCommand object for execution. */ public Command parse(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } //@@author A0139925U // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } }
Bump requests from 2.5.1 to 2.20.0 Bumps [requests](https://github.com/requests/requests) from 2.5.1 to 2.20.0. - [Release notes](https://github.com/requests/requests/releases) - [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md) - [Commits](https://github.com/requests/requests/compare/v2.5.1...v2.20.0) Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@github.com>
#!/usr/bin/env python from setuptools import setup setup( name='Scrapper', version='0.9.5', url='https://github.com/Alkemic/scrapper', license='MIT', author='Daniel Alkemic Czuba', author_email='alkemic7@gmail.com', description='Scrapper is small, Python web scraping library', py_modules=['scrapper'], keywords='scrapper,scraping,webscraping', install_requires=[ 'lxml == 3.6.1', 'requests == 2.20.0', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Indexing/Search', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
#!/usr/bin/env python from setuptools import setup setup( name='Scrapper', version='0.9.5', url='https://github.com/Alkemic/scrapper', license='MIT', author='Daniel Alkemic Czuba', author_email='alkemic7@gmail.com', description='Scrapper is small, Python web scraping library', py_modules=['scrapper'], keywords='scrapper,scraping,webscraping', install_requires=[ 'lxml == 3.6.1', 'requests == 2.5.1', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Indexing/Search', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Test dependencies: On Python 2.5, require Jinja 2.6
#! /usr/bin/python import platform import subprocess import sys def _execute(*args, **kwargs): result = subprocess.call(*args, **kwargs) if result != 0: sys.exit(result) if __name__ == '__main__': python_version = platform.python_version() deps = [ "execnet", "nose", "sqlalchemy", ] if python_version < "2.6": deps.extend([ "ssl", "multiprocessing", "pyzmq==2.1.11", "simplejson", ]) else: deps.extend([ "pyzmq", ]) # Jinja2 is a bit fragmented... if python_version < "3.3": deps.append("Jinja2==2.6") else: deps.append("Jinja2") if python_version < "2.7": deps.append("unittest2") print("Setting up dependencies...") _execute("pip install %s" % " ".join(deps), shell=True)
#! /usr/bin/python import platform import subprocess import sys def _execute(*args, **kwargs): result = subprocess.call(*args, **kwargs) if result != 0: sys.exit(result) if __name__ == '__main__': python_version = platform.python_version() deps = [ "execnet", "Jinja2", "nose", ] if python_version < "2.6": deps.extend([ "ssl", "multiprocessing", "pyzmq==2.1.11", "sqlalchemy", "simplejson", ]) else: deps.append("sqlalchemy") deps.append("pyzmq") if python_version < "2.7": deps.append("unittest2") print("Setting up dependencies...") _execute("pip install %s" % " ".join(deps), shell=True)
Check ReportWriter makes parent directories.
package com.googlecode.jslint4java.maven; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.io.File; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.googlecode.jslint4java.formatter.JSLintResultFormatter; import com.googlecode.jslint4java.formatter.JSLintXmlFormatter; public class ReportWriterTest { @Rule public TemporaryFolder tmpf = new TemporaryFolder(); private final JSLintResultFormatter formatter = new JSLintXmlFormatter(); private ReportWriter createReportWriter(String filename) { return new ReportWriter(new File(tmpf.getRoot(), filename), formatter); } @Test public void createsNonEmptyFile() { ReportWriter rw = createReportWriter("report.xml"); rw.open(); rw.close(); assertThat(rw.getReportFile().exists(), is(true)); assertThat(rw.getReportFile().length(), is(not(0L))); } @Test public void makesParentDirectory() { File parent = new File(tmpf.getRoot(), "somedir"); ReportWriter rw = new ReportWriter(new File(parent, "report.xml"), formatter); rw.open(); rw.close(); assertThat(parent.exists(), is(true)); } }
package com.googlecode.jslint4java.maven; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.io.File; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.googlecode.jslint4java.formatter.JSLintResultFormatter; import com.googlecode.jslint4java.formatter.JSLintXmlFormatter; public class ReportWriterTest { @Rule public TemporaryFolder tmpf = new TemporaryFolder(); private final JSLintResultFormatter formatter = new JSLintXmlFormatter(); private ReportWriter createReportWriter(String filename) { return new ReportWriter(new File(tmpf.getRoot(), filename), formatter); } @Test public void createsNonEmptyFile() { ReportWriter rw = createReportWriter("report.xml"); rw.open(); rw.close(); assertThat(rw.getReportFile().exists(), is(true)); assertThat(rw.getReportFile().length(), is(not(0L))); } }
Fix name of AnimationController unit test.
/*global defineSuite*/ defineSuite([ 'Core/AnimationController', 'Core/Clock' ], function( AnimationController, Clock) { "use strict"; /*global it,expect*/ it('construct with default clock', function() { var clock = new Clock(); var animationController = new AnimationController(clock); expect(animationController.clock).toEqual(clock); }); it('play, pause, playReverse, and reset affect isAnimating', function() { var clock = new Clock(); var animationController = new AnimationController(clock); expect(animationController.isAnimating()).toEqual(true); animationController.pause(); expect(animationController.isAnimating()).toEqual(false); animationController.play(); expect(animationController.isAnimating()).toEqual(true); animationController.playReverse(); expect(animationController.isAnimating()).toEqual(true); animationController.reset(); expect(animationController.isAnimating()).toEqual(false); }); });
/*global defineSuite*/ defineSuite([ 'Core/Clock', 'Core/AnimationController' ], function( Clock, AnimationController) { "use strict"; /*global it,expect*/ it('construct with default clock', function() { var clock = new Clock(); var animationController = new AnimationController(clock); expect(animationController.clock).toEqual(clock); }); it('play, pause, playReverse, and reset affect isAnimating', function() { var clock = new Clock(); var animationController = new AnimationController(clock); expect(animationController.isAnimating()).toEqual(true); animationController.pause(); expect(animationController.isAnimating()).toEqual(false); animationController.play(); expect(animationController.isAnimating()).toEqual(true); animationController.playReverse(); expect(animationController.isAnimating()).toEqual(true); animationController.reset(); expect(animationController.isAnimating()).toEqual(false); }); });
Add `ValueWasNil` test message function
package testhelpers import "fmt" const ( // ERROR MESSAGEs - Used as first argument in Error() call EM_NEED_ERR = "Should have gotten an error, but didn't" EM_UN_ERR = "Unexpected Error" // ERROR STRINGS - embed in // Could use a VAR block, fmt and %8s, but this is just as easy ES_EXPECTED = "\nexpected:" ES_GOT = "\n actual:" ES_ARGS = "\n args:" ES_SQL = "\n sql:" ES_ERR = "\n err:" ES_VALUE = "\n value:" ES_COUNT = "\n count:" ) // Supply expected and actual values and a pretty formatted string will be returned that can be passed into t.Error() func NotEqualMsg(expected, actual interface{}) string { return fmt.Sprintln(ES_EXPECTED, expected, ES_GOT, actual) } func ValueWasNil(expected interface{}) string { return NotEqualMsg(expected, "(nil)") } // Same as NotEqualMsg, except that the type names will be printed instead func TypeNotEqualMsg(expected, actual interface{}) string { eType := TypeName(expected) aType := TypeName(actual) return fmt.Sprintln(ES_EXPECTED, eType, ES_GOT, aType) } func UnexpectedErrMsg(err string) string { return fmt.Sprintln(EM_UN_ERR, ES_ERR, err) }
package testhelpers import "fmt" const ( // ERROR MESSAGEs - Used as first argument in Error() call EM_NEED_ERR = "Should have gotten an error, but didn't" EM_UN_ERR = "Unexpected Error" // ERROR STRINGS - embed in // Could use a VAR block, fmt and %8s, but this is just as easy ES_EXPECTED = "\nexpected:" ES_GOT = "\n actual:" ES_ARGS = "\n args:" ES_SQL = "\n sql:" ES_ERR = "\n err:" ES_VALUE = "\n value:" ES_COUNT = "\n count:" ) // Supply expected and actual values and a pretty formatted string will be returned that can be passed into t.Error() func NotEqualMsg(expected, actual interface{}) string { return fmt.Sprintln(ES_EXPECTED, expected, ES_GOT, actual) } // Same as NotEqualMsg, except that the type names will be printed instead func TypeNotEqualMsg(expected, actual interface{}) string { eType := TypeName(expected) aType := TypeName(actual) return fmt.Sprintln(ES_EXPECTED, eType, ES_GOT, aType) } func UnexpectedErrMsg(err string) string { return fmt.Sprintln(EM_UN_ERR, ES_ERR, err) }
Set additional fields when mapping inputs and outputs This will reduce the risk of unnecessary lazy fetching
from sevenbridges.models.file import File def map_input_output(item, api): """ Maps item to appropriate sevebridges object. :param item: Input/Output value. :param api: Api instance. :return: Mapped object. """ if isinstance(item, list): return [map_input_output(it, api) for it in item] elif isinstance(item, dict) and 'class' in item: if item['class'].lower() in ('file', 'directory'): _secondary_files = [] for _file in item.get('secondaryFiles', []): _secondary_files.append({'id': _file['path']}) data = { 'id': item['path'] } data.update({k: item[k] for k in item if k != 'path'}) if _secondary_files: data.update({ '_secondary_files': _secondary_files, 'fetched': True }) return File(api=api, **data) else: return item
from sevenbridges.models.file import File def map_input_output(item, api): """ Maps item to appropriate sevebridges object. :param item: Input/Output value. :param api: Api instance. :return: Mapped object. """ if isinstance(item, list): return [map_input_output(it, api) for it in item] elif isinstance(item, dict) and 'class' in item: if item['class'].lower() in ('file', 'directory'): _secondary_files = [] for _file in item.get('secondaryFiles', []): _secondary_files.append({'id': _file['path']}) data = { 'id': item['path'] } if _secondary_files: data.update({ '_secondary_files': _secondary_files, 'fetched': True }) return File(api=api, **data) else: return item
Remove "The Ranch" full title; Trakt search shows it first now
'use strict'; /* This was necessary to priorize Star Wars: The Clone Wars (2008) over Star Wars: Clone Wars (2003). I left this object because it could be useful for other movies/shows */ var fullTitles = { 'Star Wars: The Clone Wars': '"Star Wars: The Clone Wars"', 'The Office (U.S.)': 'The Office (US)', 'The Blind Side': '"The Blind Side"', 'The Avengers': '"The Avengers"', 'The Seven Deadly Sins': '"The Seven Deadly Sins"', 'Young and Hungry': '"Young and Hungry"', 'The 100': '"The 100"' } function Item(options) { this.title = fullTitles[options.title] || options.title; this.type = options.type; if (this.type === 'show') { this.epTitle = options.epTitle; this.season = options.season; this.episode = options.episode; } } module.exports = Item;
'use strict'; /* This was necessary to priorize Star Wars: The Clone Wars (2008) over Star Wars: Clone Wars (2003). I left this object because it could be useful for other movies/shows */ var fullTitles = { 'Star Wars: The Clone Wars': '"Star Wars: The Clone Wars"', 'The Office (U.S.)': 'The Office (US)', 'The Blind Side': '"The Blind Side"', 'The Avengers': '"The Avengers"', 'The Seven Deadly Sins': '"The Seven Deadly Sins"', 'Young and Hungry': '"Young and Hungry"', 'The 100': '"The 100"', 'The Ranch': 'The Ranch football player' } function Item(options) { this.title = fullTitles[options.title] || options.title; this.type = options.type; if (this.type === 'show') { this.epTitle = options.epTitle; this.season = options.season; this.episode = options.episode; } } module.exports = Item;
Revert "Revert "Cleans up split_response"" This reverts commit c3c62feb9fbd8b7ff35d70eaaa5fecfb2093dbb0.
from motobot import command, Notice, split_response, IRCBot from collections import defaultdict def filter_plugins(plugins, userlevel): return map( lambda plugin: (plugin.arg.trigger, plugin.func), filter( lambda plugin: plugin.type == IRCBot.command_plugin and plugin.level <= userlevel and not plugin.arg.hidden, plugins ) ) def format_group(group): return '({})'.format(', '.join(group)) if len(group) != 1 else group[0] @command('commands') def commands_command(bot, database, context, message, args): userlevel = bot.get_userlevel(context.channel, context.nick) groups = defaultdict(lambda: []) for command, func in filter_plugins(bot.plugins, userlevel): groups[func].append(command) commands = map(format_group, sorted(groups.values(), key=lambda x: x[0])) response = split_response(commands, "Bot Commands: {};") return response, Notice(context.nick)
from motobot import command, Notice, split_response, IRCBot @command('commands') def commands_command(bot, database, context, message, args): userlevel = bot.get_userlevel(context.channel, context.nick) valid_command = lambda plugin: plugin.type == IRCBot.command_plugin \ and plugin.level <= userlevel and not plugin.arg.hidden key = lambda plugin: (plugin.arg.trigger, plugin.func) command_groups = {} for command, func in map(key, filter(valid_command, bot.plugins)): value = command_groups.get(func, []) value.append(command) command_groups[func] = value format_group = lambda group: '({})'.format(', '.join(group)) \ if len(group) != 1 else group[0] commands = map(format_group, sorted(command_groups.values(), key=lambda x: x[0])) response = split_response(commands, "Bot Commands: {};") return response, Notice(context.nick)
Add note to spendingHabits to check if date picker works
import React, { Component } from 'react'; import moment from 'moment'; import Input from './Input'; export default class SpendingHabits extends Component { constructor() { super(); this.state = { date: '', } } updateDate(value) { this.setState({ date: value }) } getCurrentExpenses(dailyExpensesList) { let currentArray = dailyExpensesList.filter(data => moment(data.date).isSame(moment(this.state.date), 'day')); return currentArray.map(data => <li className='list-items' key={data.key}> {data.category}:<span className='daily-costs'> ${data.cost} </span>{ moment(data.date).format('LT')} </li>) } render() { return( <aside className='date-picker'> <Input type='date' value={ this.state.date } handle={ this.updateDate.bind(this)} /> <ul className='past-daily-expenses-list'> { this.getCurrentExpenses(this.props.dailyExpensesList) } </ul> </aside> ) } } //converter for date to milliseconds to test if date input works // http://www.epochconverter.com
import React, { Component } from 'react'; import moment from 'moment'; import Input from './Input'; export default class SpendingHabits extends Component { constructor() { super(); this.state = { date: '', } } updateDate(value) { this.setState({ date: value }) } getCurrentExpenses(dailyExpensesList) { let currentArray = dailyExpensesList.filter(data => moment(data.date).isSame(moment(this.state.date), 'day')); return currentArray.map(data => <li className='list-items' key={data.key}> {data.category}:<span className='daily-costs'> ${data.cost} </span>{ moment(data.date).format('LT')} </li>) } render() { return( <aside className='date-picker'> <Input type='date' value={ this.state.date } handle={ this.updateDate.bind(this)} /> <ul className='past-daily-expenses-list'> { this.getCurrentExpenses(this.props.dailyExpensesList) } </ul> </aside> ) } }
Make karma pick up only PhantomJS when on Travis CI
module.exports = function(config) { var browsers = process.env.TRAVIS ? [ 'PhantomJS' ] : [ 'PhantomJS', 'Chrome', 'Firefox', 'Safari' ]; config.set({ frameworks: [ 'hydro' ], singleRun: true, browsers: browsers, files: [ 'test/*.js' ], hydro: { before: [ 'build/build.js', ] }, client: { hydro: { setup: true, suite: 'hydro-require', plugins: [ 'hydro-require' ], proxies: { test: 'addTest' }, require: { 'assert': 'simple-assert' }, } }, }); };
module.exports = function(config) { config.set({ frameworks: [ 'hydro' ], singleRun: true, browsers: [ 'PhantomJS', 'Chrome', 'Firefox', 'Safari' ], files: [ 'test/*.js' ], hydro: { before: [ 'build/build.js', ] }, client: { hydro: { setup: true, suite: 'hydro-require', plugins: [ 'hydro-require' ], proxies: { test: 'addTest' }, require: { 'assert': 'simple-assert' }, } }, }); };
Remove template callback from template as it does not exist
/* Has access to the following protected methods $config(NAME): Retrieves the template config named NAME $forms(NAME): Retrieves the forms templates config named NAME (Shortcut for $config("forms")[NAME]) $views(NAME): Retrieves the views templates config named NAME (Shortcut for $config("views")[NAME]) $render(TEMPLATE, DTO): Renders the TEMPLATE using DTO data $renderList(TEMPLATE, Array[DTO]): Renders TEMPLATE using DTO data for each DTO in Array $renderListWithAction(Array[DTO], FUNCTION) Calls a specified render function for each DTO in Array. It is important that the specified action return a string value! */ $.ku4webApp.template("NAME", { //METHODS GO HERE METHOD: function() { } });
/* Has access to the following protected methods $config(NAME): Retrieves the template config named NAME $forms(NAME): Retrieves the forms templates config named NAME (Shortcut for $config("forms")[NAME]) $views(NAME): Retrieves the views templates config named NAME (Shortcut for $config("views")[NAME]) $render(TEMPLATE, DTO): Renders the TEMPLATE using DTO data $renderList(TEMPLATE, Array[DTO]): Renders TEMPLATE using DTO data for each DTO in Array $renderListWithAction(Array[DTO], FUNCTION) Calls a specified render function for each DTO in Array. It is important that the specified action return a string value! */ $.ku4webApp.template("NAME", { //METHODS GO HERE METHOD: function() { }, CALLBACK: function() { } });
Use no protocol to fetch Lato font When using https://example.com, the welcome page design looks off due to fetching the Lato font on http://. Ref: https://github.com/laravel/framework/issues/7159 Better yet, instead of https:// or http://, //
<html> <head> <link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'> <style> body { margin: 0; padding: 0; width: 100%; height: 100%; color: #B0BEC5; display: table; font-weight: 100; font-family: 'Lato'; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 96px; margin-bottom: 40px; } .quote { font-size: 24px; } </style> </head> <body> <div class="container"> <div class="content"> <div class="title">Laravel 5</div> <div class="quote">{{ Inspiring::quote() }}</div> </div> </div> </body> </html>
<html> <head> <link href='http://fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'> <style> body { margin: 0; padding: 0; width: 100%; height: 100%; color: #B0BEC5; display: table; font-weight: 100; font-family: 'Lato'; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 96px; margin-bottom: 40px; } .quote { font-size: 24px; } </style> </head> <body> <div class="container"> <div class="content"> <div class="title">Laravel 5</div> <div class="quote">{{ Inspiring::quote() }}</div> </div> </div> </body> </html>
Add file source and subjectID to processing exceptions
import pandas import typing def process_files(file_iterator: typing.Iterator[typing.IO], processor: typing.Callable) -> pandas.DataFrame: def get_frames(): for file in file_iterator: source = getattr(file, 'name', None) subject_id = getattr(file, 'cpgintegrate_subject_id', None) try: df = processor(file) except Exception as e: raise ProcessingException({"Source": source, 'SubjectID': subject_id}) from e yield (df .assign(Source=getattr(file, 'name', None), SubjectID=getattr(file, 'cpgintegrate_subject_id', None), FileSubjectID=df.index if df.index.name else None)) return pandas.DataFrame(pandas.concat((frame for frame in get_frames()))).set_index("SubjectID") class ProcessingException(Exception): """cpgintegrate processing error"""
import pandas import traceback import typing def process_files(file_iterator: typing.Iterator[typing.IO], processor: typing.Callable) -> pandas.DataFrame: def get_frames(): for file in file_iterator: df = processor(file) yield (df .assign(Source=getattr(file, 'name', None), SubjectID=getattr(file, 'cpgintegrate_subject_id', None), FileSubjectID=df.index if df.index.name else None)) return pandas.DataFrame(pandas.concat((frame for frame in get_frames()))).set_index("SubjectID")
Fix the issue generation for taster css
'use strict'; var argv = require('yargs').argv; var path = require('path'); var mainBowerFiles = require('main-bower-files'); module.exports = function(gulp, plugins, config, options) { return function() { options = options || { dest: true }; if (options.dest === undefined) { options.dest = true; } var dest = path.join(config.deployment.root, config.deployment.styles); return gulp.src(mainBowerFiles({ paths: config.componentRoot, filter: ['**/*.css'], overrides: config.bowerOverrides }), { base: './' }) .pipe(plugins.sass()) .pipe(plugins.if(argv.production, plugins.csso())) .pipe(plugins.flatten()) .pipe(plugins.if(options.dest, gulp.dest(dest))); }; };
'use strict'; var argv = require('yargs').argv; var path = require('path'); var mainBowerFiles = require('main-bower-files'); module.exports = function(gulp, plugins, config, options) { return function() { options = options || { dest: true }; if (options.dest === undefined) { options.dest = true; } var dest = path.join(config.deployment.root, config.deployment.styles); return gulp.src(mainBowerFiles({ paths: config.componentRoot, filter: '**/*.scss', overrides: config.bowerOverrides }), { base: './' }) .pipe(plugins.sass()) .pipe(plugins.if(argv.production, plugins.csso())) .pipe(plugins.flatten()) .pipe(plugins.if(options.dest, gulp.dest(dest))); }; };
Add property status in Prepare
class Prepare(object): """ Prepare the champions for the battle! Usage: hero = Prepare(name="Aragorn", base_attack=100, base_hp=100) or like this: aragorn = {"name": "Aragorn", "base_attack": 100, "base_hp": 100} hero = Prepare(**aragorn) """ def __init__(self, name, base_attack, base_hp): self.name = name self.base_attack = base_attack self.base_hp = base_hp @property def status(self): return self.__dict__ def attack(self, foe): if not isinstance(foe, Prepare): raise TypeError('foe should be a Prepare object') if foe.base_hp <= 0: raise Exception('foe is already dead! Stop hit him!') foe.base_hp = foe.base_hp - self.base_attack if foe.base_hp <= 0: print 'foe is dead.' return foe.base_hp
class Prepare(object): """ Prepare the champions for the battle! Usage: hero = Prepare(name="Aragorn", base_attack=100, base_hp=100) or like this: aragorn = {"name": "Aragorn", "base_attack": 100, "base_hp": 100} hero = Prepare(**aragorn) """ def __init__(self, name, base_attack, base_hp): self.name = name self.base_attack = base_attack self.base_hp = base_hp def attack(self, foe): if not isinstance(foe, Prepare): raise TypeError('foe should be a Prepare object') if foe.base_hp <= 0: raise Exception('foe is already dead! Stop hit him!') foe.base_hp = foe.base_hp - self.base_attack if foe.base_hp <= 0: print 'foe is dead.' return foe.base_hp
:art: Add a new line after variable declaration
'use strict'; const fs = require('fs'); class Storage { /** * Constructor * @param {string} file */ constructor(file) { this.data = null; this.file = file; } /** * Load the storage file */ load() { if (this.data !== null) { return; } if (!fs.existsSync(this.file)) { this.data = {}; return; } var json = fs.readFileSync(this.file, 'utf8'); if (json === '') { this.data = {}; return; } this.data = JSON.parse(json); } /** * Save the storage file */ save() { if (this.data !== null) { fs.writeFileSync(this.file, JSON.stringify(this.data), 'utf8'); } } /** * Set the value specified by key * @param {string} key * @param {*} value */ set(key, value) { this.load(); this.data[key] = value; this.save(); } /** * Get the value by key * @param {string} key * @returns {*} */ get(key) { let value = null; this.load(); if (key in this.data) { value = this.data[key]; } return value; } } module.exports = (path) => new Storage(path);
'use strict'; const fs = require('fs'); class Storage { /** * Constructor * @param {string} file */ constructor(file) { this.data = null; this.file = file; } /** * Load the storage file */ load() { if (this.data !== null) { return; } if (!fs.existsSync(this.file)) { this.data = {}; return; } var json = fs.readFileSync(this.file, 'utf8'); if (json === '') { this.data = {}; return; } this.data = JSON.parse(json); } /** * Save the storage file */ save() { if (this.data !== null) { fs.writeFileSync(this.file, JSON.stringify(this.data), 'utf8'); } } /** * Set the value specified by key * @param {string} key * @param {*} value */ set(key, value) { this.load(); this.data[key] = value; this.save(); } /** * Get the value by key * @param {string} key * @returns {*} */ get(key) { let value = null; this.load(); if (key in this.data) { value = this.data[key]; } return value; } } module.exports = (path) => new Storage(path);
Add option in snapshot generator to use renderer from options if passed
import renderer from 'react-test-renderer'; import shallow from 'react-test-renderer/shallow'; import 'jest-specific-snapshot'; import { getSnapshotFileName } from './utils'; function getRenderedTree(story, context, options) { const currentRenderer = options.renderer || renderer.create; const storyElement = story.render(context); return currentRenderer(storyElement, options).toJSON(); } export const snapshotWithOptions = options => ({ story, context }) => { const tree = getRenderedTree(story, context, options); expect(tree).toMatchSnapshot(); }; export const multiSnapshotWithOptions = options => ({ story, context }) => { const tree = getRenderedTree(story, context, options); const snapshotFileName = getSnapshotFileName(context); if (!snapshotFileName) { expect(tree).toMatchSnapshot(); return; } expect(tree).toMatchSpecificSnapshot(snapshotFileName); }; export const snapshot = snapshotWithOptions({}); export function shallowSnapshot({ story, context, options }) { const shallowRenderer = options.shallowRenderer || shallow.createRenderer(); const result = shallowRenderer.render(story.render(context)); expect(result).toMatchSnapshot(); } export function renderOnly({ story, context }) { const storyElement = story.render(context); renderer.create(storyElement); }
import renderer from 'react-test-renderer'; import shallow from 'react-test-renderer/shallow'; import 'jest-specific-snapshot'; import { getSnapshotFileName } from './utils'; function getRenderedTree(story, context, options) { const storyElement = story.render(context); return renderer.create(storyElement, options).toJSON(); } export const snapshotWithOptions = options => ({ story, context }) => { const tree = getRenderedTree(story, context, options); expect(tree).toMatchSnapshot(); }; export const multiSnapshotWithOptions = options => ({ story, context }) => { const tree = getRenderedTree(story, context, options); const snapshotFileName = getSnapshotFileName(context); if (!snapshotFileName) { expect(tree).toMatchSnapshot(); return; } expect(tree).toMatchSpecificSnapshot(snapshotFileName); }; export const snapshot = snapshotWithOptions({}); export function shallowSnapshot({ story, context }) { const shallowRenderer = shallow.createRenderer(); const result = shallowRenderer.render(story.render(context)); expect(result).toMatchSnapshot(); } export function renderOnly({ story, context }) { const storyElement = story.render(context); renderer.create(storyElement); }
Update to match new format for param.txt.
import unittest import cryptosite import saliweb.test import saliweb.backend import os class JobTests(saliweb.test.TestCase): """Check custom CryptoSite Job class""" def test_run_first_stepok(self): """Test successful run method, first step""" j = self.make_test_job(cryptosite.Job, 'RUNNING') fname = os.path.join(j.directory, 'param.txt') open(fname, 'w').write('testpdb\nA\n') cls = j._run_in_job_directory(j.run) self.assert_(isinstance(cls, saliweb.backend.SGERunner), "SGERunner not returned") if __name__ == '__main__': unittest.main()
import unittest import cryptosite import saliweb.test import saliweb.backend import os class JobTests(saliweb.test.TestCase): """Check custom CryptoSite Job class""" def test_run_first_stepok(self): """Test successful run method, first step""" j = self.make_test_job(cryptosite.Job, 'RUNNING') fname = os.path.join(j.directory, 'param.txt') open(fname, 'w').write('testjob\ntest@example.com\nA\n') cls = j._run_in_job_directory(j.run) self.assert_(isinstance(cls, saliweb.backend.SGERunner), "SGERunner not returned") if __name__ == '__main__': unittest.main()
Use program_name instead of script file name in macOS menu
''' Main runner entry point for Gooey. ''' import wx # wx.html and wx.xml imports required here to make packaging with # pyinstaller on OSX possible without manually specifying `hidden_imports` # in the build.spec import wx.html import wx.xml import wx.richtext # Need to be imported before the wx.App object is created. import wx.lib.inspection from gooey.gui.lang import i18n from gooey.gui import image_repository from gooey.gui.containers.application import GooeyApplication from gooey.util.functional import merge def run(build_spec): app, _ = build_app(build_spec) app.MainLoop() def build_app(build_spec): app = wx.App(False) # use actual program name instead of script file name in macOS menu app.SetAppDisplayName(build_spec['program_name']) i18n.load(build_spec['language_dir'], build_spec['language'], build_spec['encoding']) imagesPaths = image_repository.loadImages(build_spec['image_dir']) gapp = GooeyApplication(merge(build_spec, imagesPaths)) gapp.Show() return (app, gapp)
''' Main runner entry point for Gooey. ''' import wx # wx.html and wx.xml imports required here to make packaging with # pyinstaller on OSX possible without manually specifying `hidden_imports` # in the build.spec import wx.html import wx.xml import wx.richtext # Need to be imported before the wx.App object is created. import wx.lib.inspection from gooey.gui.lang import i18n from gooey.gui import image_repository from gooey.gui.containers.application import GooeyApplication from gooey.util.functional import merge def run(build_spec): app, _ = build_app(build_spec) app.MainLoop() def build_app(build_spec): app = wx.App(False) i18n.load(build_spec['language_dir'], build_spec['language'], build_spec['encoding']) imagesPaths = image_repository.loadImages(build_spec['image_dir']) gapp = GooeyApplication(merge(build_spec, imagesPaths)) gapp.Show() return (app, gapp)
Load file if params are not present
'use strict' var fs = require('fs') var path = require('path') var existFile = require('exists-file') var minimistPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'minimist') var minimist = require(minimistPath) var trimNewlinesPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'trim-newlines') var trimNewlines = require(trimNewlinesPath) var FILENAME = 'worker-farm.opts' function readConfig (filepath) { var yargs = process.argv.slice(2) if (yargs.length > 1) return yargs var filepath = path.resolve(yargs[0], FILENAME) if (!existFile(filepath)) return yargs var config = fs.readFileSync(filepath, 'utf8') config = trimNewlines(config).split('\n') return config.concat(yargs) } module.exports = readConfig()
'use strict' var fs = require('fs') var path = require('path') var existFile = require('exists-file') var minimistPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'minimist') var minimist = require(minimistPath) var trimNewlinesPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'trim-newlines') var trimNewlines = require(trimNewlinesPath) var FILENAME = 'worker-farm.opts' function readConfig (filepath) { var yargs = process.argv.slice(2) if (yargs.length === 0) return yargs var filepath = path.resolve(yargs[yargs.length - 1], FILENAME) if (!existFile(filepath)) return yargs var config = fs.readFileSync(filepath, 'utf8') config = trimNewlines(config).split('\n') return config.concat(yargs) } module.exports = readConfig()
Fix bug in job run get() method.
'use strict'; import JobClient from '../client'; let apiClient; class DrushIORun { constructor(client, project, job, identifier, data = {}) { apiClient = client; this.project = project; this.job = job || new JobClient(client, project, data.job.id); this.identifier = identifier; this.data = data; } /** * Retrieves run details for this job run. * @return {Promise} */ get() { return new Promise((resolve, reject) => { apiClient.get(`/projects/${this.project.identifier}/jobs/${this.job.identifier}/runs/${this.identifier}`).then((response) => { this.data = response.body; resolve(this) }).catch((err) => { reject(err); }); }); } } export default DrushIORun;
'use strict'; import JobClient from '../client'; let apiClient; class DrushIORun { constructor(client, project, job, identifier, data = {}) { apiClient = client; this.project = project; this.job = job || new JobClient(client, project, data.job.id); this.identifier = identifier; this.data = data; } /** * Retrieves run details for this job run. * @return {Promise} */ get() { return new Promise((resolve, reject) => { apiClient.get(`/projects/${this.project.identifier}/${this.job.identifier}/run/${this.identifier}`).then((response) => { this.data = response.body; resolve(this) }).catch((err) => { reject(err); }); }); } } export default DrushIORun;
Read long description from README.rst
# -*- encoding: UTF-8 -* from setuptools import setup with open('README.rst') as fp: README = fp.read() setup( name='steeve', version='0.1', author='Sviatoslav Abakumov', author_email='dust.harvesting@gmail.com', description=u'Tiny GNU Stow–based package manager', long_description=README, url='https://github.com/Perlence/steeve', download_url='https://github.com/Perlence/steeve/archive/master.zip', py_modules=['steeve'], zip_safe=False, entry_points={ 'console_scripts': [ 'steeve = steeve:cli', ], }, install_requires=[ 'click', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Systems Administration', 'Topic :: Utilities', ] )
# -*- encoding: UTF-8 -* from setuptools import setup with open('README.md') as fp: README = fp.read() setup( name='steeve', version='0.1', author='Sviatoslav Abakumov', author_email='dust.harvesting@gmail.com', description=u'Tiny GNU Stow–based package manager', long_description=README, url='https://github.com/Perlence/steeve', download_url='https://github.com/Perlence/steeve/archive/master.zip', py_modules=['steeve'], zip_safe=False, entry_points={ 'console_scripts': [ 'steeve = steeve:cli', ], }, install_requires=[ 'click', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Systems Administration', 'Topic :: Utilities', ] )
Use py-bcrypt version 0.4 to fix a security issue with py-bcrypt
from setuptools import setup, find_packages setup( name="CoinboxMod-auth", version="0.1", packages=find_packages(), zip_safe=True, namespace_packages=['cbpos', 'cbpos.mod'], include_package_data=True, install_requires=['sqlalchemy>=0.7','PyDispatcher>=2.0.3','ProxyTypes>=0.9','PySide>=1.1.2','py-bcrypt==0.4'], author='Coinbox POS Team', author_email='coinboxpos@googlegroups.com', description='Coinbox POS core package', license='GPLv3', url='http://coinboxpos.org/' )
from setuptools import setup, find_packages setup( name="CoinboxMod-auth", version="0.1", packages=find_packages(), zip_safe=True, namespace_packages=['cbpos', 'cbpos.mod'], include_package_data=True, install_requires=['sqlalchemy>=0.7','PyDispatcher>=2.0.3','ProxyTypes>=0.9','PySide>=1.1.2','py-bcrypt==0.2'], author='Coinbox POS Team', author_email='coinboxpos@googlegroups.com', description='Coinbox POS core package', license='GPLv3', url='http://coinboxpos.org/' )
Add the root dir variable
from setuptools import setup, find_packages import codecs import os import re root_dir = os.path.abspath(os.path.dirname(__file__)) PACKAGE = 'hackernews_scraper' def get_version(package_name): version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$") package_components = package_name.split('.') init_path = os.path.join(root_dir, *(package_components + ['__init__.py'])) with codecs.open(init_path, 'r', 'utf-8') as f: for line in f: match = version_re.match(line[:-1]) if match: return match.groups()[0] return '0.1.0' setup(name='hackernews_scraper', description='Python library for retrieving comments and stories from HackerNews', packages=find_packages(), version=get_version(PACKAGE), install_requires=['requests'], url='https://github.com/NiGhTTraX/hackernews-scraper', license='MIT', platforms='any', tests_require=['nose', 'factory_boy', 'httpretty'], )
from setuptools import setup, find_packages import codecs import os import re def get_version(package_name): version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$") package_components = package_name.split('.') init_path = os.path.join(root_dir, *(package_components + ['__init__.py'])) with codecs.open(init_path, 'r', 'utf-8') as f: for line in f: match = version_re.match(line[:-1]) if match: return match.groups()[0] return '0.1.0' PACKAGE = 'hackernews_scraper' setup(name='hackernews_scraper', description='Python library for retrieving comments and stories from HackerNews', packages=find_packages(), version=get_version(PACKAGE), install_requires=['requests'], url='https://github.com/NiGhTTraX/hackernews-scraper', license='MIT', platforms='any', tests_require=['nose', 'factory_boy', 'httpretty'], )
Fix for empty front matter
<?php namespace Spatie\YamlFrontMatter; use Illuminate\Support\Arr; class Document { protected $matter; protected $body; public function __construct($matter = [], string $body) { $this->matter = is_array($matter) ? $matter : []; $this->body = $body; } public function matter(string $key = null, $default = null) { if ($key) { return Arr::get($this->matter, $key, $default); } return $this->matter; } public function body() : string { return $this->body; } public function __get($key) { return $this->matter($key); } }
<?php namespace Spatie\YamlFrontMatter; use Illuminate\Support\Arr; class Document { protected $matter; protected $body; public function __construct(array $matter, string $body) { $this->matter = $matter; $this->body = $body; } public function matter(string $key = null, $default = null) { if ($key) { return Arr::get($this->matter, $key, $default); } return $this->matter; } public function body() : string { return $this->body; } public function __get($key) { return $this->matter($key); } }
Reset err after call to GetDocument()
package hammock import ( "fmt" "github.com/mikebell-org/go-couchdb" ) type CouchDB struct { couchdb.CouchDB } func Database(host, database, username, password string) (*CouchDB, error) { db, err := couchdb.Database(host, database, username, password) return &CouchDB{*db}, err } func Sync(db *CouchDB, path string) (changes []string, err error) { // TODO: implement a document freezing option disk_data := newDesignDocCollection() if err = disk_data.loadFromDisk(path); err == nil { for doc_name, document := range disk_data.Documents { db_data := newDesignDocument(doc_name) if err = db.GetDocument(&db_data, fmt.Sprintf("%v", doc_name)); err != nil { changes = append(changes, fmt.Sprintf("Design document %v is missing", doc_name)) err = nil } if updated, doc_changes := db_data.update(document); updated { changes = append(changes, doc_changes...) if success, e := db.PutDocument(db_data, doc_name); e != nil || !success.OK { err = e return } } } } return }
package hammock import ( "fmt" "github.com/mikebell-org/go-couchdb" ) type CouchDB struct { couchdb.CouchDB } func Database(host, database, username, password string) (*CouchDB, error) { db, err := couchdb.Database(host, database, username, password) return &CouchDB{*db}, err } func Sync(db *CouchDB, path string) (changes []string, err error) { // TODO: implement a document freezing option disk_data := newDesignDocCollection() if err = disk_data.loadFromDisk(path); err == nil { for doc_name, document := range disk_data.Documents { db_data := newDesignDocument(doc_name) if err = db.GetDocument(&db_data, fmt.Sprintf("%v", doc_name)); err != nil { changes = append(changes, fmt.Sprintf("Design document %v is missing", doc_name)) } if updated, doc_changes := db_data.update(document); updated { changes = append(changes, doc_changes...) if success, e := db.PutDocument(db_data, doc_name); e != nil || !success.OK { err = e return } } } } return }
Make camera interaction more sensitive (refs #12095)
#pylint: disable=missing-docstring #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import vtk from .. import utils class KeyPressInteractorStyle(vtk.vtkInteractorStyleMultiTouchCamera): """ An interactor style for capturing key press events in VTK window. """ def __init__(self, parent=None, **kwargs): self.AddObserver("KeyPressEvent", self.keyPress) super(KeyPressInteractorStyle, self).__init__(parent, **kwargs) self.SetMotionFactor(0.1*self.GetMotionFactor()) def keyPress(self, obj, event): #pylint: disable=unused-argument """ Executes when a key is pressed. Inputs: obj, event: Required by VTK. """ key = obj.GetInteractor().GetKeySym() if key == 'c': print '\n'.join(utils.print_camera(self.GetCurrentRenderer().GetActiveCamera()))
#pylint: disable=missing-docstring #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import vtk from .. import utils class KeyPressInteractorStyle(vtk.vtkInteractorStyleMultiTouchCamera): """ An interactor style for capturing key press events in VTK window. """ def __init__(self, parent=None, **kwargs): self.AddObserver("KeyPressEvent", self.keyPress) super(KeyPressInteractorStyle, self).__init__(parent, **kwargs) def keyPress(self, obj, event): #pylint: disable=unused-argument """ Executes when a key is pressed. Inputs: obj, event: Required by VTK. """ key = obj.GetInteractor().GetKeySym() if key == 'c': print '\n'.join(utils.print_camera(self.GetCurrentRenderer().GetActiveCamera()))
Add --upgrade to pip install in Fabfile
from fabric import task CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src' # for FreeBSD compatibility SHELL = '/bin/sh -c' @task def deploy(c): c.shell = SHELL with c.cd(CODE_DIR): pull_changes(c) with c.prefix('. ../venv/bin/activate'): update_dependencies(c) migrate_database(c) update_static_files(c) restart_app(c) def update_dependencies(c): c.run('pip install --requirement=requirements.txt --upgrade') def pull_changes(c): c.run('git fetch') c.run('git reset --hard origin/master') def migrate_database(c): c.run('python manage.py migrate --noinput') def update_static_files(c): c.run('python manage.py collectstatic --noinput') def restart_app(c): c.run('../scripts/restart-fcgi.sh') # for WSGI: # c.run('touch toidupank/wsgi.py')
from fabric import task CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src' # for FreeBSD compatibility SHELL = '/bin/sh -c' @task def deploy(c): c.shell = SHELL with c.cd(CODE_DIR): pull_changes(c) with c.prefix('. ../venv/bin/activate'): update_dependencies(c) migrate_database(c) update_static_files(c) restart_app(c) def update_dependencies(c): c.run('pip install --requirement=requirements.txt') def pull_changes(c): c.run('git fetch') c.run('git reset --hard origin/master') def migrate_database(c): c.run('python manage.py migrate --noinput') def update_static_files(c): c.run('python manage.py collectstatic --noinput') def restart_app(c): c.run('../scripts/restart-fcgi.sh') # for WSGI: # c.run('touch toidupank/wsgi.py')
Fix portflofio child template view
<?php global $post, $MODEL; /** Polylang class */ $langIds = PLL()->model->post->get_translations(get_the_ID()); $ContentType = $MODEL->getSettings('post_type', ['page_id', $langIds['en']]); $args = [ 'post_type' => $ContentType, 'orderby' => 'menu_order', 'posts_per_page' => -1]; $ContentQuery = new WP_Query( $args ); if ($ContentQuery->have_posts( )): $index = 0; while ( $ContentQuery->have_posts( ) ) : $ContentQuery->the_post( ); $url = get_the_post_thumbnail_url( $ContentQuery->post->ID, [300, 300] ); if (empty( $url ) || $url === ''){ $url = get_template_directory_uri().'/images/cover.jpg'; } ?> <div class="fw-background-container" id="brand_<?= $index ?>" data-name="" data-container='{"w":225, "h":"auto"}' style="background-image: url(<?= $url ?>); width:225px; height: 225px"> <div class="uk-label uk-position-bottom-left fw-box-title " id="name_<?= $index ?>"> <a href="<?= get_permalink( $ContentQuery->post->ID ) ?>"> <?= strtoupper( $ContentQuery->post->post_title ) ?> </a> </div> </div> <?php $index++; endwhile; endif;
<?php global $post, $MODEL; $ContentType = $MODEL->getSettings('post_type', ['page_id', $post->ID]); $args = [ 'post_type' => $ContentType, 'orderby' => 'menu_order', 'posts_per_page' => -1]; $ContentQuery = new WP_Query( $args ); if ($ContentQuery->have_posts( )): $index = 0; while ( $ContentQuery->have_posts( ) ) : $ContentQuery->the_post( ); $url = get_the_post_thumbnail_url( $ContentQuery->post->ID, [300, 300] ); if (empty( $url ) || $url === ''){ $url = get_template_directory_uri().'/images/cover.jpg'; } ?> <div class="fw-background-container" id="brand_<?= $index ?>" data-name="" data-container='{"w":225, "h":"auto"}' style="background-image: url(<?= $url ?>); width:225px; height: 225px"> <div class="uk-label uk-position-bottom-left fw-box-title " id="name_<?= $index ?>"> <a href="<?= get_permalink( $ContentQuery->post->ID ) ?>"> <?= strtoupper( $ContentQuery->post->post_title ) ?> </a> </div> </div> <?php $index++; endwhile; endif;
Bring coverage back to 100% All calls to reraise() are in branches where value is truthy, so we can't reach that code.
from types import TracebackType from typing import NoReturn, Optional, Type, Union def to_bytes( x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None ) -> bytes: if isinstance(x, bytes): return x elif not isinstance(x, str): raise TypeError(f"not expecting type {type(x).__name__}") elif encoding or errors: return x.encode(encoding or "utf-8", errors=errors or "strict") return x.encode() def to_str( x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None ) -> str: if isinstance(x, str): return x elif not isinstance(x, bytes): raise TypeError(f"not expecting type {type(x).__name__}") elif encoding or errors: return x.decode(encoding or "utf-8", errors=errors or "strict") return x.decode() def reraise( tp: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType] = None, ) -> NoReturn: try: if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value finally: value = None tb = None
from types import TracebackType from typing import NoReturn, Optional, Type, Union def to_bytes( x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None ) -> bytes: if isinstance(x, bytes): return x elif not isinstance(x, str): raise TypeError(f"not expecting type {type(x).__name__}") elif encoding or errors: return x.encode(encoding or "utf-8", errors=errors or "strict") return x.encode() def to_str( x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None ) -> str: if isinstance(x, str): return x elif not isinstance(x, bytes): raise TypeError(f"not expecting type {type(x).__name__}") elif encoding or errors: return x.decode(encoding or "utf-8", errors=errors or "strict") return x.decode() def reraise( tp: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType] = None, ) -> NoReturn: try: if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value finally: value = None tb = None
Remove add_view and add form for the hole admin
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..models import Maintenance from ..service.maintenance import MaintenanceService from ..forms import MaintenanceForm class MaintenanceAdmin(admin.DjangoServicesAdmin): service_class = MaintenanceService search_fields = ("scheduled_for", "description", "maximum_workers", 'status') list_display = ("scheduled_for", "description", "maximum_workers", 'status') fields = ( "description", "scheduled_for", "main_script", "rollback_script", "host_query","maximum_workers", "status", "celery_task_id",) save_on_top = True readonly_fields = ('status', 'celery_task_id') form = MaintenanceForm def change_view(self, request, object_id, form_url='', extra_context=None): maintenance = Maintenance.objects.get(id=object_id) if maintenance.celery_task_id: self.readonly_fields = self.fields return super(MaintenanceAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context)
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..models import Maintenance from ..service.maintenance import MaintenanceService class MaintenanceAdmin(admin.DjangoServicesAdmin): service_class = MaintenanceService search_fields = ("scheduled_for", "description", "maximum_workers", 'status') list_display = ("scheduled_for", "description", "maximum_workers", 'status') fields = ( "description", "scheduled_for", "main_script", "rollback_script", "host_query","maximum_workers", "status", "celery_task_id",) save_on_top = True readonly_fields = ('status', 'celery_task_id') def change_view(self, request, object_id, form_url='', extra_context=None): maintenance = Maintenance.objects.get(id=object_id) if maintenance.celery_task_id: self.readonly_fields = self.fields return super(MaintenanceAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context) def add_view(self, request, form_url='', extra_context=None): return super(MaintenanceAdmin, self).add_view(request, form_url, extra_context)
Reduce weight of ugly Promise constructor
const compile = require("truffle-compile"); class DebugCompiler { constructor(config) { this.config = config; } async compile() { //we need to set up a config object for the compiler. //it's the same as the existing config, but we turn on quiet. //unfortunately, we don't have Babel here, so cloning is annoying. const compileConfig = Object.assign( {}, ...Object.entries(this.config).map(([key, value]) => ({ [key]: value })) ); //clone compileConfig.quiet = true; // since `compile.all()` returns two results, we can't use promisify // and are instead stuck with using an explicit Promise constructor const { contracts, files } = await new Promise((accept, reject) => { compile.all(compileConfig, (err, contracts, files) => { if (err) { return reject(err); } return accept({ contracts, files }); }); }); return { contracts, files }; } } module.exports = { DebugCompiler };
const compile = require("truffle-compile"); class DebugCompiler { constructor(config) { this.config = config; } async compile() { const { contracts, files } = await new Promise((accept, reject) => { //we need to set up a config object for the compiler. //it's the same as the existing config, but we turn on quiet. //unfortunately, we don't have Babel here, so cloning is annoying. let compileConfig = Object.assign( {}, ...Object.entries(this.config).map(([key, value]) => ({ [key]: value })) ); //clone compileConfig.quiet = true; compile.all(compileConfig, (err, contracts, files) => { if (err) { return reject(err); } return accept({ contracts, files }); }); }); return { contracts, files }; } } module.exports = { DebugCompiler };
DeprecationWarning: Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0
# -*- coding: utf-8 -*- import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.path.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.path.which(path) break break return grains
# -*- coding: utf-8 -*- import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.which(path) break break return grains
Split copy part to a function
function copyToClipboard(str){ 'use strict'; var textArea = document.createElement('textarea'); document.body.appendChild(textArea); textArea.value = str; textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); } window.addEventListener('load', function(){ 'use strict'; // Get elements var title = document.getElementById('page_title'); var url = document.getElementById('page_url'); var copyTitle = document.getElementById('copy_title'); var copyUrl = document.getElementById('copy_url'); // Get tab info chrome.tabs.query({ active: true }, function(tabs){ 'use strict'; // Show title and url title.innerHTML = tabs[0].title; url.innerHTML = tabs[0].url; // Add click listener to copy button copyTitle.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard copyToClipboard(tabs[0].title); }); copyUrl.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard copyToClipboard(tabs[0].url); }); }); });
window.addEventListener('load', function(){ 'use strict'; // Get elements var title = document.getElementById('page_title'); var url = document.getElementById('page_url'); var copyTitle = document.getElementById('copy_title'); var copyUrl = document.getElementById('copy_url'); // Get tab info chrome.tabs.query({ active: true }, function(tabs){ 'use strict'; // Show title and url title.innerHTML = tabs[0].title; url.innerHTML = tabs[0].url; // Add click listener to copy button copyTitle.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard var textArea = document.createElement('textarea'); document.body.appendChild(textArea); textArea.value = tabs[0].title; textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); }); copyUrl.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard var textArea = document.createElement('textarea'); document.body.appendChild(textArea); textArea.value = tabs[0].url; textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); }); }); });
Check whether there is a format given (this must be checked for validity though).
# django imports from django.utils.translation import ugettext_lazy as _ from django.db import models # lfs imports from lfs.plugins import OrderNumberGenerator as Base class OrderNumberGenerator(Base): """Generates order numbers and saves the last one. **Attributes:** id The primary key of the order number. last The last stored/returned order number. format The format of the integer part of the order number. """ id = models.CharField(primary_key=True, max_length=20) last = models.IntegerField(_(u"Last order number"), default=0) format = models.CharField(blank=True, max_length=20) def get_next(self, formatted=True): """Returns the next order number. **Parameters:** formatted If True the number will be returned within the stored format. """ self.last += 1 self.save() if formatted and self.format: return self.format % self.last else: return self.last
# django imports from django.utils.translation import ugettext_lazy as _ from django.db import models # lfs imports from lfs.plugins import OrderNumberGenerator as Base class OrderNumberGenerator(Base): """Generates order numbers and saves the last one. **Attributes:** id The primary key of the order number. last The last stored/returned order number. format The format of the integer part of the order number. """ id = models.CharField(primary_key=True, max_length=20) last = models.IntegerField(_(u"Last order number"), default=0) format = models.CharField(blank=True, max_length=20) def get_next(self, formatted=True): """Returns the next order number. **Parameters:** formatted If True the number will be returned within the stored format. """ self.last += 1 self.save() if formatted: return self.format % self.last else: return self.last
Fix command fix:participant not saving correctly
<?php namespace App\Console\Commands; use App\Notifications\TargetDrawn; use URLParser; class FixParticipant extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'fix:participant {url : The URL received by one of the participants to write to their santa} {id : The participant id} {email : The correct email of the participant}'; /** * The console command description. * * @var string */ protected $description = 'Fix a participant email'; /** * Execute the console command. * * @return mixed */ public function handle() { $this->setCryptIVFromUrl($this->argument('url')); $draw = URLParser::parseByName('dearSanta', $this->argument('url'))->participant->draw; $participant = $draw->participants->find($this->argument('id')); $participant->email = $this->argument('email'); $participant->save(); $participant->notifyNow(new TargetDrawn); $this->info('Participant mail sent'); } }
<?php namespace App\Console\Commands; use App\Notifications\TargetDrawn; use URLParser; class FixParticipant extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'fix:participant {url : The URL received by one of the participants to write to their santa} {id : The participant id} {email : The correct email of the participant}'; /** * The console command description. * * @var string */ protected $description = 'Fix a participant email'; /** * Execute the console command. * * @return mixed */ public function handle() { $this->setCryptIVFromUrl($this->argument('url')); $draw = URLParser::parseByName('dearSanta', $this->argument('url'))->participant->draw; $participant = $draw->participants->find($this->argument('id')); $participant->email = $this->argument('email'); $participant->find($this->argument('id'))->save(); $participant->notifyNow(new TargetDrawn); $this->info('Participant mail sent'); } }
Set version number to 0.1.51.
from setuptools import setup, find_packages with open("README.rst", "rt") as f: readme = f.read() setup( name='gimei', version="0.1.51", description="generates the name and the address at random.", long_description=__doc__, author='Mao Nabeta', author_email='mao.nabeta@gmail.com', url='https://github.com/nabetama/gimei', packages=find_packages(), include_package_data=True, install_requires=['pyyaml'], provides=['gimei', 'name', 'random'], keywords=['gimei', 'name', 'random'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Communications :: Chat', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
from setuptools import setup, find_packages with open("README.rst", "rt") as f: readme = f.read() setup( name='gimei', version="0.1.5", description="generates the name and the address at random.", long_description=__doc__, author='Mao Nabeta', author_email='mao.nabeta@gmail.com', url='https://github.com/nabetama/gimei', packages=find_packages(), include_package_data=True, install_requires=['pyyaml'], provides=['gimei', 'name', 'random'], keywords=['gimei', 'name', 'random'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Communications :: Chat', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Add some core components to subliminal
# -*- coding: utf-8 -*- # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # # This file is part of subliminal. # # subliminal is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # subliminal is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with subliminal. If not, see <http://www.gnu.org/licenses/>. from .api import list_subtitles, download_subtitles from .async import Pool from .core import (SERVICES, LANGUAGE_INDEX, SERVICE_INDEX, SERVICE_CONFIDENCE, MATCHING_CONFIDENCE) from .infos import __version__ import logging try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass __all__ = ['SERVICES', 'LANGUAGE_INDEX', 'SERVICE_INDEX', 'SERVICE_CONFIDENCE', 'MATCHING_CONFIDENCE', 'list_subtitles', 'download_subtitles', 'Pool'] logging.getLogger(__name__).addHandler(NullHandler())
# -*- coding: utf-8 -*- # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # # This file is part of subliminal. # # subliminal is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # subliminal is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with subliminal. If not, see <http://www.gnu.org/licenses/>. from .api import list_subtitles, download_subtitles from .async import Pool from .infos import __version__ import logging try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass __all__ = ['list_subtitles', 'download_subtitles', 'Pool'] logging.getLogger(__name__).addHandler(NullHandler())
Tweak log formating to append colon and space to stdout type.
var Logger = function (config) { this.config = config; this.backend = this.config.backend || 'stdout' this.level = this.config.level || "LOG_INFO" if (this.backend == 'stdout') { this.util = require('util'); } else { if (this.backend == 'syslog') { this.util = require('node-syslog'); this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0); } else { throw "Logger: Should be 'stdout' or 'syslog'." } } } Logger.prototype = { log: function (msg, type) { if (this.backend == 'stdout') { if (!type) { type = 'DEBUG'; } this.util.log(type + ": " + msg); } else { if (!type) { type = this.level if (!this.util[type]) { throw "Undefined log level: " + type; } } else if (type == 'debug') { type = "LOG_DEBUG"; } this.util.log(this.util[type], msg); } } } exports.Logger = Logger
var Logger = function (config) { this.config = config; this.backend = this.config.backend || 'stdout' this.level = this.config.level || "LOG_INFO" if (this.backend == 'stdout') { this.util = require('util'); } else { if (this.backend == 'syslog') { this.util = require('node-syslog'); this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0); } else { throw "Logger: Should be 'stdout' or 'syslog'." } } } Logger.prototype = { log: function (msg, type) { if (this.backend == 'stdout') { if (!type) { type = 'DEBUG: '; } this.util.log(type + msg); } else { if (!type) { type = this.level if (!this.util[type]) { throw "Undefined log level: " + type; } } else if (type == 'debug') { type = "LOG_DEBUG"; } this.util.log(this.util[type], msg); } } } exports.Logger = Logger
Use EmptyOTFCompiler for test compilation
from os import remove from os.path import exists from mojo.roboFont import version from jkRFoTools.FontChooser import ProcessFonts from fontCompiler.compiler import FontCompilerOptions from fontCompiler.emptyCompiler import EmptyOTFCompiler def test_compilation(font): if font.path is None: return "ERROR: The font needs to be saved first." font = font.naked() compiler = EmptyOTFCompiler() options = FontCompilerOptions() options.outputPath = font.path + "_compiletest.otf" reports = compiler.compile(font, options) if not "makeotf" in reports: return "OK" result = reports["makeotf"] lines = result.splitlines() if lines[-2][:15] == "makeotf [Error]": test_result = "" for r in lines: if r[:18] in ["makeotfexe [ERROR]", "makeotfexe [FATAL]"]: test_result += r[11:] + "\n" else: test_result = "OK" if exists(options.outputPath): remove(options.outputPath) return test_result ProcessFonts("Test Compilation", test_compilation)
from string import split from os import remove from mojo.roboFont import version from jkRFoTools.FontChooser import ProcessFonts def test_compilation(font): temp_font = font.copy(showUI=False) for g in temp_font: g.clear() if font.path is None: return "ERROR: The font needs to be saved first." myPath = font.path + "_compiletest.otf" result = temp_font.generate(myPath, "otf") temp_font.close() lines = split(result, "\n") if version[:3] == "1.5": checkLine = -3 elif version[:3] == "1.6": checkLine = -1 else: checkLine = -10 if lines[checkLine][:15] == "makeotf [Error]": test_result = "" for r in lines: if r[:18] in ["makeotfexe [ERROR]", "makeotfexe [FATAL]"]: test_result += r[11:] + "\n" else: test_result = "OK" remove(myPath) return test_result ProcessFonts("Test Compilation", test_compilation)
Remove useless requirement on Python 3.2+
# -*- coding: utf-8 -*- import io from setuptools import setup, find_packages import sys install_requires = [] if (sys.version_info[0], sys.version_info[1]) < (3, 2): install_requires.append('futures>=2.1.3') setup( name='django-pipeline', version='1.5.2', description='Pipeline is an asset packaging library for Django.', long_description=io.open('README.rst', encoding='utf-8').read() + '\n\n' + io.open('HISTORY.rst', encoding='utf-8').read(), author='Timothée Peignier', author_email='timothee.peignier@tryphon.org', url='https://github.com/cyberdelia/django-pipeline', license='MIT', packages=find_packages(exclude=['tests', 'tests.tests']), zip_safe=False, install_requires=install_requires, include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ] )
# -*- coding: utf-8 -*- import io from setuptools import setup, find_packages setup( name='django-pipeline', version='1.5.2', description='Pipeline is an asset packaging library for Django.', long_description=io.open('README.rst', encoding='utf-8').read() + '\n\n' + io.open('HISTORY.rst', encoding='utf-8').read(), author='Timothée Peignier', author_email='timothee.peignier@tryphon.org', url='https://github.com/cyberdelia/django-pipeline', license='MIT', packages=find_packages(exclude=['tests', 'tests.tests']), zip_safe=False, install_requires=[ 'futures>=2.1.3', ], include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ] )
Make base directory configurable from command line
var readFileSync = require("fs").readFileSync; var baseDir = env.opts.query.externalExBase; exports.defineTags = function(dictionary) { dictionary.defineTag("externalExample", { mustHaveValue: true, isNamespace: false, canHaveType: true, defaultValue: [], onTagged: function(doclet, tag) { var examples = doclet.externalExamples; var example = {}; var names; if (!examples) { examples = doclet.externalExamples = []; } names = tag.value.type && tag.value.type.names; if (names) { example.isRunnable = names.indexOf("runnable") > -1; } else { example.isRunnable = false; } example.src = readFileSync( baseDir + "/" + tag.value.description + ".js", "UTF-8" ); examples.push(example); } }); };
var readFileSync = require("fs").readFileSync; exports.defineTags = function(dictionary) { dictionary.defineTag("externalExample", { mustHaveValue: true, isNamespace: false, canHaveType: true, defaultValue: [], onTagged: function(doclet, tag) { var examples = doclet.externalExamples; var example = {}; var names; if (!examples) { examples = doclet.externalExamples = []; } names = tag.value.type && tag.value.type.names; if (names) { example.isRunnable = names.indexOf("runnable") > -1; } else { example.isRunnable = false; } example.src = readFileSync( "examples/api/" + tag.value.description + ".js", "UTF-8" ); examples.push(example); } }); };
Set py2app.__version__ using pkg_resources, that ensures that the version stays in sync with the value in setup.py
""" builds Mac OS X application bundles from Python scripts New keywords for distutils' setup function specify what to build: app list of scripts to convert into gui app bundles py2app options, to be specified in the options keyword to the setup function: optimize - string or int (0, 1, or 2) includes - list of module names to include packages - list of packages to include with subpackages ignores - list of modules to ignore if they are not found excludes - list of module names to exclude dylib_excludes - list of dylibs and/or frameworks to exclude resources - list of additional files and folders to include plist - Info.plist template file, dict, or plistlib.Plist dist_dir - directory where to build the final files Items in the macosx list can also be dictionaries to further customize the build process. The following keys in the dictionary are recognized, most are optional: script (MACOSX) - list of python scripts (required) dest_base - directory and basename for the executable if a directory is contained, must be the same for all targets """ import pkg_resources __version__ = pkg_resources.require('py2app')[0].version # This makes the py2app command work in the distutils.core.setup() case import setuptools
""" builds Mac OS X application bundles from Python scripts New keywords for distutils' setup function specify what to build: app list of scripts to convert into gui app bundles py2app options, to be specified in the options keyword to the setup function: optimize - string or int (0, 1, or 2) includes - list of module names to include packages - list of packages to include with subpackages ignores - list of modules to ignore if they are not found excludes - list of module names to exclude dylib_excludes - list of dylibs and/or frameworks to exclude resources - list of additional files and folders to include plist - Info.plist template file, dict, or plistlib.Plist dist_dir - directory where to build the final files Items in the macosx list can also be dictionaries to further customize the build process. The following keys in the dictionary are recognized, most are optional: script (MACOSX) - list of python scripts (required) dest_base - directory and basename for the executable if a directory is contained, must be the same for all targets """ __version__ = "0.4.4" # This makes the py2app command work in the distutils.core.setup() case import setuptools
Fix HTTP method value error
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.common.util; /** * @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @since 0.8.0 */ public class HttpMethod { public static final String GET = "GET"; public static final String HEAD = "HEAD"; public static final String POST = "POST"; public static final String PUT = "PUT"; public static final String PATCH = "PATCH"; public static final String DELETE = "DELETE"; public static final String OPTIONS = "OPTIONS"; public static final String TRACE = "TRACE"; }
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.common.util; /** * @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @since 0.8.0 */ public class HttpMethod { public static final String GET = "GET"; public static final String HEAD = "HEAD"; public static final String POST = "POST"; public static final String PUT = "PUT"; public static final String PATCH = "PATCH"; public static final String DELETE = "DELETE"; public static final String OPTIONS = "PATCH"; public static final String TRACE = "TRACE"; }
Annotate default behaviour acc inheritance
package de.zib.gndms.model.common; /* * Copyright 2008-2011 Zuse Institute Berlin (ZIB) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import de.zib.gndms.model.ModelEntity; import javax.persistence.*; /** * Super class of grid entities with a version field * **/ //@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) @MappedSuperclass public abstract class GridEntity extends ModelEntity { private int version; @Version public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } // @Column(name="sys_id", nullable=false, length=16, columnDefinition="CHAR", updatable=false) // String systemId }
package de.zib.gndms.model.common; /* * Copyright 2008-2011 Zuse Institute Berlin (ZIB) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import de.zib.gndms.model.ModelEntity; import javax.persistence.*; /** * Super class of grid entities with a version field * **/ @Inheritance( strategy = InheritanceType.TABLE_PER_CLASS ) @MappedSuperclass public abstract class GridEntity extends ModelEntity { private int version; @Version public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } // @Column(name="sys_id", nullable=false, length=16, columnDefinition="CHAR", updatable=false) // String systemId }
Add open up lastDownloadFailed to other error cases
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2021 */ import { syncStrings } from '../localization'; export const selectTemperatureSyncMessage = ({ vaccine }) => { const { isSyncingTemps = false, error } = vaccine; if (isSyncingTemps) { return syncStrings.downloading_temperature_logs; } if (error) { return `${syncStrings.error_downloading_temperature_logs} ${error}`; } return syncStrings.sync_complete; }; export const selectIsSyncingTemps = ({ vaccine }) => { const { isSyncingTemps = false } = vaccine || {}; return isSyncingTemps; }; export const selectDownloadingLogsFrom = ({ vaccine }) => { const { downloadingLogsFrom } = vaccine; return downloadingLogsFrom; }; export const selectLastDownloadTime = ({ vaccine }, macAddress) => { const { lastDownloadTime } = vaccine; return lastDownloadTime[macAddress] ? new Date(lastDownloadTime[macAddress]) : null; }; export const selectLastDownloadFailed = ({ vaccine }, macAddress) => { const { lastDownloadStatus } = vaccine; const status = lastDownloadStatus[macAddress]; const lastDownloadFailed = status !== 'OK'; return lastDownloadFailed; }; export const selectIsDownloading = (state, macAddress) => { const downloadingLogsFrom = selectDownloadingLogsFrom(state); const isDownloading = downloadingLogsFrom === macAddress; return isDownloading; };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2021 */ import { syncStrings } from '../localization'; export const selectTemperatureSyncMessage = ({ vaccine }) => { const { isSyncingTemps = false, error } = vaccine; if (isSyncingTemps) { return syncStrings.downloading_temperature_logs; } if (error) { return `${syncStrings.error_downloading_temperature_logs} ${error}`; } return syncStrings.sync_complete; }; export const selectIsSyncingTemps = ({ vaccine }) => { const { isSyncingTemps = false } = vaccine || {}; return isSyncingTemps; }; export const selectDownloadingLogsFrom = ({ vaccine }) => { const { downloadingLogsFrom } = vaccine; return downloadingLogsFrom; }; export const selectLastDownloadTime = ({ vaccine }, macAddress) => { const { lastDownloadTime } = vaccine; return lastDownloadTime[macAddress] ? new Date(lastDownloadTime[macAddress]) : null; }; export const selectLastDownloadFailed = ({ vaccine }, macAddress) => { const { lastDownloadStatus } = vaccine; const status = lastDownloadStatus[macAddress]; const lastDownloadFailed = status === 'ERROR'; return lastDownloadFailed; }; export const selectIsDownloading = (state, macAddress) => { const downloadingLogsFrom = selectDownloadingLogsFrom(state); const isDownloading = downloadingLogsFrom === macAddress; return isDownloading; };
Make pair generation extensible to multiple words
var generatePairs = function(string) { superPairs = string.toUpperCase() .replace(/[^A-Z ]+/g, '') .split(/\s+/); superPairs = superPairs .map(function(word) { breaks = []; for (var i = 0; i < word.length - 1; i++) { breaks.push(word.slice(i, i + 2)); } return breaks; }); pairs = [].concat.apply([], superPairs); return pairs; } var whiteSimilarity = function(string1, string2) { var pairs1 = generatePairs(string1); var pairs2 = generatePairs(string2); var union = pairs1.length + pairs2.length; var hitCount = 0; for (x in pairs1) { for (y in pairs2) { if (pairs1[x] == pairs2[y]) { hitCount++; pairs2[y] = ''; } } } score = ((2.0 * hitCount) / union).toFixed(2); return score; } module.exports = whiteSimilarity;
var generatePairs = function(string) { var pairs = []; string = string.toLowerCase(); for (var i = 0; i < string.length - 1; i++) { pair = string.substr(i, 2); if (!/\s/.test(pair)) { pairs.push(pair); } } return pairs; } var whiteSimilarity = function(string1, string2) { string1 = string1.toUpperCase() .replace(/[^A-Z]+/g, ''); string2 = string1.toUpperCase() .replace(/[^A-Z]+/g, ''); var pairs1 = generatePairs(string1); var pairs2 = generatePairs(string2); var union = pairs1.length + pairs2.length; var hitCount = 0; for (x in pairs1) { for (y in pairs2) { if (pairs1[x] == pairs2[y]) { hitCount++; } } } score = ((2.0 * hitCount) / union).toFixed(2); return score; } module.exports = whiteSimilarity;
Add comments for functions that handle user account info submission
angular.module('shortly.shorten', []) .controller('AccountsController', function ($scope, $window, $location, $http, Links) { /** * Handles Stripe 'Connect' button submit. * Gets Connect account creation redirect url from server and manually sets href. */ $scope.authorize = function() { var currentUser = sessionStorage.getItem('user'); return $http({ method: 'POST', url: '/authorize', data: { username: currentUser, } }) .then(function (resp) { console.log(resp); $window.location.href = resp.data; }); }; /** * On form submit, card info is sent to Stripe for processing. * Stripe returns a one time use token to stripeCallback, which passes it to server for customerId creation and saving. */ $scope.stripeCallback = function (code, result) { var currentUser = sessionStorage.getItem('user'); if (result.error) { console.log('it failed! error: ' + result.error.message); } else { return $http({ method: 'POST', url: '/stripe/debit-token', data: { username: currentUser, cardToken: result.id } }) .then(function (resp) { console.log(resp); }); } }; });
angular.module('shortly.shorten', []) .controller('AccountsController', function ($scope, $window, $location, $http, Links) { // $scope.hasStripeConnectAccount = function() { // var currentUser = sessionStorage.getItem('user'); // console.log('user',currentUser); // }; $scope.authorize = function() { var currentUser = sessionStorage.getItem('user'); return $http({ method: 'POST', url: '/authorize', data: { username: currentUser, } }) .then(function (resp) { console.log(resp); $window.location.href = resp.data; }); }; $scope.stripeCallback = function (code, result) { var currentUser = sessionStorage.getItem('user'); if (result.error) { console.log('it failed! error: ' + result.error.message); } else { return $http({ method: 'POST', url: '/stripe/debit-token', data: { username: currentUser, cardToken: result.id } }) .then(function (resp) { console.log(resp); }); } }; });
Fix syntax error for PHP legacy versions.
<?php namespace Omise\Payment\Model\Api; class Error extends Object { /** * @var string */ protected $code = 'unexpected_error'; protected $message = 'There is an unexpected error happened, please contact our support for further investigation.'; public function __construct($error = array()) { isset($error['code']) ? $this->setCode($error['code']) : ''; isset($error['message']) ? $this->setMessage($error['message']) : ''; } /** * @param string $code */ protected function setCode($code) { $this->code = $code; } /** * @param string $message */ protected function setMessage($message) { $this->message = $message; } /** * @return string */ public function getCode() { return $this->code; } /** * @return string */ public function getMessage() { return $this->message; } }
<?php namespace Omise\Payment\Model\Api; class Error extends Object { /** * @var string */ protected $code = 'unexpected_error'; protected $message = 'There is an unexpected error happened, please contact our support for further investigation.'; public function __construct($error = array()) { isset($error['code']) ? $this->setCode($error['code']); isset($error['message']) ? $this->setMessage($error['message']); } /** * @param string $code */ protected function setCode($code) { $this->code = $code; } /** * @param string $message */ protected function setMessage($message) { $this->message = $message; } /** * @return string */ public function getCode() { return $this->code; } /** * @return string */ public function getMessage() { return $this->message; } }
Make hangout rename itself after setchatname is called
"""Allows the user to configure the bot to watch for hangout renames and change the name back to a default name accordingly""" def setchatname(bot, event, *args): """Set a chat name. If no parameters given, remove chat name""" truncatelength = 32 # What should the maximum length of the chatroom be? chatname = ' '.join(args).strip() chatname = chatname[0:truncatelength] bot.initialise_memory(event.conv_id, "conv_data") bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname) bot.memory.save() if(chatname == ''): bot.send_message_parsed(event.conv, "Removing chatname") else: bot.send_message_parsed( event.conv, "Setting chatname to '{}'".format(chatname)) """Rename Hangout""" yield from bot._client.setchatname(event.conv_id, ' '.join(args))
"""Allows the user to configure the bot to watch for hangout renames and change the name back to a default name accordingly""" def setchatname(bot, event, *args): """Set a chat name. If no parameters given, remove chat name""" truncatelength = 32 # What should the maximum length of the chatroom be? chatname = ' '.join(args).strip() chatname = chatname[0:truncatelength] bot.initialise_memory(event.conv_id, "conv_data") bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname) bot.memory.save() if(chatname == ''): bot.send_message_parsed(event.conv, "Removing chatname") else: bot.send_message_parsed( event.conv, "Setting chatname to '{}'".format(chatname))
Return empty responses (not HTTP 404) in REST API for missing data
#!/usr/bin/env python import socket from flask import Flask, abort, make_response, request from whip.db import Database app = Flask(__name__) app.config.from_envvar('WHIP_SETTINGS', silent=True) db = None @app.before_first_request def _open_db(): global db db = Database(app.config['DATABASE_DIR']) @app.route('/ip/<ip>') def lookup(ip): try: key = socket.inet_aton(ip) except socket.error: abort(400) dt = request.args.get('datetime') if dt: dt = dt.encode('ascii') else: dt = None # account for empty parameter value info_as_json = db.lookup(key, dt) if info_as_json is None: info_as_json = b'{}' # empty dict, JSON-encoded response = make_response(info_as_json) response.headers['Content-type'] = 'application/json' return response
#!/usr/bin/env python import socket from flask import Flask, abort, make_response, request from whip.db import Database app = Flask(__name__) app.config.from_envvar('WHIP_SETTINGS', silent=True) db = None @app.before_first_request def _open_db(): global db db = Database(app.config['DATABASE_DIR']) @app.route('/ip/<ip>') def lookup(ip): try: key = socket.inet_aton(ip) except socket.error: abort(400) dt = request.args.get('datetime') if dt: dt = dt.encode('ascii') else: dt = None # account for empty parameter value info_as_json = db.lookup(key, dt) if info_as_json is None: abort(404) response = make_response(info_as_json) response.headers['Content-type'] = 'application/json' return response
Add engine to Jekyll example
'use strict'; var path = require('path'); var loader = require('assemble-loader'); var matter = require('parser-front-matter'); var assemble = require('../..'); var app = assemble(); app.use(loader()); app.engine(['hbs', 'md'], require('engine-handlebars') ); app.create('layouts', { viewType: 'layout', renameKey: function (key) { return path.basename(key); } }); app.data({ site: { title: 'My Blog' } }); app.onLoad(/./, function (view, next) { matter.parse(view, next); }); /** * Build. */ app.task('site', function () { app.layouts('_layouts/*.html'); app.src('_posts/*') .pipe(app.renderFile()) .pipe(app.dest('_site')); }); app.build('site', function (err) { if (err) console.log(err); });
'use strict'; var path = require('path'); var loader = require('assemble-loader'); var matter = require('parser-front-matter'); var assemble = require('../..'); var app = assemble(); app.use(loader()); app.create('layouts', { viewType: 'layout', renameKey: function (key) { return path.basename(key); } }); app.data({ site: { title: 'My Blog' } }); app.onLoad(/./, function (view, next) { matter.parse(view, next); }); /** * Build. */ app.task('site', function () { app.layouts('_layouts/*.html'); app.src('_posts/*') .pipe(app.renderFile()) .pipe(app.dest('_site')); }); app.build('site', function (err) { if (err) console.log(err); });
Replace all . in for action.types
import S from 'sanctuary'; export const has = S.meld([S.gets, S.isJust]); const hasFunc = has(Function); const hasString = has(String); const payload = ['payload']; const path = key => payload.concat(key); export const stringPayload = hasString(payload); export const hasSubscribe = hasFunc(path('subscribe')); export const hasKey = hasString(path('key')); export const hasGet = hasFunc(path('get')); export const actionCase = S.B(S.toUpper, x => x.replace(/\./g, '_')); export const createAction = type => (payload = {}, meta = {}) => ({ type, payload, meta }); export const injectTracker = (tracker, middlewares) => middlewares.map(m => m(tracker)); export const errorWith = x => (f, msg) => { if (!f(x)) { throw new Error(msg); } };
import S from 'sanctuary'; export const has = S.meld([S.gets, S.isJust]); const hasFunc = has(Function); const hasString = has(String); const payload = ['payload']; const path = key => payload.concat(key); export const stringPayload = hasString(payload); export const hasSubscribe = hasFunc(path('subscribe')); export const hasKey = hasString(path('key')); export const hasGet = hasFunc(path('get')); export const actionCase = S.B(S.toUpper, x => x.replace('.', '_')); export const createAction = type => (payload = {}, meta = {}) => ({ type, payload, meta }); export const injectTracker = (tracker, middlewares) => middlewares.map(m => m(tracker)); export const errorWith = x => (f, msg) => { if (!f(x)) { throw new Error(msg); } };
Fix exception on task not found Silly protected method....
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.rest.RestStatus; import java.io.IOException; /** * Generic ResourceNotFoundException corresponding to the {@link RestStatus#NOT_FOUND} status code */ public class ResourceNotFoundException extends ElasticsearchException { public ResourceNotFoundException(String msg, Object... args) { super(msg, args); } public ResourceNotFoundException(String msg, Throwable cause, Object... args) { super(msg, cause, args); } public ResourceNotFoundException(StreamInput in) throws IOException { super(in); } @Override public final RestStatus status() { return RestStatus.NOT_FOUND; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.rest.RestStatus; import java.io.IOException; /** * Generic ResourceNotFoundException corresponding to the {@link RestStatus#NOT_FOUND} status code */ public class ResourceNotFoundException extends ElasticsearchException { public ResourceNotFoundException(String msg, Object... args) { super(msg, args); } protected ResourceNotFoundException(String msg, Throwable cause, Object... args) { super(msg, cause, args); } public ResourceNotFoundException(StreamInput in) throws IOException { super(in); } @Override public final RestStatus status() { return RestStatus.NOT_FOUND; } }
Protocol: Add String() method to JobId
package protocol import ( "io" "math" "strconv" . "github.com/Philipp15b/go-steam/protocol/steamlang" ) type JobId uint64 func (j JobId) String() string { if j == math.MaxUint64 { return "(none)" } return strconv.FormatUint(uint64(j), 10) } type Serializer interface { Serialize(w io.Writer) error } type Deserializer interface { Deserialize(r io.Reader) error } type Serializable interface { Serializer Deserializer } type MessageBody interface { Serializable GetEMsg() EMsg } // the default details to request in most situations const EClientPersonaStateFlag_DefaultInfoRequest = EClientPersonaStateFlag_PlayerName | EClientPersonaStateFlag_Presence | EClientPersonaStateFlag_SourceID | EClientPersonaStateFlag_GameExtraInfo const DefaultAvatar = "fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb" func ValidAvatar(avatar string) bool { return !(avatar == "0000000000000000000000000000000000000000" || len(avatar) != 40) }
package protocol import ( . "github.com/Philipp15b/go-steam/protocol/steamlang" "io" ) type JobId uint64 type Serializer interface { Serialize(w io.Writer) error } type Deserializer interface { Deserialize(r io.Reader) error } type Serializable interface { Serializer Deserializer } type MessageBody interface { Serializable GetEMsg() EMsg } // the default details to request in most situations const EClientPersonaStateFlag_DefaultInfoRequest = EClientPersonaStateFlag_PlayerName | EClientPersonaStateFlag_Presence | EClientPersonaStateFlag_SourceID | EClientPersonaStateFlag_GameExtraInfo const DefaultAvatar = "fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb" func ValidAvatar(avatar string) bool { return !(avatar == "0000000000000000000000000000000000000000" || len(avatar) != 40) }
Remove bank information from form.
from django.forms import ModelForm from django import forms from django.utils.translation import ugettext_lazy as _ from autoentrepreneur.models import UserProfile, AUTOENTREPRENEUR_ACTIVITY, \ AUTOENTREPRENEUR_PAYMENT_OPTION class UserProfileForm(ModelForm): company_name = forms.CharField(required=False, max_length=255, label=_('Company name')) company_id = forms.CharField(max_length=50, label=_('Company id')) # SIRET for France activity = forms.ChoiceField(choices=AUTOENTREPRENEUR_ACTIVITY, label=_('Activity')) creation_date = forms.DateField(label=_('Creation date')) creation_help = forms.BooleanField(required=False, label=_('Creation help')) # accre freeing_tax_payment = forms.BooleanField(required=False, label=_('Freeing tax payment')) # versement liberatoire payment_option = forms.ChoiceField(choices=AUTOENTREPRENEUR_PAYMENT_OPTION, label=_('Payment option')) class Meta: model = UserProfile exclude = ['user', 'address']
from django.forms import ModelForm from django import forms from django.utils.translation import ugettext_lazy as _ from autoentrepreneur.models import UserProfile, AUTOENTREPRENEUR_ACTIVITY, \ AUTOENTREPRENEUR_PAYMENT_OPTION class UserProfileForm(ModelForm): company_name = forms.CharField(required=False, max_length=255, label=_('Company name')) company_id = forms.CharField(max_length=50, label=_('Company id')) # SIRET for France bank_information = forms.CharField(required=False, max_length=255, label=_('Bank information')) activity = forms.ChoiceField(choices=AUTOENTREPRENEUR_ACTIVITY, label=_('Activity')) creation_date = forms.DateField(label=_('Creation date')) creation_help = forms.BooleanField(required=False, label=_('Creation help')) # accre freeing_tax_payment = forms.BooleanField(required=False, label=_('Freeing tax payment')) # versement liberatoire payment_option = forms.ChoiceField(choices=AUTOENTREPRENEUR_PAYMENT_OPTION, label=_('Payment option')) class Meta: model = UserProfile exclude = ['user', 'address']
Fix ImportError when importing after system-wide installation
#!/usr/bin/env python try: from setuptools import setup except ImportError: print('[replot] setuptools not found.') raise with open('replot/constants.py') as fh: for line in fh: line = line.strip() if line.startswith('__VERSION__'): version = line.split()[-1][1:-1] break try: from pip.req import parse_requirements from pip.download import PipSession except ImportError: print('[replot] pip not found.') raise # parse_requirements() returns generator of pip.req.InstallRequirement objects parsed_requirements = parse_requirements("requirements.txt", session=PipSession()) # reqs is a list of requirement # e.g. ['django==1.5.1', 'mezzanine==1.4.6'] install_requires = [str(ir.req) for ir in parsed_requirements] setup( name='replot', version=version, url='https://github.com/Phyks/replot/', author='Phyks (Lucas Verney)', author_email='phyks@phyks.me', license='MIT License', description='A (sane) Python plotting module, abstracting on top of Matplotlib.', packages=['replot', 'replot.grid', 'replot.helpers'], install_requires=install_requires )
#!/usr/bin/env python try: from setuptools import setup except ImportError: print('[replot] setuptools not found.') raise with open('replot/constants.py') as fh: for line in fh: line = line.strip() if line.startswith('__VERSION__'): version = line.split()[-1][1:-1] break try: from pip.req import parse_requirements from pip.download import PipSession except ImportError: print('[replot] pip not found.') raise # parse_requirements() returns generator of pip.req.InstallRequirement objects parsed_requirements = parse_requirements("requirements.txt", session=PipSession()) # reqs is a list of requirement # e.g. ['django==1.5.1', 'mezzanine==1.4.6'] install_requires = [str(ir.req) for ir in parsed_requirements] setup( name='replot', version=version, url='https://github.com/Phyks/replot/', author='Phyks (Lucas Verney)', author_email='phyks@phyks.me', license='MIT License', description='A (sane) Python plotting module, abstracting on top of Matplotlib.', packages=['replot'], install_requires=install_requires )
Test DynamicPrefixStrategy for each grid scan level (an internal threshold) to tease out possible bugs.
package org.apache.lucene.spatial.test.strategy; import org.apache.lucene.spatial.base.context.SpatialContext; import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid; import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo; import org.apache.lucene.spatial.strategy.prefix.DynamicPrefixStrategy; import org.apache.lucene.spatial.test.SpatialMatchConcern; import org.apache.lucene.spatial.test.StrategyTestCase; import org.junit.Test; import java.io.IOException; public abstract class BaseGeohashStrategyTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> { private int maxLength; protected abstract SpatialContext getSpatialContext(); @Override public void setUp() throws Exception { super.setUp(); maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible(); // SimpleIO this.shapeIO = getSpatialContext(); this.strategy = new DynamicPrefixStrategy(new GeohashSpatialPrefixGrid( shapeIO, maxLength )); this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" ); } @Test public void testGeohashStrategy() throws IOException { getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS); //execute queries for each prefix grid scan level for(int i = 0; i <= maxLength; i++) { ((DynamicPrefixStrategy)strategy).setPrefixGridScanLevel(i); executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox); } } }
package org.apache.lucene.spatial.test.strategy; import org.apache.lucene.spatial.base.context.SpatialContext; import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid; import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo; import org.apache.lucene.spatial.strategy.prefix.DynamicPrefixStrategy; import org.apache.lucene.spatial.test.SpatialMatchConcern; import org.apache.lucene.spatial.test.StrategyTestCase; import org.junit.Test; import java.io.IOException; public abstract class BaseGeohashStrategyTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> { protected abstract SpatialContext getSpatialContext(); @Override public void setUp() throws Exception { super.setUp(); int maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible(); // SimpleIO this.shapeIO = getSpatialContext(); this.strategy = new DynamicPrefixStrategy(new GeohashSpatialPrefixGrid( shapeIO, maxLength )); this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" ); } @Test public void testGeohashStrategy() throws IOException { getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS); executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox); } }
Print message when quitting on exception This makes sure that an explanatory message is printed when quitting the main loop due to an exception in a test suite but outside a test (e.g. in a beforeEach function.) [endlessm/eos-sdk#737]
const GLib = imports.gi.GLib; const Mainloop = imports.mainloop; const System = imports.system; function quitMainLoopOnException(fn) { try { fn(); } catch (e) { Mainloop.quit("jasmine"); printerr('Exception occurred outside of a test suite:', e); printerr(e.stack); System.exit(1); } } function _setTimeoutInternal(fn, time, continueTimeout) { let id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, time, function () { quitMainLoopOnException(fn); return continueTimeout; }); return { timeoutId: id }; } window.setTimeout = function (fn, time) { return _setTimeoutInternal(fn, time, false); }; window.setInterval = function (fn, time) { return _setTimeoutInternal(fn, time, true); }; window.clearTimeout = window.clearInterval = function (id) { if (typeof (id) !== 'object' || !Object.hasOwnProperty(id, 'timeoutId')) return; if (id.timeoutId > 0) { GLib.source_remove(id.timeoutId); id.timeoutId = 0; } }; window.timer = null;
const GLib = imports.gi.GLib; const Mainloop = imports.mainloop; const System = imports.system; function quitMainLoopOnException(fn) { try { fn(); } catch (e) { Mainloop.quit("jasmine"); System.exit(1); } } function _setTimeoutInternal(fn, time, continueTimeout) { let id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, time, function () { quitMainLoopOnException(fn); return continueTimeout; }); return { timeoutId: id }; } window.setTimeout = function (fn, time) { return _setTimeoutInternal(fn, time, false); }; window.setInterval = function (fn, time) { return _setTimeoutInternal(fn, time, true); }; window.clearTimeout = window.clearInterval = function (id) { if (typeof (id) !== 'object' || !Object.hasOwnProperty(id, 'timeoutId')) return; if (id.timeoutId > 0) { GLib.source_remove(id.timeoutId); id.timeoutId = 0; } }; window.timer = null;
Update package version for Pypi
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup(name='sophiabus230', version='0.5', description='Module to get the timetable of the Sophia Antipolis bus line 230', url='http://github.com/paraita/sophiabus230', author='Paraita Wohler', author_email='paraita.wohler@gmail.com', license='MIT', packages=['sophiabus230'], install_requires=[ 'beautifulsoup4', 'python-dateutil', 'future' ], test_suite='nose.collector', tests_require=[ 'mock', 'nose', 'coverage', 'coveralls' ], zip_safe=False)
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup(name='sophiabus230', version='0.4', description='Module to get the timetable of the Sophia Antipolis bus line 230', url='http://github.com/paraita/sophiabus230', author='Paraita Wohler', author_email='paraita.wohler@gmail.com', license='MIT', packages=['sophiabus230'], install_requires=[ 'beautifulsoup4', 'python-dateutil', 'future' ], test_suite='nose.collector', tests_require=[ 'mock', 'nose', 'coverage', 'coveralls' ], zip_safe=False)
Package metadata should have ASL2 as license
#! /usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import setup, find_packages from sys import version_info if version_info[:2] > (2, 5): install_requires = [] else: install_requires = ['simplejson >= 2.0.0'] setup( name = 'cm_api', version = '1.0.0', # Compatible with API v1 packages = find_packages('src'), package_dir = {'cm_api': 'src/cm_api'}, # Project uses simplejson, so ensure that it gets installed or upgraded # on the target machine install_requires = install_requires, author = 'Cloudera, Inc.', description = 'Cloudera Manager API client', license = 'Apache License 2.0', url = 'https://github.com/cloudera/cm_api', )
#! /usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import setup, find_packages from sys import version_info if version_info[:2] > (2, 5): install_requires = [] else: install_requires = ['simplejson >= 2.0.0'] setup( name = 'cm_api', version = '1.0', # Compatible with API v1 packages = find_packages('src'), package_dir = {'cm_api': 'src/cm_api'}, # Project uses simplejson, so ensure that it gets installed or upgraded # on the target machine install_requires = install_requires, author = 'Cloudera, Inc.', description = 'Cloudera Manager API client', license = 'Proprietary', url = 'http://www.cloudera.com/', )