text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix GH-3 - Fallback to relative finding (just a guess) instead of dying.
<?php // Try to find the application root directory. // Env Variable 'ApplicationPath' is set by the add_environment_variables.ps1 // script. The others are "default" paths of Azure that can be tried as // fallback. if (isset($_SERVER['ApplicationPath'])) { $appRoot = $_SERVER['ApplicationPath'] . '\app'; } else if ( file_exists("E:\approot\app")) { $appRoot = "E:\approot\app"; } else if ( file_exists("F:\approot\app")) { $appRoot = "F:\approot\app"; } else { $appRoot = __DIR__ . '\..\..\approot\app'; } require_once $appRoot . '\bootstrap.php.cache'; require_once $appRoot . '\AppKernel.php'; //require_once $appRoot . '\AppCache.php'; use Symfony\Component\HttpFoundation\Request; $kernel = new AppKernel('azure', false); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send();
<?php // Try to find the application root directory. // Env Variable 'ApplicationPath' is set by the add_environment_variables.ps1 // script. The others are "default" paths of Azure that can be tried as // fallback. if (isset($_SERVER['ApplicationPath'])) { $appRoot = $_SERVER['ApplicationPath'] . '\app'; } else if ( file_exists("E:\approot\app")) { $appRoot = "E:\approot\app"; } else if ( file_exists("F:\approot\app")) { $appRoot = "F:\approot\app"; } else { exit(1); } require_once $appRoot . '\bootstrap.php.cache'; require_once $appRoot . '\AppKernel.php'; //require_once $appRoot . '\AppCache.php'; use Symfony\Component\HttpFoundation\Request; $kernel = new AppKernel('azure', false); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send();
Send the req to the callback.
var forIn = require('for-in'), xobj = require('xhr'), XhrError = require('xhrerror'); function noop() { } function xhr(options, callback, errback) { var req = xobj(); if(Object.prototype.toString.call(options) == '[object String]') { options = { url: options }; } req.open(options.method || 'GET', options.url, true); if(options.credentials) { req.withCredentials = true; } forIn(options.headers || {}, function (value, key) { req.setRequestHeader(key, value); }); req.onreadystatechange = function() { if(req.readyState != 4) return; if([ 200, 304, 0 ].indexOf(req.status) === -1) { (errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status)); } else { (callback || noop)(req); } }; req.send(options.data || void 0); } module.exports = xhr;
var forIn = require('for-in'), xobj = require('xhr'), XhrError = require('xhrerror'); function noop() { } function xhr(options, callback, errback) { var req = xobj(); if(Object.prototype.toString.call(options) == '[object String]') { options = { url: options }; } req.open(options.method || 'GET', options.url, true); if(options.credentials) { req.withCredentials = true; } forIn(options.headers || {}, function (value, key) { req.setRequestHeader(key, value); }); req.onreadystatechange = function() { if(req.readyState != 4) return; if([ 200, 304, 0 ].indexOf(req.status) === -1) { (errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status)); } else { (callback || noop)(req.responseText); } }; req.send(options.data || void 0); } module.exports = xhr;
Kill this use strict for now Should explicitly assign to global at some point I guess.
/*global browser:true, protractor:true, httpBackend:true, By:true, expect:true, Promise:true */ var CustomWorld = (function () { var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); var HttpBackendProxy = require('http-backend-proxy'); var CustomWorld = function CustomWorld () { browser = protractor = require('protractor').getInstance(); httpBackend = new HttpBackendProxy(browser, { buffer: true }); By = protractor.By; chai.use(chaiAsPromised); expect = chai.expect; Promise = require('bluebird'); }; return CustomWorld; })(); module.exports = function () { this.World = function (callback) { var w = new CustomWorld(); return callback(w); }; return this.World; };
/*global browser:true, protractor:true, httpBackend:true, By:true, expect:true, Promise:true */ 'use strict'; var CustomWorld = (function () { var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); var HttpBackendProxy = require('http-backend-proxy'); var CustomWorld = function CustomWorld () { browser = protractor = require('protractor').getInstance(); httpBackend = new HttpBackendProxy(browser, { buffer: true }); By = protractor.By; chai.use(chaiAsPromised); expect = chai.expect; Promise = require('bluebird'); }; return CustomWorld; })(); module.exports = function () { this.World = function (callback) { var w = new CustomWorld(); return callback(w); }; return this.World; };
Use shortcode attribute instead of user role when showing members
<?php # Member template for the 'medlem' shortcode function # The $meta includes member info # Uses a $content variable if available, otherwise the meta description of the actual member. $year = $meta['it_year']; $description = ($content != null) ? $content : $meta['description']; $avatar_size = ($args != null) ? $args['avatar_size'] : 96; ?> <section class="member row"> <figure class="three columns"> <?php echo get_avatar($id, $avatar_size); ?> </figure> <div class="member-details nine columns"> <?php if($role) : ?> <hgroup> <h2><?php user_fullname(get_userdata($id));?></h2> <h3 class="sub"><?php echo $role;?></h3> </hgroup> <?php else : ?> <h2><?php user_fullname(get_userdata($id));?></h2> <?php endif;?> <p class="description"> <?php echo strip_tags($description);?> </p> </div> </section>
<?php # Member template for the 'medlem' shortcode function # The $meta includes member info # Uses a $content variable if available, otherwise the meta description of the actual member. $year = $meta['it_year']; $role = $meta['it_post']; $description = ($content != null) ? $content : $meta['description']; $avatar_size = ($args != null) ? $args['avatar_size'] : 96; ?> <section class="member row"> <figure class="three columns"> <?php echo get_avatar($id, $avatar_size); ?> </figure> <div class="member-details nine columns"> <?php if($role) : ?> <hgroup> <h2><?php user_fullname(get_userdata($id));?></h2> <h3 class="sub"><?php echo $role;?></h3> </hgroup> <?php else : ?> <h2><?php user_fullname(get_userdata($id));?></h2> <?php endif;?> <p class="description"> <?php echo strip_tags($description);?> </p> </div> </section>
Allow chaning report field names
package com.cisco.oss.foundation.logging.transactions; import org.slf4j.Logger; /** * Created by Nuna on 10/01/2016. */ public class ReportLogger extends SchedulerLogger { static private String reportNameFieldName = "ReportName"; static private String reportBodyFieldName = "ReportBody"; static public void setIvpFieldNames(String reportNameFieldName, String reportBodyFieldName) { ReportLogger.reportNameFieldName = reportNameFieldName; ReportLogger.reportBodyFieldName = reportBodyFieldName; } public static void start(final Logger logger, final Logger auditor, final String reportName) { if(!createLoggingAction(logger, auditor, new ReportLogger())) { return; } ReportLogger reportLogger = (ReportLogger) getInstance(); if (reportLogger == null) { return; } reportLogger.startInstance(reportName); } @Override protected void addPropertiesStart(String reportName) { super.addPropertiesStart("Report", reportNameFieldName, reportName); } public static void success(String reportBody) { ReportLogger logger = (ReportLogger) getInstance(); if (logger == null) { return; } addProperty(reportBodyFieldName, reportBody); logger.successInstance(); } }
package com.cisco.oss.foundation.logging.transactions; import org.slf4j.Logger; /** * Created by Nuna on 10/01/2016. */ public class ReportLogger extends SchedulerLogger { public static void start(final Logger logger, final Logger auditor, final String reportName) { if(!createLoggingAction(logger, auditor, new ReportLogger())) { return; } ReportLogger reportLogger = (ReportLogger) getInstance(); if (reportLogger == null) { return; } reportLogger.startInstance(reportName); } @Override protected void addPropertiesStart(String reportName) { super.addPropertiesStart("Report", "ReportName", reportName); } public static void success(String reportBody) { ReportLogger logger = (ReportLogger) getInstance(); if (logger == null) { return; } addProperty("ReportBody", reportBody); logger.successInstance(); } }
Fix copy & paste error
'use strict'; // FUNCTIONS // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // IS POSITIVE NUMBER // /** * Tests if a value is a positive number. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a positive number * * @example * var bool = isPositiveNumber( 5.0 ); * // returns true * @example * var bool = isPositiveNumber( new Number( 5.0 ) ); * // returns true * @example * var bool = isPositiveNumber( 3.14 ); * // returns true * @example * var bool = isPositiveNumber( -5.0 ); * // returns false * @example * var bool = isPositiveNumber( null ); * // returns false */ function isPositiveNumber( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // end FUNCTION isPositiveNumber() // EXPORTS // module.exports = isPositiveNumber;
'use strict'; // FUNCTIONS // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // IS POSITIVE NUMBER // /** * Tests if a value is a nonnegative number. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a positive number * * @example * var bool = isPositiveNumber( 5.0 ); * // returns true * @example * var bool = isPositiveNumber( new Number( 5.0 ) ); * // returns true * @example * var bool = isPositiveNumber( 3.14 ); * // returns true * @example * var bool = isPositiveNumber( -5.0 ); * // returns false * @example * var bool = isPositiveNumber( null ); * // returns false */ function isPositiveNumber( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // end FUNCTION isPositiveNumber() // EXPORTS // module.exports = isPositiveNumber;
Add error handling to browser requests.
/*! @license ©2013 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */ /** Browser replacement for the request module using jQuery. */ var EventEmitter = require('events').EventEmitter, SingleIterator = require('../../lib/iterators/Iterator').SingleIterator; require('setimmediate'); // Requests the given resource as an iterator function createRequest(settings) { var request = new EventEmitter(); // Delegate the request to jQuery's AJAX module var jqXHR = jQuery.ajax({ url: settings.url, timeout: settings.timeout, type: settings.method, headers: { accept: settings.headers && settings.headers.accept || '*/*' }, }) // Emit the result as a readable response iterator .success(function () { var response = new SingleIterator(jqXHR.responseText || ''); response.statusCode = jqXHR.status; response.headers = { 'content-type': jqXHR.getResponseHeader('content-type') }; request.emit('response', response); }) // Emit an error if the request fails .fail(function () { request.emit('error', new Error('Error requesting ' + settings.url)); }); // Aborts the request request.abort = function () { jqXHR.abort(); }; return request; } module.exports = createRequest;
/*! @license ©2013 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */ /** Browser replacement for the request module using jQuery. */ var EventEmitter = require('events').EventEmitter, SingleIterator = require('../../lib/iterators/Iterator').SingleIterator; require('setimmediate'); // Requests the given resource as an iterator function createRequest(settings) { var request = new EventEmitter(); // Delegate the request to jQuery's AJAX module var jqXHR = jQuery.ajax({ url: settings.url, timeout: settings.timeout, type: settings.method, headers: { accept: settings.headers && settings.headers.accept || '*/*' }, }) // Emit the result as a readable response iterator .success(function () { var response = new SingleIterator(jqXHR.responseText || ''); response.statusCode = jqXHR.status; response.headers = { 'content-type': jqXHR.getResponseHeader('content-type') }; request.emit('response', response); }); request.abort = function () { jqXHR.abort(); }; return request; } module.exports = createRequest;
Modify toString method for board array format
var Game = function(boardString){ var board = ''; this.board = ''; if (arguments.length === 1) { this.board = this.toArray(boardString); } else { function random() { return Math.floor(Math.random() * 10 + 6); }; var firstTwo = random(), secondTwo = random(); for ( var i = 0; i < 16; i++ ) { if (i === firstTwo || i === secondTwo) { board += '2'; } else { board += '0'; }; }; this.board = this.toArray(board); } }; Game.prototype = { toString: function() { this.board.forEach(function(row) { console.log(row.join('')); }); }, toArray: function(chars) { var boardArray = []; for( var i = 0; i < 16; i += 4) { var subarray = chars.slice(0 + i, 4 + i); boardArray.push(subarray.split('')); } return boardArray; } };
var Game = function(boardString){ var board = ''; this.board = ''; if (arguments.length === 1) { this.board = this.toArray(boardString); } else { function random() { return Math.floor(Math.random() * 10 + 6); }; var firstTwo = random(), secondTwo = random(); for ( var i = 0; i < 16; i++ ) { if (i === firstTwo || i === secondTwo) { board += '2'; } else { board += '0'; }; }; this.board = this.toArray(board); } }; Game.prototype = { toString: function() { for( var i = 0; i < 16; i += 4){ this.array = this.board.slice(0 + i, 4 + i) console.log(this.array) } }, toArray: function(chars) { var boardArray = []; for( var i = 0; i < 16; i += 4) { var subarray = chars.slice(0 + i, 4 + i); boardArray.push(subarray.split('')); } return boardArray; } };
Update store method to save/create notes
<?php /** * Created by PhpStorm. * User: studio-book * Date: 12/6/16 * Time: 6:36 PM */ namespace ShawnSandy\Summernote\App\Controllers; use App\User; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Auth; use ShawnSandy\Summernote\App\Models\Snotes; use ShawnSandy\Summernote\App\Notes\StoreNotesRequest; class NotesController extends Controller { public function index() { $notes = Snotes::with('user')->get(); return view('notes::index', compact('notes')); } public function show($id) { } public function create() { $images = []; return view('notes::create', compact('images')); } public function store(StoreNotesRequest $request){ $id = Auth::id(); $user = User::find($id); // $notes = $user->notes()->create($request->all()); $notes = $request->user()->snotes()->create($request->all()); return $notes; } public function edit($id){ } public function update(Request $request, $id) { } public function destroy($id){ } }
<?php /** * Created by PhpStorm. * User: studio-book * Date: 12/6/16 * Time: 6:36 PM */ namespace ShawnSandy\Summernote\App\Controllers; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use ShawnSandy\Summernote\App\Models\Snotes; use ShawnSandy\Summernote\App\Notes\StoreNotesRequest; class NotesController extends Controller { public function index() { $notes = Snotes::with('user')->get(); return view('notes::index', compact('notes')); } public function show($id) { } public function create() { $images = []; return view('notes::create', compact('images')); } public function store(StoreNotesRequest $request){ return $request->all(); } public function edit($id){ } public function update(Request $request, $id) { } public function destroy($id){ } }
SAK-29371: Fix javascript errors resulting from SAK-29356
var ASN_SVS = {}; /* For the cancel button - if the user made progress, we need them to confirm that they want to discard their progress */ ASN_SVS.confirmDiscardOrSubmit = function(attachmentsModified) { var inlineProgress = false; var ckEditor = CKEDITOR.instances["$name_submission_text"]; if (ckEditor) { inlineProgress = CKEDITOR.instances["$name_submission_text"].checkDirty(); } var showDiscardDialog = inlineProgress || attachmentsModified; var submitPanel = document.getElementById("submitPanel"); var confirmationDialogue = document.getElementById("confirmationDialogue"); if (showDiscardDialog) { submitPanel.setAttribute('style', 'display:none;'); confirmationDialogue.removeAttribute('style'); } else { ASN_SVS.cancelProceed(); } } ASN_SVS.cancelProceed = function() { document.addSubmissionForm.onsubmit(); document.addSubmissionForm.option.value='cancel'; document.addSubmissionForm.submit(); } ASN_SVS.undoCancel = function() { var submitPanel = document.getElementById("submitPanel"); var confirmationDialogue = document.getElementById("confirmationDialogue"); submitPanel.removeAttribute('style'); confirmationDialogue.setAttribute('style', 'display:none;'); }
var ASN_SVS = {}; /* For the cancel button - if the user made progress, we need them to confirm that they want to discard their progress */ ASN_SVS.confirmDiscardOrSubmit = function(attachmentsModified) { var inlineProgress = false; var ckEditor = CKEDITOR.instances["$name_submission_text"]; if (ckEditor) { inlineProgress = CKEDITOR.instances["$name_submission_text"].checkDirty(); } var showDiscardDialog = inlineProgress || attachmentsModified; var submitPanel = document.getElementById("submitPanel"); var confirmationDialogue = document.getElementById("confirmationDialogue"); if (showDiscardDialog) { submitPanel.setAttribute('style', 'display:none;'); confirmationDialogue.removeAttribute('style'); } else { cancelProceed(); } } ASN_SVS.cancelProceed = function() { document.addSubmissionForm.onsubmit(); document.addSubmissionForm.option.value='cancel'; document.addSubmissionForm.submit(); } ASN_SVS.undoCancel = function() { var submitPanel = document.getElementById("submitPanel"); var confirmationDialogue = document.getElementById("confirmationDialogue"); submitPanel.removeAttribute('style'); confirmationDialogue.setAttribute('style', 'display:none;'); }
Make otp_init() race condition safe. A race condition in get_or_create() may have resulted in two devices created per user. Now we guarantee only one. Not that it matters real much...
# vim:fileencoding=utf8:et:ts=4:sts=4:sw=4:ft=python from django.db import IntegrityError from django_otp import login as otp_login from django_otp.middleware import OTPMiddleware from .sotp.models import SOTPDevice from .totp.models import TOTPDevice def init_otp(request): """ Initialize OTP after login. This sets up OTP devices for django_otp and calls the middleware to fill request.user.is_verified(). """ tdev = TOTPDevice(user=request.user, name='TOTP device with LDAP secret') try: tdev.save() except IntegrityError: tdev = TOTPDevice.objects.get(user=request.user) sdev = SOTPDevice(user=request.user, name='SOTP device with LDAP secret') try: sdev.save() except IntegrityError: pass # if OTP is disabled, it will match already if tdev.verify_token(): otp_login(request, tdev) # add .is_verified() OTPMiddleware().process_request(request)
# vim:fileencoding=utf8:et:ts=4:sts=4:sw=4:ft=python from django_otp import login as otp_login from django_otp.middleware import OTPMiddleware from .sotp.models import SOTPDevice from .totp.models import TOTPDevice def init_otp(request): """ Initialize OTP after login. This sets up OTP devices for django_otp and calls the middleware to fill request.user.is_verified(). """ tdev, created = TOTPDevice.objects.get_or_create( user=request.user, defaults={ 'name': 'TOTP device with LDAP secret', }) if created: tdev.save() sdev, created = SOTPDevice.objects.get_or_create( user=request.user, defaults={ 'name': 'SOTP device with LDAP passwords', }) if created: sdev.save() # if OTP is disabled, it will match already if tdev.verify_token(): otp_login(request, tdev) # add .is_verified() OTPMiddleware().process_request(request)
Add minor change, enforce coding style
import { Meteor } from 'meteor/meteor'; const Elements = {}; Meteor.Elements = Elements; Elements.collection = new Meteor.Collection('Elements'); Elements.types = [ { humanName: 'Reference object', name: 'referenceObject', possibleChildren: [] }, { humanName: 'Hierarchy', name: 'hierarchy', possibleChildren: ['hiearchy', 'referenceObject'] }, { humanName: 'Aggregate', name: 'aggregate', possibleChildren: [] }, { humanName: 'Dimension', name: 'dimension', possibleChildren: [] }, { humanName: 'Dimensions group', name: 'dimensionGroup', possibleChildren: [] }, ]; Elements.add = function add(parentId, typeName) { const elementId = Elements.collection.insert( { parentId, typeName, childIds: [], name: '' }); Elements.collection.update( { _id: parentId }, { $addToSet: { childIds: elementId } } ); return elementId; }; Elements.remove = function remove(elementId, parentId) { Elements.collection.update({ _id: parentId }, { $pull: { childIds: elementId } }); Elements.collection.remove(elementId); }; Elements.setName = (elementId, name) => { Elements.collection.update(elementId, { $set: { name } }); }; Elements.types.nameToHumanName = (name) => { const returnType = Elements.types.find((type) => { if (type.name === name) { return true; } return false; }); return returnType.humanName; }; export default Elements;
import { Meteor } from 'meteor/meteor'; const Elements = {}; Meteor.Elements = Elements; Elements.collection = new Meteor.Collection('Elements'); Elements.types = [ { humanName: 'Reference object', name: 'referenceObject', possibleChildren: [] }, { humanName: 'Hierarchy', name: 'hierarchy', possibleChildren: ['hiearchy', 'referenceObject'] }, { humanName: 'Aggregate', name: 'aggregate', possibleChildren: [] }, { humanName: 'Dimension', name: 'dimension', possibleChildren: [] }, { humanName: 'Dimensions group', name: 'dimensionGroup', possibleChildren: [] }, ]; Elements.add = function add(parentId, typeName) { const elementId = Elements.collection.insert( { parentId, typeName, childIds: [], name: '' }); Elements.collection.update( { _id: parentId }, { $addToSet: { childIds: elementId } } ); return elementId; }; Elements.remove = function remove(elementId, parentId) { Elements.collection.update({ _id: parentId }, { $pull: { childIds: elementId } }); Elements.collection.remove(elementId); }; Elements.setName = (elementId, name) => { Elements.collection.update(elementId, { $set: {name }}); }; Elements.types.nameToHumanName = (name) => { const returnType = Elements.types.find((type) => { if (type.name === name) { return true; } return false; }); return returnType.humanName; }; export default Elements;
Use more natural language for price information
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const fuzz = require('fuzzball') async function productPrice (query, user) { const [products] = await models.sequelize.query('SELECT * FROM Products') const queriedProducts = products .filter((product) => fuzz.partial_ratio(query, product.name) > 75) .map((product) => `${product.name} costs ${product.price}¤`) return { action: 'response', body: queriedProducts.length > 0 ? queriedProducts.join(`, `) : 'Sorry I couldn\'t find any products with that name' } } function testFunction (query, user) { return { action: 'response', body: '3be2e438b7f3d04c89d7749f727bb3bd' } } module.exports = { productPrice, testFunction }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const fuzz = require('fuzzball') async function productPrice (query, user) { const [products] = await models.sequelize.query('SELECT * FROM Products') const queriedProducts = products .filter((product) => fuzz.partial_ratio(query, product.name) > 75) .map((product) => `${product.name}: ${product.price}¤`) return { action: 'response', body: queriedProducts.length > 0 ? queriedProducts.join(` `) : 'Sorry I couldn\'t find any products with that name' } } function testFunction (query, user) { return { action: 'response', body: '3be2e438b7f3d04c89d7749f727bb3bd' } } module.exports = { productPrice, testFunction }
Add hours for each task list item per day
/*global require, module*/ /** @jsx React.DOM */ var React = require('react'), randomMC = require('random-material-color'); var WeeklyViewDay = React.createClass({ render: function () { "use strict"; var iconStyle = { backgroundColor: randomMC.getColor({ text: this.props.taskName }) }; return ( <div className="tile tile-collapse"> <div className="tile-toggle"> <div className="pull-left tile-side"> <div className="avatar avatar-sm avatar-multi" title={this.props.taskName} style={iconStyle}> <span className="">{this.props.iconText}</span> </div> </div> <div className="tile-inner" title={this.props.taskName}> <div className="text-overflow"> {this.props.taskName} <span className="nav nav-list pull-right"> {this.props.hours} </span> </div> </div> </div> </div> ); } }); module.exports = WeeklyViewDay;
/*global require, module*/ /** @jsx React.DOM */ var React = require('react'), randomMC = require('random-material-color'); var WeeklyViewDay = React.createClass({ render: function () { "use strict"; var iconStyle = { backgroundColor: randomMC.getColor({ text: this.props.taskName }) }; return ( <div className="tile tile-collapse"> <div className="tile-toggle"> <div className="pull-left tile-side"> <div className="avatar avatar-sm avatar-multi" title={this.props.taskName} style={iconStyle}> <span className="">{this.props.iconText}</span> </div> </div> <div className="tile-inner" title={this.props.taskName}> <div className="text-overflow">{this.props.taskName}</div> </div> </div> </div> ); } }); module.exports = WeeklyViewDay;
Add LICENSE and static/ back to package data. Adding the static/ just in case there's ever any static files later on, since it's a standard Flask folder. Also, adding all files in templates/ so there's no surprises later on in development.
"""\ Grip ---- Render local readme files before sending off to Github. Grip is easy to set up `````````````````````` :: $ pip install grip $ cd myproject $ grip * Running on http://localhost:5000/ Links ````` * `Website <http://github.com/joeyespo/grip>`_ """ import os import sys from setuptools import setup, find_packages if sys.argv[-1] == 'publish': sys.exit(os.system('python setup.py sdist upload')) def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name='grip', version='1.2.0', description='Render local readme files before sending off to Github.', long_description=__doc__, author='Joe Esposito', author_email='joe@joeyespo.com', url='http://github.com/joeyespo/grip', license='MIT', platforms='any', packages=find_packages(), package_data={'': ['LICENSE'], 'grip': ['static/*', 'templates/*']}, install_requires=read('requirements.txt'), zip_safe=False, entry_points={'console_scripts': ['grip = grip.command:main']}, )
"""\ Grip ---- Render local readme files before sending off to Github. Grip is easy to set up `````````````````````` :: $ pip install grip $ cd myproject $ grip * Running on http://localhost:5000/ Links ````` * `Website <http://github.com/joeyespo/grip>`_ """ import os import sys from setuptools import setup, find_packages if sys.argv[-1] == 'publish': sys.exit(os.system('python setup.py sdist upload')) def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name='grip', version='1.2.0', description='Render local readme files before sending off to Github.', long_description=__doc__, author='Joe Esposito', author_email='joe@joeyespo.com', url='http://github.com/joeyespo/grip', license='MIT', platforms='any', packages=find_packages(), package_data={'grip': ['templates/*.html']}, install_requires=read('requirements.txt'), zip_safe=False, entry_points={'console_scripts': ['grip = grip.command:main']}, )
Fix several warnings in PCM-Java casestudy projects.
package edu.kit.ipd.sdq.vitruvius.casestudies.pcmjava.seffstatements.code2seff; import org.palladiosimulator.pcm.repository.BasicComponent; import org.somox.gast2seff.visitors.AbstractFunctionClassificationStrategy; import org.somox.gast2seff.visitors.InterfaceOfExternalCallFinding; import org.somox.gast2seff.visitors.ResourceDemandingBehaviourForClassMethodFinding; import edu.kit.ipd.sdq.vitruvius.framework.contracts.datatypes.CorrespondenceModel; public interface Code2SEFFFactory { BasicComponentFinding createBasicComponentFinding(); InterfaceOfExternalCallFinding createInterfaceOfExternalCallFinding( CorrespondenceModel correspondenceInstance, BasicComponent basicComponent); ResourceDemandingBehaviourForClassMethodFinding createResourceDemandingBehaviourForClassMethodFinding( CorrespondenceModel correspondenceInstance); AbstractFunctionClassificationStrategy createAbstractFunctionClassificationStrategy( BasicComponentFinding basicComponentFinding, CorrespondenceModel correspondenceInstance, BasicComponent basicComponent); }
package edu.kit.ipd.sdq.vitruvius.casestudies.pcmjava.seffstatements.code2seff; import org.palladiosimulator.pcm.repository.BasicComponent; import org.somox.gast2seff.visitors.AbstractFunctionClassificationStrategy; import org.somox.gast2seff.visitors.InterfaceOfExternalCallFinding; import org.somox.gast2seff.visitors.ResourceDemandingBehaviourForClassMethodFinding; import edu.kit.ipd.sdq.vitruvius.framework.contracts.datatypes.CorrespondenceModel; import edu.kit.ipd.sdq.vitruvius.framework.contracts.meta.correspondence.Correspondence; public interface Code2SEFFFactory { BasicComponentFinding createBasicComponentFinding(); InterfaceOfExternalCallFinding createInterfaceOfExternalCallFinding( CorrespondenceModel correspondenceInstance, BasicComponent basicComponent); ResourceDemandingBehaviourForClassMethodFinding createResourceDemandingBehaviourForClassMethodFinding( CorrespondenceModel correspondenceInstance); AbstractFunctionClassificationStrategy createAbstractFunctionClassificationStrategy( BasicComponentFinding basicComponentFinding, CorrespondenceModel correspondenceInstance, BasicComponent basicComponent); }
Add a directory and clean and clobber tasks.
var Path = require("path"), futil = require("sake/file-utils"), files = new FileList("**/*", "some/non-existing/file.js") ; require("sake/clean"); require("sake/clobber"); desc("Sample task one."); task("one", ["two"], function (t) { // task actions t.done(); }); desc("Sample task two."); task("two", function (t) { t.done(); }); directory("tmp/path/directory"); CLOBBER.include("tmp"); desc("Test text file."); fileSync("tmp/path/directory/test.txt", ["tmp/path/directory", "LICENSE"], function (t) { console.log(t.name); write(t.name, read(t.prerequisites[1], "utf8"), "utf8"); }); CLEAN.include("tmp/path/directory/test.txt"); desc("Default task."); task("default", ["tmp/path/directory/test.txt"]); taskSync("testSync", function (t) { console.log(t.name); }); taskSync("testSync2", ["testSync"], function (t) { console.log(t.name); }); // console.log(task("one").prerequisites.length); // console.log(Object.keys(Task.tasks)); // console.log(Task.getAll()); // console.log(Task.get("one") + "");
var Path = require("path"), futil = require("sake/file-utils"), files = new FileList("**/*", "some/non-existing/file.js") ; require("sake/clean"); require("sake/clobber"); desc("Sample task one."); task("one", ["two"], function (t) { // task actions t.done(); }); desc("Sample task two."); task("two", function (t) { t.done(); }); desc("Test text file."); file("test.txt", ["LICENSE"], function (t) { console.log(t.name); write(t.name, read(t.prerequisites[0], "utf8"), "utf8"); t.done(); }); desc("Default task."); task("default", ["test.txt"]); taskSync("testSync", function (t) { console.log(t.name); }); taskSync("testSync2", ["testSync"], function (t) { console.log(t.name); }); // console.log(task("one").prerequisites.length); // console.log(Object.keys(Task.tasks)); // console.log(Task.getAll()); // console.log(Task.get("one") + "");
Update Help Props So Popup Remains On-Screen
import React from 'react'; import { storiesOf } from '@storybook/react'; import { text, select } from '@storybook/addon-knobs'; import OptionsHelper from '../../utils/helpers/options-helper'; import notes from './notes.md'; import Help from './help'; storiesOf('Help', module) .add('default', () => { const children = text('children', 'This is help text'); const tooltipPosition = children ? select( 'tooltipPosition', OptionsHelper.positions, 'right' ) : undefined; const tooltipAlign = children ? select( 'tooltipAlign', OptionsHelper.alignAroundEdges, Help.defaultProps.tooltipAlign ) : undefined; const href = text('href', ''); return ( <Help tooltipPosition={ tooltipPosition } tooltipAlign={ tooltipAlign } href={ href } > {children} </Help> ); }, { notes: { markdown: notes } });
import React from 'react'; import { storiesOf } from '@storybook/react'; import { text, select } from '@storybook/addon-knobs'; import OptionsHelper from '../../utils/helpers/options-helper'; import notes from './notes.md'; import Help from './help'; storiesOf('Help', module) .add('default', () => { const children = text('children', 'This is help text'); const tooltipPosition = children ? select( 'tooltipPosition', OptionsHelper.positions, Help.defaultProps.tooltipPosition ) : undefined; const tooltipAlign = children ? select( 'tooltipAlign', OptionsHelper.alignAroundEdges, Help.defaultProps.tooltipAlign ) : undefined; const href = text('href', ''); return ( <Help tooltipPosition={ tooltipPosition } tooltipAlign={ tooltipAlign } href={ href } > {children} </Help> ); }, { notes: { markdown: notes } });
Update the PyPI version to 0.2.18.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.18', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.17', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Add mime type for sourcemaps.
from django.conf import settings from django.template import RequestContext from django.http import HttpResponse, HttpResponseNotFound from django.template import Template from cancer_browser.core.http import HttpResponseSendFile from django.core.urlresolvers import reverse import os, re def client_vars(request, base): return { 'settings': 'enable', 'jslogging': settings.JSLOGGING, 'ga_id': settings.GA_ID, 'baseurl': base, } types = { 'js': 'application/javascript', 'png': 'image/png', 'css': 'text/css', 'map': 'application/json' } def content(request, filename): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), filename) ext = os.path.splitext(filename)[1][1:] if os.path.exists(path): return HttpResponseSendFile(path, types[ext]) return HttpResponseNotFound() def drop_last(path): return re.sub(r"[^/]+/$", "", path) def page(request): from django.middleware.csrf import get_token get_token(request) # force csrf cvars = client_vars(request, drop_last(reverse(page))) dirname = os.path.dirname(os.path.realpath(__file__)) t = Template(open(os.path.join(dirname, 'index.html')).read()); c = RequestContext(request, cvars) return HttpResponse(t.render(c))
from django.conf import settings from django.template import RequestContext from django.http import HttpResponse, HttpResponseNotFound from django.template import Template from cancer_browser.core.http import HttpResponseSendFile from django.core.urlresolvers import reverse import os, re def client_vars(request, base): return { 'settings': 'enable', 'jslogging': settings.JSLOGGING, 'ga_id': settings.GA_ID, 'baseurl': base, } types = { 'js': 'application/javascript', 'png': 'image/png', 'css': 'text/css' } def content(request, filename): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), filename) ext = os.path.splitext(filename)[1][1:] if os.path.exists(path): return HttpResponseSendFile(path, types[ext]) return HttpResponseNotFound() def drop_last(path): return re.sub(r"[^/]+/$", "", path) def page(request): from django.middleware.csrf import get_token get_token(request) # force csrf cvars = client_vars(request, drop_last(reverse(page))) dirname = os.path.dirname(os.path.realpath(__file__)) t = Template(open(os.path.join(dirname, 'index.html')).read()); c = RequestContext(request, cvars) return HttpResponse(t.render(c))
Enable Python 3 compatibility using 2to3.
from setuptools import setup, find_packages CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Internationalization', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Localization', 'Topic :: Text Processing :: Linguistic', ] LONG_DESC = open('README.rst', 'rt').read() + '\n\n' + open('CHANGES.rst', 'rt').read() setup( name='num2words', version='0.5.0', description='Modules to convert numbers to words. Easily extensible.', license='LGPL', author='Taro Ogawa <tso at users sourceforge net>', author_email='tos@users.sourceforge.net', maintainer='Savoir-faire Linux inc.', maintainer_email='virgil.dupras@savoirfairelinux.com', keywords=' number word numbers words convert conversion i18n localisation localization internationalisation internationalization', url='https://github.com/savoirfairelinux/num2words', packages=find_packages(), use_2to3=True, )
from setuptools import setup, find_packages CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Internationalization', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Localization', 'Topic :: Text Processing :: Linguistic', ] LONG_DESC = open('README.rst', 'rt').read() + '\n\n' + open('CHANGES.rst', 'rt').read() setup( name='num2words', version='0.5.0', description='Modules to convert numbers to words. Easily extensible.', license='LGPL', author='Taro Ogawa <tso at users sourceforge net>', author_email='tos@users.sourceforge.net', maintainer='Savoir-faire Linux inc.', maintainer_email='virgil.dupras@savoirfairelinux.com', keywords=' number word numbers words convert conversion i18n localisation localization internationalisation internationalization', url='https://github.com/savoirfairelinux/num2words', packages=find_packages(), )
Use defaults from eslint react plugin
module.exports = { 'env': { 'browser': true, 'commonjs': true, 'es6': true }, 'extends': ['eslint:recommended', 'plugin:react/recommended'], 'installedESLint': true, 'parserOptions': { 'ecmaFeatures': { 'experimentalObjectRestSpread': true, 'jsx': true }, 'sourceType': 'module' }, 'plugins': [ 'react' ], 'rules': { 'indent': [ 'error', 'tab' ], 'linebreak-style': [ 'error', 'unix' ], 'quotes': [ 'error', 'single' ], 'semi': [ 'error', 'never' ] } };
module.exports = { 'env': { 'browser': true, 'commonjs': true, 'es6': true }, 'extends': 'eslint:recommended', 'installedESLint': true, 'parserOptions': { 'ecmaFeatures': { 'experimentalObjectRestSpread': true, 'jsx': true }, 'sourceType': 'module' }, 'plugins': [ 'react' ], 'rules': { 'indent': [ 'error', 'tab' ], 'linebreak-style': [ 'error', 'unix' ], 'quotes': [ 'error', 'single' ], 'semi': [ 'error', 'never' ] } };
Use SHA-1 hash of identity for codesign
/** * @module util-identities */ 'use strict' const util = require('./util') const debuglog = util.debuglog const flatList = util.flatList const execFileAsync = util.execFileAsync /** * This function returns a promise checking the indentity proposed and updates the identity option to a exact finding from results. * @function * @param {Object} opts - Options. * @param {string} identity - The proposed identity. * @returns {Promise} Promise. */ module.exports.findIdentitiesAsync = function (opts, identity) { // Only to look for valid identities, excluding those flagged with // CSSMERR_TP_CERT_EXPIRED or CSSMERR_TP_NOT_TRUSTED. Fixes #9 var args = [ 'find-identity', '-v' ] if (opts.keychain) { args.push(opts.keychain) } return execFileAsync('security', args) .then(function (result) { return result.split('\n').map(function (line) { if (line.indexOf(identity) >= 0) { var identityFound = line.substring(line.indexOf('"') + 1, line.lastIndexOf('"')) var identityHashFound = line.substring(line.indexOf(')') + 2, line.indexOf('"') - 1) debuglog('Identity:', '\n', '> Name:', identityFound, '\n', '> Hash:', identityHashFound) return identityHashFound } }) }) .then(flatList) }
/** * @module util-identities */ 'use strict' const util = require('./util') const debuglog = util.debuglog const flatList = util.flatList const execFileAsync = util.execFileAsync /** * This function returns a promise checking the indentity proposed and updates the identity option to a exact finding from results. * @function * @param {Object} opts - Options. * @param {string} identity - The proposed identity. * @returns {Promise} Promise. */ module.exports.findIdentitiesAsync = function (opts, identity) { // Only to look for valid identities, excluding those flagged with // CSSMERR_TP_CERT_EXPIRED or CSSMERR_TP_NOT_TRUSTED. Fixes #9 var args = [ 'find-identity', '-v' ] if (opts.keychain) { args.push(opts.keychain) } return execFileAsync('security', args) .then(function (result) { return result.split('\n').map(function (line) { if (line.indexOf(identity) >= 0) { var identityFound = opts['use-cert-id'] ? line.substring(line.indexOf(')') + 2, line.indexOf('"') - 1) : line.substring(line.indexOf('"') + 1, line.lastIndexOf('"')) debuglog('Identity:', '\n', '> Name:', identityFound) return identityFound } }) }) .then(flatList) }
Adjust prop type defs in navigation-main
//@flow import React from "react"; import { Title, Wrapper } from "./styled-components"; import { MainNav } from "../../elements/navigation-main"; import { Highlight } from "../../elements/highlight"; import { Skewify } from "../../elements/skewify"; import { MobileMenuButton } from "../../elements/mobile-menu-button"; import addActiveState from "../../global/hoc/addActiveState"; type props = { openMobileNav: () => mixed, closeMobileNav: () => {}, newMobileMenuButtonStatus: ()=>{}, ui: { mobileMenuButtonStatus: string, mobileMenuIsOpen: boolean, breakpoints: { [string]: { [string]: mixed } } } }; const ActiveTitle = addActiveState(Title); export const HeaderMain = (props: props) => <Wrapper> {props.ui.breakpoints.main.device === "mobile" && <MobileMenuButton {...props} />} <ActiveTitle> <Highlight url="/" highlightColor="transparent"> Oliver <Skewify>Askew</Skewify> </Highlight> </ActiveTitle> {props.ui.breakpoints.main.device === "desktop" && <MainNav {...props} />} </Wrapper>;
//@flow import React from "react"; import { Title, Wrapper } from "./styled-components"; import { MainNav } from "../../elements/navigation-main"; import { Highlight } from "../../elements/highlight"; import { Skewify } from "../../elements/skewify"; import { MobileMenuButton } from "../../elements/mobile-menu-button"; import addActiveState from "../../global/hoc/addActiveState"; type props = { openMobileNav: () => mixed, closeMobileNav: () => mixed, ui: { mobileMenuIsOpen: boolean, breakpoints: { main: { device: string } } } }; const ActiveTitle = addActiveState(Title); export const HeaderMain = (props: props) => <Wrapper> {props.ui.breakpoints.main.device === "mobile" && <MobileMenuButton {...props} />} <ActiveTitle> <Highlight url="/" highlightColor="transparent"> Oliver <Skewify>Askew</Skewify> </Highlight> </ActiveTitle> {props.ui.breakpoints.main.device === "desktop" && <MainNav {...props} />} </Wrapper>;
Add group reference to new mark instances.
import Bounds from './Bounds'; import GroupItem from './GroupItem'; export default function Scenegraph() { this.root = createMark({ marktype: 'group', interactive: false }); this.root.items = [new GroupItem(this.root)]; } var prototype = Scenegraph.prototype; prototype.select = function(path, markdef) { var group = this.root.items[0], mark = group.items[path[0]], i, n; try { for (i=1, n=path.length-1; i<n; ++i) { group = mark.items[path[i++]]; mark = group.items[path[i]]; } if (!mark && !markdef) throw n; if (markdef) { mark = createMark(markdef, group); group.items[path[n]] = mark; } return mark; } catch (err) { error('Invalid scenegraph path: ' + path); } }; function error(msg) { throw Error(msg); } function createMark(def, group) { return { bounds: new Bounds(), clip: !!def.clip, group: group, interactive: def.interactive === false ? false : true, items: [], marktype: def.marktype, name: def.name || undefined, role: def.role || undefined }; }
import Bounds from './Bounds'; import GroupItem from './GroupItem'; export default function Scenegraph() { this.root = createMark({ marktype: 'group', interactive: false }); this.root.items = [new GroupItem(this.root)]; } var prototype = Scenegraph.prototype; prototype.select = function(path, markdef) { var items = this.root.items[0], node, i, n; for (i=0, n=path.length-1; i<n; ++i) { items = items.items[path[i]]; if (!items) error('Invalid scenegraph path: ' + path); } items = items.items; if (!(node = items[path[n]])) { if (markdef) items[path[n]] = node = createMark(markdef); else error('Invalid scenegraph path: ' + path); } return node; }; function error(msg) { throw Error(msg); } function createMark(def) { return { bounds: new Bounds(), clip: !!def.clip, interactive: def.interactive === false ? false : true, items: [], marktype: def.marktype, name: def.name || undefined, role: def.role || undefined }; }
Fix signature of the UseControllerWork to respect last changes in WorkedInterface PHP Fatal error: Declaration of Symfony\Bundle\AsseticBundle\Factory\Worker\UseControllerWorker::process() must be compatible with Assetic\Factory\Worker\WorkerInterface::process(Assetic\Asset\AssetInterface $asset, Assetic\Factory\AssetFactory $factory)
<?php /* * This file is part of the Symfony framework. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Symfony\Bundle\AsseticBundle\Factory\Worker; use Assetic\Asset\AssetInterface; use Assetic\Factory\Worker\WorkerInterface; use Assetic\Factory\AssetFactory; /** * Prepends a fake front controller so the asset knows where it is-ish. * * @author Kris Wallsmith <kris@symfony.com> */ class UseControllerWorker implements WorkerInterface { public function process(AssetInterface $asset, AssetFactory $factory) { $targetUrl = $asset->getTargetPath(); if ($targetUrl && '/' != $targetUrl[0] && 0 !== strpos($targetUrl, '_controller/')) { $asset->setTargetPath('_controller/'.$targetUrl); } return $asset; } }
<?php /* * This file is part of the Symfony framework. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Symfony\Bundle\AsseticBundle\Factory\Worker; use Assetic\Asset\AssetInterface; use Assetic\Factory\Worker\WorkerInterface; /** * Prepends a fake front controller so the asset knows where it is-ish. * * @author Kris Wallsmith <kris@symfony.com> */ class UseControllerWorker implements WorkerInterface { public function process(AssetInterface $asset) { $targetUrl = $asset->getTargetPath(); if ($targetUrl && '/' != $targetUrl[0] && 0 !== strpos($targetUrl, '_controller/')) { $asset->setTargetPath('_controller/'.$targetUrl); } return $asset; } }
Make the mock actually a mock instead of a spy
<?php namespace Foo; class FooTest extends \PHPUnit_Framework_TestCase { public function testDummy() { $dependency = $this->prophesize(\Foo\DependencyInterface::class); $foo = new Foo($dependency->reveal()); $this->assertTrue($foo->bar()); } public function testStub() { $dependency = $this->prophesize(\Foo\DependencyInterface::class); $dependency->boolGenerator(1)->willReturn(true); $foo = new Foo($dependency->reveal()); $this->assertTrue($foo->baz()); } public function testMock() { $dependency = $this->prophesize(\Foo\DependencyInterface::class); $foo = new Foo($dependency->reveal()); $dependency->boolGenerator(1)->shouldBeCalled(); $foo->baz(); } public function testSpy() { $dependency = $this->prophesize(\Foo\DependencyInterface::class); $foo = new Foo($dependency->reveal()); $foo->baz(); $dependency->boolGenerator(1)->shouldHaveBeenCalled(); } }
<?php namespace Foo; class FooTest extends \PHPUnit_Framework_TestCase { public function testDummy() { $dependency = $this->prophesize(\Foo\DependencyInterface::class); $foo = new Foo($dependency->reveal()); $this->assertTrue($foo->bar()); } public function testStub() { $dependency = $this->prophesize(\Foo\DependencyInterface::class); $dependency->boolGenerator(1)->willReturn(true); $foo = new Foo($dependency->reveal()); $this->assertTrue($foo->baz()); } public function testMock() { $dependency = $this->prophesize(\Foo\DependencyInterface::class); $foo = new Foo($dependency->reveal()); $foo->baz(); $dependency->boolGenerator(1)->shouldBeCalled(); } public function testSpy() { $dependency = $this->prophesize(\Foo\DependencyInterface::class); $foo = new Foo($dependency->reveal()); $foo->baz(); $dependency->boolGenerator(1)->shouldHaveBeenCalled(); } }
Set migrate command settings back to production
<?php namespace jorenvanhocht\Blogify\Commands; use Illuminate\Console\Command; class BlogifyMigrateCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'blogify:migrate'; /** * The console command description. * * @var string */ protected $description = 'Run the migrations for the Blogify package'; /** * @var array */ protected $paths; /** * Construct the class */ public function __construct() { parent::__construct(); $this->paths = [ 'vendor/jorenvanhocht/blogify/database/Migrations', 'vendor/jorenvanhocht/tracert/database/Migrations', ]; } /** * Execute the console command. * * @return mixed */ public function fire() { foreach ($this->paths as $path) { $this->call('migrate', ['--path' => $path]); } } }
<?php namespace jorenvanhocht\Blogify\Commands; use Illuminate\Console\Command; class BlogifyMigrateCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'blogify:migrate'; /** * The console command description. * * @var string */ protected $description = 'Run the migrations for the Blogify package'; /** * @var array */ protected $paths; /** * Construct the class */ public function __construct() { parent::__construct(); $this->paths = [ 'packages/jorenvanhocht/blogify/database/Migrations', 'vendor/jorenvanhocht/tracert/database/Migrations', ]; } /** * Execute the console command. * * @return mixed */ public function fire() { foreach ($this->paths as $path) { $this->call('migrate', ['--path' => $path]); } } }
Update name and JSDoc for raw email collab constant.
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; /** * NOTE: The following constant corresponds to the general collaborator field in * {@link_RawTripData} and is not an actual field in a trip document. */ export const RAW_COLLAB_EMAILS = 'collaboratorEmails'; export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; /** * NOTE: The following constant corresponds to the collaborator field in * {@link_RawTripData} and is not a field in a trip document. */ export const RAW_TRIP_COLLABS = 'collaborator_email_arr'; export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
Use consistent naming in gorilla/mux middleware
// (c) Copyright IBM Corp. 2021 // (c) Copyright Instana Inc. 2016 // +build go1.12 package instamux import ( "net/http" "github.com/gorilla/mux" instana "github.com/instana/go-sensor" ) // AddMiddleware instruments the mux.Router instance with Instana func AddMiddleware(sensor *instana.Sensor, router *mux.Router) { router.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { pathTemplate, err := mux.CurrentRoute(req).GetPathTemplate() if err != nil { sensor.Logger().Debug("can not get path template from the route: ", err) pathTemplate = "" } instana.TracingHandlerFunc(sensor, pathTemplate, func(w http.ResponseWriter, req *http.Request) { next.ServeHTTP(w, req) })(w, req) }) }) }
// (c) Copyright IBM Corp. 2021 // (c) Copyright Instana Inc. 2016 // +build go1.12 package instamux import ( "net/http" "github.com/gorilla/mux" instana "github.com/instana/go-sensor" ) // AddMiddleware instruments the mux.Router instance with Instana func AddMiddleware(sensor *instana.Sensor, router *mux.Router) { router.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { pathTemplate, err := mux.CurrentRoute(r).GetPathTemplate() if err != nil { sensor.Logger().Debug("can not get path template from the route: ", err.Error()) pathTemplate = "" } instana.TracingHandlerFunc(sensor, pathTemplate, func(writer http.ResponseWriter, request *http.Request) { next.ServeHTTP(writer, request) })(w, r) }) }) }
Fix to init db in reset() method if needed.
"use strict" var PointerQueue = module.exports = (function() { let Datastore = require('nedb'); function PointerQueue() { this.db = null; } PointerQueue.prototype.getDb = function() { if (this.db == undefined) { let prefix = 'db/'; let file = prefix + 'pointerqueue.db'; this.db = new Datastore({ filename: file, autoload: true}); } return this.db; }; PointerQueue.prototype.reset = function() { let db = this.getDb(); db.remove({}, {multi: true}, function(err, numRemoved) { if (err) { console.log(err); throw err; } }); }; PointerQueue.prototype.add = function(className, objectId, attrName, data) { let db = this.getDb(); let store = { className: className , objectId: objectId , attrName: attrName , data: data }; db.insert(store, function(err, newDoc) { if (err) { console.error(err); throw err; } }); }; return PointerQueue; })();
"use strict" var PointerQueue = module.exports = (function() { let Datastore = require('nedb'); function PointerQueue() { this.db = null; } PointerQueue.prototype.getDb = function() { if (this.db == undefined) { let prefix = 'db/'; let file = prefix + 'pointerqueue.db'; this.db = new Datastore({ filename: file, autoload: true}); } return this.db; }; PointerQueue.prototype.reset = function() { if (this.db == null) { return; } this.db.remove({}, {multi: true}, function(err, numRemoved) { if (err) { console.log(err); throw err; } }); }; PointerQueue.prototype.add = function(className, objectId, attrName, data) { let db = this.getDb(); let store = { className: className , objectId: objectId , attrName: attrName , data: data }; db.insert(store, function(err, newDoc) { if (err) { console.error(err); throw err; } }); }; return PointerQueue; })();
Use the new API for models
package main import ( "goldorak" "strconv" ) func main() { /******************/ /* Initialization */ /******************/ goldorak.Initialize("config.json") conn := goldorak.Connect() calendar := conn.NewModel("calendar") /***********/ /* Actions */ /***********/ // Layout goldorak.DefaultLayout(func(action *goldorak.Action) { action.Assign("favicon", goldorak.StaticUrl("favicon.png")) action.Assign("stylesheet", goldorak.StaticUrl("styles.css")) action.Template("layout") }) // Hello world goldorak.Get("/hello", func(action *goldorak.Action, params []string) { action.Assign("name", "world") action.NoLayout() action.Template("hello") }); // Show a calendar goldorak.Get("/.*(/[0-9]+/[0-9]+)?", func(action *goldorak.Action, params []string) { cal := calendar.Find(params[0]) if cal != nil { // Show the calendar year, _ := strconv.Atoi(params[0]) month,_ := strconv.Atoi(params[1]) action.Assign("name", cal.Get("title")) action.Assign("not_used", string(year + month)) action.Template("calendar") } else { // TODO create a new calendar } }); /************/ /* Let's go */ /************/ goldorak.Start() }
package main import "goldorak" func main() { /******************/ /* Initialization */ /******************/ goldorak.Initialize("config.json") //calendar := goldorak.NewModel("calendar") /***********/ /* Actions */ /***********/ // Layout goldorak.DefaultLayout(func(action *goldorak.Action) { action.Assign("favicon", goldorak.StaticUrl("favicon.png")) action.Assign("stylesheet", goldorak.StaticUrl("styles.css")) action.Template("layout") }) // Hello world goldorak.Get("/hello", func(action *goldorak.Action, params []string) { action.Assign("name", params[0]) //action.Assign("name", calendar.Find("hello").Get("world")) //action.NoLayout() action.Template("hello") }); // Show a calendar goldorak.Get("/calendars/.*", func(action *goldorak.Action, params []string) { action.Template("calendar") }); /************/ /* Let's go */ /************/ goldorak.Start() }
Move statics to the class
import React, { Component } from 'react'; import hoistStatics from 'hoist-non-react-statics'; /* When this decorator is used, it MUST be the first (outermost) decorator. Otherwise, we cannot find and call the fetchData methods. */ export default function connectData(fetchData, clientOnly = false) { return function wrapWithFetchData(WrappedComponent) { class ConnectData extends Component { static fetchData = fetchData; static fetchInClientOnly = clientOnly; render() { return <WrappedComponent { ...this.props } />; } } return hoistStatics(ConnectData, WrappedComponent); }; }
import React, { Component } from 'react'; import hoistStatics from 'hoist-non-react-statics'; /* When this decorator is used, it MUST be the first (outermost) decorator. Otherwise, we cannot find and call the fetchData methods. */ export default function connectData(fetchData, clientOnly = false) { return function wrapWithFetchData(WrappedComponent) { class ConnectData extends Component { render() { return <WrappedComponent { ...this.props } />; } } ConnectData.fetchData = fetchData; ConnectData.fetchInClientOnly = clientOnly; return hoistStatics(ConnectData, WrappedComponent); }; }
Add raw string tests to validation tests
var test = require('tape'); var validate = require('../candidate'); var validCandidates = [ { mid: 'data', candidate: 'a=candidate:2441410931 1 udp 2121670399 172.17.42.1 40992 typ host generation 0' }, 'a=candidate:2441410931 1 udp 2121670399 172.17.42.1 40992 typ host generation 0' ]; var invalidCandidates = [ { mid: 'data', candidate: 'a=candidate:2365396244 1 udp 1853300479 10.17.131.21 59229 typ raddr 172.17.42.1 rport 59229 generation 0' }, 'a=candidate:2365396244 1 udp 1853300479 10.17.131.21 59229 typ raddr 172.17.42.1 rport 59229 generation 0' ]; test('valid candidates pass validation', function(t) { t.plan(validCandidates.length); validCandidates.forEach(function(candidate) { t.equal(validate(candidate).length, 0, 'validated ok'); }); }); test('invalid candidates are detected', function(t) { t.plan(invalidCandidates.length); invalidCandidates.forEach(function(candidate) { var errors = validate(candidate); t.ok(errors.length > 0, 'validation error detected'); }); });
var test = require('tape'); var validate = require('../candidate'); var validCandidates = [ { mid: 'data', candidate: 'a=candidate:2441410931 1 udp 2121670399 172.17.42.1 40992 typ host generation 0' } ]; var invalidCandidates = [ { mid: 'data', candidate: 'a=candidate:2365396244 1 udp 1853300479 10.17.131.21 59229 typ raddr 172.17.42.1 rport 59229 generation 0' } ]; test('valid candidates pass validation', function(t) { t.plan(validCandidates.length); validCandidates.forEach(function(candidate) { t.equal(validate(candidate).length, 0, 'validated ok'); }); }); test('invalid candidates are detected', function(t) { t.plan(invalidCandidates.length); invalidCandidates.forEach(function(candidate) { var errors = validate(candidate); t.ok(errors.length > 0, 'validation error detected'); }); });
Fix standards tests for log levels
import sys def test_level_standards(logging, log): """ Ensure that the standard log levels work """ import logging_levels.standards del sys.modules['logging_levels.standards'] # Force module to re-import assert logging.TRACE == 5 assert logging.VERBOSE == 7 log.verbose("I've said too much") assert log.last() == ['VERBOSE', "I've said too much"] log.trace("But I haven't said enough") assert log.last() == ['TRACE', "But I haven't said enough"] def test_standards_suppressed(logging, log): """ Ensure that the suppressed log level includes the suppressed exception """ import logging_levels.standards del sys.modules['logging_levels.standards'] # Force module to re-import assert logging.SUPPRESSED try: raise Exception('Suppress this') except: log.suppressed('Suppressed exception') lines = ''.join(log.readlines()) assert lines.startswith('SUPPRESSED:') assert 'Exception: Suppress this' in lines
import sys def test_level_standards(logging, log): """ Ensure that the standard log levels work """ import logging_levels.standards del sys.modules['logging_levels.standards'] # Force module to re-import assert logging.TRACE == 8 assert logging.VERBOSE == 9 log.verbose("I've said too much") assert log.last() == ['VERBOSE', "I've said too much"] log.trace("But I haven't said enough") assert log.last() == ['TRACE', "But I haven't said enough"] def test_standards_suppressed(logging, log): """ Ensure that the suppressed log level includes the suppressed exception """ import logging_levels.standards del sys.modules['logging_levels.standards'] # Force module to re-import assert logging.SUPPRESSED try: raise Exception('Suppress this') except: log.suppressed('Suppressed exception') lines = ''.join(log.readlines()) assert lines.startswith('SUPPRESSED:') assert 'Exception: Suppress this' in lines
Add an API to clear cache
var createCache = require('uber-cache'); var defaultSize = 100; function normalizeOptions(options) { options = options || {}; options.size = options.size || defaultSize; return options; } function Cache(options) { options = normalizeOptions(options); this.cache = createCache({ size: options.size }); this.nGets = 0; this.nHits = 0; } Cache.prototype = { 'get': function(key, callback) { return this.cache.get(key, function(error, cachedResponse) { this.nGets++; if (cachedResponse) { this.nHits++; } callback(error, cachedResponse); }.bind(this)); }, 'set': function(key, value, ttl, callback) { return this.cache.set(key, value, ttl, callback); }, getStatistics: function() { var hitRatio; if (this.nGets == 0) { hitRatio = 0.0; } else { hitRatio = (this.nHits / this.nGets) * 100; } return { "nGets": this.nGets, "nHits": this.nHits, "hitRatio": hitRatio }; }, clear: function(callack) { this.cache.clear(callack); } }; module.exports = Cache;
var createCache = require('uber-cache'); var defaultSize = 100; function normalizeOptions(options) { options = options || {}; options.size = options.size || defaultSize; return options; } function Cache(options) { options = normalizeOptions(options); this.cache = createCache({ size: options.size }); this.nGets = 0; this.nHits = 0; } Cache.prototype = { 'get': function(key, callback) { return this.cache.get(key, function(error, cachedResponse) { this.nGets++; if (cachedResponse) { this.nHits++; } callback(error, cachedResponse); }.bind(this)); }, 'set': function(key, value, ttl, callback) { return this.cache.set(key, value, ttl, callback); }, getStatistics: function() { var hitRatio; if (this.nGets == 0) { hitRatio = 0.0; } else { hitRatio = (this.nHits / this.nGets) * 100; } return { "nGets": this.nGets, "nHits": this.nHits, "hitRatio": hitRatio }; } }; module.exports = Cache;
Convert to float then to text.
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, division import six from .attribute import Attribute import decimal class DecimalAttribute(Attribute): type = decimal.Decimal def prepare(self, value): if value is None: return None return six.text_type(float(value)) def clean(self, value): if isinstance(value, decimal.Decimal): # Value is already an integer. return value if isinstance(value, six.string_types): # Strip the string of whitespace value = value.strip() if not value: # Value is nothing; return nothing. return None try: # Attempt to coerce whatever we have as an int. return decimal.Decimal(value) except ValueError: # Failed to do so. raise ValueError('Not a valid decimal value.')
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, division import six from .attribute import Attribute import decimal class DecimalAttribute(Attribute): type = decimal.Decimal def prepare(self, value): if value is None: return None return six.text_type(value) def clean(self, value): if isinstance(value, decimal.Decimal): # Value is already an integer. return value if isinstance(value, six.string_types): # Strip the string of whitespace value = value.strip() if not value: # Value is nothing; return nothing. return None try: # Attempt to coerce whatever we have as an int. return decimal.Decimal(value) except ValueError: # Failed to do so. raise ValueError('Not a valid decimal value.')
Add deploy task to deploy a new Nginx index page
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ] def deploy_page(): run('rm -rf fabric-workshop') run('git clone https://github.com/zkan/fabric-workshop.git') run('sudo cp fabric-workshop/index.html /usr/share/nginx/html') run('sudo service nginx restart')
# Simple Tasks def hello(): print 'Hello ThaiPy!' def hi(name='Kan'): print 'Hi ' + name # Local Commands from fabric.api import local, lcd def deploy_fizzbuzz(): with lcd('fizzbuzz'): local('python fizzbuzz_test.py') local('git add fizzbuzz.py fizzbuzz_test.py') local('git commit') local('git push origin master') # Remote Commands from fabric.api import cd, env, run env.hosts = [ 'vagrant@192.168.66.77:22', ] env.passwords = { 'vagrant@192.168.66.77:22': 'vagrant' } def create_empty_file(name='test'): env.forward_agent = True run('touch ' + name) run('ls -al') # ssh-add ~/.ssh/thaipy-demo.pem since accessing EC2 requires a key pair def my_ec2(): env.hosts = [ 'ubuntu@54.251.184.112:22', ]
Change the hash function to be generic and consistent for both family and factory.
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.vxquery.runtime.factory.hashfunction; import edu.uci.ics.hyracks.api.dataflow.value.IBinaryHashFunction; import edu.uci.ics.hyracks.api.dataflow.value.IBinaryHashFunctionFactory; import edu.uci.ics.hyracks.data.std.accessors.MurmurHash3BinaryHashFunctionFamily; public class VXQueryRawBinaryHashFunctionFactory implements IBinaryHashFunctionFactory { private static final long serialVersionUID = 1L; public static IBinaryHashFunctionFactory INSTANCE = new VXQueryRawBinaryHashFunctionFactory(); private VXQueryRawBinaryHashFunctionFactory() { } @Override public IBinaryHashFunction createBinaryHashFunction() { return MurmurHash3BinaryHashFunctionFamily.INSTANCE.createBinaryHashFunction(1); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.vxquery.runtime.factory.hashfunction; import edu.uci.ics.hyracks.api.dataflow.value.IBinaryHashFunction; import edu.uci.ics.hyracks.api.dataflow.value.IBinaryHashFunctionFactory; import edu.uci.ics.hyracks.data.std.accessors.UTF8StringBinaryHashFunctionFamily; public class VXQueryRawBinaryHashFunctionFactory implements IBinaryHashFunctionFactory { private static final long serialVersionUID = 1L; public static IBinaryHashFunctionFactory INSTANCE = new VXQueryRawBinaryHashFunctionFactory(); private VXQueryRawBinaryHashFunctionFactory() { } @Override public IBinaryHashFunction createBinaryHashFunction() { return UTF8StringBinaryHashFunctionFamily.INSTANCE.createBinaryHashFunction(1); } }
Set testing script to use YAML file (oops)
#!/usr/bin/env python # ---------------------------------------------------------------------------------------------- # Created by: Lee & Matt # # Description: Contains unit test for BioID Class # ---------------------------------------------------------------------------------------------- # ============================================================================================== from BioID import BioID # Nose test generator to iterate format test files defined in CSVs class TestFormatDefinitions(object): def test_formats(self): with open("./testing/format_tests.csv", "rU") as formats_file: test_files = formats_file.readlines()[1:] for test_file in test_files: filename, expected_format = test_file.rstrip(",\n").split(",") yield self.check_format, filename, expected_format @staticmethod def check_format(test_file, expected_format): # Putting the test file path here saves having to specify a path for each test file in the CSV test_file_path = "./testing/testFiles/" + test_file id_results = BioID("./formats.yml").identify([test_file_path]) assert id_results[test_file_path] == expected_format
#!/usr/bin/env python # ---------------------------------------------------------------------------------------------- # Created by: Lee & Matt # # Description: Contains unit test for BioID Class # ---------------------------------------------------------------------------------------------- # ============================================================================================== from BioID import BioID # Nose test generator to iterate format test files defined in CSVs class TestFormatDefinitions(object): def test_formats(self): with open("./testing/format_tests.csv", "rU") as formats_file: test_files = formats_file.readlines()[1:] for test_file in test_files: filename, expected_format = test_file.rstrip(",\n").split(",") yield self.check_format, filename, expected_format @staticmethod def check_format(test_file, expected_format): # Putting the test file path here saves having to specify a path for each test file in the CSV test_file_path = "./testing/testFiles/" + test_file id_results = BioID("./formats.json").identify([test_file_path]) assert id_results[test_file_path] == expected_format
Fix adding root class to html, not body
var $ = require('jquery'); module.exports = function(namespace) { var toggleSelector = '[data-' + namespace + '-toggle]'; var openClass = namespace + '--open'; var root = $('html').addClass(namespace); $(document) .on('click.' + namespace, toggleSelector, function(e) { e.preventDefault(); var expanded = root .toggleClass(openClass) .hasClass(openClass) ; $(toggleSelector) .attr('aria-expanded', (expanded ? 'true' : 'false')) .trigger(namespace + ':' + (expanded ? 'open' : 'close'), [this]); }) ; };
var $ = require('jquery'); module.exports = function(namespace) { var toggleSelector = '[data-' + namespace + '-toggle]'; var openClass = namespace + '--open'; var body = $(document.body).addClass(namespace); $(document) .on('click.' + namespace, toggleSelector, function(e) { e.preventDefault(); var expanded = body .toggleClass(openClass) .hasClass(openClass) ; $(toggleSelector) .attr('aria-expanded', (expanded ? 'true' : 'false')) .trigger(namespace + ':' + (expanded ? 'open' : 'close'), [this]); }) ; };
Add missing api key in product picker. Fixes #6185
$.fn.productAutocomplete = function () { 'use strict'; this.select2({ minimumInputLength: 1, multiple: true, initSelection: function (element, callback) { $.get(Spree.routes.product_search, { ids: element.val().split(','), token: Spree.api_key }, function (data) { callback(data.products); }); }, ajax: { url: Spree.routes.product_search, datatype: 'json', data: function (term, page) { return { q: { name_cont: term, sku_cont: term }, m: 'OR', token: Spree.api_key }; }, results: function (data, page) { var products = data.products ? data.products : []; return { results: products }; } }, formatResult: function (product) { return product.name; }, formatSelection: function (product) { return product.name; } }); }; $(document).ready(function () { $('.product_picker').productAutocomplete(); });
$.fn.productAutocomplete = function () { 'use strict'; this.select2({ minimumInputLength: 1, multiple: true, initSelection: function (element, callback) { $.get(Spree.routes.product_search, { ids: element.val().split(',') }, function (data) { callback(data.products); }); }, ajax: { url: Spree.routes.product_search, datatype: 'json', data: function (term, page) { return { q: { name_cont: term, sku_cont: term }, m: 'OR', token: Spree.api_key }; }, results: function (data, page) { var products = data.products ? data.products : []; return { results: products }; } }, formatResult: function (product) { return product.name; }, formatSelection: function (product) { return product.name; } }); }; $(document).ready(function () { $('.product_picker').productAutocomplete(); });
Fix title of paths page when redirected from professions page
var ProfessionsPageController = (function(){ function ProfessionsPageController( currentProfessions, currentPaths, $location ) { this.professions = currentProfessions.getCurrentData().professions; this.currentPaths = currentPaths; this.currentProfessions = currentProfessions; this.$location = $location; } ProfessionsPageController.prototype.loadPaths = function(chosenProfession) { this.currentProfessions.setNewData(chosenProfession); this.currentPaths.setNewData(chosenProfession.educationPaths); this.$location.path('/paths'); }; ProfessionsPageController.$inject = [ 'currentProfessions', 'currentPaths', '$location' ]; return ProfessionsPageController; })(); function configProfessionsPageRoute($routeProvider) { $routeProvider.when('/professions', { templateUrl: 'professions-page/professionsPage.html', controller: ProfessionsPageController, controllerAs: 'professionsPage' }); } configProfessionsPageRoute.$inject = ['$routeProvider']; angular.module('myApp.searchPage', ['ngRoute']) .config(configProfessionsPageRoute);
var ProfessionsPageController = (function(){ function ProfessionsPageController( currentProfessions, currentPaths, $location ) { this.professions = currentProfessions.getCurrentData().professions; this.currentPaths = currentPaths; this.$location = $location; } ProfessionsPageController.prototype.loadPaths = function(chosenProfession) { this.currentPaths.setNewData(chosenProfession.educationPaths); this.$location.path('/paths'); }; ProfessionsPageController.$inject = [ 'currentProfessions', 'currentPaths', '$location' ]; return ProfessionsPageController; })(); function configProfessionsPageRoute($routeProvider) { $routeProvider.when('/professions', { templateUrl: 'professions-page/professionsPage.html', controller: ProfessionsPageController, controllerAs: 'professionsPage' }); } configProfessionsPageRoute.$inject = ['$routeProvider']; angular.module('myApp.searchPage', ['ngRoute']) .config(configProfessionsPageRoute);
Add shouldDespawn tag to projectiles, so we can do piercing shots
package edu.stuy.starlorn.entities; public class Projectile extends Entity { // Angle is radians, measured from the positive x axis private double _angle, _speed; public Projectile() { super(); _angle = 0; _speed = 1; } @Override public void step() { setXY(getX() + (getSpeed() * Math.cos(getAngle())), getY() + (getSpeed() * Math.sin(getAngle()))); } public boolean shouldDespawnOnCollision() { return false; } public void setAngle(double angle) { _angle = angle; } public double getAngle() { return _angle; } public void setSpeed(double speed) { _speed = speed; } public double getSpeed() { return _speed; } }
package edu.stuy.starlorn.entities; public class Projectile extends Entity { // Angle is radians, measured from the positive x axis private double _angle, _speed; public Projectile() { super(); _angle = 0; _speed = 1; } @Override public void step() { setXY(getX() + (getSpeed() * Math.cos(getAngle())), getY() + (getSpeed() * Math.sin(getAngle()))); } public void setAngle(double angle) { _angle = angle; } public double getAngle() { return _angle; } public void setSpeed(double speed) { _speed = speed; } public double getSpeed() { return _speed; } }
CHANGE start command for RN to allow --quiet
#!/usr/bin/env node /* eslint-disable no-console */ import path from 'path'; import program from 'commander'; import Server from '../server'; program .allowUnknownOption() .option('-h, --host <host>', 'host to listen on', 'localhost') .option('-p, --port <port>', 'port to listen on', 7007) .option('-s, --secured', 'whether server is running on https') .option('-c, --config-dir [dir-name]', 'storybook config directory') .option('-e, --environment [environment]', 'DEVELOPMENT/PRODUCTION environment for webpack') .option('-i, --manual-id', 'allow multiple users to work with same storybook') .option('--smoke-test', 'Exit after successful start') .parse(process.argv); const projectDir = path.resolve(); const configDir = path.resolve(program.configDir || './storybook'); const listenAddr = [program.port]; if (program.host) { listenAddr.push(program.host); } const server = new Server({ projectDir, configDir, environment: program.environment, manualId: program.manualId, secured: program.secured, }); server.listen(...listenAddr, err => { if (err) { throw err; } const address = `http://${program.host}:${program.port}/`; console.info(`\nReact Native Storybook started on => ${address}\n`); if (program.smokeTest) { process.exit(0); } });
#!/usr/bin/env node /* eslint-disable no-console */ import path from 'path'; import program from 'commander'; import Server from '../server'; program .option('-h, --host <host>', 'host to listen on', 'localhost') .option('-p, --port <port>', 'port to listen on', 7007) .option('-s, --secured', 'whether server is running on https') .option('-c, --config-dir [dir-name]', 'storybook config directory') .option('-e, --environment [environment]', 'DEVELOPMENT/PRODUCTION environment for webpack') .option('-i, --manual-id', 'allow multiple users to work with same storybook') .option('--smoke-test', 'Exit after successful start') .parse(process.argv); const projectDir = path.resolve(); const configDir = path.resolve(program.configDir || './storybook'); const listenAddr = [program.port]; if (program.host) { listenAddr.push(program.host); } const server = new Server({ projectDir, configDir, environment: program.environment, manualId: program.manualId, secured: program.secured, }); server.listen(...listenAddr, err => { if (err) { throw err; } const address = `http://${program.host}:${program.port}/`; console.info(`\nReact Native Storybook started on => ${address}\n`); if (program.smokeTest) { process.exit(0); } });
Make sure email_access_validated_at is not null after being populated
""" Revision ID: 0313_email_access_validated_at Revises: 0312_populate_returned_letters Create Date: 2020-01-28 18:03:22.237386 """ from alembic import op import sqlalchemy as sa revision = '0313_email_access_validated_at' down_revision = '0312_populate_returned_letters' def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True)) # if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date. op.execute(""" UPDATE users SET email_access_validated_at = created_at """) op.execute(""" UPDATE users SET email_access_validated_at = logged_in_at WHERE auth_type = 'email_auth' AND email_access_validated_at IS NOT NULL """) op.alter_column('users', 'email_access_validated_at', nullable=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'email_access_validated_at') # ### end Alembic commands ###
""" Revision ID: 0313_email_access_validated_at Revises: 0312_populate_returned_letters Create Date: 2020-01-28 18:03:22.237386 """ from alembic import op import sqlalchemy as sa revision = '0313_email_access_validated_at' down_revision = '0312_populate_returned_letters' def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True)) # if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date. op.execute(""" UPDATE users SET email_access_validated_at = created_at WHERE auth_type = 'sms_auth' """) op.execute(""" UPDATE users SET email_access_validated_at = logged_in_at WHERE auth_type = 'email_auth' """) op.alter_column('users', 'email_access_validated_at', nullable=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'email_access_validated_at') # ### end Alembic commands ###
Implement between method on sort code object
<?php namespace Cs278\BankModulus; use Cs278\BankModulus\Exception\SortCodeInvalidException; final class SortCode { private $parts; public function __construct($value) { if (6 !== strlen($value)) { throw SortCodeInvalidException::create($value); } $this->parts = str_split($value, 2); } public function compareTo(SortCode $b) { if ($this == $b) { return 0; } if ($this < $b) { return -1; } return 1; } public function isBetween(SortCode $start, SortCode $end) { return 0 <= $this->compareTo($start) && -1 === $this->compareTo($end); } public function format($format) { return sprintf( $format, $this->parts[0], $this->parts[1], $this->parts[2] ); } }
<?php namespace Cs278\BankModulus; use Cs278\BankModulus\Exception\SortCodeInvalidException; final class SortCode { private $parts; public function __construct($value) { if (6 !== strlen($value)) { throw SortCodeInvalidException::create($value); } $this->parts = str_split($value, 2); } public function compareTo(SortCode $b) { if ($this == $b) { return 0; } if ($this < $b) { return -1; } return 1; } public function isBetween(SortCode $start, SortCode $end) { var_dump($this->compareTo($start)); var_dump($this->compareTo($end)); } public function format($format) { return sprintf( $format, $this->parts[0], $this->parts[1], $this->parts[2] ); } }
Add server property to dummy DBMS
/* * * Copyright (c) 2006-2020, Speedment, 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.speedment.test.connector.support; import com.speedment.runtime.config.Dbms; import com.speedment.runtime.config.DbmsUtil; import com.speedment.runtime.config.trait.HasNameUtil; import java.util.HashMap; import java.util.Map; public final class Dummies { private Dummies() { } public static Dbms dbms() { final Map<String, Object> data = new HashMap<>(); data.put(DbmsUtil.IP_ADDRESS, "localhost"); data.put(DbmsUtil.PORT, 3066); data.put(DbmsUtil.USERNAME, "username"); data.put(DbmsUtil.SERVER_NAME, "server"); data.put(HasNameUtil.NAME, "name"); return Dbms.create(null, data); } }
/* * * Copyright (c) 2006-2020, Speedment, 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.speedment.test.connector.support; import com.speedment.runtime.config.Dbms; import com.speedment.runtime.config.DbmsUtil; import com.speedment.runtime.config.trait.HasNameUtil; import java.util.HashMap; import java.util.Map; public final class Dummies { private Dummies() { } public static Dbms dbms() { final Map<String, Object> data = new HashMap<>(); data.put(DbmsUtil.IP_ADDRESS, "localhost"); data.put(DbmsUtil.PORT, 3066); data.put(DbmsUtil.USERNAME, "username"); data.put(HasNameUtil.NAME, "name"); return Dbms.create(null, data); } }
Fix Union Pay credit card regex
import assertString from './util/assertString'; /* eslint-disable max-len */ const creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})|62[0-9]{14}$/; /* eslint-enable max-len */ export default function isCreditCard(str) { assertString(str); const sanitized = str.replace(/[^0-9]+/g, ''); if (!creditCard.test(sanitized)) { return false; } let sum = 0; let digit; let tmpNum; let shouldDouble; for (let i = sanitized.length - 1; i >= 0; i--) { digit = sanitized.substring(i, (i + 1)); tmpNum = parseInt(digit, 10); if (shouldDouble) { tmpNum *= 2; if (tmpNum >= 10) { sum += ((tmpNum % 10) + 1); } else { sum += tmpNum; } } else { sum += tmpNum; } shouldDouble = !shouldDouble; } return !!((sum % 10) === 0 ? sanitized : false); }
import assertString from './util/assertString'; /* eslint-disable max-len */ const creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})|62[0-9]{5,}$/; /* eslint-enable max-len */ export default function isCreditCard(str) { assertString(str); const sanitized = str.replace(/[^0-9]+/g, ''); if (!creditCard.test(sanitized)) { return false; } let sum = 0; let digit; let tmpNum; let shouldDouble; for (let i = sanitized.length - 1; i >= 0; i--) { digit = sanitized.substring(i, (i + 1)); tmpNum = parseInt(digit, 10); if (shouldDouble) { tmpNum *= 2; if (tmpNum >= 10) { sum += ((tmpNum % 10) + 1); } else { sum += tmpNum; } } else { sum += tmpNum; } shouldDouble = !shouldDouble; } return !!((sum % 10) === 0 ? sanitized : false); }
fix(print): Print out errors now uses right variable
// Taken from https://muffinresearch.co.uk/removing-leading-whitespace-in-es6-template-strings/ export const singleLineString = (strings, ...values) => { let output = ''; for (let i = 0; i < values.length; i++) { output += strings[i] + values[i]; } output += strings[values.length]; let lines = output.split(/(?:\r\n|\n|\r)/); return lines.map((line) => { return line.replace(/^\s+/gm, ''); }).join(' ').trim(); }; export const print = (target, name, descriptor) => { const method = descriptor.value; descriptor.value = function (...args) { const msg = method.apply(this, args); console.log(singleLineString`${msg}`); if (args[0]) console.error(args[0]); return this; } } export const exit = (target, name, descriptor) => { const method = descriptor.value; descriptor.value = function (...args) { method.apply(this, args); process.exit(1); return this; } } export const promiseWrapper = (fn, ...args) => { return new Promise((resolve, reject) => { try { fn.apply(this, args); resolve(); } catch (err) { reject(err); } }); };
// Taken from https://muffinresearch.co.uk/removing-leading-whitespace-in-es6-template-strings/ export const singleLineString = (strings, ...values) => { let output = ''; for (let i = 0; i < values.length; i++) { output += strings[i] + values[i]; } output += strings[values.length]; let lines = output.split(/(?:\r\n|\n|\r)/); return lines.map((line) => { return line.replace(/^\s+/gm, ''); }).join(' ').trim(); }; export const print = (target, name, descriptor) => { const method = descriptor.value; descriptor.value = function (...args) { const msg = method.apply(this, args); console.log(singleLineString`${msg}`); args[0] ? console.log(err) : void(0); return this; } } export const exit = (target, name, descriptor) => { const method = descriptor.value; descriptor.value = function (...args) { method.apply(this, args); process.exit(1); return this; } } export const promiseWrapper = (fn, ...args) => { return new Promise((resolve, reject) => { try { fn.apply(this, args); resolve(); } catch (err) { reject(err); } }); };
Introduce 3 new traits to reduce code duplication
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Sequence\Model; class Sequence implements SequenceInterface { /** * @var mixed */ protected $id; /** * @var int */ protected $index = 0; /** * @var string */ protected $type; /** * @param string $type */ public function __construct($type) { $this->type = $type; } /** * {@inheritdoc} */ public function getId() { return $this->id; } /** * {@inheritdoc} */ public function getType() { return $this->type; } /** * {@inheritdoc} */ public function getIndex() { return $this->index; } /** * {@inheritdoc} */ public function incrementIndex() { ++$this->index; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Sequence\Model; class Sequence implements SequenceInterface { /** * @var mixed */ protected $id; /** * @var integer */ protected $index = 0; /** * @var string */ protected $type; /** * @param string $type */ public function __construct($type) { $this->type = $type; } /** * {@inheritdoc} */ public function getId() { return $this->id; } /** * {@inheritdoc} */ public function getType() { return $this->type; } /** * {@inheritdoc} */ public function getIndex() { return $this->index; } /** * {@inheritdoc} */ public function incrementIndex() { ++$this->index; } }
fix(macro): Change the byline format for NPK MAcro
""" NPKSisteNytt Metadata Macro will perform the following changes to current content item: - change the byline to "(NPK-NTB)" - change the signoff to "npk@npk.no" - change the body footer to "(©NPK)" - NB: copyrightsign, not @ - change the service to "NPKSisteNytt" """ def npk_metadata_macro(item, **kwargs): item['byline'] = 'NPK-' + item.get('byline', '') item['sign_off'] = 'npk@npk.no' item['body_footer'] = '(©NPK)' item['language'] = 'nn-NO' item['anpa_category'] = [ { 'qcode': 's', 'single_value': True, 'name': 'NPKSisteNytt', 'language': 'nn-NO', 'scheme': None } ] return item name = 'NPKSisteNytt Metadata Macro' label = 'NPKSisteNytt Metadata Macro' callback = npk_metadata_macro access_type = 'frontend' action_type = 'direct'
""" NPKSisteNytt Metadata Macro will perform the following changes to current content item: - change the byline to "(NPK-NTB)" - change the signoff to "npk@npk.no" - change the body footer to "(©NPK)" - NB: copyrightsign, not @ - change the service to "NPKSisteNytt" """ def npk_metadata_macro(item, **kwargs): item['byline'] = 'NPK ' + item.get('byline', '') item['sign_off'] = 'npk@npk.no' item['body_footer'] = '(©NPK)' item['language'] = 'nn-NO' item['anpa_category'] = [ { 'qcode': 's', 'single_value': True, 'name': 'NPKSisteNytt', 'language': 'nn-NO', 'scheme': None } ] return item name = 'NPKSisteNytt Metadata Macro' label = 'NPKSisteNytt Metadata Macro' callback = npk_metadata_macro access_type = 'frontend' action_type = 'direct'
Add config in Bundle Extension
<?php namespace Victoire\Widget\PollBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class VictoireWidgetPollExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); $container->setParameter( 'victoire_widget_poll.victoire_menu_item', $config['victoire_menu_item'] ); } }
<?php namespace Victoire\Widget\PollBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class VictoireWidgetPollExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
FIX bug when sending notification to multiple partners
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import api, models class ResPartner(models.Model): _inherit = 'res.partner' @api.multi def schedule_meeting(self): old_action = super(ResPartner, self).schedule_meeting() new_action = self.env.ref( 'crm_switzerland.action_calendar_event_partner').read()[0] new_action['domain'] = [('partner_ids', 'in', self.ids)] new_action['context'] = { 'default_partner_ids': old_action['context'][ 'default_partner_ids'] } return new_action @api.model def _notify_prepare_template_context(self, message): # modification of context for lang message = message.with_context(lang=self[:1].lang or self.env.lang) return super(ResPartner, self).\ _notify_prepare_template_context(message)
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import api, models class ResPartner(models.Model): _inherit = 'res.partner' @api.multi def schedule_meeting(self): old_action = super(ResPartner, self).schedule_meeting() new_action = self.env.ref( 'crm_switzerland.action_calendar_event_partner').read()[0] new_action['domain'] = [('partner_ids', 'in', self.ids)] new_action['context'] = { 'default_partner_ids': old_action['context'][ 'default_partner_ids'] } return new_action @api.model def _notify_prepare_template_context(self, message): # modification of context for lang message = message.with_context(lang=self.lang) return super(ResPartner, self).\ _notify_prepare_template_context(message)
Write meta robots only when content type is HTML
'use strict'; var Transform = require('stream').Transform; var contentTypes = require('./content-types'); module.exports = function(config) { function createStream() { return new Transform({ decodeStrings: false, transform: function(chunk, encoding, next) { var updated = chunk.toString().replace('</head>', '<meta name="ROBOTS" content="NOINDEX, NOFOLLOW"/>\n</head>'); this.push(updated, 'utf8'); next(); } }); } function metaRobots(data) { // this leaks to all sites that are visited by the client & it can block the client from accessing the proxy if https is not avaliable. if (contentTypes.html.indexOf(data.contentType) != -1) { data.stream = data.stream.pipe(createStream()); } } metaRobots.createStream = createStream; // for testing return metaRobots; };
'use strict'; var Transform = require('stream').Transform; var contentTypes = require('./content-types'); module.exports = function(config) { function createStream() { return new Transform({ decodeStrings: false, transform: function(chunk, encoding, next) { var updated = chunk.toString().replace('</head>', '<meta name="ROBOTS" content="NOINDEX, NOFOLLOW"/>\n</head>'); this.push(updated, 'utf8'); next(); } }); } function metaRobots(data) { // this leaks to all sites that are visited by the client & it can block the client from accessing the proxy if https is not avaliable. if (contentTypes.shouldProcess(config, data)) { data.stream = data.stream.pipe(createStream()); } } metaRobots.createStream = createStream; // for testing return metaRobots; };
Use simulant to do ‘timeupdate’ event; improve assertion
/* eslint-env mocha */ const Vue = require('vue-test'); const sinon = require('sinon'); const simulant = require('simulant'); const audioRenderer = require('../../src/views/index.vue'); function makeVm(propsData) { const Ctor = Vue.extend(audioRenderer); return new Ctor({ propsData }).$mount(); } describe('audio mp3 render component', () => { describe('timeUpdate', () => { it('does not error out if <audio> dispatches event after unmount', () => { // regression test for https://github.com/learningequality/kolibri/issues/1276 const vm = makeVm({ defaultFile: '' }); const audioEl = vm.$el.querySelector('#audio'); const updateTimeSpy = sinon.spy(vm, 'updateTime'); // unmount the vm to simulate original situation vm.$destroy(); // then dispatch timeupdate event immediately after simulant.fire(audioEl, 'timeupdate'); Vue.nextTick(() => { sinon.assert.called(updateTimeSpy); }); }); }); });
/* eslint-env mocha */ const Vue = require('vue-test'); const sinon = require('sinon'); const audioRenderer = require('../../src/views/index.vue'); function makeVm(propsData) { const Ctor = Vue.extend(audioRenderer); return new Ctor({ propsData }).$mount(); } describe('audio mp3 render component', () => { describe('timeUpdate', () => { it('does not error out if <audio> is undefined', () => { // regression test for https://github.com/learningequality/kolibri/issues/1276 const vm = makeVm({ defaultFile: '' }); const audioEl = vm.$el.querySelector('#audio'); try { // unmount the vm to simulate original situation vm.$destroy(); // then dispatch an event audioEl.dispatchEvent(new Event('timeupdate')); } catch (err) { sinon.assert.fail('No exceptions were expected'); } }); }); });
Change DATE_FORMAT to be equivalent to datetime.isoformat()
"""Default settings for all environments. These settings will be extended by additional config files in ROOT/config. Run `python manage.py create_config` to create such a config file. """ from os.path import abspath, dirname, join # Custom ROOT_DIR = abspath(join(dirname(__file__), "..")) # Flask DEBUG = False TESTING = False # Flask-SQLALchemy # Eve ID_FIELD = "id" AUTH_FIELD = "_author" DATE_FORMAT = "%Y-%m-%dT%H:%M:%S" BANDWIDTH_SAVER = False RESOURCE_METHODS = ['GET', 'POST'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] PUBLIC_METHODS = ['GET'] # This is the only way to make / public XML = False # Eve, file storage options RETURN_MEDIA_AS_BASE64_STRING = False EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url'] STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump' STORAGE_URL = r'/storage'
"""Default settings for all environments. These settings will be extended by additional config files in ROOT/config. Run `python manage.py create_config` to create such a config file. """ from os.path import abspath, dirname, join # Custom ROOT_DIR = abspath(join(dirname(__file__), "..")) # Flask DEBUG = False TESTING = False # Flask-SQLALchemy # Eve ID_FIELD = "id" AUTH_FIELD = "_author" DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ" BANDWIDTH_SAVER = False RESOURCE_METHODS = ['GET', 'POST'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] PUBLIC_METHODS = ['GET'] # This is the only way to make / public XML = False # Eve, file storage options RETURN_MEDIA_AS_BASE64_STRING = False EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url'] STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump' STORAGE_URL = r'/storage'
Fix global variables issue - Occurs when u try to migrate
<?php namespace App\Providers; use Bouncer; use App\Rental; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // Role seed. Bouncer::seeder(function () { Bouncer::allow('active') ->to(''); Bouncer::allow('blocked') ->to(''); Bouncer::allow('admin') ->to(''); }); // Rental global variables if (Schema::hasTable('rentals')) { view()->share('rentalCount', Rental::all()->count()); view()->share('rentalOption', Rental::where('Status', 1)->count()); view()->share('rentalNew', Rental::where('Status', 0)->count()); } } /** * Register any application services. * * @return void */ public function register() { // } }
<?php namespace App\Providers; use Bouncer; use App\Rental; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // Role seed. Bouncer::seeder(function () { Bouncer::allow('active') ->to(''); Bouncer::allow('blocked') ->to(''); Bouncer::allow('admin') ->to(''); }); // Rental global variables view()->share('rentalCount', Rental::all()->count()); view()->share('rentalOption', Rental::where('Status', 1)->count()); view()->share('rentalNew', Rental::where('Status', 0)->count()); } /** * Register any application services. * * @return void */ public function register() { // } }
Fix scriptsToHTML prototype test to work in IE
import expect from 'expect' import scriptsToHTML from '../src/utils/scriptsToHTML' describe('scriptsToHTML', () => { it('converts a scripts object into an HTML string', () => { function ProtoTest() {} ProtoTest.prototype = { foo: 'bar' } const scripts = [ 'string.js', Object.assign(new ProtoTest(), { src: 'Test.js' }), { src: 'async.js', async: true, onerror: 'nope' }, ] const result = scriptsToHTML(scripts, 'test(this.src)') const expectedResult = ` <script src="string.js" onerror="test(this.src)"></script> <script src="Test.js" onerror="test(this.src)"></script> <script src="async.js" async="true" onerror="test(this.src)"></script> `.replace(/\n\s*/g, '') expect(result).toBe(expectedResult) }) })
import expect from 'expect' import scriptsToHTML from '../src/utils/scriptsToHTML' describe('scriptsToHTML', () => { it('converts a scripts object into an HTML string', () => { const scripts = [ 'string.js', Object.create({ foo: 'bar' }, { src: { value: 'Test.js', enumerable: true } }), { src: 'async.js', async: true, onerror: 'nope' }, ] const result = scriptsToHTML(scripts, 'test(this.src)') const expectedResult = ` <script src="string.js" onerror="test(this.src)"></script> <script src="Test.js" onerror="test(this.src)"></script> <script src="async.js" async="true" onerror="test(this.src)"></script> `.replace(/\n\s*/g, '') expect(result).toBe(expectedResult) }) })
Add newline at end of generated JSON files
#!/usr/bin/env node const {readFile, writeFile} = require('fs') function updateDependencies(template, dependencies, packageJson) { const PKG = require(`../templates/${template}/package.json`) dependencies = Object.keys(PKG.dependencies || {}).reduce(function(acum, name) { acum[name] = dependencies[name] return acum }, {}) updateJson(`templates/${template}/dependencies.json`, dependencies) updateJson(`templates/${template}/package.json`, {...PKG, ...packageJson, dependencies}) } function updateJson(file, newData) { readFile(file, 'utf8', function(error, data='{}') { if(error && error.code !== 'ENOENT') throw error data = Object.assign(JSON.parse(data), newData) writeFile(file, JSON.stringify(data, null, 2)+'\n', function(error) { if(error) throw error }) }) } const {author, bugs, contributors, dependencies, devDependencies, homepage, license, repository, version} = require('../package.json') updateJson('templates/re-base/devDependencies.json' , devDependencies) const packageJson = {author, bugs, contributors, homepage, license, repository, version} updateDependencies('re-base' , dependencies, packageJson) updateDependencies('re-dux' , dependencies, packageJson) updateDependencies('re-route', dependencies, packageJson) updateDependencies('re-start', dependencies, packageJson)
#!/usr/bin/env node const {readFile, writeFile} = require('fs') function updateDependencies(template, dependencies, packageJson) { const PKG = require(`../templates/${template}/package.json`) dependencies = Object.keys(PKG.dependencies || {}).reduce(function(acum, name) { acum[name] = dependencies[name] return acum }, {}) updateJson(`templates/${template}/dependencies.json`, dependencies) updateJson(`templates/${template}/package.json`, {...PKG, ...packageJson, dependencies}) } function updateJson(file, newData) { readFile(file, 'utf8', function(error, data='{}') { if(error && error.code !== 'ENOENT') throw error data = Object.assign(JSON.parse(data), newData) writeFile(file, JSON.stringify(data, null, 2), function(error) { if(error) throw error }) }) } const {author, bugs, contributors, dependencies, devDependencies, homepage, license, repository, version} = require('../package.json') updateJson('templates/re-base/devDependencies.json' , devDependencies) const packageJson = {author, bugs, contributors, homepage, license, repository, version} updateDependencies('re-base' , dependencies, packageJson) updateDependencies('re-dux' , dependencies, packageJson) updateDependencies('re-route', dependencies, packageJson) updateDependencies('re-start', dependencies, packageJson)
Add a new constant which includes vendor account approvals percent
// Copyright 2020 DSR Corporation // // 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 types import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) // Default parameter values. const ( DclMaxMemoCharacters uint64 = authtypes.DefaultMaxMemoCharacters DclTxSigLimit uint64 = authtypes.DefaultTxSigLimit DclTxSizeCostPerByte uint64 = 0 // gas is not needed in DCL DclSigVerifyCostED25519 uint64 = 0 // gas is not needed in DCL DclSigVerifyCostSecp256k1 uint64 = 0 // gas is not needed in DCL AccountApprovalsPercent float64 = 0.66 VendorAccountApprovalsPercent float64 = 0.33 )
// Copyright 2020 DSR Corporation // // 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 types import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) // Default parameter values. const ( DclMaxMemoCharacters uint64 = authtypes.DefaultMaxMemoCharacters DclTxSigLimit uint64 = authtypes.DefaultTxSigLimit DclTxSizeCostPerByte uint64 = 0 // gas is not needed in DCL DclSigVerifyCostED25519 uint64 = 0 // gas is not needed in DCL DclSigVerifyCostSecp256k1 uint64 = 0 // gas is not needed in DCL AccountApprovalsPercent float64 = 0.66 )
Use the parent id object in the toString method
var Deffy = require("deffy") , Typpy = require("typpy") ; var SEPARATOR = "_"; function SubElmId(type, name, parent) { if (Typpy(type, SubElm)) { parent = name; name = type.name; type = type.type; } this.type = type; this.name = name; this.parentId = parent; } SubElmId.prototype.toString = function () { return [this.type, this.parentId, this.name].join(SEPARATOR); }; function SubElm(type, data, parent) { if (Typpy(data, SubElm)) { return data; } this.name = SubElm.Name(data); this.label = Deffy(data.label, this.name); this.type = type; this.id = new SubElmId(this, parent.id) this.lines = {}; } SubElm.Name = function (input) { return input.name || input.event || input.serverMethod || input.method; }; SubElm.Id = SubElmId; module.exports = SubElm;
var Deffy = require("deffy") , Typpy = require("typpy") ; var SEPARATOR = "_"; function SubElmId(type, name, parent) { if (Typpy(type, SubElm)) { parent = name; name = type.name; type = type.type; } this.type = type; this.name = name; this.parentName = parent; } SubElmId.prototype.toString = function () { return [this.type, this.parentName, this.name].join(SEPARATOR); }; function SubElm(type, data, parent) { if (Typpy(data, SubElm)) { return data; } this.name = SubElm.Name(data); this.label = Deffy(data.label, this.name); this.type = type; this.id = new SubElmId(this, parent.name) this.lines = {}; } SubElm.Name = function (input) { return input.name || input.event || input.serverMethod || input.method; }; SubElm.Id = SubElmId; module.exports = SubElm;
FIX version in installation hint for webworker-threads
var logUtils = require('../utils/log-utils.js'); // var log = logUtils.log; var warn = logUtils.warn; //////// async / threaded grammar compiler support: //////////////// var asyncSupport = false; try { // log('#################### start detecting async grammar support...') var Threads = require('webworker-threads'); var thread = Threads.create(); thread.eval(function testAsync(){return true;}).eval('testAsync()', function(_err, _result){ // log('#################### detected async grammar support -> ', _result, ', error? -> ', _err); thread.destroy(); }); //if we are here, assume that webworker-threads has been properly installed & compiled (i.e. is available) asyncSupport = true; } catch(err){ try { require('worker_threads'); asyncSupport = true; } catch(err){ warn('[INFO] could not load implementation for WebWorkers, e.g. (experimental) worker_threads or webworker-threads (>= version 0.8.x): cannot use WebWorkers/parallel threads for compling grammars etc.'); } } module.exports = { isAsyncSupported: function(){ return asyncSupport; } }
var logUtils = require('../utils/log-utils.js'); // var log = logUtils.log; var warn = logUtils.warn; //////// async / threaded grammar compiler support: //////////////// var asyncSupport = false; try { // log('#################### start detecting async grammar support...') var Threads = require('webworker-threads'); var thread = Threads.create(); thread.eval(function testAsync(){return true;}).eval('testAsync()', function(_err, _result){ // log('#################### detected async grammar support -> ', _result, ', error? -> ', _err); thread.destroy(); }); //if we are here, assume that webworker-threads has been properly installed & compiled (i.e. is available) asyncSupport = true; } catch(err){ try { require('worker_threads'); asyncSupport = true; } catch(err){ warn('[INFO] could not load implementation for WebWorkers, e.g. (experimental) worker_threads or webworker-threads (>= version 8.x): cannot use WebWorkers/parallel threads for compling grammars etc.'); } } module.exports = { isAsyncSupported: function(){ return asyncSupport; } }
Fix copying icon in packager
const fs = require('fs-extra') const path = require('path') const { ROOT_PATH } = require('./constants') class ReleaseAssets { /** * Copies the assets into the releases folders * @param platforms: the platforms to build for * @return promise */ static copyAssetsIntoReleases (platforms) { const platformsSet = new Set(platforms) if (platformsSet.has('darwin')) { fs.copySync(path.join(__dirname, 'dmg/First Run.html'), path.join(ROOT_PATH, 'WMail-darwin-x64/First Run.html')) } if (platformsSet.has('linux')) { fs.copySync(path.join(ROOT_PATH, 'assets/icons/app.png'), path.join(ROOT_PATH, 'WMail-linux-ia32/icon.png')) fs.copySync(path.join(ROOT_PATH, 'assets/icons/app.png'), path.join(ROOT_PATH, 'WMail-linux-x64/icon.png')) } return Promise.resolve() } } module.exports = ReleaseAssets
const fs = require('fs-extra') const path = require('path') const { ROOT_PATH } = require('./constants') class ReleaseAssets { /** * Copies the assets into the releases folders * @param platforms: the platforms to build for * @return promise */ static copyAssetsIntoReleases (platforms) { const platformsSet = new Set(platforms) if (platformsSet.has('darwin')) { fs.copySync(path.join(__dirname, 'dmg/First Run.html'), path.join(ROOT_PATH, 'WMail-darwin-x64/First Run.html')) } else if (platformsSet.has('linux')) { fs.copySync(path.join(ROOT_PATH, 'assets/icons/app.png'), path.join(ROOT_PATH, 'WMail-linux-ia32/icon.png')) fs.copySync(path.join(ROOT_PATH, 'assets/icons/app.png'), path.join(ROOT_PATH, 'WMail-linux-x64/icon.png')) } return Promise.resolve() } } module.exports = ReleaseAssets
Make function name more descript
"use strict"; let db = require('./db'); function generateBase36Stub(length) { let result = "" for(let i = 0; i < length; i++) { let value = Math.round(Math.random() * 35) if (value > 9) result += String.fromCharCode(value + 87); else result += value } return result; } function shortenUrl(req, res) { let url = req.params.url; let nurl = generateBase36Stub(5); let collision = false; while(collision) { db.oneOrNone('select exists(select * from urls where nurl = $1 limit 1);', nurl) .then(function(data) { if (data.exists) { nurl = generateBase36Stub(5); collision = true; } else collision = false; }).catch(function(error) { console.log('Error: ' + error); res.send(500); }); } db.none('insert into urls(url, nurl) values($1, $2);', [url, nurl]); res.jsonp({ "oldurl" : url, "newurl" : req.host + '/' + nurl }); } module.exports = shortenUrl;
"use strict"; let db = require('./db'); function generateStub(length) { let result = "" for(let i = 0; i < length; i++) { let value = Math.round(Math.random() * 35) if (value > 9) result += String.fromCharCode(value + 87); else result += value } return result; } function shortenUrl(req, res) { let url = req.params.url; let nurl = generateStub(5); let collision = false; while(collision) { db.oneOrNone('select exists(select * from urls where nurl = $1 limit 1);', nurl) .then(function(data) { if (data.exists) { nurl = generateStub(5); collision = true; } else collision = false; }).catch(function(error) { console.log('Error: ' + error); res.send(500); }); } db.none('insert into urls(url, nurl) values($1, $2);', [url, nurl]); res.jsonp({ "oldurl" : url, "newurl" : req.host + '/' + nurl }); } module.exports = shortenUrl;
Remove color switcher fade effect
$(document).ready(function () { $('#primaryPostForm').validate() // Image preview in upload input $('.form__input--upload').on('change', function () { var label = $(this).data('label'); var image = (window.URL ? URL : webkitURL).createObjectURL(this.files[0]); $(label).css('background-image', 'url(' + image + ')'); $('.remover').css('display', 'block'); }) $('.remover').on('click', function () { var input = $(this).data('for'); var label = $(input).data('label'); $(input).wrap('<form>').closest('form').get(0).reset(); $(input).unwrap(); $(label).css('background-image', 'none'); $('.remover').css('display', 'none'); }) $('.color-switcher-button').on('click', function() { $('link#stylesheet').attr('href', $(this).data('stylesheet')); }) });
$(document).ready(function () { $('#primaryPostForm').validate() // Image preview in upload input $('.form__input--upload').on('change', function () { var label = $(this).data('label'); var image = (window.URL ? URL : webkitURL).createObjectURL(this.files[0]); $(label).css('background-image', 'url(' + image + ')'); $('.remover').css('display', 'block'); }) $('.remover').on('click', function () { var input = $(this).data('for'); var label = $(input).data('label'); $(input).wrap('<form>').closest('form').get(0).reset(); $(input).unwrap(); $(label).css('background-image', 'none'); $('.remover').css('display', 'none'); }) $('.color-switcher-button').on('click', function() { $('body').fadeOut('fast').siblings('head').find('link#stylesheet').attr('href', $(this).data('stylesheet')).closest('head').siblings('body').fadeIn('fast'); }) });
Update Oozie and Hive URLs.
var CELOS_USER = "celos"; var CELOS_DEFAULT_OOZIE = "http://oozie002.ny7.collective-media.net:11000/oozie"; var CELOS_DEFAULT_HDFS = "hdfs://nameservice1"; var NAME_NODE = CELOS_DEFAULT_HDFS; var JOB_TRACKER = "admin1.ny7.collective-media.net:8032"; var HIVE_METASTORE = "thrift://hive-meta.ny7.collective-media.net:9803"; var CELOS_DEFAULT_OOZIE_PROPERTIES = { "user.name": CELOS_USER, "jobTracker" : JOB_TRACKER, "nameNode" : CELOS_DEFAULT_HDFS, "hiveMetastore": HIVE_METASTORE, "oozie.use.system.libpath": "true" };
var CELOS_USER = "celos"; var CELOS_DEFAULT_OOZIE = "http://admin1.ny7.collective-media.net:11000/oozie"; var CELOS_DEFAULT_HDFS = "hdfs://nameservice1"; var NAME_NODE = CELOS_DEFAULT_HDFS; var JOB_TRACKER = "admin1.ny7.collective-media.net:8032"; var HIVE_METASTORE = "thrift://admin1.ny7.collective-media.net:9083"; var CELOS_DEFAULT_OOZIE_PROPERTIES = { "user.name": CELOS_USER, "jobTracker" : JOB_TRACKER, "nameNode" : CELOS_DEFAULT_HDFS, "hiveMetastore": HIVE_METASTORE, "oozie.use.system.libpath": "true" };
Fix cards not getting shuffled
var _ = require('underscore'); var cards = require('./cards.js'); function CardPool(collection) { this.answerCards = cards.getAnswerCards(collection); this.answerCardIndex = 0; this.questionCards = cards.getQuestionCards(collection); this.questionCardIndex = 0; var reshuffleQuestionCards = function() { this.questionCards = _.shuffle(this.questionCards); this.questionCardIndex = 0; }.bind(this); var reshuffleAnswerCards = function() { this.answerCards = _.shuffle(this.answerCards); this.answerCardIndex = 0; }.bind(this); this.randomQuestionCard = function() { var card = this.questionCards[this.questionCardIndex]; this.questionCardIndex++; if(this.questionCardIndex >= this.questionCards.length) reshuffleQuestionCards(); return card; } this.randomAnswerCard = function() { var card = this.answerCards[this.answerCardIndex]; this.answerCardIndex++; if(this.answerCardIndex >= this.answerCards.length) reshuffleAnswerCards(); return card; } this.reshuffleCards = function() { reshuffleAnswerCards(); reshuffleQuestionCards(); } this.reshuffleCards(); } exports.CardPool = CardPool;
var _ = require('underscore'); var cards = require('./cards.js'); function CardPool(collection) { this.answerCards = cards.getAnswerCards(collection); this.answerCardIndex = 0; this.questionCards = cards.getQuestionCards(collection); this.questionCardIndex = 0; function reshuffleQuestionCards() { this.questionCards = _.shuffle(this.questionCards); this.questionCardIndex = 0; } function reshuffleAnswerCards() { this.answerCards = _.shuffle(this.answerCards); this.answerCardIndex = 0; } this.randomQuestionCard = function() { var card = this.questionCards[this.questionCardIndex]; this.questionCardIndex++; if(this.questionCardIndex >= this.questionCards.length) reshuffleQuestionCards(); return card; } this.randomAnswerCard = function() { var card = this.answerCards[this.answerCardIndex]; this.answerCardIndex++; if(this.answerCardIndex >= this.answerCards.length) reshuffleAnswerCards(); return card; } this.reshuffleCards = function() { reshuffleAnswerCards(); reshuffleQuestionCards() } reshuffleQuestionCards(); reshuffleAnswerCards(); } exports.CardPool = CardPool;
Make progress toward auto-registration for FreeBSD
var os = require('os'), exec = require('child_process').exec; exports.lookup_hostname = function (callback) { var os_type = os.type(); var process_hostname = function(error, stdout, stderr) { if ( error != null ) { console.error("Could not look up hostname: " + error); process.exit(1); } callback( stdout.replace(/\n/g, "") ); }; if ( os_type === 'SunOS' ) { exec("/usr/bin/zonename", process_hostname ); return; } if ( os_type === 'Linux' || os_type === 'FreeBSD' ) { exec("/bin/hostname", process_hostname ); return; } console.log("don't know what I am supposed to look up"); }
var os = require('os'), exec = require('child_process').exec; exports.lookup_hostname = function (callback) { var os_type = os.type(); var process_hostname = function(error, stdout, stderr) { if ( error != null ) { console.error("Could not look up hostname: " + error); process.exit(1); } callback( stdout.replace(/\n/g, "") ); }; if ( os_type === 'SunOS' ) { exec("/usr/bin/zonename", process_hostname ); return; } if ( os_type === 'Linux' ) { exec("/bin/hostname", process_hostname ); return; } console.log("don't know what I am supposed to look up"); }
Fix for if tax is set and not shown correct in backend
<?php class Billmate_BillmateInvoice_Helper_Total extends Mage_Core_Helper_Abstract { public function addToBlock($block) { $order = $block->getOrder(); $info = $order->getPayment()->getMethodInstance()->getInfoInstance(); $storeId = Mage::app()->getStore()->getId(); $vatOption = Mage::getStoreConfig("tax/sales_display/price", $storeId); $invoiceFee = $info->getAdditionalInformation('billmateinvoice_fee'); $invoiceTax = $info->getAdditionalInformation('billmateinvoice_fee_tax'); $origInvFee = Mage::getStoreConfig('payment/billmateinvoice/billmate_fee'); if($invoiceTax != 0 && ($invoiceFee == $origInvFee)){ $invoiceFee += $invoiceTax; } $extra = ''; $fee = new Varien_Object(); $fee->setCode('billmateinvoice_fee'); $label = Mage::helper('billmateinvoice')->__('Billmate Invoice Fee (Incl. Vat)'); $fee->setLabel($label); $fee->setBaseValue($invoiceFee); $fee->setValue($invoiceFee); $block->addTotalBefore($fee, 'shipping'); return $block; } }
<?php class Billmate_BillmateInvoice_Helper_Total extends Mage_Core_Helper_Abstract { public function addToBlock($block) { $order = $block->getOrder(); $info = $order->getPayment()->getMethodInstance()->getInfoInstance(); $storeId = Mage::app()->getStore()->getId(); $vatOption = Mage::getStoreConfig("tax/sales_display/price", $storeId); $invoiceFee = $info->getAdditionalInformation('billmateinvoice_fee'); $extra = ''; $fee = new Varien_Object(); $fee->setCode('billmateinvoice_fee'); $label = Mage::helper('billmateinvoice')->__('Billmate Invoice Fee (Incl. Vat)'); $fee->setLabel($label); $fee->setBaseValue($invoiceFee); $fee->setValue($invoiceFee); $block->addTotalBefore($fee, 'shipping'); return $block; } }
Modify to use right toolkit. First blood!
#!/usr/bin/php <?php /* * list_buckets.php * * List S3 buckets. * * Copyright 2009-2010 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy * of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license.txt" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the * License. * * Modified by Jeffrey S. Haemer <jeffrey.haemer@gmail.com> */ error_reporting(E_ALL); require_once('AWSSDKforPHP/sdk.class.php'); // Create the S3 access object $s3 = new AmazonS3(); // Retrieve list of S3 buckets $buckets = $s3->get_bucket_list(); // Display list of buckets foreach ($buckets as $bucket) { print($bucket . "\n"); } exit(0); ?>
#!/usr/bin/php <?php /* * list_buckets.php * * List S3 buckets. * * Copyright 2009-2010 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy * of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license.txt" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the * License. */ error_reporting(E_ALL); require_once('cloudfusion.class.php'); // Create the S3 access object $s3 = new AmazonS3(); // Retrieve list of S3 buckets $buckets = $s3->get_bucket_list(); // Display list of buckets foreach ($buckets as $bucket) { print($bucket . "\n"); } exit(0); ?>
Add test for handling Infinity in json
# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"' def test_inf(self): res = float('inf') self.assertEquals(json.dumps(res), 'null')
# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import uuid from sentry.utils import json from sentry.testutils import TestCase class JSONTest(TestCase): def test_uuid(self): res = uuid.uuid4() self.assertEquals(json.dumps(res), '"%s"' % res.hex) def test_datetime(self): res = datetime.datetime(day=1, month=1, year=2011, hour=1, minute=1, second=1) self.assertEquals(json.dumps(res), '"2011-01-01T01:01:01.000000Z"') def test_set(self): res = set(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_frozenset(self): res = frozenset(['foo', 'bar']) self.assertEquals(json.dumps(res), '["foo","bar"]') def test_escape(self): res = '<script>alert(1);</script>' assert json.dumps(res) == '"<script>alert(1);</script>"' assert json.dumps(res, escape=True) == '"<script>alert(1);<\/script>"'
Update TestDefaultConfig to include target dimensions
package oak import ( "os" "testing" "github.com/stretchr/testify/assert" ) func TestDefaultConfig(t *testing.T) { err := LoadConf("default.config") assert.Nil(t, err) assert.Equal(t, conf, SetupConfig) f, err := os.Open("default.config") assert.Nil(t, err) err = LoadConfData(f) assert.Nil(t, err) SetupConfig = Config{ Assets: Assets{"a/", "a/", "i/", "f/"}, Debug: Debug{"FILTER", "INFO"}, Screen: Screen{0, 0, 240, 320, 2, 0, 0}, Font: Font{"hint", 20.0, 36.0, "luxisr.ttf", "green"}, FrameRate: 30, DrawFrameRate: 30, Language: "German", Title: "Some Window", BatchLoad: true, GestureSupport: true, LoadBuiltinCommands: true, } initConf() assert.Equal(t, SetupConfig, conf) // Failure to load err = LoadConf("nota.config") assert.NotNil(t, err) }
package oak import ( "os" "testing" "github.com/stretchr/testify/assert" ) func TestDefaultConfig(t *testing.T) { err := LoadConf("default.config") assert.Nil(t, err) assert.Equal(t, conf, SetupConfig) f, err := os.Open("default.config") assert.Nil(t, err) err = LoadConfData(f) assert.Nil(t, err) SetupConfig = Config{ Assets: Assets{"a/", "a/", "i/", "f/"}, Debug: Debug{"FILTER", "INFO"}, Screen: Screen{0, 0, 240, 320, 2}, Font: Font{"hint", 20.0, 36.0, "luxisr.ttf", "green"}, FrameRate: 30, DrawFrameRate: 30, Language: "German", Title: "Some Window", BatchLoad: true, GestureSupport: true, LoadBuiltinCommands: true, } initConf() assert.Equal(t, SetupConfig, conf) // Failure to load err = LoadConf("nota.config") assert.NotNil(t, err) }
Include up to date CSS Styled Content TS
<?php if (!defined ('TYPO3_MODE')) { die ('Access denied.'); } // Automatically include TypoScript dependencies \FluidTYPO3\Flux\Core::addStaticTypoScript('EXT:css_styled_content/static/'); \FluidTYPO3\Flux\Core::addStaticTypoScript('EXT:tev/Configuration/TypoScript'); // Hook into RealURL config generation $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/realurl/class.tx_realurl_autoconfgen.php']['extensionConfiguration']['tev'] = 'Tev\\Tev\\Hook\\RealUrlAutoConfigurationHook->updateConfig'; // Add new cache type to clear RealURL config $TYPO3_CONF_VARS['SC_OPTIONS']['additionalBackendItems']['cacheActions'][] = 'Tev\\Tev\\Url\\CacheMenu'; $TYPO3_CONF_VARS['BE']['AJAX']['tx_tev::clearcacheurl'] = 'Tev\\Tev\\Url\\Cache->clear';
<?php if (!defined ('TYPO3_MODE')) die ('Access denied.'); // Automatically include TypoScript dependencies FluidTYPO3\Flux\Core::addStaticTypoScript('EXT:css_styled_content/static/v6.2'); FluidTYPO3\Flux\Core::addStaticTypoScript('EXT:tev/Configuration/TypoScript'); // Hook into RealURL config generation $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/realurl/class.tx_realurl_autoconfgen.php']['extensionConfiguration']['tev'] = 'Tev\\Tev\\Hook\\RealUrlAutoConfigurationHook->updateConfig'; // Add new cache type to clear RealURL config $TYPO3_CONF_VARS['SC_OPTIONS']['additionalBackendItems']['cacheActions'][] = 'Tev\\Tev\\Url\\CacheMenu'; $TYPO3_CONF_VARS['BE']['AJAX']['tx_tev::clearcacheurl'] = 'Tev\\Tev\\Url\\Cache->clear';
Add brackets to end state
'use strict'; var pathwayApp = angular.module('pathwayApp', ['ui.router', 'templates', 'Devise', 'ngCookies']); pathwayApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) { //Default route $urlRouterProvider.otherwise('/'); $locationProvider.html5Mode(true); $stateProvider .state('home', { url: '/', templateUrl: 'index.html', }) .state('login', { url: '/user/login', templateUrl: 'login.html', controller: 'UserController' }) .state('register', { url: '/user/new', templateUrl: 'register.html', controller: 'UserController' }) .state('discover', { url: '/discover', templateUrl: 'discover.html', controller: 'HomeController' }) .state('createProject', { url: '/project/new', templateUrl: 'newProject.html', controller: 'ProjectController' }) .state('showPathway', { url: '/pathway/:id', templateUrl: 'pathway.html', controller: 'PathwayController' }) .state('showProject', { url: '/pathway/:pathway_id/project/:id', templateUrl: 'project.html', controller: 'ProjectController' }) });
'use strict'; var pathwayApp = angular.module('pathwayApp', ['ui.router', 'templates', 'Devise', 'ngCookies']); pathwayApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) { //Default route $urlRouterProvider.otherwise('/'); $locationProvider.html5Mode(true); $stateProvider .state('home', { url: '/', templateUrl: 'index.html', }) .state('login', { url: '/user/login', templateUrl: 'login.html', controller: 'UserController' }) .state('register', { url: '/user/new', templateUrl: 'register.html', controller: 'UserController' }) .state('discover', { url: '/discover', templateUrl: 'discover.html', controller: 'HomeController' .state('createProject', { url: '/project/new', templateUrl: 'newProject.html', controller: 'ProjectController' }) .state('showPathway', { url: '/pathway/:id', templateUrl: 'pathway.html', controller: 'PathwayController' }) .state('showProject', { url: '/pathway/:pathway_id/project/:id', templateUrl: 'project.html', controller: 'ProjectController' }) });
Update the reason why the router service is still not used
import Ember from 'ember'; import { lazyClick } from '../helpers/lazy-click'; const { Component, inject, computed } = Ember; export default Component.extend({ // TODO Switch back to the router service once the service behaves more like Route // https://github.com/emberjs/ember.js/issues/15801 // router: inject.service('router'), _router: inject.service('-routing'), router: computed.alias('_router.router'), tagName: 'tr', classNames: ['server-agent-row', 'is-interactive'], classNameBindings: ['isActive:is-active'], agent: null, isActive: computed('agent', 'router.currentURL', function() { // TODO Switch back to the router service once the service behaves more like Route // https://github.com/emberjs/ember.js/issues/15801 // const targetURL = this.get('router').urlFor('servers.server', this.get('agent')); // const currentURL = `${this.get('router.rootURL').slice(0, -1)}${this.get('router.currentURL')}`; const router = this.get('router'); const targetURL = router.generate('servers.server', this.get('agent')); const currentURL = `${router.get('rootURL').slice(0, -1)}${router .get('currentURL') .split('?')[0]}`; return currentURL === targetURL; }), click() { const transition = () => this.get('router').transitionTo('servers.server', this.get('agent')); lazyClick([transition, event]); }, });
import Ember from 'ember'; import { lazyClick } from '../helpers/lazy-click'; const { Component, inject, computed } = Ember; export default Component.extend({ // TODO Switch back to the router service style when it is no longer feature-flagged // router: inject.service('router'), _router: inject.service('-routing'), router: computed.alias('_router.router'), tagName: 'tr', classNames: ['server-agent-row', 'is-interactive'], classNameBindings: ['isActive:is-active'], agent: null, isActive: computed('agent', 'router.currentURL', function() { // TODO Switch back to the router service style when it is no longer feature-flagged // const targetURL = this.get('router').urlFor('servers.server', this.get('agent')); // const currentURL = `${this.get('router.rootURL').slice(0, -1)}${this.get('router.currentURL')}`; const router = this.get('router'); const targetURL = router.generate('servers.server', this.get('agent')); const currentURL = `${router.get('rootURL').slice(0, -1)}${router .get('currentURL') .split('?')[0]}`; return currentURL === targetURL; }), click() { const transition = () => this.get('router').transitionTo('servers.server', this.get('agent')); lazyClick([transition, event]); }, });
Abort on csrf error for login
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Http\Middleware; use Auth; use Closure; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; use Illuminate\Session\TokenMismatchException; class VerifyCsrfToken extends BaseVerifier { protected $except = [ 'oauth/authorize', 'oauth/access_token', ]; protected $abort = [ 'session', ]; public function handle($request, Closure $next) { try { return parent::handle($request, $next); } catch (TokenMismatchException $_e) { if (starts_with($request->decodedPath(), $this->abort)) { abort(403, 'Reload page and try again'); } else { $request->session()->flush(); Auth::logout(); $request->attributes->set('skip_session', true); return $next($request); } } } }
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Http\Middleware; use Auth; use Closure; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; use Illuminate\Session\TokenMismatchException; class VerifyCsrfToken extends BaseVerifier { protected $except = [ 'oauth/authorize', 'oauth/access_token', ]; public function handle($request, Closure $next) { try { return parent::handle($request, $next); } catch (TokenMismatchException $_e) { $request->session()->flush(); Auth::logout(); $request->attributes->set('skip_session', true); return $next($request); } } }
Change assertTrue(isinstance()) by optimal assert Some of tests use different method of assertTrue(isinstance(A, B)) or assertEqual(type(A), B). The correct way is to use assertIsInstance(A, B) provided by testtools Change-Id: Id6ff634d7af3ee3b2eb4add770b0ba589bb08d1d
# Copyright 2016 AT&T Corp # 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. import webob from murano.api import versions from murano.api.middleware import version_negotiation from murano.tests.unit import base class MiddlewareVersionNegotiationTest(base.MuranoTestCase): def test_middleware_version_negotiation_default(self): middleware_vn = version_negotiation.VersionNegotiationFilter(None) request = webob.Request.blank('/environments') result = middleware_vn.process_request(request) self.assertIsInstance(result, versions.Controller)
# Copyright 2016 AT&T Corp # 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. import webob from murano.api import versions from murano.api.middleware import version_negotiation from murano.tests.unit import base class MiddlewareVersionNegotiationTest(base.MuranoTestCase): def test_middleware_version_negotiation_default(self): middleware_vn = version_negotiation.VersionNegotiationFilter(None) request = webob.Request.blank('/environments') result = middleware_vn.process_request(request) self.assertTrue(isinstance(result, versions.Controller))
Use https for load font files This will prevent errors from displaying for anyone using the theme behind https
var self = module.exports = { __module: { provides: { "resources/use_scripts": {}, "resources/use_stylesheets": {}, "resources/register_assets_dir": {after: ['resources/bootstrap', 'resources/hadron']}, "resources/register_views_dir": {} }, properties: { fontAwesome: 'resources/font-awesome' } }, register_assets_dir: function() { return __dirname + "/../../assets"; }, register_views_dir: function() { return __dirname + "/../../views"; }, use_scripts: function() { }, use_stylesheets: function() { return { default: [ self.fontAwesome.exports.stylesheets.all, "https://fonts.googleapis.com/css?family=Lato:300,400,700", "styles/main.less" ], admin: [ "styles/admin.less" ] }; } };
var self = module.exports = { __module: { provides: { "resources/use_scripts": {}, "resources/use_stylesheets": {}, "resources/register_assets_dir": {after: ['resources/bootstrap', 'resources/hadron']}, "resources/register_views_dir": {} }, properties: { fontAwesome: 'resources/font-awesome' } }, register_assets_dir: function() { return __dirname + "/../../assets"; }, register_views_dir: function() { return __dirname + "/../../views"; }, use_scripts: function() { }, use_stylesheets: function() { return { default: [ self.fontAwesome.exports.stylesheets.all, "http://fonts.googleapis.com/css?family=Lato:300,400,700", "styles/main.less" ], admin: [ "styles/admin.less" ] }; } };
Add dynamic links to GMN home page from 404 and 500 HTML templates
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # 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. """Django template context processors Before rendering a template, Django calls context processors as set up in settings_default.TEMPLATE_CONTEXT_PROCESSORS. The context processors are functions that are expected to return a dict which will be merged into the environment available to the template. """ import django.conf def global_settings(request): """Expose some values from settings.py to templates """ return { 'BASE_URL': django.conf.settings.BASE_URL, }
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # 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. """Django template context processors Before rendering a template, Django calls context processors as set up in settings_default.TEMPLATE_CONTEXT_PROCESSORS. The context processors are functions that are expected to return a dict which will be merged into the environment available to the template. """ import django.conf def global_settings(request): """Expose some values from settings.py to templates """ return { 'BASE_URL': django.conf.settings.BASE_URL, }
Add checkboxselectmultiple widget for admin form
from __future__ import absolute_import from django import forms from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.all(), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
from __future__ import absolute_import from django import forms from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.all(), required=False ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
Add common directory to include path
<?php /** * Flipside Common Code Autoload Function * * Autoload Flipside Common code Classes with the syntax Namespace/class.Classname.php * * @author Patrick Boyd / problem@burningflipside.com * @copyright Copyright (c) 2015, Austin Artistic Reconstruction * @license http://www.apache.org/licenses/ Apache 2.0 License */ if(file_exists(__DIR__ . '/vendor/autoload.php')) { require(__DIR__ . '/vendor/autoload.php'); } set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__); spl_autoload_register(function ($class) { // project-specific namespace prefix $prefix = 'Flipside\\'; // base directory for the namespace prefix $base_dir = __DIR__ . '/'; // does the class use the namespace prefix? $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { // no, move to the next registered autoloader return; } // get the relative class name $relative_class = substr($class, $len); // replace the namespace prefix with the base directory, replace namespace // separators with directory separators in the relative class name, append // with .php $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php'; // if the file exists, require it if (file_exists($file)) { require $file; } }); /* vim: set tabstop=4 shiftwidth=4 expandtab: */
<?php /** * Flipside Common Code Autoload Function * * Autoload Flipside Common code Classes with the syntax Namespace/class.Classname.php * * @author Patrick Boyd / problem@burningflipside.com * @copyright Copyright (c) 2015, Austin Artistic Reconstruction * @license http://www.apache.org/licenses/ Apache 2.0 License */ if(file_exists(__DIR__ . '/vendor/autoload.php')) { require(__DIR__ . '/vendor/autoload.php'); } spl_autoload_register(function ($class) { // project-specific namespace prefix $prefix = 'Flipside\\'; // base directory for the namespace prefix $base_dir = __DIR__ . '/'; // does the class use the namespace prefix? $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { // no, move to the next registered autoloader return; } // get the relative class name $relative_class = substr($class, $len); // replace the namespace prefix with the base directory, replace namespace // separators with directory separators in the relative class name, append // with .php $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php'; // if the file exists, require it if (file_exists($file)) { require $file; } }); /* vim: set tabstop=4 shiftwidth=4 expandtab: */
Append loader suffix to webpack loader
const webpack = require('webpack'); module.exports = (config) => { const { env } = process; config.set({ frameworks: ['mocha'], files: ['test/index.js'], preprocessors: { 'test/index.js': ['webpack', 'sourcemap'] }, webpack: { module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('test'), __DEV__: true }) ], devtool: 'cheap-module-inline-source-map' }, webpackMiddleware: { noInfo: true }, reporters: ['mocha'], mochaReporter: { output: 'autowatch' }, customLaunchers: { ChromeCi: { base: 'Chrome', flags: ['--no-sandbox'] } }, browsers: env.BROWSER ? env.BROWSER.split(',') : ['Chrome', 'Firefox'] }); };
const webpack = require('webpack'); module.exports = (config) => { const { env } = process; config.set({ frameworks: ['mocha'], files: ['test/index.js'], preprocessors: { 'test/index.js': ['webpack', 'sourcemap'] }, webpack: { module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('test'), __DEV__: true }) ], devtool: 'cheap-module-inline-source-map' }, webpackMiddleware: { noInfo: true }, reporters: ['mocha'], mochaReporter: { output: 'autowatch' }, customLaunchers: { ChromeCi: { base: 'Chrome', flags: ['--no-sandbox'] } }, browsers: env.BROWSER ? env.BROWSER.split(',') : ['Chrome', 'Firefox'] }); };
Enable no subdir support for links
<?php /** * HTML Methods * * @author Edwin Dayot <edwin.dayot@sfr.fr> * @copyright 2014 */ /** * HTML Class */ class HTML { /** * Link method * * @param string $link * * @return string Constructed URL */ static function link($link) { $link = !empty($link) ? '/' . trim($link, '/') : ''; $script_name = trim(dirname(dirname($_SERVER['SCRIPT_NAME']))) != '/' ? '/' . trim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/') : ''; return $_SERVER['REQUEST_SCHEME'] . '://' . trim($_SERVER['SERVER_NAME'], '/') . $script_name . $link; } static function getCurrentURL() { return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; } }
<?php /** * HTML Methods * * @author Edwin Dayot <edwin.dayot@sfr.fr> * @copyright 2014 */ /** * HTML Class */ class HTML { /** * Link method * * @param string $link * * @return string Constructed URL */ static function link($link) { return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . dirname(dirname($_SERVER['SCRIPT_NAME'])) . '/' . trim($link, '/'); } static function getCurrentURL() { return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; } }
Add skip test when Memcache not defined
<?php namespace Test\Type\Functional; use Bcol\Component\Type\Cache; /** * Class MemcachedStub * * @author Brice Colucci <brice.colucci@gmail.com> */ class MemcachedStub implements Cache { /** * @var \Memcache */ private $cache; public function __construct() { if (false === class_exists('\Memcache')) { throw new \PHPUnit_Framework_SkippedTestError('Test cannot be ran, you need Memcache'); } $this->cache = new \Memcache(); $this->cache->addserver("localhost"); } /** * @param string $key * @param mixed $value * * @return mixed */ public function add($key, $value) { $this->cache->add($key, $value); } /** * @param $key * * @return mixed */ public function get($key) { return $this->cache->get($key); } }
<?php namespace Test\Type\Functional; use Bcol\Component\Type\Cache; /** * Class MemcachedStub * * @author Brice Colucci <brice.colucci@gmail.com> */ class MemcachedStub implements Cache { /** * @var \Memcache */ private $cache; public function __construct() { $this->cache = new \Memcache(); $this->cache->addserver("localhost"); } /** * @param string $key * @param mixed $value * * @return mixed */ public function add($key, $value) { $this->cache->add($key, $value); } /** * @param $key * * @return mixed */ public function get($key) { return $this->cache->get($key); } }
Add fix to periods helper method
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import Realm from 'realm'; export class PeriodSchedule extends Realm.Object { getUseablePeriodsForProgram(program, maxOrdersPerPeriod) { const periods = this.periods.filter( period => period.numberOfRequisitionsForProgram(program) < maxOrdersPerPeriod ); return periods; } addPeriodIfUnique(period) { if (this.periods.filtered('id == $0', period.id).length > 0) return; this.periods.push(period); } } export default PeriodSchedule; PeriodSchedule.schema = { name: 'PeriodSchedule', primaryKey: 'id', properties: { id: 'string', name: { type: 'string', default: 'Placeholder Name' }, periods: { type: 'list', objectType: 'Period' }, }, };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import Realm from 'realm'; export class PeriodSchedule extends Realm.Object { getUseablePeriodsForProgram(program, maxOrdersPerPeriod) { const periods = this.periods.reduce(period => { if (period.numberOfRequisitionsForProgram(program) >= maxOrdersPerPeriod) return null; return period; }); return periods; } addPeriodIfUnique(period) { if (this.periods.filtered('id == $0', period.id).length > 0) return; this.periods.push(period); } } export default PeriodSchedule; PeriodSchedule.schema = { name: 'PeriodSchedule', primaryKey: 'id', properties: { id: 'string', name: { type: 'string', default: 'Placeholder Name' }, periods: { type: 'list', objectType: 'Period' }, }, };
Return Content-Type header with JSON size info
import argparse import json from flask import Flask, request parser = argparse.ArgumentParser(description="Start a Blindstore server.") parser.add_argument('-d', '--debug', action='store_true', help="enable Flask debug mode. DO NOT use in production.") args = parser.parse_args() NUM_RECORDS = 5 RECORD_SIZE = 64 app = Flask(__name__) @app.route('/db_size') def get_db_size(): return json.dumps({'num_records': NUM_RECORDS, 'record_size': RECORD_SIZE}), \ 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def get(): public_key = request.form['PUBLIC_KEY'] enc_index = request.form['ENC_INDEX'] return "/retrieve index '{index}' with key '{key}'".format(index=enc_index, key=public_key) @app.route('/set', methods=['POST']) def put(): enc_index = request.form['ENC_INDEX'] enc_data = request.form['ENC_DATA'] return "/set '{index}' to '{data}'".format(data=enc_data, index=enc_index) if __name__ == '__main__': app.run(debug=args.debug)
import argparse import json from flask import Flask, request parser = argparse.ArgumentParser(description="Start a Blindstore server.") parser.add_argument('-d', '--debug', action='store_true', help="enable Flask debug mode. DO NOT use in production.") args = parser.parse_args() NUM_RECORDS = 5 RECORD_SIZE = 64 app = Flask(__name__) @app.route('/db_size') def get_db_size(): return json.dumps({'num_records': NUM_RECORDS, 'record_size': RECORD_SIZE}) @app.route('/retrieve', methods=['POST']) def get(): public_key = request.form['PUBLIC_KEY'] enc_index = request.form['ENC_INDEX'] return "/retrieve index '{index}' with key '{key}'".format(index=enc_index, key=public_key) @app.route('/set', methods=['POST']) def put(): enc_index = request.form['ENC_INDEX'] enc_data = request.form['ENC_DATA'] return "/set '{index}' to '{data}'".format(data=enc_data, index=enc_index) if __name__ == '__main__': app.run(debug=args.debug)
Replace deprecated url.parse() with WHATWG URL API
const redis = require('redis') const config = require('config') const logger = require('./logger.js')() const initRedisClient = function () { let client, redisInfo if (config.redis.url) { redisInfo = new URL(config.redis.url) client = redis.createClient(redisInfo.port, redisInfo.hostname) } else { client = redis.createClient(config.redis.port, 'localhost') } const closeRedisConnection = function (error, exitCode) { if (error) { logger.error(error) } client.quit() client.on('end', function () { logger.info('Disconnected from Redis') }) } // We do not want too many connections being made to Redis (especially for Streetmix production), // so before a process exits, close the connection to Redis. process.on('beforeExit', closeRedisConnection) process.on('SIGINT', closeRedisConnection) process.on('uncaughtException', closeRedisConnection) client.on('error', closeRedisConnection) client.on('connect', function () { logger.info('Connected to Redis') // Use the password in the URL if provided; otherwise use the one provided by config const redisAuth = (config.redis.url && redisInfo) ? redisInfo.password : config.redis.password if (redisAuth) { client.auth(redisAuth, function (error) { if (error) throw error }) } }) return client } module.exports = initRedisClient
const redis = require('redis') const config = require('config') const url = require('url') const logger = require('./logger.js')() const initRedisClient = function () { let client, redisInfo if (config.redis.url) { redisInfo = url.parse(config.redis.url) client = redis.createClient(redisInfo.port, redisInfo.hostname) } else { client = redis.createClient(config.redis.port, 'localhost') } const closeRedisConnection = function (error, exitCode) { if (error) { logger.error(error) } client.quit() client.on('end', function () { console.log('Disconnected from Redis') }) } // We do not want too many connections being made to Redis (especially for Streetmix production), // so before a process exits, close the connection to Redis. process.on('beforeExit', closeRedisConnection) process.on('SIGINT', closeRedisConnection) process.on('uncaughtException', closeRedisConnection) client.on('error', closeRedisConnection) client.on('connect', function () { console.log('Connected to Redis') const redisAuth = (config.redis.url && redisInfo) ? redisInfo.auth.split(':')[1] : config.redis.password if (redisAuth) { client.auth(redisAuth, function (error) { if (error) throw error }) } }) return client } module.exports = initRedisClient
Use test.touch() instead of os.utime() in a test. No intended functionality change. TBR=evan Review URL: https://chromiumcodereview.appspot.com/9234034
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that app bundles are rebuilt correctly. """ import TestGyp import os import sys if sys.platform == 'darwin': test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode']) test.run_gyp('test.gyp', chdir='app-bundle') test.build('test.gyp', test.ALL, chdir='app-bundle') # Touch a source file, rebuild, and check that the app target is up-to-date. test.touch('app-bundle/TestApp/main.m', None) test.build('test.gyp', test.ALL, chdir='app-bundle') test.up_to_date('test.gyp', test.ALL, chdir='app-bundle') test.pass_test()
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that app bundles are rebuilt correctly. """ import TestGyp import os import sys if sys.platform == 'darwin': test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode']) test.run_gyp('test.gyp', chdir='app-bundle') test.build('test.gyp', test.ALL, chdir='app-bundle') # Touch a source file, rebuild, and check that the app target is up-to-date. os.utime('app-bundle/TestApp/main.m', None) test.build('test.gyp', test.ALL, chdir='app-bundle') test.up_to_date('test.gyp', test.ALL, chdir='app-bundle') test.pass_test()
STYLE: Change order parameter for module couch-provider
var request = require('request'); var _ = require('underscore'); var Promise = require('bluebird'); var Stream = require('stream'); var Boom = require('boom'); module.exports = function (server, conf) { require('couch-provider')(conf.dataproviders, server, 'clusterprovider'); var clustermodel = require('clusterpost-model'); var Joi = require('joi'); const isJobDocument = function(doc){ Joi.assert(doc, clustermodel.job); return Promise.resolve(doc); } server.method({ name: 'clusterprovider.isJobDocument', method: isJobDocument, options: {} }); const validateJobOwnership = function(doc, credentials){ return new Promise(function(resolve, reject){ if(doc.userEmail === credentials.email || credentials.scope.indexOf('admin') || (credentials.executionserver && credentials.executionserver === doc.executionserver)){ resolve(doc); }else{ reject(Boom.unauthorized("You are not allowed to access this job document!")); } }); } server.method({ name: 'clusterprovider.validateJobOwnership', method: validateJobOwnership, options: {} }); }
var request = require('request'); var _ = require('underscore'); var Promise = require('bluebird'); var Stream = require('stream'); var Boom = require('boom'); module.exports = function (server, conf) { require('couch-provider')(server, conf.dataproviders, 'clusterprovider'); var clustermodel = require('clusterpost-model'); var Joi = require('joi'); const isJobDocument = function(doc){ Joi.assert(doc, clustermodel.job); return Promise.resolve(doc); } server.method({ name: 'clusterprovider.isJobDocument', method: isJobDocument, options: {} }); const validateJobOwnership = function(doc, credentials){ return new Promise(function(resolve, reject){ if(doc.userEmail === credentials.email || credentials.scope.indexOf('admin') || (credentials.executionserver && credentials.executionserver === doc.executionserver)){ resolve(doc); }else{ reject(Boom.unauthorized("You are not allowed to access this job document!")); } }); } server.method({ name: 'clusterprovider.validateJobOwnership', method: validateJobOwnership, options: {} }); }
Add code to tooltipify all tooltip links
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require underscore //= require backbone //= require handlebars.runtime //= require twitter/bootstrap/bootstrap-alert //= require twitter/bootstrap/bootstrap-button //= require twitter/bootstrap/bootstrap-carousel //= require twitter/bootstrap/bootstrap-collapse //= require twitter/bootstrap/bootstrap-dropdown //= require twitter/bootstrap/bootstrap-modal //= require twitter/bootstrap/bootstrap-tooltip //= require twitter/bootstrap/bootstrap-popover //= require twitter/bootstrap/bootstrap-scrollspy //= require twitter/bootstrap/bootstrap-tab //= require twitter/bootstrap/bootstrap-transition //= require twitter/bootstrap/bootstrap-typeahead //= require google-code-prettify-rails/prettify //= require fitgem_client $(document).ready(function(){ prettyPrint(); $("a[rel=tooltip]").tooltip(); });
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require underscore //= require backbone //= require handlebars.runtime //= require twitter/bootstrap/bootstrap-alert //= require twitter/bootstrap/bootstrap-button //= require twitter/bootstrap/bootstrap-carousel //= require twitter/bootstrap/bootstrap-collapse //= require twitter/bootstrap/bootstrap-dropdown //= require twitter/bootstrap/bootstrap-modal //= require twitter/bootstrap/bootstrap-tooltip //= require twitter/bootstrap/bootstrap-popover //= require twitter/bootstrap/bootstrap-scrollspy //= require twitter/bootstrap/bootstrap-tab //= require twitter/bootstrap/bootstrap-transition //= require twitter/bootstrap/bootstrap-typeahead //= require google-code-prettify-rails/prettify //= require fitgem_client $(document).ready(function(){ prettyPrint(); });
Use same path for native services base dir NativeServicesTestFixture did not use a File with absolute path which caused the location of the nativeServicesBaseDir to change into the actual test directory instead of keeping it top-level in the subproject dir.
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.testfixtures.internal; import org.gradle.internal.nativeintegration.services.NativeServices; import java.io.File; public class NativeServicesTestFixture { static NativeServices nativeServices; static boolean initialized; public static synchronized void initialize() { if (!initialized) { System.setProperty("org.gradle.native", "true"); File nativeDir = getNativeServicesDir(); NativeServices.initialize(nativeDir); initialized = true; } } public static synchronized NativeServices getInstance() { if (nativeServices == null) { initialize(); nativeServices = NativeServices.getInstance(); } return nativeServices; } public static File getNativeServicesDir() { return new File("build/native-libs").getAbsoluteFile(); } }
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.testfixtures.internal; import org.gradle.internal.nativeintegration.services.NativeServices; import java.io.File; public class NativeServicesTestFixture { static NativeServices nativeServices; static boolean initialized; public static synchronized void initialize() { if (!initialized) { System.setProperty("org.gradle.native", "true"); File nativeDir = getNativeServicesDir(); NativeServices.initialize(nativeDir); initialized = true; } } public static synchronized NativeServices getInstance() { if (nativeServices == null) { initialize(); nativeServices = NativeServices.getInstance(); } return nativeServices; } public static File getNativeServicesDir() { return new File("build/native-libs"); } }
Revert "accept 'magic 8 ball' as input"
var bodyParser = require('body-parser'); var answers = require('./answers.js'); var express = require('express'); var request = require('request'); var app = express(); var port = process.env.PORT || 3000; var postOptions = { url: 'https://api.groupme.com/v3/bots/post', method: 'POST' }; app.use(bodyParser.json()); app.route('/') .get(function(req, res) { sayBot(res); //res.end('Thanks'); }) .post(function(req, res) { if(req.body.name.toLowerCase().indexOf('magic eight ball') < 0 && req.body.text.toLowerCase().indexOf('magic eight ball') > -1) { setTimeout(sayBot(res), 4000); }else { res.send('Thanks'); } }); function sayBot(res) { var botData = { bot_id: process.env.BOT_ID, text: answers[Math.floor(Math.random()*answers.length)] }; postOptions.json = botData; request(postOptions, function(error, response, body) { res.end('Thanks'); }); } app.listen(port, function(){ console.log('The magic happens on port ' + port); }); exports.app = app;
var bodyParser = require('body-parser'); var answers = require('./answers.js'); var express = require('express'); var request = require('request'); var app = express(); var port = process.env.PORT || 3000; var triggers = ['magic eight ball', 'magic 8 ball']; var postOptions = { url: 'https://api.groupme.com/v3/bots/post', method: 'POST' }; app.use(bodyParser.json()); app.route('/') .get(function(req, res) { sayBot(res); //res.end('Thanks'); }) .post(function(req, res) { if(isTriggered(text)) { setTimeout(sayBot(res), 4000); }else { res.send('Thanks'); } }); function sayBot(res) { var botData = { bot_id: process.env.BOT_ID, text: answers[Math.floor(Math.random()*answers.length)] }; postOptions.json = botData; request(postOptions, function(error, response, body) { res.end('Thanks'); }); } function isTriggered(text) { var loweredText = text.toLowerCase(); for(var i = 0; i < triggers.length; i ++) { if(loweredText.indexOf(triggers[i]) > -1 ) { return true; } } return false; } app.listen(port, function(){ console.log('The magic happens on port ' + port); }); exports.app = app;
Reduce queries used to lookup config
# Eve W-Space # Copyright (C) 2013 Andrew Austin and other contributors # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. An additional term under section # 7 of the GPL is included in the LICENSE file. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from core.models import ConfigEntry def get_config(name, user): """ Gets the correct config value for the given key name. Value with the given user has priority over any default value. """ try: return ConfigEntry.objects.get(name=name, user=user) except ConfigEntry.DoesNotExist: return ConfigEntry.objects.get(name=name, user=None)
# Eve W-Space # Copyright (C) 2013 Andrew Austin and other contributors # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. An additional term under section # 7 of the GPL is included in the LICENSE file. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from core.models import ConfigEntry def get_config(name, user): """ Gets the correct config value for the given key name. Value with the given user has priority over any default value. """ if ConfigEntry.objects.filter(name=name, user=user).count() != 0: return ConfigEntry.objects.get(name=name, user=user) # No user value, look for global / default if ConfigEntry.objects.filter(name=name, user=None).count() != 0: return ConfigEntry.objects.get(name=name, user=None) else: raise KeyError("No configuration entry with key %s was found." % name)
Remove blank line in JSON string.
package cnmidori_test import ( "fmt" "io/ioutil" "os" "path" "github.com/northbright/cnmidori" "github.com/northbright/pathhelper" ) const ( settingsStr string = ` { "redis-servers":[ {"name":"user", "addr":"localhost:6379", "password":"123456"}, {"name":"data", "addr":"localhost:6380", "password":"123456"} ] }` ) func ExampleNewServer() { serverRoot, _ := pathhelper.GetCurrentExecDir() settingsFile := path.Join(serverRoot, "settings.json") if err := ioutil.WriteFile(settingsFile, []byte(settingsStr), 0755); err != nil { fmt.Fprintf(os.Stderr, "ioutil.WriteFile() error: %v\n", err) return } server, err := cnmidori.NewServer(settingsFile) if err != nil { fmt.Fprintf(os.Stderr, "NewServer(%v) error: %v\n", settingsFile, err) return } fmt.Fprintf(os.Stderr, "NewServer() OK. server = %v\n", server) // Output: }
package cnmidori_test import ( "fmt" "io/ioutil" "os" "path" "github.com/northbright/cnmidori" "github.com/northbright/pathhelper" ) const ( settingsStr string = ` { "redis-servers":[ {"name":"user", "addr":"localhost:6379", "password":"123456"}, {"name":"data", "addr":"localhost:6380", "password":"123456"} ] } ` ) func ExampleNewServer() { serverRoot, _ := pathhelper.GetCurrentExecDir() settingsFile := path.Join(serverRoot, "settings.json") if err := ioutil.WriteFile(settingsFile, []byte(settingsStr), 0755); err != nil { fmt.Fprintf(os.Stderr, "ioutil.WriteFile() error: %v\n", err) return } server, err := cnmidori.NewServer(settingsFile) if err != nil { fmt.Fprintf(os.Stderr, "NewServer(%v) error: %v\n", settingsFile, err) return } fmt.Fprintf(os.Stderr, "NewServer() OK. server = %v\n", server) // Output: }
Tidy up of contrib policy
<?php if(!isset($category)): ?> <div class="felix-item-title felix-item-title felix-item-title-generic"> <h3>write for us</h3> </div> <div class="felix-contribute"> <p>Interested in becoming a news reporter? Or just have a favourite something to share with Imperial? Write for Felix - it's easy!</p> <p>Got a tip you'd like to share? We welcome anonymous messages too.</p> <center><a class="button small" href="<?php echo STANDARD_URL; ?>issuearchive/">Find out how to contribute</a></center> </div> <?php else: ?> <div class="felix-item-title felix-item-title felix-item-title-generic"> <h3>write for <?php echo $category->getLabel(); ?></h3> </div> <div class="felix-contribute"> <p>Want to write for this section? Drop the editors a line via the contact details above and they'll let you how to get involved - contributors always welcome!</p> </div> <?php endif; ?>
<?php if(!isset($category)): ?> <div class="felix-item-title felix-item-title felix-item-title-generic"> <h3>write for us</h3> </div> <p>Interested in becoming a news reporter? Or just have a favourite something to share with Imperial? Write for Felix - it's easy!</p> <p>Got a tip you'd like to share? We welcome anonymous messages too.</p> <center><a class="button" href="<?php echo STANDARD_URL; ?>issuearchive/">Find out how to contribute</a></center> <?php else: ?> <div class="felix-item-title felix-item-title felix-item-title-generic"> <h3>write for <?php echo $category->getLabel(); ?></h3> </div> <p><b>TO BE IMPLEMENTED!!!</b></p> <?php endif; ?>
Update libc's DrillerRead to use the new posix read calling convention to support variable read
import simuvex from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength class DrillerRead(simuvex.SimProcedure): ''' A custom version of read which has a symbolic return value. ''' def run(self, fd, dst, length): self.argument_types = {0: SimTypeFd(), 1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)), 2: SimTypeLength(self.state.arch)} self.return_type = SimTypeLength(self.state.arch) if self.state.se.max_int(length) == 0: return self.state.se.BVV(0, self.state.arch.bits) sym_length = self.state.se.BV("sym_length", self.state.arch.bits) self.state.add_constraints(sym_length <= length) self.state.add_constraints(sym_length >= 0) data = self.state.posix.read(fd, length, dst_addr=dst) return sym_length simprocedures = [("read", DrillerRead)]
import simuvex from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength class DrillerRead(simuvex.SimProcedure): ''' A custom version of read which has a symbolic return value. ''' def run(self, fd, dst, length): self.argument_types = {0: SimTypeFd(), 1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)), 2: SimTypeLength(self.state.arch)} self.return_type = SimTypeLength(self.state.arch) if self.state.se.max_int(length) == 0: return self.state.se.BVV(0, self.state.arch.bits) sym_length = self.state.se.BV("sym_length", self.state.arch.bits) self.state.add_constraints(sym_length <= length) self.state.add_constraints(sym_length >= 0) _ = self.state.posix.pos(fd) data = self.state.posix.read(fd, length) self.state.store_mem(dst, data) return sym_length simprocedures = [("read", DrillerRead)]
Fix infinte loop in selection layer Java8 IntStreams can get into an infinite loop if the limit is never reached. The selection layer should use the minimum between the number of available instances and the desired instance. Signed-off-by: Tommy Shiou <fd59d852321c3431be8a979962d50c7894293a47@turn.com>
package com.turn.edc.selection.impl; import com.turn.edc.discovery.CacheInstance; import com.turn.edc.exception.InvalidParameterException; import com.turn.edc.selection.SelectionProvider; import java.util.Collection; import java.util.List; import java.util.Random; import com.google.common.collect.Lists; /** * Selection provider that has a uniform distribution across the instances * * @author tshiou */ public class UniformDistributionSelection implements SelectionProvider { private final List<CacheInstance> instances; private final int nInstances; public UniformDistributionSelection(List<CacheInstance> serviceInstances) { this.instances = serviceInstances; this.nInstances = serviceInstances.size(); } @Override public Collection<CacheInstance> allInstances() { return this.instances; } @Override public Collection<CacheInstance> selectInstances(int n) throws InvalidParameterException { if (nInstances < 1) { throw new InvalidParameterException("Not enough instances to select from!"); } if (n == 0) { return Lists.newArrayList(); } int[] indices = new Random().ints(0, nInstances).distinct().limit(Math.min(n, nInstances)).toArray(); List<CacheInstance> selected = Lists.newArrayListWithCapacity(indices.length); for (Integer i : indices) { selected.add(instances.get(i)); } return selected; } }
package com.turn.edc.selection.impl; import com.turn.edc.discovery.CacheInstance; import com.turn.edc.exception.InvalidParameterException; import com.turn.edc.selection.SelectionProvider; import java.util.Collection; import java.util.List; import java.util.Random; import com.google.common.collect.Lists; /** * Selection provider that has a uniform distribution across the instances * * @author tshiou */ public class UniformDistributionSelection implements SelectionProvider { private final List<CacheInstance> instances; private final int nInstances; public UniformDistributionSelection(List<CacheInstance> serviceInstances) { this.instances = serviceInstances; this.nInstances = serviceInstances.size(); } @Override public Collection<CacheInstance> allInstances() { return this.instances; } @Override public Collection<CacheInstance> selectInstances(int n) throws InvalidParameterException { if (nInstances < 1) { throw new InvalidParameterException("Not enough instances to select from!"); } if (n == 0) { return Lists.newArrayList(); } int[] indices = new Random().ints(0, nInstances).distinct().limit(n).toArray(); List<CacheInstance> selected = Lists.newArrayListWithCapacity(indices.length); for (Integer i : indices) { selected.add(instances.get(i)); } return selected; } }
Fix 'Againgit add *' unit test...
<?php /** * Corresponding Class to test Exchangerate class. * * * @author Ricardo Madrigal <soporte@d3catalyst.com> */ class ExchangerateTest extends PHPUnit_Framework_TestCase{ /** * Just check if the YourClass has no syntax error. * */ public function testIsThereAnySyntaxError(){ $var = new D3Catalyst\Exchangerate\Exchangerate; $this->assertTrue(is_object($var)); unset($var); } /** * Check if the Exchange Rate can retrieve currency info. * */ public function testgetExchangeCurrency(){ $var = new D3Catalyst\Exchangerate\Exchangerate; $var->setCurrency('USD','MXN'); $this->assertTrue(is_numeric($var->getExchangeValue())); unset($var); } }
<?php /** * Corresponding Class to test Exchangerate class. * * * @author Ricardo Madrigal <soporte@d3catalyst.com> */ class ExchangerateTest extends PHPUnit_Framework_TestCase{ /** * Just check if the YourClass has no syntax error. * */ public function testIsThereAnySyntaxError(){ $var = new D3Catalyst\Exchangerate\Exchange; $this->assertTrue(is_object($var)); unset($var); } /** * Check if the Exchange Rate can retrieve currency info. * */ public function testgetExchangeCurrency(){ $var = new D3Catalyst\Exchangerate\Exchange; $var->setCurrency('USD','MXN'); $this->assertTrue(is_numeric($var->getExchangeValue())); unset($var); } }
Add empty path utility method A quick way of deleting content inside a given directory
<?php use Codeception\Configuration; use Codeception\Util\Debug; use Illuminate\Filesystem\Filesystem; /** * Output Path * * @author Alin Eugen Deac <aedart@gmail.com> */ trait OutputPath { /** * Creates an output path, if it does not already exist */ public function createOutputPath() { if(!file_exists($this->outputPath())){ mkdir($this->outputPath(), 0755, true); Debug::debug(sprintf('<info>Created output path </info><debug>%s</debug>', $this->outputPath())); } } /** * Deletes all files and folders inside the given path * * @param string $path */ public function emptyPath($path) { // Remove all created folders inside output path $fs = new Filesystem(); $folders = $fs->directories($path); foreach($folders as $directory){ $fs->deleteDirectory($directory); } } /** * Returns the output directory path * * @return string * @throws \Codeception\Exception\ConfigurationException */ public function outputPath() { return Configuration::outputDir(); } }
<?php use Codeception\Configuration; use Codeception\Util\Debug; /** * Output Path * * @author Alin Eugen Deac <aedart@gmail.com> */ trait OutputPath { /** * Creates an output path, if it does not already exist */ public function createOutputPath() { if(!file_exists($this->outputPath())){ mkdir($this->outputPath(), 0755, true); Debug::debug(sprintf('<info>Created output path </info><debug>%s</debug>', $this->outputPath())); } } /** * Returns the output directory path * * @return string * @throws \Codeception\Exception\ConfigurationException */ public function outputPath() { return Configuration::outputDir(); } }