| text
				 stringlengths 17 1.47k | positive
				 stringlengths 673 4.43k | negative
				 stringlengths 677 2.81k | 
|---|---|---|
| 
	Move import statements into the transform function | 
	//     requirish
//     Copyright 2014 Enrico Stara '[email protected]'
//     Released under the MIT License
//     https://github.com/enricostara/require-mainify
// The require('...') regular expression
var requireRegExp = /require\s*\(\s*(["'])(.*?)\1\s*\)\s*/g;
// The transform function
module.exports = function (file) {
    // Import dependencies
    var path = require('path');
    var through = require('through2');
    var resolve = require('resolve');
    // Retrieve the file relative path
    var fileFolder = path.dirname(file);
    var relativeToRoot = path.relative(fileFolder, '.');
    // Transform `require(..)`
    return through(function (buf, enc, next) {
        this.push(buf.toString('utf8').replace(requireRegExp, replacer));
        next();
    });
    // `require(..)` replacer
    function replacer(match, quote, require) {
        var replacement = 'require(' + quote;
        try {
            resolve.sync(require);
        } catch (exc) {
            try {
                // Try to resolve the require statement starting from the root folder
                resolve.sync(require, {paths: ['.']});
                replacement += relativeToRoot + path.sep;
            } catch (exc2) {
            }
        }
        replacement += require + quote + ')';
//        console.log(replacement);
        return replacement;
    }
};
// Modify the module internal paths
function _(module) {
    console.log(module.filename);
    (module.paths && module.paths.push('.'));
}
module.exports._ = _;
 | 
	//     requirish
//     Copyright 2014 Enrico Stara '[email protected]'
//     Released under the MIT License
//     https://github.com/enricostara/require-mainify
// Import dependencies
var path = require('path');
var through = require('through2');
var resolve = require('resolve');
// The require('...') regular expression
var requireRegExp = /require\s*\(\s*(["'])(.*?)\1\s*\)\s*/g;
// The transform function
module.exports = function (file) {
    var fileFolder = path.dirname(file);
    var relativeToRoot = path.relative(fileFolder, '.');
    return through(function (buf, enc, next) {
        this.push(buf.toString('utf8').replace(requireRegExp, replacer));
        next();
    });
    function replacer(match, quote, require) {
        var replacement = 'require(\'';
        try {
            resolve.sync(require);
        } catch (exc) {
            try {
                // Try to resolve the require statement starting from the root folder
                resolve.sync(require, {paths: ['.']});
                replacement += relativeToRoot + path.sep;
            } catch (exc2) {
            }
        }
        replacement += require + '\')';
        return replacement;
    }
};
function _(module) {
    console.log(module.filename);
    (module.paths && module.paths.push('.'));
}
module.exports._ = _; | 
| 
	Refactor email task variable names | 
	from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
    """
    """
    try:
        transactions = Transaction.objects.export_transactions()
        debit_sum = Decimal(0)
        attachment = CSVAttachmentWriter()
        for transaction in transactions:
            attachment.writerow([transaction['product__account_number'], '',
                                 transaction['price__sum']])
            debit_sum += transaction['price__sum']
        debit_account = getattr(settings, 'SHOPIFY_DEBIT_ACCOUNT_NUMBER', None)
        attachment.writerow([debit_account, debit_sum, ''])
        message = EmailMessage('Journal Vouchers Import', '',
                               to=[m[1] for m in settings.MANAGERS])
        message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
        message.send()
    except Exception as exc:
        logger.debug("MIP export failed: %s" % exc)
        logger.warn('MIP export failed, retrying')
        raise email_mip_import_file.retry(exc=exc)
 | 
	from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
    """
    """
    try:
        credits = Transaction.objects.export_transactions()
        debit = Decimal(0)
        attachment = CSVAttachmentWriter()
        for credit in credits:
            attachment.writerow([credit['product__account_number'], '',
                                 credit['price__sum']])
            debit += credit['price__sum']
        debit_account = getattr(settings, 'SHOPIFY_DEBIT_ACCOUNT_NUMBER', None)
        attachment.writerow([debit_account, debit, ''])
        message = EmailMessage('Journal Vouchers Import', '',
                               to=[m[1] for m in settings.MANAGERS])
        message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
        message.send()
    except Exception as exc:
        logger.debug("MIP export failed: %s" % exc)
        logger.warn('MIP export failed, retrying')
        raise email_mip_import_file.retry(exc=exc)
 | 
| 
	Add a submitted value to the form | 
	app.controller('LoginCtrl', ['$scope', '$log', '$route', 'User',
    function($scope, $log, $route, User) {
        $scope.loginForm = {};
        $scope.errors = {};
        $scope.login = function() {
            $log.debug('Setting all the form fields to $dirty...');
            angular.forEach($scope.form, function(ctrl, field) {
                // Dirty hack because $scope.form contains so much more than just the fields
                if (typeof ctrl === 'object' && ctrl.hasOwnProperty('$modelValue')) {
                    ctrl.$dirty = true;
                    ctrl.$pristine = false;
                }
            });
            if ($scope.form.$invalid) {
                $log.debug('Form is invalid. Not sending request to server.')
                return;
            }
            $scope.form.submitted = true;
            $log.debug('Attempting to log user in...');
            User.login($scope.loginForm.email, $scope.loginForm.password).then(function(data) {
                $route.reload();
            }).catch(function(data) {
                $log.debug('Unable to log user in... %o', data);
                $scope.errors = {}
                angular.forEach(data.errors, function(error, field) {
                    $scope.form[field].$setValidity('server', false);
                    $scope.errors[field] = error;
                });
            });
        };
    }
]);
 | 
	app.controller('LoginCtrl', ['$scope', '$log', '$route', 'User',
    function($scope, $log, $route, User) {
        $scope.loginForm = {};
        $scope.errors = {};
        $scope.login = function() {
            $log.debug('Setting all the form fields to $dirty...');
            angular.forEach($scope.form, function(ctrl, field) {
                // Dirty hack because $scope.form contains so much more than just the fields
                if (typeof ctrl === 'object' && ctrl.hasOwnProperty('$modelValue')) {
                    ctrl.$dirty = true;
                    ctrl.$pristine = false;
                }
            });
            if ($scope.form.$invalid) {
                $log.debug('Form is invalid. Not sending request to server.')
                return;
            }
            $log.debug('Attempting to log user in...');
            User.login($scope.loginForm.email, $scope.loginForm.password).then(function(data) {
                $route.reload();
            }).catch(function(data) {
                $log.debug('Unable to log user in... %o', data);
                $scope.errors = {}
                angular.forEach(data.errors, function(error, field) {
                    $scope.form[field].$setValidity('server', false);
                    $scope.errors[field] = error;
                });
            });
        };
    }
]);
 | 
| 
	Revert to dto in one-string requests. | 
	package com.royalrangers.controller;
import com.royalrangers.dto.ResponseResult;
import com.royalrangers.dto.user.EmailDto;
import com.royalrangers.service.SubscribeService;
import com.royalrangers.utils.ResponseBuilder;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/subscribe")
public class SubscribeController {
    @Autowired
    private SubscribeService subscribeService;
    @PostMapping
    @ApiOperation(value = "Create subscriber")
    public ResponseResult subscribe(@RequestBody EmailDto request) {
        String email = request.getMail();
        log.info("Add subscriber: " + email);
        try {
            subscribeService.add(email);
            return ResponseBuilder.success(String.format("Email %s added to subscribers list", email));
        } catch (Exception e) {
            return ResponseBuilder.fail(e.getMessage());
        }
    }
    @DeleteMapping
    @ApiOperation(value = "Delete subscriber")
    public ResponseResult unsubscribe(@RequestBody EmailDto request) {
        String email = request.getMail();
        log.info("Remove subscriber: " + email);
        try {
            subscribeService.remove(email);
            return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email));
        } catch (Exception e) {
            return ResponseBuilder.fail(e.getMessage());
        }
    }
}
 | 
	package com.royalrangers.controller;
import com.royalrangers.dto.ResponseResult;
import com.royalrangers.dto.user.EmailDto;
import com.royalrangers.service.SubscribeService;
import com.royalrangers.utils.ResponseBuilder;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/subscribe")
public class SubscribeController {
    @Autowired
    private SubscribeService subscribeService;
    @PostMapping
    @ApiOperation(value = "Create subscriber")
    public ResponseResult subscribe(@RequestBody EmailDto request) {
        String email = request.getMail();
        log.info("Add subscriber: " + email);
        try {
            subscribeService.add(email);
            return ResponseBuilder.success(String.format("Email %s added to subscribers list", email));
        } catch (Exception e) {
            return ResponseBuilder.fail(e.getMessage());
        }
    }
    @DeleteMapping
    @ApiOperation(value = "Delete subscriber")
    public ResponseResult unsubscribe(@RequestBody String email) {
        log.info("Remove subscriber: " + email);
        try {
            subscribeService.remove(email);
            return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email));
        } catch (Exception e) {
            return ResponseBuilder.fail(e.getMessage());
        }
    }
}
 | 
| 
	Use 30s timeout in waitfor function in case things happen slower than they should | 
	/**
 * @fileoverview Run the bootstrap service
 */
var port = 3020,
    system = require('system'),
    page = require('webpage').create(),
    serverObj = require('./server').create(port),
    util = require('./util'),
    module = system.args[1],
    config = system.args[2];
if (!module) {
    console.error('missing module');
    serverObj.close();
    phantom.exit(1);
}
if (!config) {
    console.error('missing config');
    serverObj.close();
    phantom.exit(1);
}
config = decodeURIComponent(config);
var url = 'http://localhost:' + port + '/' + module + '.html?config=' + config;
console.log('<!-- html generated by Livefyre -->');
page.open(url, function(status) {
    if (status !== 'success') {
        console.error('Page could not be opened');
        serverObj.close();
        phantom.exit(1);
    }
    // TODO(rrp): Generalize this bit
    // Wait for fyre-comment-stream el? (need to ensure 100% loaded somehow)
    util.waitFor(function() {
        return page.evaluate(function() {
            return document.getElementsByClassName('fyre-comment-stream').length > 0;
        });
    }, function() {
        var html = page.evaluate(function() {
            return document.getElementById('bs').innerHTML;
        });
        console.log(html);
        serverObj.close();
        phantom.exit();
    }, 30000);
});
 | 
	/**
 * @fileoverview Run the bootstrap service
 */
var port = 3020,
    system = require('system'),
    page = require('webpage').create(),
    serverObj = require('./server').create(port),
    util = require('./util'),
    module = system.args[1],
    config = system.args[2];
if (!module) {
    console.error('missing module');
    serverObj.close();
    phantom.exit(1);
}
if (!config) {
    console.error('missing config');
    serverObj.close();
    phantom.exit(1);
}
config = decodeURIComponent(config);
var url = 'http://localhost:' + port + '/' + module + '.html?config=' + config;
console.log('<!-- html generated by Livefyre -->');
page.open(url, function(status) {
    if (status !== 'success') {
        console.error('Page could not be opened');
        serverObj.close();
        phantom.exit(1);
    }
    // TODO(rrp): Generalize this bit
    // Wait for fyre-comment-stream el? (need to ensure 100% loaded somehow)
    util.waitFor(function() {
        return page.evaluate(function() {
            return document.getElementsByClassName('fyre-comment-stream').length > 0;
        });
    }, function() {
        var html = page.evaluate(function() {
            return document.getElementById('bs').innerHTML;
        });
        console.log(html);
        serverObj.close();
        phantom.exit();
    });
});
 | 
| 
	Tweak to make sorting work when two objects have same name. | 
	package com.quollwriter.data.comparators;
import java.util.*;
import com.quollwriter.data.*;
public class ChapterItemSorter implements Comparator<ChapterItem>
{
    public int compare (ChapterItem o1,
                        ChapterItem o2)
    {
/*
        if (o1.getKey () == null)
        {
            
            return 1;
            
        }
        if (o2.getKey () == null)
        {
            
            return 1;
            
        }
  */  
        if (o1.getPosition () == o2.getPosition ())
        {
            
            if ((o1.getKey () == null)
                ||
                (o1.getName () == null)
               )
            {
                
                return 1;
                
            }
    
            if ((o2.getKey () == null)
                ||
                (o2.getName () == null)
               )
            {
                
                return 1;
                
            }
            
            if ((o1 instanceof Scene)
                &&
                (o2 instanceof OutlineItem)
               )
            {
                
                return -1;
                        
            }
            if ((o2 instanceof Scene)
                &&
                (o1 instanceof OutlineItem)
               )
            {
                
                return 1;
                        
            }
                        
            int nc = o1.getName ().compareTo (o2.getName ());
            
            if (nc == 0)
            {
                
                // Return the one created first.
                return o1.getDateCreated ().compareTo (o2.getDateCreated ());
                    
            } 
                
            return nc;
            
            //return (int) (o1.getKey () - o2.getKey ());
            
        }
        return o1.getPosition () - o2.getPosition ();
    }
    public boolean equals (Object o)
    {
        return this == o;
    }
}
 | 
	package com.quollwriter.data.comparators;
import java.util.*;
import com.quollwriter.data.*;
public class ChapterItemSorter implements Comparator<ChapterItem>
{
    public int compare (ChapterItem o1,
                        ChapterItem o2)
    {
/*
        if (o1.getKey () == null)
        {
            
            return 1;
            
        }
        if (o2.getKey () == null)
        {
            
            return 1;
            
        }
  */  
        if (o1.getPosition () == o2.getPosition ())
        {
            
            if ((o1.getKey () == null)
                ||
                (o1.getName () == null)
               )
            {
                
                return 1;
                
            }
    
            if ((o2.getKey () == null)
                ||
                (o2.getName () == null)
               )
            {
                
                return 1;
                
            }
            
            if ((o1 instanceof Scene)
                &&
                (o2 instanceof OutlineItem)
               )
            {
                
                return -1;
                        
            }
            if ((o2 instanceof Scene)
                &&
                (o1 instanceof OutlineItem)
               )
            {
                
                return 1;
                        
            }
            
            return o1.getName ().compareTo (o2.getName ());
            
            //return (int) (o1.getKey () - o2.getKey ());
            
        }
        return o1.getPosition () - o2.getPosition ();
    }
    public boolean equals (Object o)
    {
        return this == o;
    }
}
 | 
| 
	Fix declaration in case block | 
	import makeDebug from 'debug';
import fp from 'mostly-func';
import { getItems } from 'feathers-hooks-common';
const debug = makeDebug('mostly:feathers-mongoose:hooks:cache');
const defaultOptions = {
  idField: 'id',
};
export default function (cacheMap, opts) {
  opts = Object.assign({}, defaultOptions, opts);
  
  return context => {
    const idName = opts.idField || (context.service || {}).id;
    const svcName = (context.service || {}).name;
    let items = getItems(context);
    items = Array.isArray(items) ? items : [items];
    if (context.type === 'after') {
      if (context.method === 'remove') return;
      items.forEach(item => {
        debug(`>> ${svcName} service set cache`, item[idName]);
        cacheMap.set(item[idName], fp.clone(item));
      });
      return;
    }
    switch (context.method) {
      case 'find': // fall through
      case 'create':
        return;
      case 'get': {
        let value = cacheMap.get(context.id);
        if (value) {
          debug(`<< ${svcName} service get cache`, context.id);
          context.result = value;
        }
        return context;
      }
      default: // update, patch, remove
        if (context.id) {
          cacheMap.delete(context.id);
          return;
        }
        items.forEach(item => {
          debug(`>> ${svcName} service delete cache`, item[idName]);
          cacheMap.delete(item[idName]);
        });
    }
  };
} | 
	import makeDebug from 'debug';
import fp from 'mostly-func';
import { getItems } from 'feathers-hooks-common';
const debug = makeDebug('mostly:feathers-mongoose:hooks:cache');
const defaultOptions = {
  idField: 'id',
};
export default function (cacheMap, opts) {
  opts = Object.assign({}, defaultOptions, opts);
  
  return context => {
    const idName = opts.idField || (context.service || {}).id;
    const svcName = (context.service || {}).name;
    let items = getItems(context);
    items = Array.isArray(items) ? items : [items];
    if (context.type === 'after') {
      if (context.method === 'remove') return;
      items.forEach(item => {
        debug(`>> ${svcName} service set cache`, item[idName]);
        cacheMap.set(item[idName], fp.clone(item));
      });
      return;
    }
    switch (context.method) {
      case 'find': // fall through
      case 'create':
        return;
      case 'get':
        const value = cacheMap.get(context.id);
        if (value) {
          debug(`<< ${svcName} service get cache`, context.id);
          context.result = value;
        }
        return context;
      default: // update, patch, remove
        if (context.id) {
          cacheMap.delete(context.id);
          return;
        }
        items.forEach(item => {
          debug(`>> ${svcName} service delete cache`, item[idName]);
          cacheMap.delete(item[idName]);
        });
    }
  };
} | 
| 
	[libdotify] Fix path creation/git detection bugs | 
	import os
import shlex
import logging
import subprocess
import contextlib
@contextlib.contextmanager
def cd(newdir):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)
def execute(cmd):
    args = shlex.split(cmd)
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out = p.communicate()
    for line in out:
        if not line: continue
        logging.info(line.rstrip())
    if p.returncode != 0:
        logging.error("{} failed with {}".format(cmd, p.returncode))
def git_update(dotmodule, dst, plugins):
    for plugin in plugins:
        if ".git" in plugin:
            name = os.path.basename(plugin).rpartition(".git")[0] # replace trailing ".git"
        else:
            name = os.path.basename(plugin)
        path = "{}{}".format(dst, name)
        print("path: {} ({})".format(path, name))
        if os.path.exists(path):
            logging.debug("updating {} plugin {}".format(dotmodule, name))
            with cd(path):
                execute("git pull")
        else:
            logging.debug("cloning {} plugin {}".format(dotmodule, name))
            try:
                os.makedirs(os.path.split(dst)[0])
            except FileExistsError:
                pass
            with cd(dst):
                execute("git clone --recursive {}".format(plugin))
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
 | 
	import os
import shlex
import logging
import subprocess
import contextlib
@contextlib.contextmanager
def cd(newdir):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)
def execute(cmd):
    args = shlex.split(cmd)
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out = p.communicate()
    for line in out:
        if not line: continue
        logging.info(line.rstrip())
    if p.returncode != 0:
        logging.error("{} failed with {}".format(cmd, p.returncode))
def git_update(dotmodule, dst, plugins):
    for plugin in plugins:
        if "\.git" in plugin:
            name = os.path.basename(plugin).rpartition(".git")[0] # replace trailing ".git"
        else:
            name = os.path.basename(plugin)
        path = "{}{}".format(dst, name)
        if os.path.exists(path):
            logging.debug("updating {} plugin {}".format(dotmodule, name))
            with cd(path):
                execute("git pull")
        else:
            logging.debug("cloning {} plugin {}".format(dotmodule, name))
            os.makedirs(dst)
            with cd(dst):
                execute("git clone --recursive {}".format(plugin))
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
 | 
| 
	Sort import statements in another file | 
	from ..auth_provider import KnowledgeAuthProvider
from ..models import User
from flask import (
    redirect,
    render_template,
    request,
    url_for,
)
from ldap3 import Server, Connection, ALL
class LdapAuthProvider(KnowledgeAuthProvider):
    _registry_keys = ['ldap']
    def init(self):
        if not self.app.config.get('LDAP_SERVER'):
            raise RuntimeError(
                "Use of LDAP authentication requires specification of the LDAP_SERVER configuration variable.")
        self.server = Server(self.app.config['LDAP_SERVER'], get_info=ALL)
    def prompt(self):
        return render_template('auth-login-form.html', skip_password=False)
    def authorize(self):
        user = self.get_user()
        if user is None:
            raise RuntimeError("No such user or invalid credentials")
        if self.validate(user) is False:
            return render_template("auth-login-form.html",
                                   error_message="Uh-oh, it looks like something in your credentials was wrong...")
        self._perform_login(user)
        return redirect(url_for('index.render_feed'))
    def validate(self, user):
        userdn = self.app.config['LDAP_USERDN_SCHEMA'].format(user_id=user.identifier)
        password = request.form['password']
        conn = Connection(self.server, user=userdn, password=password)
        return conn.bind()
    def get_user(self):
        return User(identifier=request.form['username'])
 | 
	from flask import request, render_template, redirect, url_for
from ldap3 import Server, Connection, ALL
from ldap3.core.exceptions import LDAPSocketOpenError
from ..models import User
from ..auth_provider import KnowledgeAuthProvider
class LdapAuthProvider(KnowledgeAuthProvider):
    _registry_keys = ['ldap']
    def init(self):
        if not self.app.config.get('LDAP_SERVER'):
            raise RuntimeError(
                "Use of LDAP authentication requires specification of the LDAP_SERVER configuration variable.")
        self.server = Server(self.app.config['LDAP_SERVER'], get_info=ALL)
    def prompt(self):
        return render_template('auth-login-form.html', skip_password=False)
    def authorize(self):
        user = self.get_user()
        if user is None:
            raise RuntimeError("No such user or invalid credentials")
        if self.validate(user) is False:
            return render_template("auth-login-form.html",
                                   error_message="Uh-oh, it looks like something in your credentials was wrong...")
        self._perform_login(user)
        return redirect(url_for('index.render_feed'))
    def validate(self, user):
        userdn = self.app.config['LDAP_USERDN_SCHEMA'].format(user_id=user.identifier)
        password = request.form['password']
        conn = Connection(self.server, user=userdn, password=password)
        return conn.bind()
    def get_user(self):
        return User(identifier=request.form['username'])
 | 
| 
	Fix a bug of undefinded variable | 
	<?php
namespace Vinala\Kernel\Process;
use Vinala\Kernel\Filesystem\File;
/**
 * Model class.
 */
class Model extends Process
{
    public static function create($class, $table, $rt = null)
    {
        $class = ucfirst($class);
        $file = $class;
        $root = is_null($rt) ? Process::root : $rt;
        $path = $root."resources/models/$file.php";
        if (!File::exists($path)) {
            File::put($path, self::set($class, $table));
            //
            return true;
        }
        return false;
    }
    public static function set($class, $table)
    {
        $txt = "<?php\n\nnamespace App\Model;\n\nuse Vinala\Kernel\MVC\ORM;\n\n";
        $txt .= self::docs("$class Model");
        $txt .= "class $class extends ORM\n{";
        $txt .= "\n\n\t/**\n\t* The name of the DataTable\n\t*\n\t* @param string\n\t*/";
        $txt .= "\n\tpublic ".'$_table'." = '$table';\n\n}";
        //
        return $txt;
    }
    /**
     *   Listing all schemas.
     */
    public static function ListAll()
    {
        $models = glob(root().'resources/models/*.php');
        //
        return $models;
    }
}
 | 
	<?php
namespace Vinala\Kernel\Process;
use Vinala\Kernel\Filesystem\File;
/**
 * Model class.
 */
class Model extends Process
{
    public static function create($class, $table, $rt = null)
    {
        $class = ucfirst($class);
        $file = $class;
        $root = is_null($rt) ? Process::root : $rt;
        $path = $root."resources/models/$file.php";
        if (!File::exists($path)) {
            File::put($path, self::set($class, $table));
            //
            return true;
        }
        return false;
    }
    public static function set($class, $table)
    {
        $txt = "<?php\n\nnamespace App\Model;\n\nuse Vinala\Kernel\MVC\ORM;\n\n";
        $txt .= self::docs("$name Model");
        $txt .= "class $class extends ORM\n{";
        $txt .= "\n\n\t/**\n\t* The name of the DataTable\n\t*\n\t* @param string\n\t*/";
        $txt .= "\n\tpublic ".'$_table'." = '$table';\n\n}";
        //
        return $txt;
    }
    /**
     *   Listing all schemas.
     */
    public static function ListAll()
    {
        $models = glob(root().'resources/models/*.php');
        //
        return $models;
    }
}
 | 
| 
	FIX Late static binding in config property for max age | 
	<?php
/**
 * Abstract controller for actions that provide an API endpoint.
 */
abstract class ApiController extends Controller
{
    /**
     * Given a result payload, format as a JSON response and return
     *
     * @param array $data
     * @return SS_HTTPResponse
     */
    protected function formatResponse(array $data)
    {
        $response = new SS_HTTPResponse();
        $response
            ->addHeader('Content-Type', 'application/json')
            ->setBody(Convert::raw2json($data, JSON_PRETTY_PRINT));
        // Don't cache anything in dev mode
        if (Director::get_environment_type() !== 'dev') {
            // Only cache failure messages for one minute, otherwise use the configured cache age
            $cacheAge = empty($data['success']) ? 60 : Config::inst()->get(static::class, 'cache_age');
            $response->addHeader('Cache-Control', 'max-age=' . $cacheAge);
        }
        return $response;
    }
    /**
     * Overrides this method only to prepend capturing any provided framework version header
     *
     * @inheritDoc
     */
    protected function handleAction($request, $action)
    {
        $frameworkVersionHeader = $request->getHeader('Silverstripe-Framework-Version');
        if ($frameworkVersionHeader) {
            ApiCallerVersions::create([
                'Endpoint' => $request->getURL(),
                'Version' => $frameworkVersionHeader,
            ])->write();
        }
        return parent::handleAction($request, $action);
    }
}
 | 
	<?php
/**
 * Abstract controller for actions that provide an API endpoint.
 */
abstract class ApiController extends Controller
{
    /**
     * Given a result payload, format as a JSON response and return
     *
     * @param array $data
     * @return SS_HTTPResponse
     */
    protected function formatResponse(array $data)
    {
        $response = new SS_HTTPResponse();
        $response
            ->addHeader('Content-Type', 'application/json')
            ->setBody(Convert::raw2json($data, JSON_PRETTY_PRINT));
        // Don't cache anything in dev mode
        if (Director::get_environment_type() !== 'dev') {
            // Only cache failure messages for one minute, otherwise use the configured cache age
            $cacheAge = empty($data['success']) ? 60 : Config::inst()->get(__CLASS__, 'cache_age');
            $response->addHeader('Cache-Control', 'max-age=' . $cacheAge);
        }
        return $response;
    }
    /**
     * Overrides this method only to prepend capturing any provided framework version header
     *
     * @inheritDoc
     */
    protected function handleAction($request, $action)
    {
        $frameworkVersionHeader = $request->getHeader('Silverstripe-Framework-Version');
        if ($frameworkVersionHeader) {
            ApiCallerVersions::create([
                'Endpoint' => $request->getURL(),
                'Version' => $frameworkVersionHeader,
            ])->write();
        }
        return parent::handleAction($request, $action);
    }
}
 | 
| 
	Add missing dependency on Pillow | 
	#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup
with open('README.rst') as readme_file:
    readme = readme_file.read()
requirements = [
    'pyzmq',
    'docopt',
    'virtualenv',
    'requests',
    'Pillow',
]
setup(
    name='tingbot',
    version='0.3',
    description="Python APIs to write apps for Tingbot",
    long_description=readme,
    author="Joe Rickerby",
    author_email='[email protected]',
    url='https://github.com/tingbot/tingbot-python',
    packages=[
        'tingbot',
        'tbtool'
    ],
    package_dir={'tingbot': 'tingbot',
                 'tbtool': 'tbtool'},
    include_package_data=True,
    install_requires=requirements,
    license="BSD",
    zip_safe=False,
    keywords='tingbot',
    classifiers=[
        'Intended Audience :: Developers',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
    ],
    entry_points={
        'console_scripts': [
            'tbtool = tbtool.__main__:main',
        ],
    },
    test_suite='tests',
    tests_require=['httpretty','mock'],
)
 | 
	#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup
with open('README.rst') as readme_file:
    readme = readme_file.read()
requirements = [
    'pyzmq',
    'docopt',
    'virtualenv',
    'requests'
]
setup(
    name='tingbot',
    version='0.3',
    description="Python APIs to write apps for Tingbot",
    long_description=readme,
    author="Joe Rickerby",
    author_email='[email protected]',
    url='https://github.com/tingbot/tingbot-python',
    packages=[
        'tingbot',
        'tbtool'
    ],
    package_dir={'tingbot': 'tingbot',
                 'tbtool': 'tbtool'},
    include_package_data=True,
    install_requires=requirements,
    license="BSD",
    zip_safe=False,
    keywords='tingbot',
    classifiers=[
        'Intended Audience :: Developers',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
    ],
    entry_points={
        'console_scripts': [
            'tbtool = tbtool.__main__:main',
        ],
    },
    test_suite='tests',
    tests_require=['httpretty','mock'],
)
 | 
| 
	Fix database backends analyzer: 'postgresql' backend has been deprecated in 1.2 | 
	import ast
from .base import BaseAnalyzer, Result
class DB_BackendsVisitor(ast.NodeVisitor):
    def __init__(self):
        self.found = []
    removed_items = {
        'django.db.backends.postgresql':
            'django.db.backends.postgresql_psycopg2',
    }
    def visit_Str(self, node):
        if node.s in self.removed_items.keys():
            self.found.append((node.s, node))
class DB_BackendsAnalyzer(BaseAnalyzer):
    def analyze_file(self, filepath, code):
        if not isinstance(code, ast.AST):
            return
        visitor = DB_BackendsVisitor()
        visitor.visit(code)
        for name, node in visitor.found:
            propose = visitor.removed_items[name]
            result = Result(
                description = (
                    '%r database backend has beed deprecated in Django 1.2 '
                    'and removed in 1.4. Use %r instead.' % (name, propose)
                ),
                path = filepath,
                line = node.lineno)
            lines = self.get_file_lines(filepath, node.lineno, node.lineno)
            for lineno, important, text in lines:
                result.source.add_line(lineno, text, important)
                result.solution.add_line(lineno, text.replace(name, propose), important)
            yield result
 | 
	import ast
from .base import BaseAnalyzer, Result
class DB_BackendsVisitor(ast.NodeVisitor):
    def __init__(self):
        self.found = []
    removed_items = {
        'django.db.backends.postgresql':
            'django.db.backends.postgresql_psycopg2',
    }
    def visit_Str(self, node):
        if node.s in self.removed_items.keys():
            self.found.append((node.s, node))
class DB_BackendsAnalyzer(BaseAnalyzer):
    def analyze_file(self, filepath, code):
        if not isinstance(code, ast.AST):
            return
        visitor = DB_BackendsVisitor()
        visitor.visit(code)
        for name, node in visitor.found:
            propose = visitor.removed_items[name]
            result = Result(
                description = (
                    '%r database backend has beed deprecated in Django 1.3 '
                    'and removed in 1.4. Use %r instead.' % (name, propose)
                ),
                path = filepath,
                line = node.lineno)
            lines = self.get_file_lines(filepath, node.lineno, node.lineno)
            for lineno, important, text in lines:
                result.source.add_line(lineno, text, important)
                result.solution.add_line(lineno, text.replace(name, propose), important)
            yield result
 | 
| 
	Add unit test to determine if the classes ExamineExe and ExamineSnap will work properly.
Fixed a bug `assert len(record) == 1` in 'test_not_exception' method in class `TestExamineExe`. | 
	from contextlib import contextmanager
import pytest
from pyroSAR._dev_config import ExamineExe
from pyroSAR.snap.auxil import ExamineSnap
@contextmanager
def not_raises(ExpectedException):
    try:
        yield
    except ExpectedException:
        raise AssertionError(
            "Did raise exception {0} when it should not!".format(
                repr(ExpectedException)
            )
        )
    except Exception:
        raise AssertionError(
            "An unexpected exception {0} raised.".format(repr(Exception))
        )
class TestExemineExe:
    def test_exception(self):
        with pytest.warns(UserWarning):
            ExamineExe.examine('some_exe_file.exe')
    def test_not_exception(self):
        SNAP_EXECUTABLE = ['snap64.exe', 'snap32.exe', 'snap.exe', 'snap']
        with pytest.warns(None) as record:
            ExamineExe.examine(SNAP_EXECUTABLE)
        assert len(record) == 0
class TestExamineSnap:
    def test_exception(self):
        with pytest.warns(UserWarning):
            ExamineSnap(snap_executable='some_exe_file.exe')
    def test_not_exception(self):
        with pytest.warns(None) as record:
            ExamineSnap()
        assert len(record) == 0
 | 
	import pytest
from contextlib import contextmanager
from pyroSAR._dev_config import ExamineExe
from pyroSAR.snap.auxil import ExamineSnap
@contextmanager
def not_raises(ExpectedException):
    try:
        yield
    except ExpectedException:
        raise AssertionError(
            "Did raise exception {0} when it should not!".format(
                repr(ExpectedException)
            )
        )
    except Exception:
        raise AssertionError(
            "An unexpected exception {0} raised.".format(repr(Exception))
        )
class TestExemineExe:
    def test_exception(self):
        with pytest.warns(UserWarning):
            ExamineExe.examine('some_exe_file.exe')
    def test_warn_snap(self):
        with pytest.warns(UserWarning):
            ExamineExe.examine('snap')
    # def test_not_exception(self):
    #     SNAP_EXECUTABLE = ['snap64.exe', 'snap32.exe', 'snap.exe', 'snap']
    #     with not_raises(ValueError):
    #         ExamineExe.examine(SNAP_EXECUTABLE)
class TestExamineSnap:
    def test_exception(self):
        with pytest.warns(UserWarning):
            ExamineExe.examine('some_exe_file.exe')
    # def test_not_exception(self):
    #     with not_raises(AssertionError):
    #         test_snap_exe = ExamineSnap() | 
| 
	Add tracking category when uploading with a Campaign
Change-Id: I0790fc499c0b4960590f03222a1738cc72d7b173 | 
	package org.wikimedia.commons.campaigns;
import android.net.Uri;
import org.wikimedia.commons.contributions.Contribution;
import java.util.ArrayList;
import java.util.Date;
public class CampaignContribution extends Contribution {
    private Campaign campaign;
    private ArrayList<String> fieldValues;
    public CampaignContribution(Uri localUri, String remoteUri, String filename, String description, long dataLength, Date dateCreated, Date dateUploaded, String creator, String editSummary, Campaign campaign) {
        super(localUri, remoteUri, filename, description, dataLength, dateCreated, dateUploaded, creator, editSummary);
        this.campaign = campaign;
    }
    public Campaign getCampaign() {
        return campaign;
    }
    public void setCampaign(Campaign campaign) {
        this.campaign = campaign;
    }
    @Override
    public String getTrackingTemplates() {
        StringBuffer buffer = new StringBuffer();
        if(campaign.getAutoAddWikitext() != null) {
            buffer.append(campaign.getAutoAddWikitext()).append("\n");
        }
        if(campaign.getAutoAddCategories() != null && campaign.getAutoAddCategories().size() != 0) {
            for(String cat : campaign.getAutoAddCategories()) {
                buffer.append("[[Category:").append(cat).append("]]").append("\n");
            }
        } else {
            buffer.append("{{subst:unc}}\n");
        }
        buffer.append("[[Category:").append(campaign.getTrackingCategory()).append("\n");
        return buffer.toString();
    }
    @Override
    public String getDescription() {
        return super.getDescription();
    }
}
 | 
	package org.wikimedia.commons.campaigns;
import android.net.Uri;
import org.wikimedia.commons.contributions.Contribution;
import java.util.ArrayList;
import java.util.Date;
public class CampaignContribution extends Contribution {
    private Campaign campaign;
    private ArrayList<String> fieldValues;
    public CampaignContribution(Uri localUri, String remoteUri, String filename, String description, long dataLength, Date dateCreated, Date dateUploaded, String creator, String editSummary, Campaign campaign) {
        super(localUri, remoteUri, filename, description, dataLength, dateCreated, dateUploaded, creator, editSummary);
        this.campaign = campaign;
    }
    public Campaign getCampaign() {
        return campaign;
    }
    public void setCampaign(Campaign campaign) {
        this.campaign = campaign;
    }
    @Override
    public String getTrackingTemplates() {
        StringBuffer buffer = new StringBuffer();
        if(campaign.getAutoAddWikitext() != null) {
            buffer.append(campaign.getAutoAddWikitext()).append("\n");
        }
        if(campaign.getAutoAddCategories() != null && campaign.getAutoAddCategories().size() != 0) {
            for(String cat : campaign.getAutoAddCategories()) {
                buffer.append("[[Category:").append(cat).append("]]").append("\n");
            }
        } else {
            buffer.append("{{subst:unc}}\n");
        }
        return buffer.toString();
    }
    @Override
    public String getDescription() {
        return super.getDescription();
    }
}
 | 
| 
	[Admin] Improve the shipment ship form | 
	(function($) {
  $.fn.extend({
    requireConfirmation: function() {
      return this.each(function() {
        return $(this).on('click', function(event) {
          event.preventDefault();
          var actionButton = $(this);
          if (actionButton.is('a')) {
            $('#confirmation-button').attr('href', actionButton.attr('href'));
          }
          if (actionButton.is('button')) {
            $('#confirmation-button').on('click', function(event) {
              event.preventDefault();
              return actionButton.closest('form').submit();
            });
          }
          return $('#confirmation-modal').modal('show');
        });
      });
    }
  });
  $(document).ready(function() {
    $('#sidebar')
        .first()
        .sidebar('attach events', '#sidebar-toggle', 'show')
    ;
    $('.ui.checkbox').checkbox();
    $('.ui.accordion').accordion();
    $('.link.ui.dropdown').dropdown({action: 'hide'});
    $('.button.ui.dropdown').dropdown({action: 'hide'});
    $('.menu .item').tab();
    $('.form button').on('click', function() {
      return $(this).closest('form').addClass('loading');
    });
    $('.message .close').on('click', function() {
      return $(this).closest('.message').transition('fade');
    });
    $('.loadable.button').on('click', function() {
      return $(this).addClass('loading');
    });
    $('.popups').popup();
    $('[data-requires-confirmation]').requireConfirmation();
    $('.special.cards .image').dimmer({
      on: 'hover'
    });
  });
})(jQuery);
 | 
	(function($) {
  $.fn.extend({
    requireConfirmation: function() {
      return this.each(function() {
        return $(this).on('click', function(event) {
          event.preventDefault();
          var actionButton = $(this);
          if (actionButton.is('a')) {
            $('#confirmation-button').attr('href', actionButton.attr('href'));
          }
          if (actionButton.is('button')) {
            $('#confirmation-button').on('click', function(event) {
              event.preventDefault();
              return actionButton.closest('form').submit();
            });
          }
          return $('#confirmation-modal').modal('show');
        });
      });
    }
  });
  $(document).ready(function() {
    $('#sidebar')
        .first()
        .sidebar('attach events', '#sidebar-toggle', 'show')
    ;
    $('.ui.checkbox').checkbox();
    $('.ui.accordion').accordion();
    $('.link.ui.dropdown').dropdown({action: 'hide'});
    $('.button.ui.dropdown').dropdown({action: 'hide'});
    $('.menu .item').tab();
    $('.form button').on('click', function() {
      return $(this).closest('form').addClass('loading');
    });
    $('.message .close').on('click', function() {
      return $(this).closest('.message').transition('fade');
    });
    $('.loadable.button').on('click', function() {
      return $(this).addClass('loading');
    });
    $('[data-requires-confirmation]').requireConfirmation();
    $('.special.cards .image').dimmer({
      on: 'hover'
    });
  });
})(jQuery);
 | 
| 
	Resolve session from container, not from request. | 
	<?php
namespace FluxBB\Auth;
use FluxBB\Core;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Auth\Guard;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('Illuminate\Contracts\Auth\Guard', function () {
            $hasher = $this->app->make('Illuminate\Contracts\Hashing\Hasher');
            $session = $this->app->make('Symfony\Component\HttpFoundation\Session\SessionInterface');
            $provider = new EloquentUserProvider($hasher, 'FluxBB\Models\User');
            $guard = new Guard($provider, $session);
            $guard->setCookieJar($this->app->make('Illuminate\Contracts\Cookie\QueueingFactory'));
            $guard->setDispatcher($this->app->make('Illuminate\Contracts\Events\Dispatcher'));
            $guard->setRequest($this->app->make('Symfony\Component\HttpFoundation\Request'));
            return $guard;
        });
        if (Core::isInstalled()) {
            $this->app->extend('view', function ($view) {
                $view->share('user', $this->app->make('Illuminate\Contracts\Auth\Guard')->user());
                return $view;
            });
        }
    }
}
 | 
	<?php
namespace FluxBB\Auth;
use FluxBB\Core;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Auth\Guard;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('Illuminate\Contracts\Auth\Guard', function () {
            $hasher = $this->app->make('Illuminate\Contracts\Hashing\Hasher');
            $session = $this->app->make('request')->getSession();
            $provider = new EloquentUserProvider($hasher, 'FluxBB\Models\User');
            $guard = new Guard($provider, $session);
            $guard->setCookieJar($this->app->make('Illuminate\Contracts\Cookie\QueueingFactory'));
            $guard->setDispatcher($this->app->make('Illuminate\Contracts\Events\Dispatcher'));
            $guard->setRequest($this->app->make('Symfony\Component\HttpFoundation\Request'));
            return $guard;
        });
        if (Core::isInstalled()) {
            $this->app->extend('view', function ($view) {
                $view->share('user', $this->app->make('Illuminate\Contracts\Auth\Guard')->user());
                return $view;
            });
        }
    }
}
 | 
| 
	Reduce scope of method (used in tests only). | 
	package no.deichman.services.utils;
import no.deichman.services.repository.Repository;
import no.deichman.services.uridefaults.BaseURI;
import org.apache.commons.lang3.RandomStringUtils;
public class UniqueURI {
    public static final int NO_OF_DIGITS = 12;
    private String getRandom() {
        return RandomStringUtils.randomNumeric(NO_OF_DIGITS);
    }
    private String getRandom(String type, BaseURI baseURI) {
        String random;
        switch (type) {
            case "work":        random = baseURI.getWorkURI() + "w" + getRandom();
                break;
            case "publication": random = baseURI.getPublicationURI() + "p" + getRandom();
                break;
            default:            random = null;
                break;
        }
        if (random == null) {
            throw new IllegalArgumentException("Unknown URI-type");
        }
        return random;
    }
    public String getNewURI(String type, Repository repository, BaseURI baseURI) {
        String random = null;
        boolean exists = true;
        while (exists) {
            random = getRandom(type, baseURI);
            exists = checkResourceExistence(random, repository);
        }
        return random;
    }
    boolean checkResourceExistence(String random, Repository repository) {
        return repository.askIfResourceExists(random);
    }
}
 | 
	package no.deichman.services.utils;
import no.deichman.services.repository.Repository;
import no.deichman.services.uridefaults.BaseURI;
import org.apache.commons.lang3.RandomStringUtils;
public class UniqueURI {
    public static final int NO_OF_DIGITS = 12;
    private String getRandom() {
        return RandomStringUtils.randomNumeric(NO_OF_DIGITS);
    }
    private String getRandom(String type, BaseURI baseURI) {
        String random;
        switch (type) {
            case "work":        random = baseURI.getWorkURI() + "w" + getRandom();
                break;
            case "publication": random = baseURI.getPublicationURI() + "p" + getRandom();
                break;
            default:            random = null;
                break;
        }
        if (random == null) {
            throw new IllegalArgumentException("Unknown URI-type");
        }
        return random;
    }
    public String getNewURI(String type, Repository repository, BaseURI baseURI) {
        String random = null;
        boolean exists = true;
        while (exists) {
            random = getRandom(type, baseURI);
            exists = checkResourceExistence(random, repository);
        }
        return random;
    }
    public boolean checkResourceExistence(String random, Repository repository) {
        return repository.askIfResourceExists(random);
    }
}
 | 
| 
	Test if `__distarray__()['buffer']` returns a buffer. | 
	import unittest
import distarray as da
from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError
class TestDistributedArrayProtocol(unittest.TestCase):
    def setUp(self):
        try:
            comm = create_comm_of_size(4)
        except InvalidCommSizeError:
            raise unittest.SkipTest('Must run with comm size > 4.')
        else:
            self.larr = da.LocalArray((16,16),
                                     grid_shape=(4,),
                                     comm=comm, buf=None, offset=0)
    def test_has_export(self):
        self.assertTrue(hasattr(self.larr, '__distarray__'))
    def test_export_keys(self):
        required_keys = set(("buffer", "dimdata"))
        export_data = self.larr.__distarray__()
        exported_keys = set(export_data.keys())
        self.assertEqual(required_keys, exported_keys)
    def test_export_buffer(self):
        """See if we actually export a buffer."""
        export_data = self.larr.__distarray__()
        memoryview(export_data['buffer'])
    def test_round_trip(self):
        new_larr = da.localarray(self.larr)
        self.assertEqual(new_larr.local_array, self.larr.local_array)
if __name__ == '__main__':
    try:
        unittest.main()
    except SystemExit:
        pass
 | 
	import unittest
import distarray as da
from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError
class TestDistributedArrayProtocol(unittest.TestCase):
    def setUp(self):
        try:
            comm = create_comm_of_size(4)
        except InvalidCommSizeError:
            raise unittest.SkipTest('Must run with comm size > 4.')
        else:
            self.larr = da.LocalArray((16,16),
                                     grid_shape=(4,),
                                     comm=comm, buf=None, offset=0)
    def test_has_export(self):
        self.assertTrue(hasattr(self.larr, '__distarray__'))
    def test_export_keys(self):
        required_keys = set(("buffer", "dimdata"))
        export_data = self.larr.__distarray__()
        exported_keys = set(export_data.keys())
        self.assertEqual(required_keys, exported_keys)
    def test_round_trip(self):
        new_larr = da.localarray(self.larr)
        self.assertEqual(new_larr.local_array, self.larr.local_array)
if __name__ == '__main__':
    try:
        unittest.main()
    except SystemExit:
        pass
 | 
| 
	Improve destroy method to actually catch calls / read of destroy objects properties / methods | 
	(function(exports) {
    // Dependencies -----------------------------------------------------------
    var Class = require('./Class').Class,
        is = require('./is').is;
    // Implementation ---------------------------------------------------------
    var Base = Class(function(id) {
        if (id !== undefined) {
            is.assert(is.Integer(id));
            this._id = id;
        } else {
            this._id = ++exports.Base.id;
        }
        this.log('Created');
    }, {
        $id: 0,
        destroy: function() {
            this.log('Destroyed');
            for(var i in this) {
                if (this.hasOwnProperty(i)) {
                    if (Object.defineProperty) {
                        Object.defineProperty(this, i, {
                            get: (function(i) {
                                return function() {
                                    throw new TypeError('Access to property "' + i + '" of destroyed class instance.');
                                };
                            })(i)
                        });
                    } else {
                        this[i] = null;
                    }
                } else if (is.Function(this[i])) {
                    this[i] = (function(i) {
                        return function() {
                            throw new TypeError('Call to method "' + i + '" of destroyed class instance.');
                        };
                    })(i);
                }
            }
        },
        // Setter / Getter ----------------------------------------------------
        getId: function() {
            return this._id;
        },
        // Helpers ------------------------------------------------------------
        log: function() {
            var params = [this];
            params.push.apply(params, arguments);
            is.log.apply(this, params);
        },
        toString: function() {
            return 'Base';
        }
    });
    exports.Base = Base;
})(typeof exports !== 'undefined' ? exports : this);
 | 
	(function(exports) {
    // Dependencies -----------------------------------------------------------
    var Class = require('./Class').Class,
        is = require('./is').is;
    // Implementation ---------------------------------------------------------
    var Base = Class(function(id) {
        if (id !== undefined) {
            is.assert(is.Integer(id));
            this._id = id;
        } else {
            this._id = ++exports.Base.id;
        }
        this.log('Created');
    }, {
        $id: 0,
        destroy: function() {
            this.log('Destroyed');
            for(var i in this) {
                // TODO overwrite all methods with a throw new Error('Destroyed') one
                if (this.hasOwnProperty(i)) {
                    this[i] = null;
                }
            }
        },
        // Setter / Getter ----------------------------------------------------
        getId: function() {
            return this._id;
        },
        // Helpers ------------------------------------------------------------
        log: function() {
            var params = [this];
            params.push.apply(params, arguments);
            is.log.apply(this, params);
        },
        toString: function() {
            return 'Base';
        }
    });
    exports.Base = Base;
})(typeof exports !== 'undefined' ? exports : this);
 | 
| 
	Use the docstring as the CLI description. | 
	#!/usr/bin/env python
# pylint: disable=import-error
"""A CLI tool for generating files from Jinja2 templates and environment
variables."""
from __future__ import (
    absolute_import,
    division,
    print_function,
    unicode_literals,
)  # pylint: disable=duplicate-code
from os import environ
from sys import stdin, stdout
import argparse
from argparse import ArgumentParser
from jinja2 import Environment
import template.filters
__version__ = "0.6.4"
def render(template_string):
    """Render the template."""
    env = Environment(autoescape=True)
    # Add all functions in template.filters as Jinja filters.
    # pylint: disable=invalid-name
    for tf in filter(lambda x: not x.startswith("_"), dir(template.filters)):
        env.filters[tf] = getattr(template.filters, tf)
    t = env.from_string(template_string)
    return t.render(environ)
def main():
    """Main entrypoint."""
    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        "filename",
        help="Input filename",
        type=argparse.FileType("r"),
        nargs="?",
    )
    parser.add_argument(
        "-o",
        "--output",
        help="Output to filename",
        type=argparse.FileType("w"),
    )
    args = parser.parse_args()
    infd = args.filename if args.filename else stdin
    outfd = args.output if args.output else stdout
    print(render(infd.read()), file=outfd)
if __name__ == "__main__":
    main()
 | 
	#!/usr/bin/env python
# pylint: disable=import-error
"""Generate files from Jinja2 templates and environment variables."""
from __future__ import (
    absolute_import,
    division,
    print_function,
    unicode_literals,
)  # pylint: disable=duplicate-code
from os import environ
from sys import stdin, stdout
import argparse
from argparse import ArgumentParser
from jinja2 import Environment
import template.filters
__version__ = "0.6.4"
def render(template_string):
    """Render the template."""
    env = Environment(autoescape=True)
    # Add all functions in template.filters as Jinja filters.
    # pylint: disable=invalid-name
    for tf in filter(lambda x: not x.startswith("_"), dir(template.filters)):
        env.filters[tf] = getattr(template.filters, tf)
    t = env.from_string(template_string)
    return t.render(environ)
def main():
    """Main entrypoint."""
    parser = ArgumentParser(
        description="""A CLI tool for generating files from Jinja2 templates
        and environment variables."""
    )
    parser.add_argument(
        "filename",
        help="Input filename",
        type=argparse.FileType("r"),
        nargs="?",
    )
    parser.add_argument(
        "-o",
        "--output",
        help="Output to filename",
        type=argparse.FileType("w"),
    )
    args = parser.parse_args()
    infd = args.filename if args.filename else stdin
    outfd = args.output if args.output else stdout
    print(render(infd.read()), file=outfd)
if __name__ == "__main__":
    main()
 | 
| 
	Update unit tests to work with compact hash format added in d192cc4 | 
	<?php
class HashPathExtensionTest extends PHPUnit_Framework_TestCase
{
    public function testHashFile()
    {
        $hashPath = new HashPathExtension();
        $this->assertEquals(
            'L32cPgz9Rj8qwwSRHsr8A',
            $hashPath->HashFile(
                __DIR__ . '/test.txt',
                false
            )
        );
        
        $this->assertEquals(
            '',
            $hashPath->HashFile(
                'fakefile',
                false
            )
        );
    }
    public function testHashPath()
    {
        $hashPath = new HashPathExtension();
        $this->assertEquals(
            '/tests/test.vL32cPgz9Rj8qwwSRHsr8A.txt',
            $hashPath->HashPath(
                '/tests/test.txt',
                false
            )
        );
        $hashPath->setFormat('%s/%s.v.%s.%s');
        $this->assertEquals(
            '/tests/test.v.L32cPgz9Rj8qwwSRHsr8A.txt',
            $hashPath->HashPath(
                '/tests/test.txt',
                false
            )
        );
    }
} | 
	<?php
class HashPathExtensionTest extends PHPUnit_Framework_TestCase
{
    public function testHashFile()
    {
        $hashPath = new HashPathExtension();
        $this->assertEquals(
            '2f7d9c3e0cfd47e8fcab0c12447b2bf0',
            $hashPath->HashFile(
                __DIR__ . '/test.txt',
                false
            )
        );
        
        $this->assertEquals(
            '',
            $hashPath->HashFile(
                'fakefile',
                false
            )
        );
    }
    public function testHashPath()
    {
        $hashPath = new HashPathExtension();
        $this->assertEquals(
            '/tests/test.v2f7d9c3e0cfd47e8fcab0c12447b2bf0.txt',
            $hashPath->HashPath(
                '/tests/test.txt',
                false
            )
        );
        $hashPath->setFormat('%s/%s.v.%s.%s');
        $this->assertEquals(
            '/tests/test.v.2f7d9c3e0cfd47e8fcab0c12447b2bf0.txt',
            $hashPath->HashPath(
                '/tests/test.txt',
                false
            )
        );
    }
} | 
| 
	Include luhn package update version 1.0.1 | 
	
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Luhn Algorithm Validator -- long description
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
    long_description = f.read()
setup(
    name='luhn_algorithm_validator',
    version='1.0.1',
    packages = ['luhn'],
    description='Luhn Account Number Validator',
    long_description=long_description,
    # Project homepage
    url='https://github.com/garwoodpr/LuhnAlgorithmProof',
    # Author details
    author='Clint Garwood',
    author_email='[email protected]',
    # License
    license='MIT',
    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 3 - Alpha',
        # Indicate who your project is intended for
        'Topic :: Text Processing :: General',
        'Topic :: Scientific/Engineering :: Information Analysis',
        'Topic :: Office/Business :: Financial',
        'Programming Language :: Python :: 3.4', 
        'Operating System :: OS Independent', 
        'Natural Language :: English', 
        'License :: OSI Approved :: MIT License',
        'Intended Audience :: Customer Service', 
    ],
    keywords=['Luhn Algorithm', 'account number validation', 'credit card validation', 'text analysis', 'information processing', 'data verification', cryptography, 'numerical decoding',
    ],
)
 | 
	
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Luhn Algorithm Validator -- long description
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
    long_description = f.read()
setup(
    name='luhn_algorithm_validator',
    version='1.0.0',
    description='Luhn Account Number Validator',
    long_description=long_description,
    # Project homepage
    url='https://github.com/garwoodpr/LuhnAlgorithmProof',
    # Author details
    author='Clint Garwood',
    author_email='[email protected]',
    # License
    license='MIT',
    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 3 - Alpha',
        # Indicate who your project is intended for
        'Topic :: Text Processing :: General',
        'Topic :: Scientific/Engineering :: Information Analysis',
        'Topic :: Office/Business :: Financial',
        'Programming Language :: Python :: 3.4', 
        'Operating System :: OS Independent', 
        'Natural Language :: English', 
        'License :: OSI Approved :: MIT License',
        'Intended Audience :: Customer Service', 
    ]
    keywords=['Luhn Algorithm', 'account number validation', 'credit card validation', 'text analysis', 'information processing', 'data verification', cryptography, 'numerical decoding',
    ]
)
 | 
| 
	Add paste and pymongo dependencies | 
	#!/usr/bin/python
from setuptools import setup, find_packages
EXTRAS_REQUIRES = dict(
    web=[
        'bottle>=0.11',
        'paste>=1.7.5.1',
    ],
    mongo=[
        'pymongo>=2.3',
    ],
    test=[
        'pytest>=2.2.4',
        'mock>=0.8.0',
        ],
    dev=[
        'ipython>=0.13',
        ],
    )
# Tests always depend on all other requirements, except dev
for k,v in EXTRAS_REQUIRES.iteritems():
    if k == 'test' or k == 'dev':
        continue
    EXTRAS_REQUIRES['test'] += v
setup(
    name='tle',
    version='0.0.1',
    description=('tle -- Glue code for TheLeanEntrepreneur between the '
                 'Gumroad and Kajabi APIs'
                 ),
    author='Andres Buritica',
    author_email='[email protected]',
    maintainer='Andres Buritica',
    maintainer_email='[email protected]',
    packages = find_packages(),
    test_suite='nose.collector',
    install_requires=[
        'setuptools',
        ],
    extras_require=EXTRAS_REQUIRES,
    entry_points={
        'console_scripts': [
            'tle = tle.cli.glue_api:main[web]',
            ],
        },
    )
 | 
	#!/usr/bin/python
from setuptools import setup, find_packages
EXTRAS_REQUIRES = dict(
    web=[
        'bottle>=0.11',
        ],
    test=[
        'pytest>=2.2.4',
        'mock>=0.8.0',
        ],
    dev=[
        'ipython>=0.13',
        ],
    )
# Tests always depend on all other requirements, except dev
for k,v in EXTRAS_REQUIRES.iteritems():
    if k == 'test' or k == 'dev':
        continue
    EXTRAS_REQUIRES['test'] += v
setup(
    name='tle',
    version='0.0.1',
    description=('tle -- Glue code for TheLeanEntrepreneur between the '
                 'Gumroad and Kajabi APIs'
                 ),
    author='Andres Buritica',
    author_email='[email protected]',
    maintainer='Andres Buritica',
    maintainer_email='[email protected]',
    packages = find_packages(),
    test_suite='nose.collector',
    install_requires=[
        'setuptools',
        ],
    extras_require=EXTRAS_REQUIRES,
    entry_points={
        'console_scripts': [
            'tle = tle.cli.glue_api:main[web]',
            ],
        },
    )
 | 
| 
	Fix up the 2FA login form | 
	@extends('layout.clean')
@section('content')
    <div class="login">
        <div class="col-xs-12 col-xs-offset-0 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4 text-center">
            <div class="welcome-logo">
                <img class="logo" height="50" src="{{ url('img/cachet-logo.svg') }}" alt="Cachet">
            </div>
            <form method="POST" action="/auth/2fa" accept-charset="UTF-8">
                <fieldset>
                    <legend>{{ trans('dashboard.login.two-factor') }}</legend>
                    @if(Session::has('error'))
                    <p class="text-danger">{{ Session::get('error') }}</p>
                    @endif
                    <div class="form-group">
                        <label class="sr-only">{{ trans('forms.login.2fauth') }}</label>
                        <input type="text" name="code" class="form-control" placeholder="{{ trans('forms.login.2fauth') }}" required>
                    </div>
                    <hr>
                    <div class="form-group">
                        <button type="submit" class="btn btn-lg btn-block btn-success">{{ trans('dashboard.login.login') }}</button>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>
@stop
 | 
	@extends('layout.clean')
@section('content')
    <div class="login">
        <div class="col-xs-12 col-xs-offset-0 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4 text-center">
            <div class="welcome-logo">
                <img class="logo" height="50" src="{{ url('img/cachet-logo.svg') }}" alt="Cachet">
            </div>
            {{ Form::open() }}
            <fieldset>
                <legend>{{ trans('dashboard.login.two-factor') }}</legend>
                @if(Session::has('error'))
                <p class="text-danger">{{ Session::get('error') }}</p>
                @endif
                <div class="form-group">
                    <label class="sr-only">{{ trans('forms.login.2fauth') }}</label>
                    {{ Form::text('code', null, [
                        'class' => 'form-control', 'placeholder' => trans('forms.login.2fauth'), 'required' => 'required'
                    ]) }}
                </div>
                <hr />
                <div class="form-group">
                    <button type="submit" class="btn btn-lg btn-block btn-success">{{ trans('dashboard.login.login') }}</button>
                </div>
            </fieldset>
            {{ Form::close() }}
        </div>
    </div>
@stop
 | 
| 
	Remove logging statment used for debugging. | 
	package foam.lib.json;
import foam.lib.parse.*;
public class FObjectParser extends ProxyParser {
  public FObjectParser() {
    super(new Seq1(7,
                   new Whitespace(),
                   new Literal("{"),
                   new Whitespace(),
                   new KeyParser("class"),
                   new Whitespace(),
                   new Literal(":"),
                   new Whitespace(),
                   new Parser() {
        private Parser delegate = new StringParser();
        public PStream parse(PStream ps, ParserContext x) {
          ps = delegate.parse(ps, x);
          if ( ps == null ) return null;
          Class c;
          try {
            c = Class.forName(ps.value().toString());
          } catch(ClassNotFoundException e) {
            throw new RuntimeException(e);
          }
          ParserContext subx = x.sub();
          try {
            subx.set("obj", c.newInstance());
          } catch(InstantiationException e) {
            throw new RuntimeException(e);
          } catch(IllegalAccessException e) {
            throw new RuntimeException(e);
          }
          ps = ModelParserFactory.getInstance(c).parse(ps, subx);
          if ( ps != null ) {
            return ps.setValue(subx.get("obj"));
          }
          return null;
        }
      },
                   new Whitespace(),
                   new Literal("}")));
  }
}
 | 
	package foam.lib.json;
import foam.lib.parse.*;
public class FObjectParser extends ProxyParser {
  public FObjectParser() {
    super(new Seq1(7,
                   new Whitespace(),
                   new Literal("{"),
                   new Whitespace(),
                   new KeyParser("class"),
                   new Whitespace(),
                   new Literal(":"),
                   new Whitespace(),
                   new Parser() {
        private Parser delegate = new StringParser();
        public PStream parse(PStream ps, ParserContext x) {
          ps = delegate.parse(ps, x);
          if ( ps == null ) return null;
          Class c;
          try {
            c = Class.forName(ps.value().toString());
          } catch(ClassNotFoundException e) {
            throw new RuntimeException(e);
          }
          ParserContext subx = x.sub();
          try {
            subx.set("obj", c.newInstance());
          } catch(InstantiationException e) {
            throw new RuntimeException(e);
          } catch(IllegalAccessException e) {
            throw new RuntimeException(e);
          }
          System.out.println("Parsing: " + c.getName());
          ps = ModelParserFactory.getInstance(c).parse(ps, subx);
          if ( ps != null ) {
            return ps.setValue(subx.get("obj"));
          }
          return null;
        }
      },
                   new Whitespace(),
                   new Literal("}")));
  }
}
 | 
| 
	Use js `equal value and equal type` when comparing meetingId | 
	// @flow
import { Meeting } from '../actions/ActionTypes';
import { createSelector } from 'reselect';
import createEntityReducer from 'app/utils/createEntityReducer';
export default createEntityReducer({
  key: 'meetings',
  types: {
    fetch: Meeting.FETCH,
    mutate: Meeting.CREATE
  },
  mutate(state, action) {
    switch (action.type) {
      case Meeting.DELETE.SUCCESS:
        return {
          ...state,
          items: state.items.filter(id => action.meta.meetingId !== id)
        };
      case Meeting.SET_INVITATION_STATUS.SUCCESS: {
        const { meetingId, status, user } = action.meta;
        return {
          ...state,
          byId: {
            ...state.byId,
            [meetingId]: {
              ...state.byId[meetingId],
              invitations: state.byId[meetingId].invitations.map(invitation => {
                if (invitation.user.id === user) {
                  invitation.status = status;
                }
                return invitation;
              })
            }
          }
        };
      }
      default:
        return state;
    }
  }
});
export const selectMeetings = createSelector(
  state => state.meetings.byId,
  state => state.meetings.items,
  (meetingsById, meetingIds) => meetingIds.map(id => meetingsById[id])
);
export const selectMeetingById = createSelector(
  state => state.meetings.byId,
  (state, props) => props.meetingId,
  (meetingsById, meetingId) => meetingsById[meetingId]
);
 | 
	// @flow
import { Meeting } from '../actions/ActionTypes';
import { createSelector } from 'reselect';
import createEntityReducer from 'app/utils/createEntityReducer';
export default createEntityReducer({
  key: 'meetings',
  types: {
    fetch: Meeting.FETCH,
    mutate: Meeting.CREATE
  },
  mutate(state, action) {
    switch (action.type) {
      case Meeting.DELETE.SUCCESS:
        return {
          ...state,
          items: state.items.filter(id => action.meta.meetingId != id)
        };
      case Meeting.SET_INVITATION_STATUS.SUCCESS: {
        const { meetingId, status, user } = action.meta;
        return {
          ...state,
          byId: {
            ...state.byId,
            [meetingId]: {
              ...state.byId[meetingId],
              invitations: state.byId[meetingId].invitations.map(invitation => {
                if (invitation.user.id === user) {
                  invitation.status = status;
                }
                return invitation;
              })
            }
          }
        };
      }
      default:
        return state;
    }
  }
});
export const selectMeetings = createSelector(
  state => state.meetings.byId,
  state => state.meetings.items,
  (meetingsById, meetingIds) => meetingIds.map(id => meetingsById[id])
);
export const selectMeetingById = createSelector(
  state => state.meetings.byId,
  (state, props) => props.meetingId,
  (meetingsById, meetingId) => meetingsById[meetingId]
);
 | 
| 
	jf-vscroll: Use one time watch, instead of timeout to init element height init | 
	export function jfVScrollElement($compile) {
    return {
        restrict: 'E',
        scope: {
            data: '=',
            template: '=',
            variable: '=',
            index: '=',
            vscroll: '='
        },
        template: '<div class="compile-placeholder"></div>',
        controller: jfVScrollElementController,
        controllerAs: 'jfVScrollElement',
        bindToController: true,
        link: function(scope, element, attrs, directiveCtrl) {
            let elementScope = scope.$parent.$parent.$parent.$new();
            let target = $(element).find('.compile-placeholder');
            elementScope[directiveCtrl.variable] = directiveCtrl.data;
            elementScope['$index'] = directiveCtrl.index;
            directiveCtrl.elementScope = elementScope;
            let compiled = $compile($(`<div>${directiveCtrl.template}</div>`))(elementScope);
            target.replaceWith(compiled);
        }
    }
}
class jfVScrollElementController {
    constructor($scope, $element, $timeout) {
        this.$element = $element;
        let unwatchHeight = $scope.$watch('jfVScrollElement.childrenHeight', () => {
            if (this.childrenHeight) {
                this.vscroll.setItemHeight(this.childrenHeight);
                unwatchHeight();
            }
        })
        $scope.$watch('jfVScrollElement.data', () => {
            this.elementScope[this.variable] = this.data;
        })
    }
    get childrenHeight() {
        return $(this.$element).children().height();
    }
}
 | 
	export function jfVScrollElement($compile) {
    return {
        restrict: 'E',
        scope: {
            data: '=',
            template: '=',
            variable: '=',
            index: '=',
            vscroll: '='
        },
        template: '<div class="compile-placeholder"></div>',
        controller: jfVScrollElementController,
        controllerAs: 'jfVScrollElement',
        bindToController: true,
        link: function(scope, element, attrs, directiveCtrl) {
            let elementScope = scope.$parent.$parent.$parent.$new();
            let target = $(element).find('.compile-placeholder');
            elementScope[directiveCtrl.variable] = directiveCtrl.data;
            elementScope['$index'] = directiveCtrl.index;
            directiveCtrl.elementScope = elementScope;
            let compiled = $compile($(`<div>${directiveCtrl.template}</div>`))(elementScope);
            target.replaceWith(compiled);
        }
    }
}
class jfVScrollElementController {
    constructor($scope, $element, $timeout) {
        $timeout(() => {
            let height = $($element).children().height();
            if (height) this.vscroll.setItemHeight(height);
        });
        $scope.$watch('jfVScrollElement.data', () => {
            this.elementScope[this.variable] = this.data;
        })
    }
}
 | 
| 
	Use protocol-agnostic URL for webapp
issue: #1 | 
	(function() {
  "use strict";
  var xkcdUrl = "http://xkcd.com";
  var appUrl = "//xkcd-imgs.herokuapp.com/";
  var btns = document.getElementsByClassName("xkcd-refresh");
  var divs = document.getElementsByClassName("xkcd-img");
  var imgUrl;
  var imgTitle;
  function xkcdGet() {
    /**
    * Retrieving a URL to a random image
    */
    var req = new XMLHttpRequest();
    req.onload = function() {
      var res = JSON.parse(this.responseText);
      imgUrl = res.url;
      imgTitle = res.title;
      /**
      * Adding image to DOM
      */
      var link = document.createElement("a");
      var img = document.createElement("img");
      link.title = imgTitle;
      link.href = xkcdUrl;
      img.src = imgUrl;
      img.alt = "comic comes here";
      link.appendChild(img);
      var div;
      for (var index = 0; index < divs.length; index++) {
        div = divs[index];
        if (div.hasChildNodes()) {
          div.removeChild(div.childNodes[0]);
        }
        div.appendChild(link);
      }
    };
    req.open("get", appUrl, true);
    req.send();
  }
  xkcdGet();
  /**
  * Adding click function for refreshing
  */
  for (var index = 0; index < btns.length; index++) {
    btns[index].addEventListener("click", xkcdGet);
  }
})();
 | 
	(function() {
  "use strict";
  var xkcdUrl = "http://xkcd.com";
  var appUrl = "http://xkcd-imgs.herokuapp.com/";
  var btns = document.getElementsByClassName("xkcd-refresh");
  var divs = document.getElementsByClassName("xkcd-img");
  var imgUrl;
  var imgTitle;
  function xkcdGet() {
    /**
    * Retrieving a URL to a random image
    */
    var req = new XMLHttpRequest();
    req.onload = function() {
      var res = JSON.parse(this.responseText);
      imgUrl = res.url;
      imgTitle = res.title;
      /**
      * Adding image to DOM
      */
      var link = document.createElement("a");
      var img = document.createElement("img");
      link.title = imgTitle;
      link.href = xkcdUrl;
      img.src = imgUrl;
      img.alt = "comic comes here";
      link.appendChild(img);
      var div;
      for (var index = 0; index < divs.length; index++) {
        div = divs[index];
        if (div.hasChildNodes()) {
          div.removeChild(div.childNodes[0]);
        }
        div.appendChild(link);
      }
    };
    req.open("get", appUrl, true);
    req.send();
  }
  xkcdGet();
  /**
  * Adding click function for refreshing
  */
  for (var index = 0; index < btns.length; index++) {
    btns[index].addEventListener("click", xkcdGet);
  }
})();
 | 
| 
	Load tld files completely async | 
	'use babel';
import fs from 'fs';
import readInTld from '../readInTld';
import {add as addToRegistry} from '../registry';
export function register() {
    const userHome = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
    const tldSources = atom.config.get('autocomplete-jsp.tldSources');
    // TODO: refresh on config change
    Promise.all(tldSources
            .map(path => path = path.replace('~', userHome))
            .map(path => new Promise((resolve, reject) =>
                fs.readdir(path, (err, fileNames) => {
                    if (err) {
                        return reject(err);
                    }
                    resolve(fileNames
                        .filter(name => name.endsWith('.tld'))
                        .map(name => `${path.replace(/\/$/, '')}/${name}`)
                    );
                })
            ))
        )
        // TODO: reload on change
        .then(result => Promise.all(result
                .reduce((all, next) => all.concat(next), [])
                .map(readInTld)
            )
        )
        .then(tldDescs => tldDescs
            .forEach(tldDesc => {
                tldDesc.functions.forEach(fnDesc =>
                    addToRegistry({
                        element: fnDesc,
                        liveTime: Infinity,
                    })
                );
                tldDesc.tags.forEach(tagDesc =>
                    addToRegistry({
                        element: tagDesc,
                        liveTime: Infinity,
                    })
                );
            })
        )
        .catch(err =>
            atom.notifications.addWarning(err.msg, {
                dismissable: true,
                detail: `Caused by:\n${err.causedBy}`,
            })
        );
}
 | 
	'use babel';
import fs from 'fs';
import readInTld from '../readInTld';
import {add as addToRegistry} from '../registry';
export function register() {
    const userHome = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
    let tldPathes = [];
    // TODO: refresh on config change
    atom.config.get('autocomplete-jsp.tldSources').forEach(dir => {
            dir = dir.replace('~', userHome);
            fs.readdirSync(dir)
                .filter(fileName => fileName.endsWith('.tld'))
                .forEach(fileName => {
                    const path = `${dir.replace(/\/$/, '')}/${fileName}`;
                    tldPathes.push(path);
                });
        });
    // TODO: when a tld changes, we have to some how reload it..
    Promise.all(tldPathes.map(readInTld))
        .then(tldDescs => {
            tldDescs.forEach(tldDesc => {
                tldDesc.functions.forEach(fnDesc => {
                    addToRegistry({
                        element: fnDesc,
                        // TODO: not Infinity
                        liveTime: Infinity,
                    });
                });
                tldDesc.tags.forEach(tagDesc => {
                    addToRegistry({
                        element: tagDesc,
                        // TODO: not Infinity
                        liveTime: Infinity,
                    });
                });
            });
        })
        .catch(err => {
            atom.notifications.addWarning(err.msg, {
                dismissable: true,
                detail: `Caused by:\n${err.causedBy}`,
            });
        });
}
 | 
| 
	Add parameter to allow for output xml flag | 
	package org.eobjects.build;
import java.io.File;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public abstract class AbstractDotnetTestMojo extends AbstractDotnetMojo {
	@Parameter(property = "dotnet.test.outputxml", required = false, defaultValue = "TestResults.xml")
    private String outputXml;
    private final ObjectMapper objectMapper = new ObjectMapper();
    public void executeInternal() throws MojoFailureException {
        final PluginHelper helper = getPluginHelper();
        for (File subDirectory : helper.getProjectDirectories()) {
            if (isTestRunnable(subDirectory)) {
                helper.executeCommand(subDirectory, "dotnet", "test", "-c", helper.getBuildConfiguration(), "-xml", outputXml);
            }
        }
    }
    private boolean isTestRunnable(File subDirectory) {
        // check if there is a 'testRunner' attribute defined in project.json
        final File projectJsonFile = new File(subDirectory, "project.json");
        final ObjectNode root;
        try {
            root = (ObjectNode) objectMapper.readTree(projectJsonFile);
        } catch (Exception e) {
            getLog().warn("Failed to parse '" + projectJsonFile
                    + "' in order to determine if a 'testRunner' attribute is set.");
            return false;
        }
        final JsonNode testRunnerNode = root.get("testRunner");
        return testRunnerNode != null && !testRunnerNode.isMissingNode();
    }
}
 | 
	package org.eobjects.build;
import java.io.File;
import org.apache.maven.plugin.MojoFailureException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public abstract class AbstractDotnetTestMojo extends AbstractDotnetMojo {
    private final ObjectMapper objectMapper = new ObjectMapper();
    public void executeInternal() throws MojoFailureException {
        final PluginHelper helper = getPluginHelper();
        for (File subDirectory : helper.getProjectDirectories()) {
            if (isTestRunnable(subDirectory)) {
                helper.executeCommand(subDirectory, "dotnet", "test", "-c", helper.getBuildConfiguration());
            }
        }
    }
    private boolean isTestRunnable(File subDirectory) {
        // check if there is a 'testRunner' attribute defined in project.json
        final File projectJsonFile = new File(subDirectory, "project.json");
        final ObjectNode root;
        try {
            root = (ObjectNode) objectMapper.readTree(projectJsonFile);
        } catch (Exception e) {
            getLog().warn("Failed to parse '" + projectJsonFile
                    + "' in order to determine if a 'testRunner' attribute is set.");
            return false;
        }
        final JsonNode testRunnerNode = root.get("testRunner");
        return testRunnerNode != null && !testRunnerNode.isMissingNode();
    }
}
 | 
| 
	Change type check in encode to ctype_digit() for greater compatibility | 
	<?php
namespace Bijective;
/**
 * @author Brian Freytag <[email protected]>
 */
class BijectiveTranslator implements BijectiveInterface
{
    /** @var string */
    private $alphabet;
    /**
     * @param $alphabet
     */
    public function __construct($alphabet)
    {
        $this->alphabet = $alphabet;
    }
    /**
     * Encodes any integer into an encoded string
     *
     * @param integer $int
     *
     * @throws \InvalidArgumentException
     * @return string
     */
    public function encode($int)
    {
        if (!ctype_digit($int)) {
            throw new \InvalidArgumentException('You can only encode a number');
        }
        if ($int == 0) {
            return $this->alphabet[0];
        }
        $string = '';
        $base = strlen($this->alphabet);
        while ($int > 0) {
            $string .= $this->alphabet[($int % $base)];
            $int = floor($int / $base);
        }
        return strrev($string);
    }
    /**
     * Decodes any string into an interval value
     *
     * @param $str
     *
     * @throws \InvalidArgumentException
     * @return int
     */
    public function decode($str)
    {
        if (!is_string($str)) {
            throw new \InvalidArgumentException('You can only decode a string');
        }
        $int = 0;
        $base = strlen($this->alphabet);
        for ($i=0; $i < strlen($str); $i++) {
            $pos = strpos($this->alphabet, $str[$i]);
            $int = $int * $base + $pos;
        }
        return $int;
    }
}
 | 
	<?php
namespace Bijective;
/**
 * @author Brian Freytag <[email protected]>
 */
class BijectiveTranslator implements BijectiveInterface
{
    /** @var string */
    private $alphabet;
    /**
     * @param $alphabet
     */
    public function __construct($alphabet)
    {
        $this->alphabet = $alphabet;
    }
    /**
     * Encodes any integer into an encoded string
     *
     * @param integer $int
     *
     * @throws \InvalidArgumentException
     * @return string
     */
    public function encode($int)
    {
        if (!is_int($int)) {
            throw new \InvalidArgumentException('You can only encode an integer');
        }
        if ($int == 0) {
            return $this->alphabet[0];
        }
        $string = '';
        $base = strlen($this->alphabet);
        while ($int > 0) {
            $string .= $this->alphabet[($int % $base)];
            $int = floor($int / $base);
        }
        return strrev($string);
    }
    /**
     * Decodes any string into an interval value
     *
     * @param $str
     *
     * @throws \InvalidArgumentException
     * @return int
     */
    public function decode($str)
    {
        if (!is_string($str)) {
            throw new \InvalidArgumentException('You can only decode a string');
        }
        $int = 0;
        $base = strlen($this->alphabet);
        for ($i=0; $i < strlen($str); $i++) {
            $pos = strpos($this->alphabet, $str[$i]);
            $int = $int * $base + $pos;
        }
        return $int;
    }
}
 | 
| 
	Increase code coverage on FrequencyTransformer | 
	<?php
namespace Recurrence\tests\units\RruleTransformer;
require_once __DIR__.'/../../../../src/Recurrence/RruleTransformer/FreqTransformer.php';
use atoum;
/**
 * Class FreqTransformer
 * @package Recurrence\tests\units\RruleTransformer
 */
class FreqTransformer extends atoum
{
    /**
     * Failed : Missing frequency value
     */
    public function testMissingValue()
    {
        $this->assert
            ->exception(function () {
                (new \Recurrence\RruleTransformer\FreqTransformer())->transform('DTSTART=20170520;INTERVAL=1');
            })
            ->isInstanceOf('InvalidArgumentException')
        ;
    }
    /**
     * Failed : Use an invalid frequency value, but pattern match on first check
     */
    public function testInvalidValue()
    {
        $this->assert
            ->exception(function () {
                (new \Recurrence\RruleTransformer\FreqTransformer())->transform('FREQ=INVALID;DTSTART=20170520;INTERVAL=1');
            })
            ->isInstanceOf('InvalidArgumentException')
        ;
    }
    /**
     * Failed : Use an invalid frequency value, but patter do not match at all
     */
    public function testReallyInvalidValue()
    {
        $this->assert
            ->exception(function () {
                (new \Recurrence\RruleTransformer\FreqTransformer())->transform('FREQ=666;DTSTART=20170520;INTERVAL=1');
            })
            ->isInstanceOf('InvalidArgumentException')
        ;
    }
    /**
     * Success : Use an valid frequency value
     */
    public function testValidValue()
    {
        $frequency = (new \Recurrence\RruleTransformer\FreqTransformer())->transform('FREQ=MONTHLY;DTSTART=20170520;INTERVAL=1');
        $this->assert
            ->string((string) $frequency)
            ->isEqualTo('MONTHLY')
        ;
    }
} | 
	<?php
namespace Recurrence\tests\units\RruleTransformer;
require_once __DIR__.'/../../../../src/Recurrence/RruleTransformer/FreqTransformer.php';
use atoum;
/**
 * Class FreqTransformer
 * @package Recurrence\tests\units\RruleTransformer
 */
class FreqTransformer extends atoum
{
    /**
     * Failed : Missing frequency value
     */
    public function testMissingValue()
    {
        $this->assert
            ->exception(function () {
                (new \Recurrence\RruleTransformer\FreqTransformer())->transform('DTSTART=20170520;INTERVAL=1');
            })
            ->isInstanceOf('InvalidArgumentException')
        ;
    }
    /**
     * Failed : Use an invalid frequency value
     */
    public function testInvalidValue()
    {
        $this->assert
            ->exception(function () {
                (new \Recurrence\RruleTransformer\FreqTransformer())->transform('FREQ=INVALID;DTSTART=20170520;INTERVAL=1');
            })
            ->isInstanceOf('InvalidArgumentException')
        ;
    }
    /**
     * Success : Use an valid frequency value
     */
    public function testValidValue()
    {
        $frequency = (new \Recurrence\RruleTransformer\FreqTransformer())->transform('FREQ=MONTHLY;DTSTART=20170520;INTERVAL=1');
        $this->assert
            ->string((string) $frequency)
            ->isEqualTo('MONTHLY')
        ;
    }
} | 
| 
	Put new lines here and there | 
	const path = require('path');
const should = require('should');
const pluginsLoader = require('../../lib/plugins');
// Caching fixture plugin, but redefining its properties for testing plugin load.
const pluginName = 'express-gateway-plugin-test';
const pluginDirectory = path.join(__dirname, '../fixtures', pluginName);
const testPlugin = require(pluginDirectory);
testPlugin.schema = {
  '$id': `http://express-gateway.io/schemas/plugin/${pluginName}.json`,
  'required': ['schema-test-param']
};
testPlugin.init = (pluginContext) => {
  pluginContext.registerPolicy('schema-test-policy');
};
describe('Plugin schema validation on load', () => {
  it('fails loading when parameter undefined', () => {
    const missingParameterConfig = {
      'config': {
        'systemConfig': {
          'plugins': {
            'test': {
              'package': pluginDirectory
            }
          }
        }
      }
    };
    const loadedPlugins = pluginsLoader.load(missingParameterConfig);
    should(loadedPlugins).have.property('policies').empty();
  });
  it('loads plugin and registers policy successfully', () => {
    const config = {
      'config': {
        'systemConfig': {
          'plugins': {
            'test': {
              'package': pluginDirectory,
              'schema-test-param': 'defined'
            }
          }
        }
      }
    };
    const loadedPlugins = pluginsLoader.load(config);
    should(loadedPlugins).have.property('policies', ['schema-test-policy']);
  });
});
 | 
	const path = require('path');
const should = require('should');
const pluginsLoader = require('../../lib/plugins');
// Caching fixture plugin, but redefining its properties for testing plugin load.
const pluginName = 'express-gateway-plugin-test';
const pluginDirectory = path.join(__dirname, '../fixtures', pluginName);
const testPlugin = require(pluginDirectory);
testPlugin.schema = {
  '$id': `http://express-gateway.io/schemas/plugin/${pluginName}.json`,
  'required': ['schema-test-param']
};
testPlugin.init = (pluginContext) => {
  pluginContext.registerPolicy('schema-test-policy');
};
describe('Plugin schema validation on load', () => {
  it('fails loading when parameter undefined', () => {
    const missingParameterConfig = {
      'config': {
        'systemConfig': {
          'plugins': {
            'test': {
              'package': pluginDirectory
            }
          }
        }
      }
    };
    const loadedPlugins = pluginsLoader.load(missingParameterConfig);
    should(loadedPlugins).a.property('policies').be.empty();
  });
  it('loads plugin and registers policy successfully', () => {
    const config = {
      'config': {
        'systemConfig': {
          'plugins': {
            'test': {
              'package': pluginDirectory,
              'schema-test-param': 'defined'
            }
          }
        }
      }
    };
    const loadedPlugins = pluginsLoader.load(config);
    should(loadedPlugins).have.a.property('policies', ['schema-test-policy']);
  });
});
 | 
| 
	Fix typo that raises KeyError in taskboard | 
	# -*- coding: utf-8 -*-
from django.db.models.loading import get_model
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from taiga.base import exceptions as exc
from .serializers import ResolverSerializer
class ResolverViewSet(viewsets.ViewSet):
    permission_classes = (IsAuthenticated,)
    def list(self, request, **kwargs):
        serializer = ResolverSerializer(data=request.QUERY_PARAMS)
        if not serializer.is_valid():
            raise exc.BadRequest(serializer.errors)
        data = serializer.data
        project_model = get_model("projects", "Project")
        project = get_object_or_404(project_model, slug=data["project"])
        result = {
            "project": project.pk
        }
        if data["us"]:
            result["us"] = get_object_or_404(project.user_stories.all(), ref=data["us"]).pk
        if data["task"]:
            result["us"] = get_object_or_404(project.tasks.all(), ref=data["task"]).pk
        if data["issue"]:
            result["issue"] = get_object_or_404(project.issues.all(), ref=data["issue"]).pk
        if data["milestone"]:
            result["milestone"] = get_object_or_404(project.milestones.all(), slug=data["milestone"]).pk
        return Response(result)
 | 
	# -*- coding: utf-8 -*-
from django.db.models.loading import get_model
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from taiga.base import exceptions as exc
from .serializers import ResolverSerializer
class ResolverViewSet(viewsets.ViewSet):
    permission_classes = (IsAuthenticated,)
    def list(self, request, **kwargs):
        serializer = ResolverSerializer(data=request.QUERY_PARAMS)
        if not serializer.is_valid():
            raise exc.BadRequest(serializer.errors)
        data = serializer.data
        project_model = get_model("projects", "Project")
        project = get_object_or_404(project_model, slug=data["project"])
        result = {
            "project": project.pk
        }
        if data["us"]:
            result["us"] = get_object_or_404(project.user_stories.all(), ref=data["us"]).pk
        if data["task"]:
            result["us"] = get_object_or_404(project.tasks.all(), ref=data["task"]).pk
        if data["issue"]:
            result["issue"] = get_object_or_404(project.issues.all(), ref=data["issue"]).pk
        if data["milestone"]:
            result["milestone"] = get_object_or_404(project.milestones.all(), slug=data["milestones"]).pk
        return Response(result)
 | 
| 
	Use arrow functions and replace deprecated ListView with a FlatList | 
	'use strict';
import React, {Component} from 'react';
import {
  AppRegistry,
  FlatList,
  StyleSheet,
  View,
} from 'react-native';
class CollectionView extends Component {
  groupItems = (items, itemsPerRow) => {
    let itemsGroups = [];
    let group = [];
    items.forEach(function (item) {
      if (group.length === itemsPerRow) {
        itemsGroups.push(group);
        group = [item];
      } else {
        group.push(item);
      }
    });
    if (group.length > 0) {
      itemsGroups.push(group);
    }
    return itemsGroups;
  };
  renderGroup = ({item}) => {
    const items = item.map((item, index) => {
      return this.props.renderItem(item, index);
    });
    return (
      <View style={styles.group}>
        {items}
      </View>
    );
  };
  render = () => {
    const groups = this.groupItems(this.props.items, this.props.itemsPerRow);
    return (
      <FlatList
        {...this.props}
        renderItem={this.renderGroup}
        data={groups}
      />
    );
  };
}
var styles = StyleSheet.create({
  group: {
    flexDirection : 'row',
    alignItems    : 'center',
    justifyContent: 'center',
    overflow      : 'hidden'
  }
});
module.exports = CollectionView;
 | 
	'use strict';
import React, { Component } from 'react';
import {
  AppRegistry,
  View,
  StyleSheet,
  ListView,
} from 'react-native';
class CollectionView extends Component {
  groupItems = function(items, itemsPerRow) {
      var itemsGroups = [];
      var group = [];
      items.forEach(function(item) {
        if (group.length === itemsPerRow) {
          itemsGroups.push(group);
          group = [item];
        } else {
          group.push(item);
        }
      });
      if (group.length > 0) {
        itemsGroups.push(group);
      }
      return itemsGroups;
  }
  renderGroup = function(group) {
    var that = this;
    var items = group.map(function(item, index) {
      return that.props.renderItem(item, index);
    });
    return (
      <View style={styles.group}>
        {items}
      </View>
    );
  }
  render = function() {
      var groups = this.groupItems(this.props.items, this.props.itemsPerRow);
      var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      return (<ListView
        {...this.props}
        renderRow={this.renderGroup}
        dataSource={ds.cloneWithRows(groups)}
      />);
  }
}
var styles = StyleSheet.create({
  group: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden'
  }
});
module.exports = CollectionView;
 | 
| 
	Exclude Endpoints with a <format> parameter | 
	from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.utils.module_loading import import_string
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
    def __init__(self):
        self.endpoints = []
        root_urlconf = import_string(settings.ROOT_URLCONF)
        if hasattr(root_urlconf, 'urls'):
            self.get_all_view_names(root_urlconf.urls.urlpatterns)
        else:
            self.get_all_view_names(root_urlconf.urlpatterns)
    def get_all_view_names(self, urlpatterns, parent_pattern=None):
        for pattern in urlpatterns:
            if isinstance(pattern, RegexURLResolver):
                parent_pattern = None if pattern._regex == "^" else pattern
                self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=parent_pattern)
            elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern) and not self._is_format_endpoint(pattern):
                api_endpoint = ApiEndpoint(pattern, parent_pattern)
                self.endpoints.append(api_endpoint)
    def _is_drf_view(self, pattern):
        """
        Should check whether a pattern inherits from DRF's APIView
        """
        return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
    def _is_format_endpoint(self, pattern):
        """
        Exclude endpoints with a "format" parameter
        """
        return '?P<format>' in pattern._regex
    def get_endpoints(self):
        return self.endpoints
 | 
	from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.utils.module_loading import import_string
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
    def __init__(self):
        self.endpoints = []
        root_urlconf = import_string(settings.ROOT_URLCONF)
        if hasattr(root_urlconf, 'urls'):
            self.get_all_view_names(root_urlconf.urls.urlpatterns)
        else:
            self.get_all_view_names(root_urlconf.urlpatterns)
    def get_all_view_names(self, urlpatterns, parent_pattern=None):
        for pattern in urlpatterns:
            if isinstance(pattern, RegexURLResolver):
                parent_pattern = None if pattern._regex == "^" else pattern
                self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=parent_pattern)
            elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
                api_endpoint = ApiEndpoint(pattern, parent_pattern)
                self.endpoints.append(api_endpoint)
    def _is_drf_view(self, pattern):
        # Should check whether a pattern inherits from DRF's APIView
        return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
    def get_endpoints(self):
        return self.endpoints
 | 
| 
	Move Blink call into post-update event, not pre-update. | 
	<?php
namespace Northstar\Providers;
use Northstar\Models\User;
use DoSomething\Gateway\Blink;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::creating(function (User $user) {
            // Set source automatically if not provided.
            $user->source = $user->source ?: client_id();
        });
        User::created(function (User $user) {
            // Send payload to Blink for Customer.io profile.
            if (config('features.blink')) {
                app(Blink::class)->userCreate($user->toBlinkPayload());
            }
            // Send metrics to StatHat.
            app('stathat')->ezCount('user created');
            app('stathat')->ezCount('user created - '.$user->source);
        });
        User::updating(function (User $user) {
            // Write profile changes to the log, with redacted values for hidden fields.
            $changed = array_replace_keys($user->getDirty(), $user->getHidden(), '*****');
            logger('updated user', ['id' => $user->id, 'client_id' => client_id(), 'changed' => $changed]);
        });
        User::updated(function (User $user) {
            // Send payload to Blink for Customer.io profile.
            if (config('features.blink')) {
                app(Blink::class)->userCreate($user->toBlinkPayload());
            }
        });
    }
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
 | 
	<?php
namespace Northstar\Providers;
use Northstar\Models\User;
use DoSomething\Gateway\Blink;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::creating(function (User $user) {
            // Set source automatically if not provided.
            $user->source = $user->source ?: client_id();
        });
        User::created(function (User $user) {
            // Send payload to Blink for Customer.io profile.
            if (config('features.blink')) {
                app(Blink::class)->userCreate($user->toBlinkPayload());
            }
            // Send metrics to StatHat.
            app('stathat')->ezCount('user created');
            app('stathat')->ezCount('user created - '.$user->source);
        });
        User::updating(function (User $user) {
            // Send payload to Blink for Customer.io profile.
            if (config('features.blink')) {
                app(Blink::class)->userCreate($user->toBlinkPayload());
            }
            // Write profile changes to the log, with redacted values for hidden fields.
            $changed = array_replace_keys($user->getDirty(), $user->getHidden(), '*****');
            logger('updated user', ['id' => $user->id, 'client_id' => client_id(), 'changed' => $changed]);
        });
    }
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
 | 
| 
	Change migration to fallback to old country | 
	from django.core.management.base import LabelCommand
from django_countries.countries import COUNTRIES
from corehq.apps.domain.models import Domain
class Command(LabelCommand):
    help = "Migrates old django domain countries from string to list. Sept 2014."
    args = ""
    label = ""
    def handle(self, *args, **options):
        print "Migrating Domain countries"
        country_lookup = {x[1].lower(): x[0] for x in COUNTRIES}
        #Special cases
        country_lookup["USA"] = country_lookup["united states"]
        country_lookup["California"] = country_lookup["united states"]
        country_lookup["Wales"] = country_lookup["united kingdom"]
        for domain in Domain.get_all():
            if domain.deployment._doc.get('countries', None):
                continue
            try:
                country = None
                if domain.deployment._doc.get('country', None):
                    country = domain.deployment._doc['country']
                elif domain._doc.get('country', None):
                    country = domain._doc['country']
                if country:
                    if ',' in country:
                        countries = country.split(',')
                    elif ' and ' in country:
                        countries = country.split(' and ')
                    else:
                        countries = [country]
                    abbr = []
                    for country in countries:
                        country = country.strip().lower()
                        if country in country_lookup.keys():
                            abbr.append(country_lookup[country])
                    domain.deployment.countries = abbr
                    domain.save()
            except Exception as e:
                print "There was an error migrating the domain named %s." % domain.name
                print "Error: %s" % e
 | 
	from django.core.management.base import LabelCommand
from django_countries.countries import COUNTRIES
from corehq.apps.domain.models import Domain
class Command(LabelCommand):
    help = "Migrates old django domain countries from string to list. Sept 2014."
    args = ""
    label = ""
    def handle(self, *args, **options):
        print "Migrating Domain countries"
        country_lookup = {x[1].lower(): x[0] for x in COUNTRIES}
        #Special cases
        country_lookup["USA"] = country_lookup["united states"]
        country_lookup["California"] = country_lookup["united states"]
        country_lookup["Wales"] = country_lookup["united kingdom"]
        for domain in Domain.get_all():
            try:
                if isinstance(domain.deployment.country, basestring):
                    if ',' in domain.deployment.country:
                        countries = domain.deployment.country.split(',')
                    elif ' and ' in domain.deployment.country:
                        countries = domain.deployment.country.split(' and ')
                    else:
                        countries = [domain.deployment.country]
                    abbr = []
                    for country in countries:
                        country = country.strip().lower()
                        if country in country_lookup.keys():
                            abbr.append(country_lookup[country])
                    domain.deployment.countries = abbr
                    domain.save()
            except Exception as e:
                print "There was an error migrating the domain named %s." % domain.name
                print "Error: %s", e
 | 
| 
	Fix button class on upload modal
no issue
- this makes sure that the cancel button on the upload modal gets the
  correct class | 
	import ModalDialog from 'ghost/components/gh-modal-dialog';
import upload from 'ghost/assets/lib/uploader';
var UploadModal = ModalDialog.extend({
    layoutName: 'components/gh-modal-dialog',
    didInsertElement: function () {
        this._super();
        upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')});
    },
    confirm: {
        reject: {
            func: function () { // The function called on rejection
                return true;
            },
            buttonClass: 'btn btn-default',
            text: 'Cancel' // The reject button text
        },
        accept: {
            buttonClass: 'btn btn-blue right',
            text: 'Save', // The accept button texttext: 'Save'
            func: function () {
                var imageType = 'model.' + this.get('imageType');
                if (this.$('.js-upload-url').val()) {
                    this.set(imageType, this.$('.js-upload-url').val());
                } else {
                    this.set(imageType, this.$('.js-upload-target').attr('src'));
                }
                return true;
            }
        }
    },
    actions: {
        closeModal: function () {
            this.sendAction();
        },
        confirm: function (type) {
            var func = this.get('confirm.' + type + '.func');
            if (typeof func === 'function') {
                func.apply(this);
            }
            this.sendAction();
            this.sendAction('confirm' + type);
        }
    }
});
export default UploadModal;
 | 
	import ModalDialog from 'ghost/components/gh-modal-dialog';
import upload from 'ghost/assets/lib/uploader';
var UploadModal = ModalDialog.extend({
    layoutName: 'components/gh-modal-dialog',
    didInsertElement: function () {
        this._super();
        upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')});
    },
    confirm: {
        reject: {
            func: function () { // The function called on rejection
                return true;
            },
            buttonClass: true,
            text: 'Cancel' // The reject button text
        },
        accept: {
            buttonClass: 'btn btn-blue right',
            text: 'Save', // The accept button texttext: 'Save'
            func: function () {
                var imageType = 'model.' + this.get('imageType');
                if (this.$('.js-upload-url').val()) {
                    this.set(imageType, this.$('.js-upload-url').val());
                } else {
                    this.set(imageType, this.$('.js-upload-target').attr('src'));
                }
                return true;
            }
        }
    },
    actions: {
        closeModal: function () {
            this.sendAction();
        },
        confirm: function (type) {
            var func = this.get('confirm.' + type + '.func');
            if (typeof func === 'function') {
                func.apply(this);
            }
            this.sendAction();
            this.sendAction('confirm' + type);
        }
    }
});
export default UploadModal;
 | 
| 
	Refactor migration script to handle case where Postgres is being used but psycopg2 isn't installed | 
	from __future__ import unicode_literals
from django import VERSION
from django.db import migrations, models
can_use_arrayfield = False
chapters_field = models.Field()  # Dummy field
if VERSION >= (1, 8):
    try:
        from django.contrib.postgres.fields import ArrayField
        chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)
        can_use_arrayfield = True
    except ImportError:
        # We can't use ArrayField if psycopg2 is not installed
        pass
class Migration(migrations.Migration):
    dependencies = [
        ('core', '0003_withfloatfield'),
    ]
    operations = []
    pg_only_operations = [
        migrations.CreateModel(
            name='BookWithChapters',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100, verbose_name='Book name')),
                ('chapters', chapters_field)
            ],
        ),
    ]
    def apply(self, project_state, schema_editor, collect_sql=False):
        if can_use_arrayfield and schema_editor.connection.vendor.startswith("postgres"):
            self.operations = self.operations + self.pg_only_operations
        return super(Migration, self).apply(project_state, schema_editor, collect_sql)
 | 
	from __future__ import unicode_literals
from django import VERSION
from django.db import migrations, models
if VERSION >= (1, 8):
    from django.contrib.postgres.fields import ArrayField
    chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)
else:
    chapters_field = models.Field()  # Dummy field
class PostgresOnlyCreateModel(migrations.CreateModel):
    def database_forwards(self, app_label, schema_editor, from_state, to_state):
        if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
            super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state)
    def database_backwards(self, app_label, schema_editor, from_state, to_state):
        if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
            super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state)
class Migration(migrations.Migration):
    dependencies = [
        ('core', '0003_withfloatfield'),
    ]
    operations = [
        PostgresOnlyCreateModel(
            name='BookWithChapters',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100, verbose_name='Book name')),
                ('chapters', chapters_field)
            ],
        ),
    ]
 | 
| 
	Set user circle at home | 
	package components;
import com.badlogic.ashley.core.Component;
import dataObjects.Profile;
import javafx.scene.shape.Circle;
import utils.Constants;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
 * Created by Thagus on 19/10/16.
 */
public class ProfileComponent implements Component{
    public CityBlockComponent home, work;
    public Profile profile;
    public ProfileComponent(Profile profile, HashMap<CityBlockComponent.BlockType, ArrayList<CityBlockComponent>> cityBlocksIndex, Circle circleToReposition){
        this.profile = profile;
        Random random = new Random();
        //Select the home of the user
        home = cityBlocksIndex.get(CityBlockComponent.BlockType.RESIDENTIAL).get(random.nextInt(cityBlocksIndex.get(CityBlockComponent.BlockType.RESIDENTIAL).size()));
        circleToReposition.setCenterX(home.block.getX() + Constants.BLOCK_SIZE/2);
        circleToReposition.setCenterY(home.block.getY() + Constants.BLOCK_SIZE/2);
        //Define the work block
        if(profile.isHomeWorker()){ //If he/she works from home, the work block ant the home block are the same
            work = home;
        }
        else{
            switch(profile.getWorkArea()){  //We must select the work block according the profession
                case RESIDENTIAL:
                case BUSINESS:
                case SHOPPING:
                case PARK:
                    work = cityBlocksIndex.get(profile.getWorkArea()).get(random.nextInt(cityBlocksIndex.get(profile.getWorkArea()).size()));
                    break;
                case TRAFFIC:
                    work = null;
                    break;
            }
        }
    }
}
 | 
	package components;
import com.badlogic.ashley.core.Component;
import dataObjects.Profile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
 * Created by Thagus on 19/10/16.
 */
public class ProfileComponent implements Component{
    public CityBlockComponent home, work;
    public Profile profile;
    public ProfileComponent(Profile profile, HashMap<CityBlockComponent.BlockType, ArrayList<CityBlockComponent>> cityBlocksIndex){
        this.profile = profile;
        Random random = new Random();
        //Select the home of the user
        home = cityBlocksIndex.get(CityBlockComponent.BlockType.RESIDENTIAL).get(random.nextInt(cityBlocksIndex.get(CityBlockComponent.BlockType.RESIDENTIAL).size()));
        //Define the work block
        if(profile.isHomeWorker()){ //If he/she works from home, the work block ant the home block are the same
            work = home;
        }
        else{
            switch(profile.getWorkArea()){  //We must select the work block according the profession
                case RESIDENTIAL:
                case BUSINESS:
                case SHOPPING:
                case PARK:
                    work = cityBlocksIndex.get(profile.getWorkArea()).get(random.nextInt(cityBlocksIndex.get(profile.getWorkArea()).size()));
                    break;
                case TRAFFIC:
                    work = null;
                    break;
            }
        }
    }
}
 | 
| 
	Make test more resilient to countries already existing in test database | 
	<?php
use App\Models\Country;
class UsersControllerTest extends TestCase
{
    /**
     * Checks whether an OK status is returned when the
     * profile order update request is valid.
     */
    public function testStore()
    {
        config()->set('osu.user.allow_registration', true);
        $this
            ->json('POST', route('users.store'), [
                'user' => [
                    'username' => 'user1',
                    'user_email' => '[email protected]',
                    'password' => 'hunter22',
                ],
            ], [
                'HTTP_USER_AGENT' => config('osu.client.user_agent'),
            ])->assertJsonFragment([
                'username' => 'user1',
            ]);
    }
    public function testStoreWithCountry()
    {
        config()->set('osu.user.allow_registration', true);
        $country = Country::inRandomOrder()->first() ?? factory(Country::class)->create();
        $this
            ->json('POST', route('users.store'), [
                'user' => [
                    'username' => 'user1',
                    'user_email' => '[email protected]',
                    'password' => 'hunter22',
                ],
            ], [
                'HTTP_USER_AGENT' => config('osu.client.user_agent'),
                'HTTP_CF_IPCOUNTRY' => $country->getKey(),
            ])->assertJsonFragment([
                'username' => 'user1',
                'country' => [
                    'code' => $country->getKey(),
                    'name' => $country->name,
                ],
            ]);
    }
}
 | 
	<?php
use App\Models\Country;
class UsersControllerTest extends TestCase
{
    /**
     * Checks whether an OK status is returned when the
     * profile order update request is valid.
     */
    public function testStore()
    {
        config()->set('osu.user.allow_registration', true);
        $this
            ->json('POST', route('users.store'), [
                'user' => [
                    'username' => 'user1',
                    'user_email' => '[email protected]',
                    'password' => 'hunter22',
                ],
            ], [
                'HTTP_USER_AGENT' => config('osu.client.user_agent'),
            ])->assertJsonFragment([
                'username' => 'user1',
            ]);
    }
    public function testStoreWithCountry()
    {
        config()->set('osu.user.allow_registration', true);
        $country = factory(Country::class)->create();
        $this
            ->json('POST', route('users.store'), [
                'user' => [
                    'username' => 'user1',
                    'user_email' => '[email protected]',
                    'password' => 'hunter22',
                ],
            ], [
                'HTTP_USER_AGENT' => config('osu.client.user_agent'),
                'HTTP_CF_IPCOUNTRY' => $country->getKey(),
            ])->assertJsonFragment([
                'username' => 'user1',
                'country' => [
                    'code' => $country->getKey(),
                    'name' => $country->name,
                ],
            ]);
    }
}
 | 
| 
	Fix url to keywords; fix cmd line usage | 
	#!/usr/bin/env python
from __future__ import print_function
import json
import os
import sys
import requests
import scraperwiki
def main(argv=None):
    if argv is None:
        argv = sys.argv
    arg = argv[1:]
    if len(arg) > 0:
        # Developers can supply URL as an argument...
        keywords = arg[0]
    else:
        # ... but normally the URL comes from the allSettings.json file
        with open(os.path.expanduser("~/allSettings.json")) as settings:
            keywords = json.load(settings)['input']
    return store_search(keywords)
def store_search(keywords):
    """
    Store results of search to .
    """
    base_url = "http://localhost:59742/blog/post/_search"
    params = {'q': 'body:' + keywords, 'pretty': 'true'}
    response = requests.get(base_url, params=params)
    j = response.json()
    scraperwiki.sql.execute('DROP TABLE IF EXISTS results')
    hits = j['hits']['hits']
    
    results = []
    for hit in hits:	        
        doc = hit['_source']['body'] 
   	score = hit['_score']
 	doc_id = hit['_id']
	results.append(dict(doc=doc, score=score, doc_id=doc_id))
    
    scraperwiki.sql.save(unique_keys=['doc_id'], data=results, table_name='results')
    
if __name__ == '__main__':
    main()
 | 
	#!/usr/bin/env python
from __future__ import print_function
import json
import os
import sys
import requests
import scraperwiki
def main(argv=None):
    if argv is None:
        argv = sys.argv
    arg = argv[1:]
    if len(arg) > 0:
        # Developers can supply URL as an argument...
        url = arg[0]
    else:
        # ... but normally the URL comes from the allSettings.json file
        with open(os.path.expanduser("~/allSettings.json")) as settings:
            keywords = json.load(settings)['input']
    return store_search(keywords)
def store_search(keywords):
    """
    Store results of search to .
    """
    base_url = "http://localhost:59742/blog/post/_search"
    params = {'q': 'body:' + keywords, 'pretty': 'true'}
    response = requests.get(base_url, params=params)
    j = response.json()
    scraperwiki.sql.execute('DROP TABLE IF EXISTS results')
    hits = j['hits']['hits']
    
    results = []
    for hit in hits:	        
        doc = hit['_source']['body'] 
   	score = hit['_score']
 	doc_id = hit['_id']
	results.append(dict(doc=doc, score=score, doc_id=doc_id))
    
    scraperwiki.sql.save(unique_keys=['doc_id'], data=results, table_name='results')
    
if __name__ == '__main__':
    main()
 | 
| 
	Throw an exception if the test importer cannot handle an import. | 
	package io.bit3.jsass;
import io.bit3.jsass.importer.Import;
import io.bit3.jsass.importer.Importer;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedList;
public class TestImporter implements Importer {
  @Override
  public Collection<Import> apply(String url, Import previous) {
    if ("functions".equals(url)) {
      return new LinkedList<>();
    }
    if ("include".equals(url)) {
      // Importers does not support SASS syntax, so we enforce scss here
      // String syntax = previous.substring(previous.length() - 4);
      String syntax = "scss";
      String resourcePath = String.format("/%s/src/include.%s", syntax, syntax);
      URL resource = getClass().getResource(resourcePath);
      String basePath = String.format("/%s/src", syntax);
      URL base = getClass().getResource(basePath);
      try {
        String contents = IOUtils.toString(resource);
        Import importSource = new Import(
            new URI(String.format("include.%s", syntax)),
            base.toURI(),
            contents
        );
        Collection<Import> list = new LinkedList<>();
        list.add(importSource);
        return list;
      } catch (IOException | URISyntaxException e) {
        throw new RuntimeException(e);
      }
    }
    throw new IllegalArgumentException("Cannot handle import \"" + url + "\"");
  }
}
 | 
	package io.bit3.jsass;
import io.bit3.jsass.importer.Import;
import io.bit3.jsass.importer.Importer;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedList;
public class TestImporter implements Importer {
  @Override
  public Collection<Import> apply(String url, Import previous) {
    if ("functions".equals(url)) {
      return new LinkedList<>();
    }
    if ("include".equals(url)) {
      // Importers does not support SASS syntax, so we enforce scss here
      // String syntax = previous.substring(previous.length() - 4);
      String syntax = "scss";
      String resourcePath = String.format("/%s/src/include.%s", syntax, syntax);
      URL resource = getClass().getResource(resourcePath);
      String basePath = String.format("/%s/src", syntax);
      URL base = getClass().getResource(basePath);
      try {
        String contents = IOUtils.toString(resource);
        Import importSource = new Import(
            new URI(String.format("include.%s", syntax)),
            base.toURI(),
            contents
        );
        Collection<Import> list = new LinkedList<>();
        list.add(importSource);
        return list;
      } catch (IOException | URISyntaxException e) {
        throw new RuntimeException(e);
      }
    }
    return null;
  }
}
 | 
| 
	Call au lieu de Popen pour synchroniser | 
	# -*- coding: utf-8 -*-
# traitement global des fichiers wav
import os,numpy,octaveIO,string,subprocess
def createDataFiles():
    if not os.path.exists('data'):
        os.makedirs('data')
        print "Please add some data, I don't work for free"
    else:
        res = []
        for root, dirs, files in os.walk('data'):
            print root,dirs,files
            for file in files:
                if file.endswith(".wav"):
                    print "treating file "+file
                    name=os.path.splitext(file)[0]
                    fileName = os.path.join(root, name)
                    wavName = fileName+'.wav'
                    matName = fileName+'.mat'
                    #print string.join(['octave','--eval','cepstraux('+'\''+wavName+'\',\''+matName+'\')'])
                    subprocess.call(['octave','--eval','cepstraux('+'\''+wavName+'\',\''+matName+'\')'])
                    triplet=octaveIO.retrieve(matName,['mu','sig','pi'])
                    res.append(triplet)
        return res
                    
res = createDataFiles()
print res
 | 
	# -*- coding: utf-8 -*-
# traitement global des fichiers wav
import os,numpy,octaveIO,string,subprocess
def createDataFiles():
    if not os.path.exists('data'):
        os.makedirs('data')
        print "Please add some data, I don't work for free"
    else:
        res = []
        for root, dirs, files in os.walk('data'):
            print root,dirs,files
            for file in files:
                if file.endswith(".wav"):
                    print "treating file "+file
                    name=os.path.splitext(file)[0]
                    fileName = os.path.join(root, name)
                    wavName = fileName+'.wav'
                    matName = fileName+'.mat'
                    #print string.join(['octave','--eval','cepstraux('+'\''+wavName+'\',\''+matName+'\')'])
                    subprocess.Popen(['octave','--eval','cepstraux('+'\''+wavName+'\',\''+matName+'\')'])
                    # triplet=octaveIO.retrieve(matName,['mu','sig','pi'])
                    # res.append(triplet)
        return res
                    
createDataFiles()
 | 
| 
	Handle args in the review helper. | 
	#!/usr/bin/python
import argparse
import json
import utils
def component_reviews(component, reviewer=None):
    cmd = ('ssh review.openstack.org gerrit query --format json '
           '--current-patch-set project:%s status:open '
           'limit:10000'
           % component)
    if reviewer:
        cmd += ' reviewer:%s' % reviewer
    else:
        cmd += ' --all-approvals'
    stdout = utils.runcmd(cmd)
    reviews = []
    for line in stdout.split('\n'):
        if not line:
            continue
        try:
            packet = json.loads(line)
            if packet.get('project') == component:
                reviews.append(packet)
        except ValueError as e:
            print 'Could not decode:'
            print '  %s' % line
            print '  Error: %s' % e
    return reviews
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--username', default='mikalstill',
                        help='The username (if any) to filter by')
    ARGS = parser.parse_args()
    
    reviews = component_reviews('openstack/nova', reviewer=ARGS.username)
    print '%s reviews found' % len(reviews)
    for review in reviews:
        print
        for key in sorted(review.keys()):
            if key == 'patchSets':
                print '%s:' % key
                for ps in review[key]:
                    print '    %s' % ps
            else:
                print '%s: %s' %(key, review[key])
 | 
	#!/usr/bin/python
import json
import utils
def component_reviews(component, reviewer=None):
    cmd = ('ssh review.openstack.org gerrit query --format json '
           '--current-patch-set project:%s status:open '
           'limit:10000'
           % component)
    if reviewer:
        cmd += ' reviewer:%s' % reviewer
    else:
        cmd += ' --all-approvals'
    stdout = utils.runcmd(cmd)
    reviews = []
    for line in stdout.split('\n'):
        if not line:
            continue
        try:
            packet = json.loads(line)
            if packet.get('project') == component:
                reviews.append(packet)
        except ValueError as e:
            print 'Could not decode:'
            print '  %s' % line
            print '  Error: %s' % e
    return reviews
if __name__ == '__main__':
    reviews = component_reviews('openstack/nova', reviewer='[email protected]')
    print '%s reviews found' % len(reviews)
    for review in reviews:
        print
        for key in sorted(review.keys()):
            if key == 'patchSets':
                print '%s:' % key
                for ps in review[key]:
                    print '    %s' % ps
            else:
                print '%s: %s' %(key, review[key])
 | 
| 
	Fix linting rule for switch-case indentation | 
	module.exports = {
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true,
        "node": true,
        "mocha": true
    },
    "extends": "eslint:recommended",
    "plugins": ["eslint-plugin-jsdoc", "eslint-plugin-markdown"],
    "parserOptions": {
        "ecmaVersion": 2018
    },
    "overrides": {
      files: ["**/*.md"],
      rules: {
        "eol-last": ["off"],
        "no-console": ["off"],
        "no-undef": ["off"],
        "no-unused-vars": ["warn"],
        "padded-blocks": ["off"],
        "import/unambiguous": ["off"],
        "import/no-unresolved": ["off"],
        "node/no-missing-import": ["off"]
      }
    },
    "rules": {
        "indent": [
            "error",
            4,
            { "SwitchCase": 1 }
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "quotes": [
            "error",
            "double"
        ],
        "semi": [
            "error",
            "always"
        ],
        "no-console": ["off"]
    }
}; | 
	module.exports = {
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true,
        "node": true,
        "mocha": true
    },
    "extends": "eslint:recommended",
    "plugins": ["eslint-plugin-jsdoc", "eslint-plugin-markdown"],
    "parserOptions": {
        "ecmaVersion": 2018
    },
    "overrides": {
      files: ["**/*.md"],
      rules: {
        "eol-last": ["off"],
        "no-console": ["off"],
        "no-undef": ["off"],
        "no-unused-vars": ["warn"],
        "padded-blocks": ["off"],
        "import/unambiguous": ["off"],
        "import/no-unresolved": ["off"],
        "node/no-missing-import": ["off"]
      }
    },
    "rules": {
        "indent": [
            "error",
            4
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "quotes": [
            "error",
            "double"
        ],
        "semi": [
            "error",
            "always"
        ],
        "no-console": ["off"]
    }
}; | 
| 
	Use colors and quality attributes on manual image fetching | 
	angular
    .module('ngVibrant')
    .directive('vibrant', vibrant);
function vibrant($vibrant) {
    var directive = {
        restrict: 'AE',
        scope: {
            model: '=ngModel', //Model
            url: '@?',
            swatch: '@?',
            quality: '@?',
            colors: '@?'
        },
        link: link
    };
    return directive;
    function link(scope, element, attrs) {
        scope.model = [];
        if (angular.isUndefined(attrs.quality)) {
            attrs.quality = $vibrant.getDefaultQuality();
        }
        if (angular.isUndefined(attrs.colors)) {
            attrs.colors = $vibrant.getDefaultColors();
        }
        if (angular.isDefined(attrs.url)) {
            $vibrant.get(attrs.url, attrs.colors, attrs.quality).then(function(swatches) {
                scope.model = angular.isDefined(attrs.swatch) ? swatches[attrs.swatch] : swatches;
            });
        }else {
            element.on('load', function() {
                var swatches = $vibrant(element[0], attrs.colors, attrs.quality);
                scope.model = angular.isDefined(attrs.swatch) ? swatches[attrs.swatch] : swatches;
            });
        }
    }
}
 | 
	angular
    .module('ngVibrant')
    .directive('vibrant', vibrant);
function vibrant($vibrant) {
    var directive = {
        restrict: 'AE',
        scope: {
            model: '=ngModel', //Model
            url: '@?',
            swatch: '@?',
            quality: '@?',
            colors: '@?'
        },
        link: link
    };
    return directive;
    function link(scope, element, attrs) {
        scope.model = [];
        if (angular.isUndefined(attrs.quality)) {
            attrs.quality = $vibrant.getDefaultQuality();
        }
        if (angular.isUndefined(attrs.colors)) {
            attrs.colors = $vibrant.getDefaultColors();
        }
        if (angular.isDefined(attrs.url)) {
            $vibrant.get(attrs.url).then(function(swatches) {
                scope.model = angular.isDefined(attrs.swatch) ? swatches[attrs.swatch] : swatches;
            });
        }else {
            element.on('load', function() {
                var swatches = $vibrant(element[0], attrs.colors, attrs.quality);
                scope.model = angular.isDefined(attrs.swatch) ? swatches[attrs.swatch] : swatches;
            });
        }
    }
}
 | 
| 
	Make sure that the channel creation and storage works
Signed-off-by: Rohan Jain <[email protected]> | 
	import json
from tornado import testing
from qotr.server import make_application
from qotr.channels import Channels
class TestChannelHandler(testing.AsyncHTTPTestCase):
    '''
    Test the channel creation handler.
    '''
    port = None
    application = None
    def get_app(self):
        Channels.reset()
        return make_application()
    def test_create(self):
        salt = "common"
        channel_id = "test-channel"
        key_hash = 'hmac-key'
        body = "&".join([
            "id={channel_id}",
            "salt={salt}",
            "key_hash={key_hash}"
        ]).format(**locals())
        response = json.loads(self.fetch(
            '/c/new', method='POST',
            body=body
        ).body.decode('utf8'))
        self.assertEqual({
            "salt": salt,
            "id": channel_id
        }, response)
        channel = Channels.get(channel_id)
        self.assertEqual(salt, channel.salt)
        self.assertEqual(key_hash, key_hash)
    def test_confict(self):
        body = "&".join([
            "id=common",
            "salt=test-channel",
            "key_hash=hmac-key"
        ])
        self.fetch('/c/new', method='POST', body=body)
        response = json.loads(self.fetch(
            '/c/new', method='POST',
            body=body
        ).body.decode('utf8'))
        self.assertTrue("error" in response)
 | 
	import json
from tornado import testing, httpserver
from qotr.server import make_application
from qotr.channels import Channels
class TestChannelHandler(testing.AsyncHTTPTestCase):
    '''
    Test the channel creation handler.
    '''
    port = None
    application = None
    def get_app(self):
        Channels.reset()
        return make_application()
    def test_create(self):
        salt = "common"
        channel_id = "test-channel"
        body = "&".join([
            "id={channel_id}",
            "salt={salt}",
            "key_hash=hmac-key"
        ]).format(**locals())
        response = json.loads(self.fetch(
            '/c/new', method='POST',
            body=body
        ).body.decode('utf8'))
        self.assertEqual({
            "salt": salt,
            "id": channel_id
        }, response)
    def test_confict(self):
        body = "&".join([
            "id=common",
            "salt=test-channel",
            "key_hash=hmac-key"
        ])
        self.fetch('/c/new', method='POST', body=body)
        response = json.loads(self.fetch(
            '/c/new', method='POST',
            body=body
        ).body.decode('utf8'))
        self.assertTrue("error" in response)
 | 
| 
	Add concat step to default grunt task | 
	/// <binding BeforeBuild='bower, concat' ProjectOpened='bower:install' />
/*
This file in the main entry point for defining grunt tasks and using grunt plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
*/
module.exports = function (grunt) {
    grunt.initConfig({
        bower: {
            install: {
                options: {
                    targetDir: "wwwroot/lib",
                    layout: "byComponent",
                    cleanTargetDir: true
                }
            }
        },
        concat: {
            js: {
                src: "Assets/js/*.js",
                dest: "wwwroot/js/site.js"
            },
            css: {
                src: "Assets/css/*.css",
                dest: "wwwroot/css/site.css"
            }
        },
    });
    grunt.registerTask("default", ["bower:install", "concat"]);
    grunt.loadNpmTasks("grunt-bower-task");
    grunt.loadNpmTasks("grunt-contrib-concat");
};
 | 
	/// <binding BeforeBuild='bower, concat' ProjectOpened='bower:install' />
/*
This file in the main entry point for defining grunt tasks and using grunt plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
*/
module.exports = function (grunt) {
    grunt.initConfig({
        bower: {
            install: {
                options: {
                    targetDir: "wwwroot/lib",
                    layout: "byComponent",
                    cleanTargetDir: true
                }
            }
        },
        concat: {
            js: {
                src: "Assets/js/*.js",
                dest: "wwwroot/js/site.js"
            },
            css: {
                src: "Assets/css/*.css",
                dest: "wwwroot/css/site.css"
            }
        },
    });
    grunt.registerTask("default", ["bower:install"]);
    grunt.loadNpmTasks("grunt-bower-task");
    grunt.loadNpmTasks("grunt-contrib-concat");
};
 | 
| 
	Move survey action celery task import to method scope. | 
	from go.vumitools.conversation.definition import (
    ConversationDefinitionBase, ConversationAction)
class SendSurveyAction(ConversationAction):
    action_name = 'send_survey'
    action_display_name = 'Send Survey'
    needs_confirmation = True
    needs_group = True
    needs_running = True
    def check_disabled(self):
        if self._conv.has_channel_supporting_generic_sends():
            return None
        return ("This action needs channels capable of sending"
                " messages attached to this conversation.")
    def perform_action(self, action_data):
        return self.send_command(
            'send_survey', batch_id=self._conv.batch.key,
            msg_options={}, delivery_class=self._conv.delivery_class)
class DownloadUserDataAction(ConversationAction):
    action_name = 'download_user_data'
    action_display_name = 'Download User Data'
    action_display_verb = 'Send CSV via e-mail'
    def perform_action(self, action_data):
        # This is Django-only, but the module get imported in vumi-land.
        from go.apps.surveys.tasks import export_vxpolls_data
        return export_vxpolls_data.delay(self._conv.user_account.key,
                                         self._conv.key)
class ConversationDefinition(ConversationDefinitionBase):
    conversation_type = 'surveys'
    actions = (
        SendSurveyAction,
        DownloadUserDataAction,
    )
 | 
	from go.vumitools.conversation.definition import (
    ConversationDefinitionBase, ConversationAction)
from go.apps.surveys.tasks import export_vxpolls_data
class SendSurveyAction(ConversationAction):
    action_name = 'send_survey'
    action_display_name = 'Send Survey'
    needs_confirmation = True
    needs_group = True
    needs_running = True
    def check_disabled(self):
        if self._conv.has_channel_supporting_generic_sends():
            return None
        return ("This action needs channels capable of sending"
                " messages attached to this conversation.")
    def perform_action(self, action_data):
        return self.send_command(
            'send_survey', batch_id=self._conv.batch.key,
            msg_options={}, delivery_class=self._conv.delivery_class)
class DownloadUserDataAction(ConversationAction):
    action_name = 'download_user_data'
    action_display_name = 'Download User Data'
    action_display_verb = 'Send CSV via e-mail'
    def perform_action(self, action_data):
        return export_vxpolls_data.delay(self._conv.user_account.key,
                                         self._conv.key)
class ConversationDefinition(ConversationDefinitionBase):
    conversation_type = 'surveys'
    actions = (
        SendSurveyAction,
        DownloadUserDataAction,
    )
 | 
| 
	Use new snarl plugin feature instead of emulating / waiting. | 
	module.exports = {
  '{USER:NEW}': function(message, cb) {
    var self = this;
    if (!self.config || !self.config.welcome) return;
    var user = message.user;
    self.__rpc('im.open', {
      user: user.id
    }, function(err, response) {
      if (!response || !response.channel || !response.channel.id) {
        return console.error('Invalid response:', err, response);
      }
      if (self.config.welcome instanceof Array) {
        var timing = 15000; // start timing (send first message 15 seconds in)
        var spacing = 15000; // interval between messages
        self.config.welcome.forEach(function(message) {
          setTimeout(function() {
            self.__say(response.channel.id, formatText(message));
          }, timing);
          timing += spacing;
        });
      } else {
        self.__say(response.channel.id, formatText(self.config.welcome));
      }
    });
    function formatText(input) {
      for (var id in self.channelMap) {
        var channel = self.channelMap[id];
        input = input.replace('{{channel:'+channel.name+'}}', '<#'+id+'>');
      }
      for (var id in self.userMap) {
        var user = self.userMap[id];
        input = input.replace('{{user:'+user.name+'}}', '<#'+id+'>');
      }
      input = input.replace('{{user}}', '<@'+user.id+'>');
      return input;
    }
  }
};
 | 
	module.exports = {
  '{USER}': function(user, cb) {
    var self = this;
    if (!self.config || !self.config.welcome) return;
    // simulate a real user delay
    setTimeout(function() {
      var knownUser = ~Object.keys(self.userMap).indexOf(user.id);
      if (!knownUser) {
        self.__rpc('im.open', {
          user: user.id
        }, function(err, response) {
          if (!response || !response.channel || !response.channel.id) {
            return console.error('Invalid response:', err, response);
          }
          if (self.config.welcome instanceof Array) {
            var timing = 0;
            var spacing = 15000;
            self.config.welcome.forEach(function(message) {
              setTimeout(function() {
                self.__say(response.channel.id, formatText(message));
              }, timing);
              timing += spacing;
            });
          } else {
            self.__say(response.channel.id, self.config.welcome);
          }
        });
      }
    }, 1000);
    function formatText(input) {
      for (var id in self.channelMap) {
        var channel = self.channelMap[id];
        input = input.replace('{{channel:'+channel.name+'}}', '<#'+id+'>');
      }
      for (var id in self.userMap) {
        var channel = self.userMap[id];
        input = input.replace('{{channel:'+channel.name+'}}', '<#'+id+'>');
      }
      input = input.replace('{{user}}', '<@'+user.id+'>');
      return input;
    }
  }
};
 | 
| 
	Improve error message when encountering missing type builders | 
	import PropTypes from 'proptypes'
export default {
  any: {
    options: {
      of: PropTypes.array.isRequired
    },
    parse(options, typeBuilders, schema) {
      const containsTypes = options.of.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        if (!typeBuilder) {
          throw new Error(`Invalid type: ${typeDef.type}.`)
        }
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {of: containsTypes}
    }
  },
  reference: {
    primitive: 'string',
    options: {
      title: PropTypes.string,
      to: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.array
      ]).isRequired
    },
    parse(options, typeBuilders, schema) {
      const toTypeDefs = Array.isArray(options.to) ? options.to : [options.to]
      const toTypes = toTypeDefs.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        if (!typeBuilder) {
          throw new Error(
            `Missing type builder for ${typeDef.type}. Did you forget to declare the type "${typeDef.type}" in the schema?`
          )
        }
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {to: toTypes}
    }
  },
  text: {
    primitive: 'string',
    options: {
      title: PropTypes.string,
      format: PropTypes.oneOf(['markdown', 'html', 'plain']),
      maxLength: PropTypes.number
    },
    defaultOptions: {
      format: 'plain'
    }
  }
}
 | 
	import PropTypes from 'proptypes'
export default {
  any: {
    options: {
      of: PropTypes.array.isRequired
    },
    parse(options, typeBuilders, schema) {
      const containsTypes = options.of.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        if (!typeBuilder) {
          throw new Error(`Invalid type: ${typeDef.type}.`)
        }
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {of: containsTypes}
    }
  },
  reference: {
    primitive: 'string',
    options: {
      title: PropTypes.string,
      to: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.array
      ]).isRequired
    },
    parse(options, typeBuilders, schema) {
      const toTypeDefs = Array.isArray(options.to) ? options.to : [options.to]
      const toTypes = toTypeDefs.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {to: toTypes}
    }
  },
  text: {
    primitive: 'string',
    options: {
      title: PropTypes.string,
      format: PropTypes.oneOf(['markdown', 'html', 'plain']),
      maxLength: PropTypes.number
    },
    defaultOptions: {
      format: 'plain'
    }
  }
}
 | 
| 
	Move lexer whitespace check first | 
	<?php
namespace Igorw\Ilias;
class Lexer
{
    private $whitespace = [' ', "\t", "\r", "\n"];
    private $nonAtom = ['(', ')', ' ', "\t", "\r", "\n"];
    public function tokenize($code)
    {
        $tokens = [];
        for ($i = 0, $length = strlen($code); $i < $length; $i++) {
            $char = $code[$i];
            // kill whitespace
            if (in_array($char, $this->whitespace)) {
                continue;
            }
            // parens are single tokens
            if (in_array($char, ['(', ')'])) {
                $tokens[] = $char;
                continue;
            }
            // quote token (just the quote character)
            if ("'" === $char) {
                $tokens[] = $char;
                continue;
            }
            // atom token
            $atom = '';
            $next = $char;
            do {
                $atom .= $next;
                $next = ($length > $i+1) ? $code[$i+1] : null;
            } while (null !== $next && !in_array($next, $this->nonAtom) && ++$i);
            $tokens[] = $atom;
        }
        return $tokens;
    }
}
 | 
	<?php
namespace Igorw\Ilias;
class Lexer
{
    private $whitespace = [' ', "\t", "\r", "\n"];
    private $nonAtom = ['(', ')', ' ', "\t", "\r", "\n"];
    public function tokenize($code)
    {
        $tokens = [];
        for ($i = 0, $length = strlen($code); $i < $length; $i++) {
            $char = $code[$i];
            // parens are single tokens
            if (in_array($char, ['(', ')'])) {
                $tokens[] = $char;
                continue;
            }
            // kill whitespace
            if (in_array($char, $this->whitespace)) {
                continue;
            }
            // quote token (just the quote character)
            if ("'" === $char) {
                $tokens[] = $char;
                continue;
            }
            // atom token
            $atom = '';
            $next = $char;
            do {
                $atom .= $next;
                $next = ($length > $i+1) ? $code[$i+1] : null;
            } while (null !== $next && !in_array($next, $this->nonAtom) && ++$i);
            $tokens[] = $atom;
        }
        return $tokens;
    }
}
 | 
| 
	Add more test for svg | 
	var cheerio = require('cheerio');
var mock = require('./mock');
var AssetsInliner = require('../lib/output/assets-inliner');
describe('Assets Inliner Output', function() {
    describe('SVG', function() {
        var output;
        before(function() {
            var SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" version="1.1"><rect width="200" height="100" stroke="black" stroke-width="6" fill="green"/></svg>';
            return mock.outputDefaultBook(AssetsInliner, {
                'README.md': '',
                'inline.md': 'This is a svg: '+SVG,
                'test.svg': '<?xml version="1.0" encoding="UTF-8"?>' + SVG
            })
            .then(function(_output) {
                output = _output;
            });
        });
        it('should correctly SVG files convert to PNG', function() {
            var page = output.book.getPage('README.md');
            var $ = cheerio.load(page.content);
            // Is there an image?
            var $img = $('img');
            $img.length.should.equal(1);
            // Does the file exists
            var src = $img.attr('src');
            output.should.have.file(src);
        });
        it('should correctly inline SVG convert to PNG', function() {
            var page = output.book.addPage('README.md');
            var $ = cheerio.load(page.content);
            // Is there an image?
            var $img = $('img');
            $img.length.should.equal(1);
            // Does the file exists
            var src = $img.attr('src');
            output.should.have.file(src);
        });
    });
});
 | 
	var cheerio = require('cheerio');
var mock = require('./mock');
var AssetsInliner = require('../lib/output/assets-inliner');
describe('Assets Inliner Output', function() {
    describe('SVG', function() {
        var output;
        before(function() {
            return mock.outputDefaultBook(AssetsInliner, {
                'README.md': '',
                'test.svg': '<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" version="1.1"><rect width="200" height="100" stroke="black" stroke-width="6" fill="green"/></svg>'
            })
            .then(function(_output) {
                output = _output;
            });
        });
        it('should correctly convert to PNG', function() {
            var readme = output.book.getPage('README.md');
            var $ = cheerio.load(readme.content);
            // Is there an image?
            var $img = $('img');
            $img.length.should.equal(1);
            // Does the file exists
            var src = $img.attr('src');
            output.should.have.file(src);
        });
    });
});
 | 
| 
	Add undefined instead of nan if only one number | 
	inlist_module.directive('gdOnevarResults', function() { return {
    require:'^ngController', //input_list_ctrl
    templateUrl:'app/views/onevar_results_table.html',
    link: function(scope,elem,attrs,ctrl) {
        scope.$watch('inctrl.stats', function(stats) {
            document.getElementById('onevar_results_main').innerHTML
                = '';
            innerdivstring = '';
            keys = Object.keys(stats);
            for(i=0; i<keys.length; i++) {
                var row = document.createElement('tr');
                var detail_desc = document.createElement('td');
                detail_desc.innerHTML = (ctrl.detail_desc[keys[i]]);
                row.appendChild(detail_desc);
                var symbol_desc = document.createElement('td');
                symbol_desc.innerHTML = 
                    '<script type="math/tex">' 
                    + ctrl.symbolic_desc[keys[i]] + '</script>';
                row.appendChild(symbol_desc);
                var data = document.createElement('td');
                if(!stats[keys[i]] && stats[keys[i]] != 0) {
                    data.innerHTML = 'Undefined'
                } else {
                    data.innerHTML = '<script type="math/tex">' + 
                        stats[keys[i]] + '</script>';
                }
                row.appendChild(data);
                document.getElementById('onevar_results_main')
                    .appendChild(row);
            }
            MathJax.Hub.Queue(['Typeset',MathJax.Hub,'onevar_table_main']);
        },true);
    },
}});
 | 
	inlist_module.directive('gdOnevarResults', function() { return {
    require:'^ngController', //input_list_ctrl
    templateUrl:'app/views/onevar_results_table.html',
    link: function(scope,elem,attrs,ctrl) {
        scope.$watch('inctrl.stats', function(stats) {
            document.getElementById('onevar_results_main').innerHTML
                = '';
            innerdivstring = '';
            keys = Object.keys(stats);
            for(i=0; i<keys.length; i++) {
                var row = document.createElement('tr');
                var detail_desc = document.createElement('td');
                detail_desc.innerHTML = (ctrl.detail_desc[keys[i]]);
                row.appendChild(detail_desc);
                var symbol_desc = document.createElement('td');
                symbol_desc.innerHTML = 
                    '<script type="math/tex">' 
                    + ctrl.symbolic_desc[keys[i]] + '</script>';
                row.appendChild(symbol_desc);
                var data = document.createElement('td');
                data.innerHTML = '<script type="math/tex">' + 
                    stats[keys[i]] + '</script>';
                row.appendChild(data);
                document.getElementById('onevar_results_main')
                    .appendChild(row);
            }
            MathJax.Hub.Queue(['Typeset',MathJax.Hub,'onevar_table_main']);
        },true);
    },
}});
 | 
| 
	Use attribute object from state | 
	import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
export default class CopyButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.copyBtnRef = React.createRef();
    this.clipboardRef = React.createRef();
  }
  static defaultProps = {
    content: '',
  };
  state = {
    btnAttributes: {},
  };
  componentDidMount() {
    this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
      text: () => this.props.content,
    });
    this.clipboardRef.current.on('success', () => {
      const self = this;
      this.setState({
        btnAttributes: {
          'data-balloon': '複製成功!',
          'data-balloon-visible': '',
          'data-balloon-pos': 'up',
        }});
      setTimeout(function() {
        self.setState({ btnAttributes: {} });
      }, 1000);
    });
  }
  render() {
    return (
      <button
        ref={this.copyBtnRef}
        key="copy"
        onClick={() => {}}
        className="btn-copy"
        { ...this.state.btnAttributes }
      >
        複製到剪貼簿
        <style jsx>{`
          .btn-copy {
            margin-left: 10px;
          }
        `}</style>
      </button>
    );
  }
}
 | 
	import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
import levelNames from "../constants/levelNames";
export default class CopyButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.copyBtnRef = React.createRef();
    this.clipboardRef = React.createRef();
  }
  static defaultProps = {
    content: '',
  };
  componentDidMount() {
    this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
      text: () => this.props.content,
    });
    this.clipboardRef.current.on('success', () => {
      // this.setState({ isSuccessMsgShow: true });
      const copyBtnRef = this.copyBtnRef.current;
      copyBtnRef.setAttribute('data-balloon', '複製成功!');
      copyBtnRef.setAttribute('data-balloon-visible', '');
      copyBtnRef.setAttribute('data-balloon-pos', 'up');
      setTimeout(function() {
        copyBtnRef.removeAttribute('data-balloon');
        copyBtnRef.removeAttribute('data-balloon-visible');
        copyBtnRef.removeAttribute('data-balloon-pos');
      }, 3000);
    });
  }
  render() {
    return (
      <button
        ref={this.copyBtnRef}
        key="copy"
        onClick={() => {}}
        className="btn-copy"
      >
        複製到剪貼簿
        <style jsx>{`
          .btn-copy {
            margin-left: 10px;
          }
        `}</style>
      </button>
    );
  }
}
 | 
| 
	8: Create documentation of DataSource Settings 
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | 
	######
#  Create a file (html or markdown) with the output of
#      - JVMHeap
#      - LogFiles
#      - Ports
#      - Variables
#
#  Author:        Christoph Stoettner
#  Mail:          [email protected]
#  Documentation: http://scripting101.stoeps.de
#
#  Version:       2.0
#  Date:          2014-06-08
#
#  License:       Apache 2.0
#
# TODO: Create a menu for file selection
import sys
import os.path
filename = raw_input( 'Path and Filename to Documentation file: ' )
if (os.path.isfile( filename )):
            answer = raw_input( "File exists, Overwrite, Append or Abort? (O|A|X)" ).lower()
            if answer == "o":
                sys.stdout = open( filename, "w")
            elif answer == "a":
                sys.stdout = open( filename, "a")
            else:
                print "Exit"
                sys.exit()
print '# JVM Settings of all AppServers:'
execfile( 'ibmcnx/doc/JVMSettings.py' )
print '# Used Ports:'
execfile( 'ibmcnx/doc/Ports.py' )
print '# LogFile Settgins:'
execfile( 'ibmcnx/doc/LogFiles.py' )
print '# WebSphere Variables'
execfile( 'ibmcnx/doc/Variables.py' ) | 
	######
#  Create a file (html or markdown) with the output of
#      - JVMHeap
#      - LogFiles
#      - Ports
#      - Variables
#
#  Author:        Christoph Stoettner
#  Mail:          [email protected]
#  Documentation: http://scripting101.stoeps.de
#
#  Version:       2.0
#  Date:          2014-06-08
#
#  License:       Apache 2.0
#
# TODO: Create a menu for file selection
import sys
import os.path
filename = raw_input( 'Path and Filename to Documentation file: ' )
if (os.path.isfile( fileopen )):
            answer = raw_input( "File exists, Overwrite, Append or Abort? (O|A|X)" ).lower()
            if answer == "o":
                sys.stdout = open( filename, "w")
            elif answer == "a":
                sys.stdout = open( filename, "a")
            else:
                print "Exit"
                sys.exit()
print '# JVM Settings of all AppServers:'
execfile( 'ibmcnx/doc/JVMSettings.py' )
print '# Used Ports:'
execfile( 'ibmcnx/doc/Ports.py' )
print '# LogFile Settgins:'
execfile( 'ibmcnx/doc/LogFiles.py' )
print '# WebSphere Variables'
execfile( 'ibmcnx/doc/Variables.py' ) | 
| 
	Add process_id into the $state.go statements. Have chooseExistingProcess make a REST call to get the list of processes. | 
	(function (module) {
    module.controller('ProjectHomeController', ProjectHomeController);
    ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"];
    function ProjectHomeController(project, mcmodal, templates, $state, Restangular) {
        var ctrl = this;
        ctrl.project = project;
        ctrl.chooseTemplate = chooseTemplate;
        ctrl.chooseExistingProcess = chooseExistingProcess;
        ctrl.createSample = createSample;
        ctrl.useTemplate = useTemplate;
        ctrl.templates = templates;
        /////////////////////////
        function chooseTemplate() {
            mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
                $state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
            });
        }
        function useTemplate(templateName) {
            $state.go('projects.project.processes.create', {process: templateName, process_id: ''});
        }
        function createSample() {
            $state.go('projects.project.processes.create', {process: 'As Received', process_id: ''});
        }
        function chooseExistingProcess() {
            Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
                mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
                    var processName = existingProcess.process_name ? existingProcess.process_name : 'TEM';
                    $state.go('projects.project.processes.create', {process: processName, process_id: existingProcess.id});
                });
            });
        }
    }
}(angular.module('materialscommons')));
 | 
	(function (module) {
    module.controller('ProjectHomeController', ProjectHomeController);
    ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state"];
    function ProjectHomeController(project, mcmodal, templates, $state) {
        var ctrl = this;
        ctrl.project = project;
        ctrl.chooseTemplate = chooseTemplate;
        ctrl.chooseExistingProcess = chooseExistingProcess;
        ctrl.createSample = createSample;
        ctrl.useTemplate = useTemplate;
        ctrl.templates = templates;
        /////////////////////////
        function chooseTemplate() {
            mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
                $state.go('projects.project.processes.create', {process: processTemplateName});
            });
        }
        function useTemplate(templateName) {
            $state.go('projects.project.processes.create', {process: templateName});
        }
        function createSample() {
            $state.go('projects.project.processes.create', {process: 'As Received'});
        }
        function chooseExistingProcess() {
            mcmodal.chooseExistingProcess(ctrl.project).then(function (existingProcess) {
                $state.go('projects.project.processes.create', {process:  existingProcess.process_name, process_id: existingProcess.id});
            });
        }
    }
}(angular.module('materialscommons')));
 | 
| 
	Throw an uncaught exception if all docs failed | 
	<?php
namespace App;
use Exception;
use ScoutEngines\Elasticsearch\ElasticsearchEngine as BaseEngine;
class ElasticsearchEngine extends BaseEngine
{
    /**
     * Update the given model in the index.
     *
     * @param  Collection  $models
     * @return void
     */
    public function update($models)
    {
        $params['body'] = [];
        $models->each(function($model) use (&$params)
        {
            $params['body'][] = [
                'update' => $this->getIdIndexType($model)
            ];
            $params['body'][] = [
                'doc' => $model->toSearchableArray(),
                'doc_as_upsert' => true
            ];
        });
        $result = $this->elastic->bulk($params);
        // TODO: Requeue only the models that failed?
        if (isset($result['errors']) && $result['errors'] === true)
        {
            $failedDocs = array_values(array_filter($result['items'], function($item) {
                return isset($item['update']['error']);
            }));
            // If all docs failed, throw an uncaught exception
            if (count($failedDocs) === count($result['items']))
            {
                throw new Exception(json_encode($result));
            }
            foreach ($failedDocs as $doc)
            {
                try {
                    throw new Exception(json_encode($doc));
                } catch (Exception $e) {
                    // https://laravel.com/docs/5.7/errors - The `report` Helper
                    report($e);
                }
            }
        }
    }
}
 | 
	<?php
namespace App;
use Exception;
use ScoutEngines\Elasticsearch\ElasticsearchEngine as BaseEngine;
class ElasticsearchEngine extends BaseEngine
{
    /**
     * Update the given model in the index.
     *
     * @param  Collection  $models
     * @return void
     */
    public function update($models)
    {
        $params['body'] = [];
        $models->each(function($model) use (&$params)
        {
            $params['body'][] = [
                'update' => $this->getIdIndexType($model)
            ];
            $params['body'][] = [
                'doc' => $model->toSearchableArray(),
                'doc_as_upsert' => true
            ];
        });
        $result = $this->elastic->bulk($params);
        // TODO: Requeue only the models that failed?
        if (isset($result['errors']) && $result['errors'] === true)
        {
            $failedDocs = array_values(array_filter($result['items'], function($item) {
                return isset($item['update']['error']);
            }));
            foreach ($failedDocs as $doc)
            {
                try {
                    throw new Exception(json_encode($doc));
                } catch (Exception $e) {
                    // https://laravel.com/docs/5.7/errors - The `report` Helper
                    report($e);
                }
            }
        }
    }
}
 | 
| 
	Use BleCommunicationWin on CI tests | 
	import logging
import re
import sys
import os
from ruuvitag_sensor.url_decoder import UrlDecoder
_LOGGER = logging.getLogger(__name__)
macRegex = '[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$'
ruuviStart = 'ruuvi_'
if sys.platform.startswith('win') or os.environ.get('CI') == 'True':
    # Use BleCommunicationWin also for ci as can't use gattlib
    from ruuvitag_sensor.ble_communication import BleCommunicationWin
    ble = BleCommunicationWin()
else:
    from ruuvitag_sensor.ble_communication import BleCommunicationNix
    ble = BleCommunicationNix()
class RuuviTagSensor(object):
    def __init__(self, mac, name):
        if not re.match(macRegex, mac.lower()):
            raise ValueError('{} is not valid mac address'.format(mac))
        self._decoder = UrlDecoder()
        self._mac = mac
        self._state = {}
        self._name = name
    @property
    def mac(self):
        return self._mac
    @property
    def name(self):
        return self._name
    @property
    def state(self):
        return self._state
    def update(self):
        data = ble.get_data(self._mac)
        self._state = self._decoder.get_data(data)
        return self._state
    @staticmethod
    def find_ruuvitags():
        return [(address, name) for address, name in ble.find_ble_devices()
                if name.startswith(ruuviStart)]
 | 
	import logging
import re
import sys
from ruuvitag_sensor.url_decoder import UrlDecoder
_LOGGER = logging.getLogger(__name__)
macRegex = '[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$'
ruuviStart = 'ruuvi_'
if sys.platform.startswith('win'):
    from ruuvitag_sensor.ble_communication import BleCommunicationWin
    ble = BleCommunicationWin()
else:
    from ruuvitag_sensor.ble_communication import BleCommunicationNix
    ble = BleCommunicationNix()
class RuuviTagSensor(object):
    def __init__(self, mac, name):
        if not re.match(macRegex, mac.lower()):
            raise ValueError('{} is not valid mac address'.format(mac))
        self._decoder = UrlDecoder()
        self._mac = mac
        self._state = {}
        self._name = name
    @property
    def mac(self):
        return self._mac
    @property
    def name(self):
        return self._name
    @property
    def state(self):
        return self._state
    def update(self):
        data = ble.get_data(self._mac)
        self._state = self._decoder.get_data(data)
        return self._state
    @staticmethod
    def find_ruuvitags():
        return [(address, name) for address, name in ble.find_ble_devices()
                if name.startswith(ruuviStart)]
 | 
| 
	Stop button always visible when clock is running | 
	$(function(){
    var yourSound = new Audio('notification.ogg');
    yourSound.loop = true;
    $('.start button').click(function(ev){
        $('.start').toggleClass('hidden');
        $('.stop').toggleClass('hidden');
        $(".example").TimeCircles({
            "animation": "ticks",
            "count_past_zero": false,
            "circle_bg_color": "#f1f1f1",
            "time": {
                    Days: {
                    show: false
                },
                Hours: {
                    show: false
                },
                Minutes: {
                    color: "#1abc9c"
                },
                Seconds: {
                    color: "#e74c3c"
                }
            }
        }).addListener(function(unit, value, total){
            if(!total){
                yourSound.play();
            }
        });
    });
    $('.stop button').click(function(ev){
        yourSound.pause();
        $(".example").TimeCircles().destroy();
        $('.stop').toggleClass('hidden');
        $('.start').toggleClass('hidden');
    });
}); | 
	$(function(){
    var yourSound = new Audio('notification.ogg');
    yourSound.loop = true;
    $('.start button').click(function(ev){
        $('.start').toggleClass('hidden');
        $(".example").TimeCircles({
            "animation": "ticks",
            "count_past_zero": false,
            "circle_bg_color": "#f1f1f1",
            "time": {
                    Days: {
                    show: false
                },
                Hours: {
                    show: false
                },
                Minutes: {
                    color: "#1abc9c"
                },
                Seconds: {
                    color: "#e74c3c"
                }
            }
        }).addListener(function(unit, value, total){
            if(!total){
                yourSound.play();
                $('.stop').toggleClass('hidden');
            }
        });
    });
    $('.stop button').click(function(ev){
        yourSound.pause();
        $(".example").TimeCircles().destroy();
        $('.stop').toggleClass('hidden');
        $('.start').toggleClass('hidden');
    });
}); | 
| 
	Change expected result array which should be returned by the projects webservice. The test is still failing | 
	<?php
namespace fennecweb;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'listingProjectsTestUser';
    const USERID = 'listingProjectsTestUser';
    const PROVIDER = 'listingProjectsTestUser';
    public function testExecute()
    {
        //Test for error returned by user is not logged in
        list($service) = WebService::factory('listing/Projects');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array("error" => \fennecweb\ajax\listing\Projects::ERROR_NOT_LOGGED_IN);
        
        $this->assertEquals($expected, $results);
        
        //Test for correct project
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'listingProjectsTestUserToken'
        );
        list($service) = WebService::factory('listing/Projects');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array(
            array(
                "id" => "This is a Table ID",
                "import_date" => "2016-05-17 10:00:52.627236+00",
                "rows" => 10,
                "columns" => 5
            )
        );
        $this->assertEquals($expected, $results);
    }
}
 | 
	<?php
namespace fennecweb;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'listingProjectsTestUser';
    const USERID = 'listingProjectsTestUser';
    const PROVIDER = 'listingProjectsTestUser';
    public function testExecute()
    {
        //Test for error returned by user is not logged in
        list($service) = WebService::factory('listing/Projects');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array("error" => \fennecweb\ajax\listing\Projects::ERROR_NOT_LOGGED_IN);
        
        $this->assertEquals($expected, $results);
        
        //Test for correct project
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'listingProjectsTestUserToken'
        );
        list($service) = WebService::factory('listing/Projects');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array(
            array(
                "This is a Table ID",
                "2016-05-17 10:00:52.627236+00",
                10,
                5
            )
        );
        $this->assertEquals($expected, $results);
    }
}
 | 
| 
	Refactor init method with _blocks attribute | 
	"""A template for describing a Dakota experiment."""
import os
import importlib
class Experiment(object):
    """Describe parameters to create an input file for a Dakota experiment."""
    def __init__(self,
                 environment='environment',
                 method='vector_parameter_study',
                 variables='continuous_design',
                 interface='direct',
                 responses='response_functions',
                 **kwargs):
        """Create a set of default experiment parameters."""
        self._blocks = ('environment', 'method', 'variables',
                        'interface', 'responses')
        for section in self._blocks:
            cls = self._import(section, eval(section), **kwargs)
            setattr(self, section, cls)
    def _get_subpackage_namespace(self, subpackage):
        return os.path.splitext(self.__module__)[0] + '.' + subpackage
    def _import(self, subpackage, module, **kwargs):
        namespace = self._get_subpackage_namespace(subpackage) + '.' + module
        module = importlib.import_module(namespace)
        cls = getattr(module, module.classname)
        return cls(**kwargs)
    def __str__(self):
        s = '# Dakota input file\n'
        for section in self._blocks:
            s += str(getattr(self, section))
        return s
 | 
	"""A template for describing a Dakota experiment."""
import os
import importlib
import inspect
blocks = ['environment', 'method', 'variables', 'interface', 'responses']
class Experiment(object):
    """Describe parameters to create an input file for a Dakota experiment."""
    def __init__(self,
                 method='vector_parameter_study',
                 variables='continuous_design',
                 interface='direct',
                 responses='response_functions',
                 **kwargs):
        """Create a set of default experiment parameters."""
        self.environment = self._import('environment', 'environment', **kwargs)
        self.method = self._import('method', method, **kwargs)
        self.variables = self._import('variables', variables, **kwargs)
        self.interface = self._import('interface', interface, **kwargs)
        self.responses = self._import('responses', responses, **kwargs)
    def _get_subpackage_namespace(self, subpackage):
        return os.path.splitext(self.__module__)[0] + '.' + subpackage
    def _import(self, subpackage, module, **kwargs):
        namespace = self._get_subpackage_namespace(subpackage) + '.' + module
        module = importlib.import_module(namespace)
        cls = getattr(module, module.classname)
        return cls(**kwargs)
    def __str__(self):
        s = '# Dakota input file\n'
        for section in blocks:
            s += str(getattr(self, section))
        return s
 | 
| 
	Add test to cover container collisions | 
	(function() {
    var defur = require('../../../src/defur');
    var assert = require('chai').assert;
    suite('defur:', function() {
        var services = null;
        setup(function() {
            services = {};
        });
        test('`defur` is a function', function() {
            assert.isFunction(defur);
        });
        test('`defur` defers execution of definition', function() {
            defur('foo', services, function() {
                throw new Error('This should be deferred.');
            });
            assert.throws(function() {
                services.foo;
            });
        });
        test('`defur` creates the service only once', function() {
            defur('foo', services, function() {
                return {};
            });
            assert.strictEqual(services.foo, services.foo);
        });
        test('`defur` services don\'t collide', function() {
            defur('foo', services, function() {
                return {};
            });
            defur('bar', services, function() {
                return {};
            });
            assert.notEqual(services.foo, services.bar);
        });
        test('`defur` works with multiple service containers', function() {
            var otherServices = {};
            defur('foo', services, function() {
                return {};
            });
            defur('foo', otherServices, function() {
                return {};
            });
            assert.notEqual(services.foo, otherServices.foo);
        });
    });
})();
 | 
	(function() {
    var defur = require('../../../src/defur');
    var assert = require('chai').assert;
    suite('defur:', function() {
        var services = null;
        setup(function() {
            services = {};
        });
        test('`defur` is a function', function() {
            assert.isFunction(defur);
        });
        test('`defur` defers execution of definition', function() {
            defur('foo', services, function() {
                throw new Error('This should be deferred.');
            });
            assert.throws(function() {
                services.foo;
            });
        });
        test('`defur` creates the service only once', function() {
            defur('foo', services, function() {
                return {};
            });
            assert.strictEqual(services.foo, services.foo);
        });
        test('`defur` works with multiple service containers', function() {
            var otherServices = {};
            defur('foo', services, function() {
                return {};
            });
            defur('foo', otherServices, function() {
                return {};
            });
            assert.notEqual(services.foo, otherServices.foo);
        });
    });
})();
 | 
| 
	Use date as formatting type
Date is a formatting type instead of a real one. This seems to work. | 
	'use strict';
module.exports = {
    'required': [
        'sender',
        'receiver',
        'items',
        'due',
        'paymentDays'
    ],
    'properties': {
        'id': require('../id'),
        'invoiceId': {
            'type': 'number',
            'description': 'Unique invoice id generated internally by the backend',
            'readOnly': true
        },
        'status': {
            '$ref': '#/definitions/InvoiceStatus',
            'readOnly': true
        },
        'sender': {
            '$ref': '#/definitions/User'
        },
        'receiver': {
            '$ref': '#/definitions/Client'
        },
        'items': {
            'type': 'array',
            'description': 'Billable items attached to the invoice',
            'minItems': 1,
            'items': {
                '$ref': '#/definitions/InvoiceItem'
            }
        },
        'due': {
            'type': 'string',
            'format': 'date',
            'description': 'Day in which the invoice is due'
        },
        'paymentDays': {
            'type': 'number',
            'description': 'Amount of days to pay the bill',
            'default': 8
        }
    }
};
 | 
	'use strict';
module.exports = {
    'required': [
        'sender',
        'receiver',
        'items',
        'due',
        'paymentDays'
    ],
    'properties': {
        'id': require('../id'),
        'invoiceId': {
            'type': 'number',
            'description': 'Unique invoice id generated internally by the backend',
            'readOnly': true
        },
        'status': {
            '$ref': '#/definitions/InvoiceStatus',
            'readOnly': true
        },
        'sender': {
            '$ref': '#/definitions/User'
        },
        'receiver': {
            '$ref': '#/definitions/Client'
        },
        'items': {
            'type': 'array',
            'description': 'Billable items attached to the invoice',
            'minItems': 1,
            'items': {
                '$ref': '#/definitions/InvoiceItem'
            }
        },
        'due': {
            'type': 'string', // XXX: should be date
            'description': 'Day in which the invoice is due'
        },
        'paymentDays': {
            'type': 'number',
            'description': 'Amount of days to pay the bill',
            'default': 8
        }
    }
};
 | 
| 
	[api] Update user session profile when self updating | 
	package io.openex.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import io.openex.database.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component
@EnableAsync
public class AppConfig {
    private final static String ANONYMOUS_USER = "anonymousUser";
    // Validations
    public final static String MANDATORY_MESSAGE = "This value should not be blank.";
    public static User currentUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (ANONYMOUS_USER.equals(principal)) {
            User anonymousUser = new User();
            anonymousUser.setId("anonymous");
            anonymousUser.setEmail("[email protected]");
            return anonymousUser;
        }
        assert principal instanceof User;
        return (User) principal;
    }
    public static void updateSessionUser(User user) {
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    @Bean
    ObjectMapper openexJsonMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
        mapper.registerModule(new Hibernate5Module());
        return mapper;
    }
}
 | 
	package io.openex.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import io.openex.database.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component
@EnableAsync
public class AppConfig {
    private final static String ANONYMOUS_USER = "anonymousUser";
    // Validations
    public final static String MANDATORY_MESSAGE = "This value should not be blank.";
    public static User currentUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (ANONYMOUS_USER.equals(principal)) {
            User anonymousUser = new User();
            anonymousUser.setId("anonymous");
            anonymousUser.setEmail("[email protected]");
            return anonymousUser;
        }
        assert principal instanceof User;
        return (User) principal;
    }
    @Bean
    ObjectMapper openexJsonMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
        mapper.registerModule(new Hibernate5Module());
        return mapper;
    }
}
 | 
| 
	Test that output is being passed to load method | 
	<?php
class CM_Provision_LoaderTest extends CMTest_TestCase {
    public function testLoad() {
        $serviceManager = new CM_Service_Manager();
        $outputStream = new CM_OutputStream_Null();
        $script = $this->mockObject('CM_Provision_Script_Abstract');
        $loadMethod = $script->mockMethod('load')->set(function (CM_Service_Manager $manager, $output) use ($serviceManager, $outputStream) {
            $this->assertSame($serviceManager, $manager);
            $this->assertSame($outputStream, $output);
        });
        /** @var CM_Provision_Script_Abstract $script */
        $loader = new CM_Provision_Loader($outputStream);
        $loader->setServiceManager($serviceManager);
        $loader->registerScript($script);
        $loader->load();
        $this->assertSame(1, $loadMethod->getCallCount());
    }
    public function testGetScriptList() {
        $script1 = $this->mockObject('CM_Provision_Script_Abstract');
        $script2 = $this->mockObject('CM_Provision_Script_Abstract');
        $script2->mockMethod('getRunLevel')->set(10);
        $script3 = $this->mockObject('CM_Provision_Script_Abstract');
        $script3->mockMethod('getRunLevel')->set(1);
        $loader = new CM_Provision_Loader();
        $loader->registerScript($script1);
        $loader->registerScript($script2);
        $loader->registerScript($script3);
        $scriptList = CMTest_TH::callProtectedMethod($loader, '_getScriptList');
        $expected = [$script3, $script1, $script2];
        $this->assertSame($expected, $scriptList);
    }
}
 | 
	<?php
class CM_Provision_LoaderTest extends CMTest_TestCase {
    public function testLoad() {
        $serviceManager = new CM_Service_Manager();
        $script = $this->mockObject('CM_Provision_Script_Abstract');
        $loadMethod = $script->mockMethod('load')->set(function (CM_Service_Manager $manager) use ($serviceManager) {
            $this->assertSame($serviceManager, $manager);
        });
        /** @var CM_Provision_Script_Abstract $script */
        $loader = new CM_Provision_Loader();
        $loader->setServiceManager($serviceManager);
        $loader->registerScript($script);
        $loader->load();
        $this->assertSame(1, $loadMethod->getCallCount());
    }
    public function testGetScriptList() {
        $script1 = $this->mockObject('CM_Provision_Script_Abstract');
        $script2 = $this->mockObject('CM_Provision_Script_Abstract');
        $script2->mockMethod('getRunLevel')->set(10);
        $script3 = $this->mockObject('CM_Provision_Script_Abstract');
        $script3->mockMethod('getRunLevel')->set(1);
        $loader = new CM_Provision_Loader();
        $loader->registerScript($script1);
        $loader->registerScript($script2);
        $loader->registerScript($script3);
        $scriptList = CMTest_TH::callProtectedMethod($loader, '_getScriptList');
        $expected = [$script3, $script1, $script2];
        $this->assertSame($expected, $scriptList);
    }
}
 | 
| 
	Remove return types for now | 
	<?php namespace Lecturize\Taxonomies\Traits;
use Lecturize\Taxonomies\Models\Taxonomy;
use Lecturize\Taxonomies\Models\Term;
/**
 * Class ModelFinder
 * @package Lecturize\Taxonomies\Traits
 */
trait ModelFinder
{
    /**
     * Find term by slug.
     *
     * @param  string  $slug
     * @return Term
     */
    public function findTerm(string $slug)
    {
        return Term::whereSlug($slug)->first();
    }
    /**
     * Find taxonomy by term id.
     *
     * @param  int     $term_id
     * @param  string  $taxonomy
     * @return Taxonomy
     */
    public function findTaxonomyByTerm(int $term_id, string $taxonomy)
    {
        return $this->findCategory($term_id, $taxonomy, 'id');
    }
    /**
     * Find category by term (category title) and taxonomy.
     *
     * @param  string|int  $term
     * @param  string      $taxonomy
     * @param  string      $term_field
     * @return Taxonomy
     */
    public function findCategory($term, string $taxonomy, string $term_field = 'title')
    {
        return Taxonomy::taxonomy($taxonomy)
                       ->term($term, $term_field)
                       ->first();
    }
} | 
	<?php namespace Lecturize\Taxonomies\Traits;
use Lecturize\Taxonomies\Models\Taxonomy;
use Lecturize\Taxonomies\Models\Term;
/**
 * Class ModelFinder
 * @package Lecturize\Taxonomies\Traits
 */
trait ModelFinder
{
    /**
     * Find term by slug.
     *
     * @param  string  $slug
     * @return Term
     */
    public function findTerm(string $slug): Term
    {
        return Term::whereSlug($slug)->first();
    }
    /**
     * Find taxonomy by term id.
     *
     * @param  int     $term_id
     * @param  string  $taxonomy
     * @return Taxonomy
     */
    public function findTaxonomyByTerm(int $term_id, string $taxonomy): Taxonomy
    {
        return $this->findCategory($term_id, $taxonomy, 'id');
    }
    /**
     * Find category by term (category title) and taxonomy.
     *
     * @param  string|int  $term
     * @param  string      $taxonomy
     * @param  string      $term_field
     * @return Taxonomy
     */
    public function findCategory($term, string $taxonomy, string $term_field = 'title'): Taxonomy
    {
        return Taxonomy::taxonomy($taxonomy)
                       ->term($term, $term_field)
                       ->first();
    }
} | 
| 
	Set sample times to every 5 minutes.
Show the time of a timeout. | 
	"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
[email protected]
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
# number of seconds between samples, set to zero to run once and exit
sample_seconds = 60 * 5
def main():
    print("started")
    while True:
        try:
            watts = watts_generated()
            now = time.strftime("%H:%M:%S")
            line = "%s\t%s\n" % (now, watts)
            # print(line)
            write_to_logfile(line)
        except requests.exceptions.ConnectTimeout:
            print("Connect timeout at %s" % time.strftime("%H:%M:%S"))
        if sample_seconds > 0:
            time.sleep(sample_seconds)
        else:
            return
def write_to_logfile(line):
    today = time.strftime("%Y_%m_%d")
    file_name = today + ".csv"
    out_file = open(file_name, "a")
    out_file.write(line)
    out_file.close()
def watts_generated():
    url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
    r = requests.get(url, timeout=2)
    json_data = r.json()
    result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
    return result
if __name__ == "__main__":
    main()
 | 
	"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
[email protected]
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60  # how many seconds between samples, set to zero to run once and exit
def main():
    print("started")
    while True:
        try:
            watts = watts_generated()
            now = time.strftime("%H:%M:%S")
            line = "%s\t%s\n" % (now, watts)
            # print(line)
            write_to_logfile(line)
        except requests.exceptions.ConnectTimeout:
            print("Connect timeout")
        if sample_seconds > 0:
            time.sleep(sample_seconds)
        else:
            return
def write_to_logfile(line):
    today = time.strftime("%Y_%m_%d")
    file_name = today + ".csv"
    out_file = open(file_name, "a")
    out_file.write(line)
    out_file.close()
def watts_generated():
    url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
    r = requests.get(url, timeout=2)
    json_data = r.json()
    result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
    return result
if __name__ == "__main__":
    main()
 | 
| 
	Fix data log fixture foreign keys | 
	from django.core.management.base import BaseCommand
from django.core import serializers
from data_log import models
import json
class Command(BaseCommand):
    help = 'Create Data Log Report fixtures'
    def handle(self, *args, **kwargs):
        self.stdout.write(self.style.HTTP_INFO('Creating fixtures for Data Log Reports...'))
        JSONSerializer = serializers.get_serializer("json")
        j = JSONSerializer()
        data = []
        models_to_serialize = [
            models.LevelReport, 
            models.SummonReport, 
            models.MagicShopRefreshReport, 
            models.MagicBoxCraftingReport, 
            models.WishReport, 
            models.RuneCraftingReport
        ]
        pks = []
        for model in models_to_serialize:
            self.stdout.write(self.style.WARNING(model.__name__))
            serialized_data = json.loads(j.serialize(model.objects.order_by('-generated_on')[:100]))
            pks += [d['pk'] for d in serialized_data]
            data += serialized_data
        
        self.stdout.write(self.style.WARNING(models.Report.__name__))
        reports = json.loads(j.serialize(models.Report.objects.order_by('-generated_on')[:100]))
        self.stdout.write(self.style.HTTP_INFO("Finishing special reports..."))
        reports += json.loads(j.serialize(models.Report.objects.filter(pk__in=pks)))
        data = reports + data
        self.stdout.write(self.style.HTTP_INFO('Saving fixtures to file'))
        with open("fixture_reports.json", "w+") as f:
            json.dump(data, f)
        self.stdout.write(self.style.SUCCESS('Done!'))
 | 
	from django.core.management.base import BaseCommand
from django.core import serializers
from data_log import models
import json
class Command(BaseCommand):
    help = 'Create Data Log Report fixtures'
    def handle(self, *args, **kwargs):
        self.stdout.write(self.style.HTTP_INFO('Creating fixtures for Data Log Reports...'))
        JSONSerializer = serializers.get_serializer("json")
        j = JSONSerializer()
        data = []
        models_to_serialize = [
            models.LevelReport, 
            models.SummonReport, 
            models.MagicShopRefreshReport, 
            models.MagicBoxCraftingReport, 
            models.WishReport, 
            models.RuneCraftingReport
        ]
        for model in models_to_serialize:
            self.stdout.write(self.style.WARNING(model.__name__))
            data += json.loads(j.serialize(model.objects.order_by('-generated_on')[:100]))
        
        self.stdout.write(self.style.WARNING(models.Report.__name__))
        data += json.loads(j.serialize(models.Report.objects.order_by('-generated_on')[:1000]))
        with open("fixture_reports.json", "w+") as f:
            json.dump(data, f)
        self.stdout.write(self.style.SUCCESS('Done!'))
 | 
| 
	Add gridImageId to continueReading fragments | 
	import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import { getFragment } from 'meteor/vulcan:core';
export const withContinueReading = component => {
  // FIXME: For some unclear reason, using a ...fragment in the 'sequence' part
  // of this query doesn't work (leads to a 400 Bad Request), so this is expanded
  // out to a short list of individual fields.
  const continueReadingQuery = gql`
    query ContinueReadingQuery {
      ContinueReading {
        sequence {
          _id
          title
          gridImageId
          canonicalCollectionSlug
        }
        collection {
          _id
          title
          slug
          gridImageId
        }
        lastReadPost {
          ...PostsList
        }
        nextPost {
          ...PostsList
        }
        numRead
        numTotal
        lastReadTime
      }
    }
    ${getFragment("PostsList")}
  `;
  return graphql(continueReadingQuery,
    {
      alias: "withContinueReading",
      options: (props) => ({
        variables: {}
      }),
      props(props) {
        return {
          continueReadingLoading: props.data.loading,
          continueReading: props.data.ContinueReading,
        }
      }
    }
  )(component);
}
 | 
	import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import { getFragment } from 'meteor/vulcan:core';
export const withContinueReading = component => {
  // FIXME: For some unclear reason, using a ...fragment in the 'sequence' part
  // of this query doesn't work (leads to a 400 Bad Request), so this is expanded
  // out to a short list of individual fields.
  const continueReadingQuery = gql`
    query ContinueReadingQuery {
      ContinueReading {
        sequence {
          _id
          title
          gridImageId
          canonicalCollectionSlug
        }
        collection {
          _id
          title
          slug
        }
        lastReadPost {
          ...PostsList
        }
        nextPost {
          ...PostsList
        }
        numRead
        numTotal
        lastReadTime
      }
    }
    ${getFragment("PostsList")}
  `;
  return graphql(continueReadingQuery,
    {
      alias: "withContinueReading",
      options: (props) => ({
        variables: {}
      }),
      props(props) {
        return {
          continueReadingLoading: props.data.loading,
          continueReading: props.data.ContinueReading,
        }
      }
    }
  )(component);
}
 | 
| 
	Allow additional response states (queued, downloading, processing) | 
	import Ember from 'ember';
export default Ember.Route.extend({
  createFeedFromGtfsService: Ember.inject.service('create-feed-from-gtfs'),
  beforeModel: function(transition) {
    var controller = this;
    var feedModel = this.get('createFeedFromGtfsService').feedModel;
    var url = feedModel.get('url');
    var adapter = this.get('store').adapterFor('feeds');
    var fetch_info_url = adapter.urlPrefix()+'/feeds/fetch_info';
    var promise = adapter.ajax(fetch_info_url, 'post', {data:{url:url}});
    promise.then(function(response) {
      if (response.status == 'complete') {
        feedModel.set('id', response.feed.onestop_id);
        feedModel.set('operators_in_feed', response.feed.operators_in_feed);
        response.operators.map(function(operator){feedModel.addOperator(operator)});
        return feedModel;
      } else {
        transition.abort();
        return Ember.run.later(controller, function(){
          transition.retry();
        }, 1000);
      }
    }).catch(function(error) {
      error.errors.forEach(function(error){
        feedModel.get('errors').add('url', error.message);
      });
    });
    return promise;
  },
  model: function() {
    return this.get('createFeedFromGtfsService').feedModel;
  },
  actions: {
    error: function(error, transition) {
      return this.transitionTo('feeds.new');
    }
  }
});
 | 
	import Ember from 'ember';
export default Ember.Route.extend({
  createFeedFromGtfsService: Ember.inject.service('create-feed-from-gtfs'),
  beforeModel: function(transition) {
    var controller = this;
    var feedModel = this.get('createFeedFromGtfsService').feedModel;
    var url = feedModel.get('url');
    var adapter = this.get('store').adapterFor('feeds');
    var fetch_info_url = adapter.urlPrefix()+'/feeds/fetch_info';
    var promise = adapter.ajax(fetch_info_url, 'post', {data:{url:url}});
    promise.then(function(response) {
      if (response.status == 'complete') {
        feedModel.set('id', response.feed.onestop_id);
        feedModel.set('operators_in_feed', response.feed.operators_in_feed);
        response.operators.map(function(operator){feedModel.addOperator(operator)});
        return feedModel;
      } else if (response.status == 'processing') {
        transition.abort();
        return Ember.run.later(controller, function(){
          transition.retry();
        }, 1000);
      }
    }).catch(function(error) {
      error.errors.forEach(function(error){
        feedModel.get('errors').add('url', error.message);  
      });
    });
    return promise;
  },
  model: function() {
    return this.get('createFeedFromGtfsService').feedModel;
  },
  actions: {
    error: function(error, transition) {
      return this.transitionTo('feeds.new');
    }
  }
});
 | 
| 
	Make sure the auth middleware returns
Thus not breaking the chain of middleware return values | 
	import { REHYDRATE } from 'redux-persist/constants'
import {
  refreshAuthenticationToken,
  scheduleAuthRefresh,
} from '../actions/authentication'
import { AUTHENTICATION } from '../constants/action_types'
const toMilliseconds = seconds => seconds * 1000
// Get a timeout value about 100ms before a given date,
// or at least not in the past
const futureTimeout = time => {
  let msFromNow = time - new Date()
  // Establish a lead time of 100ms before expiration date
  msFromNow = msFromNow - 100
  // Let's not set a timeout for in the past
  return Math.max(msFromNow, 0)
}
export const authentication = store => next => action => {
  const { payload, type } = action
  switch (type) {
    case REHYDRATE:
      if (action.key === 'authentication') {
        const { createdAt, expiresIn, refreshToken } = payload
        if (!refreshToken) break
        const now = new Date()
        const expirationDate = new Date(toMilliseconds(createdAt + expiresIn))
        if (expirationDate < now) {
          store.dispatch(refreshAuthenticationToken(refreshToken))
        } else {
          const newTimeout = futureTimeout(expirationDate)
          store.dispatch(scheduleAuthRefresh(refreshToken, newTimeout))
        }
      }
      break
    case AUTHENTICATION.REFRESH_SUCCESS:
    case AUTHENTICATION.USER_SUCCESS:
      store.dispatch(scheduleAuthRefresh(
        payload.response.refreshToken,
        toMilliseconds(7100)
      ))
      break
    default:
      break
  }
  return next(action)
}
 | 
	import { REHYDRATE } from 'redux-persist/constants'
import {
  refreshAuthenticationToken,
  scheduleAuthRefresh,
} from '../actions/authentication'
import { AUTHENTICATION } from '../constants/action_types'
const toMilliseconds = seconds => seconds * 1000
// Get a timeout value about 100ms before a given date,
// or at least not in the past
const futureTimeout = time => {
  let msFromNow = time - new Date()
  // Establish a lead time of 100ms before expiration date
  msFromNow = msFromNow - 100
  // Let's not set a timeout for in the past
  return Math.max(msFromNow, 0)
}
export const authentication = store => next => action => {
  const { payload, type } = action
  switch (type) {
    case REHYDRATE:
      if (action.key === 'authentication') {
        const { createdAt, expiresIn, refreshToken } = payload
        if (!refreshToken) break
        const now = new Date()
        const expirationDate = new Date(toMilliseconds(createdAt + expiresIn))
        if (expirationDate < now) {
          store.dispatch(refreshAuthenticationToken(refreshToken))
        } else {
          const newTimeout = futureTimeout(expirationDate)
          store.dispatch(scheduleAuthRefresh(refreshToken, newTimeout))
        }
      }
      break
    case AUTHENTICATION.REFRESH_SUCCESS:
    case AUTHENTICATION.USER_SUCCESS:
      store.dispatch(scheduleAuthRefresh(
        payload.response.refreshToken,
        toMilliseconds(7100)
      ))
      break
    default:
      break
  }
  next(action)
}
 | 
| 
	Fix layer model serialize method to use new organization | 
	cinema.models.LayerModel = Backbone.Model.extend({
    constructor: function (defaults, options) {
        Backbone.Model.call(this, {}, options);
        if (typeof defaults === 'string') {
            this.setFromString(defaults);
        } else if (defaults) {
            this.set('state', defaults);
        }
    },
    /**
     * Convert an object that maps layer identifiers to color-by values into
     * a single string that is consumable by other parts of the application.
     */
    serialize: function () {
        var query = '';
        _.each(this.get('state'), function (v, k) {
            query += k + v;
        });
        return query;
    },
    /**
     * Convert a query string to an object that maps layer identifiers to
     * their color-by value. The query string is a sequence of two-character
     * pairs, where the first character identifies the layer ID and the second
     * character identifies which field it should be colored by.
     *
     * The query string is then saved to the model.
     */
    unserialize: function (query) {
        var obj = {};
        if (query.length % 2) {
            return console.error('Query string "' + query + '" has odd length.');
        }
        for (var i = 0; i < query.length; i += 2) {
            obj[query[i]] = query[i + 1];
        }
        return obj;
    },
    /**
     * Set the layers by a "query string".
     */
    setFromString: function (query) {
        var obj = this.unserialize(query);
        this.set('state', obj);
    }
});
 | 
	cinema.models.LayerModel = Backbone.Model.extend({
    constructor: function (defaults, options) {
        Backbone.Model.call(this, {}, options);
        if (typeof defaults === 'string') {
            this.setFromString(defaults);
        } else if (defaults) {
            this.set('state', defaults);
        }
    },
    /**
     * Convert an object that maps layer identifiers to color-by values into
     * a single string that is consumable by other parts of the application.
     */
    serialize: function () {
        var query = '';
        _.each(this.attributes, function (v, k) {
            query += k + v;
        });
        return query;
    },
    /**
     * Convert a query string to an object that maps layer identifiers to
     * their color-by value. The query string is a sequence of two-character
     * pairs, where the first character identifies the layer ID and the second
     * character identifies which field it should be colored by.
     *
     * The query string is then saved to the model.
     */
    unserialize: function (query) {
        var obj = {};
        if (query.length % 2) {
            return console.error('Query string "' + query + '" has odd length.');
        }
        for (var i = 0; i < query.length; i += 2) {
            obj[query[i]] = query[i + 1];
        }
        return obj;
    },
    /**
     * Set the layers by a "query string".
     */
    setFromString: function (query) {
        var obj = this.unserialize(query);
        this.set('state', obj);
    }
});
 | 
| 
	Include attach method in DummyOperation | 
	from hoomd.triggers import Trigger
from hoomd.meta import _Operation, _TriggeredOperation
class DummySimulation:
    def __init__(self):
        self.state = DummyState()
        self.operations = DummyOperations()
        self._cpp_sys = DummySystem()
class DummySystem:
    def __init__(self):
        self.dummy_list = []
class DummyState:
    def __init__(self):
        pass
    @property
    def particle_types(self):
        return ['A', 'B']
class DummyOperations:
    pass
class DummyCppObj:
    def __init__(self):
        self._dict = dict()
    def setTypeParam(self, type_, value):
        self._dict[type_] = value
    def getTypeParam(self, type_):
        return self._dict[type_]
    @property
    def param1(self):
        return self._param1
    @param1.setter
    def param1(self, value):
        self._param1 = value
    @property
    def param2(self):
        return self._param2
    @param2.setter
    def param2(self, value):
        self._param2 = value
class DummyOperation(_Operation):
    '''Requires that user manually add param_dict and typeparam_dict items.
    This is for testing purposes.
    '''
    def attach(self, simulation):
        self._cpp_obj = "cpp obj"
class DummyTriggeredOp(_TriggeredOperation):
    _cpp_list_name = 'dummy_list'
class DummyTrigger(Trigger):
    def __call__(self, ts):
        return True
 | 
	from hoomd.triggers import Trigger
from hoomd.meta import _Operation, _TriggeredOperation
class DummySimulation:
    def __init__(self):
        self.state = DummyState()
        self.operations = DummyOperations()
        self._cpp_sys = DummySystem()
class DummySystem:
    def __init__(self):
        self.dummy_list = []
class DummyState:
    def __init__(self):
        pass
    @property
    def particle_types(self):
        return ['A', 'B']
class DummyOperations:
    pass
class DummyCppObj:
    def __init__(self):
        self._dict = dict()
    def setTypeParam(self, type_, value):
        self._dict[type_] = value
    def getTypeParam(self, type_):
        return self._dict[type_]
    @property
    def param1(self):
        return self._param1
    @param1.setter
    def param1(self, value):
        self._param1 = value
    @property
    def param2(self):
        return self._param2
    @param2.setter
    def param2(self, value):
        self._param2 = value
class DummyOperation(_Operation):
    '''Requires that user manually add param_dict and typeparam_dict items.
    This is for testing purposes.
    '''
    pass
class DummyTriggeredOp(_TriggeredOperation):
    _cpp_list_name = 'dummy_list'
class DummyTrigger(Trigger):
    def __call__(self, ts):
        return True
 | 
| 
	Remove userReadinfo and evenSchedule objects. | 
	var base = require('./base.js');
exports.assemble = {
    addSchedule: 
        function (parameters, response) {
            var userEventEntry = { 
                availability: JSON.stringify(parameters.availability),
                Users_id: parameters.usersid, 
                Events_id: parameters.eventsid
            };
            base.dbInsert('userevents', userEventEntry, response);
        },
    
    addUser:
        function(parameters, response){
            var userEntry = {
                name: parameters.userName,
                password: parameters.userPassword,
                email: parameters.userEmail,
                default_availability: JSON.stringify(parameters.availability)
            };
            base.dbInsert('users',userEntry,response);
        },
    
    viewUser:
        function (parameters , response) {
            var queryString = 
                'SELECT * FROM Users WHERE id = ' +  parameters.usersid;
            base.dbSelect(queryString, response);
        },
    
    viewEventSchedules: // View all the schedules in an appointed event
        function (parameters, response) {
            var queryString = 
                'SELECT start_date, end_date FROM Events WHERE id = ' + parameters.eventsid;
            base.dbSelect(queryString, response);
        },
    
    addEvent:
        function (parameters, response) {
            var eventEntry = { 
                                name: parameters.eventName,
                                start_date: parameters.eventStartDate, 
                                end_date: parameters.eventEndDate,
                                description: parameters.eventDescription
                            };
            base.dbInsert('events', eventEntry, response);
        }        
}  | 
	var base = require('./base.js');
exports.assemble = {
    addSchedule: 
        function (parameters, response) {
            var userEventEntry = { 
                availability: JSON.stringify(parameters.availability),
                Users_id: parameters.usersid, 
                Events_id: parameters.eventsid
            };
            base.dbInsert('userevents', userEventEntry, response);
        },
    
    addUser:
        function(parameters, response){
            var userEntry = {
                name: parameters.userName,
                password: parameters.userPassword,
                email: parameters.userEmail,
                default_availability: JSON.stringify(parameters.availability)
            };
            base.dbInsert('users',userEntry,response);
        },
    
    viewUser:
        function (parameters , response) {
            var userReadInfo = { 
                Users_id: parameters.usersid 
            };
            var queryString = 
                'SELECT * FROM Users WHERE id = ' +  userReadInfo;
            // dbSelect function uses queryString and responds back with DB data in a JSON format(?)
            base.dbSelect(queryString, response);
        },
    
    viewEventSchedules: // View all the schedules in an appointed event
        function (parameters, response) {
            var eventSchedules = {
                 Events_id: parameters.eventsid
            };
         
            var queryString = 
                'SELECT start_date, end_date FROM Events WHERE id = ' + eventSchedules;
            base.dbSelect(queryString, response);
        },
    
    addEvent:
        function (parameters, response) {
            var eventEntry = { 
                                name: parameters.eventName,
                                start_date: parameters.eventStartDate, 
                                end_date: parameters.eventEndDate,
                                description: parameters.eventDescription
                            };
            base.dbInsert('events', eventEntry, response);
        }        
}  | 
| 
	Fix filenames of DisableLoadBalancerForAgents and EnableLoadBalancerForAgents | 
	/*******************************************************************************
* Copyright (C) 2012 eBay Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/* jshint -W074 */
define([
    "require",
    "when/sequence",
    "./DisableLoadBalancerForAgents",
    "./EnableLoadBalancerForAgents",
    "./Deploy",
    "./Prompt",
    "./Verify",
    "./CheckVerifyResult",
    "./DeployAndCheckVerifyResult",
    "./VerifyAndCheckResult"
],
function(require, sequence) {
    var _getTask = function (taskName) {
        return require('./' + taskName);
    };
    var tasks = {
        createTask: function (data) {
            return function() {
                var tasks = [];
                var task = _getTask(data.name);
                tasks.push(task.execute(data));
                return sequence(tasks);
            };
        },
        getTaskInformation: function (taskName) {
            var task = _getTask(taskName);
            return task.getInfo();
        }
    };
    return tasks;
});
 | 
	/*******************************************************************************
* Copyright (C) 2012 eBay Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/* jshint -W074 */
define([
    "require",
    "when/sequence",
    "./DisableLoadbalancerForAgents",
    "./EnableLoadbalancerForAgents",
    "./Deploy",
    "./Prompt",
    "./Verify",
    "./CheckVerifyResult",
    "./DeployAndCheckVerifyResult",
    "./VerifyAndCheckResult"
],
function(require, sequence) {
    var _getTask = function (taskName) {
        return require('./' + taskName);
    };
    var tasks = {
        createTask: function (data) {
            return function() {
                var tasks = [];
                var task = _getTask(data.name);
                tasks.push(task.execute(data));
                return sequence(tasks);
            };
        },
        getTaskInformation: function (taskName) {
            var task = _getTask(taskName);
            return task.getInfo();
        }
    };
    return tasks;
});
 | 
| 
	Fix unit test assertion for number of pre-included apps | 
	window = {};
var assert = require('assert');
var model = require('../../lib/model')({
    memory: true,
    noConnect: true
});
describe('Model', function () {
    describe('interface', function () {
        it('should expose expected objects', function () {
            assert.equal(typeof model.history, 'object');
            assert.equal(typeof model.user, 'object');
            assert.equal(typeof model.apps, 'object');
        });
        it('should expose expected functions', function () {
            assert.equal(typeof model.restore, 'function');
            assert.equal(typeof model.save, 'function');
            assert.equal(typeof model.observe, 'function');
        });
    });
    describe('first run', function () {
        it('should have the expected history', function () {
            assert.deepEqual(model.history, {
                ftu: true,
                path: '/ftu'
            });
        });
        it('should have the expected user', function () {
            // @todo
            assert.deepEqual(model.user, {
                name: null,
                location: null,
                avatar: null
            });
        });
        it('should have the expected apps', function () {
            // @todo
            assert.equal(model.apps.length, 0);
        });
    });
});
 | 
	window = {};
var assert = require('assert');
var model = require('../../lib/model')({
    memory: true,
    noConnect: true
});
describe('Model', function () {
    describe('interface', function () {
        it('should expose expected objects', function () {
            assert.equal(typeof model.history, 'object');
            assert.equal(typeof model.user, 'object');
            assert.equal(typeof model.apps, 'object');
        });
        it('should expose expected functions', function () {
            assert.equal(typeof model.restore, 'function');
            assert.equal(typeof model.save, 'function');
            assert.equal(typeof model.observe, 'function');
        });
    });
    describe('first run', function () {
        it('should have the expected history', function () {
            assert.deepEqual(model.history, {
                ftu: true,
                path: '/ftu'
            });
        });
        it('should have the expected user', function () {
            // @todo
            assert.deepEqual(model.user, {
                name: null,
                location: null,
                avatar: null
            });
        });
        it('should have the expected apps', function () {
            // @todo
            assert.equal(model.apps.length, 1);
        });
    });
});
 | 
| 
	Add div.clearfix to ensure links work in phone mode | 
	<?php
/**
 * Default template for displaying post content
 *
 * @package ZnWP Bootstrap Theme
 */
global $znwp_theme;
?>
            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
              <h1 class="post-title">
                <?php if (is_single()): ?>
                  <?php the_title(); ?>
                <?php else: ?>
                  <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <?php endif; ?>
              </h1>
              <time><span class="glyphicon glyphicon-time"></span> <?php the_date(); ?></time>
              <hr class="title-divider" />
              <?php if (is_single()): ?>
                <?php the_content(); ?>
                <br />
                <?php
                previous_post_link(
                    '<div class="link-block post-prev">%link</div>',
                    '<span class="glyphicon glyphicon-chevron-left"></span> %title'
                );
                next_post_link(
                    '<div class="link-block post-next">%link</div>',
                    '%title <span class="glyphicon glyphicon-chevron-right"></span>'
                );
                ?>
                <div class="visible-xs clearfix"></div>
              <?php else: ?>
                <?php the_excerpt(); ?>
              <?php endif; ?>
            </article>
 | 
	<?php
/**
 * Default template for displaying post content
 *
 * @package ZnWP Bootstrap Theme
 */
global $znwp_theme;
?>
            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
              <h1 class="post-title">
                <?php if (is_single()): ?>
                  <?php the_title(); ?>
                <?php else: ?>
                  <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <?php endif; ?>
              </h1>
              <time><span class="glyphicon glyphicon-time"></span> <?php the_date(); ?></time>
              <hr class="title-divider" />
              <?php if (is_single()): ?>
                <?php the_content(); ?>
                <br />
                <?php
                previous_post_link(
                    '<div class="link-block post-prev">%link</div>',
                    '<span class="glyphicon glyphicon-chevron-left"></span> %title'
                );
                next_post_link(
                    '<div class="link-block post-next">%link</div>',
                    '%title <span class="glyphicon glyphicon-chevron-right"></span>'
                );
                ?>
              <?php else: ?>
                <?php the_excerpt(); ?>
              <?php endif; ?>
            </article>
 | 
| 
	Fix typo in folders service description | 
	<?php
namespace GrooveHQ\Service;
class MailboxesDescription extends BasicServiceDescription
{
    protected function getServiceDescription()
    {
        return [
            'operations' => [
                'mailboxes' => [
                    'summary' => 'Listing mailboxes',
                    'httpMethod' => 'GET',
                    'uri' => '/mailboxes',
                    'parameters' => [],
                ],
                'folders' => [
                    'summary' => 'Listing mailboxes',
                    'httpMethod' => 'GET',
                    'uri' => '/folders',
                    'parameters' => [
                        'mailbox' => [
                            'description' => 'The ID or email address of a Mailbox to filter by',
                            'type' => 'string',
                            'required' => false,
                            'location' => 'query'
                        ],
                    ],
                ]
            ]
        ];
    }
}
 | 
	<?php
namespace GrooveHQ\Service;
class MailboxesDescription extends BasicServiceDescription
{
    protected function getServiceDescription()
    {
        return [
            'operations' => [
                'mailboxes' => [
                    'summary' => 'Listing mailboxes',
                    'httpMethod' => 'GET',
                    'uri' => '/mailboxes',
                    'parameters' => [],
                ],
                'folders' => [
                    'summary' => 'Listing mailboxes',
                    'httpMethod' => 'GET',
                    'uri' => '/mailboxes',
                    'parameters' => [
                        'mailbox' => [
                            'description' => 'The ID or email address of a Mailbox to filter by',
                            'type' => 'string',
                            'required' => false,
                            'location' => 'query'
                        ],
                    ],
                ]
            ]
        ];
    }
}
 | 
| 
	Add getCommand handler for strings | 
	package com.avairebot.orion.commands;
import net.dv8tion.jda.core.entities.Message;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandHandler {
    private static final Map<List<String>, CommandContainer> commands = new HashMap<>();
    public static CommandContainer getCommand(Message message) {
        return getCommand(message.getContent().split(" ")[0].toLowerCase());
    }
    public static CommandContainer getCommand(String commandTrigger) {
        for (Map.Entry<List<String>, CommandContainer> entry : commands.entrySet()) {
            for (String trigger : entry.getKey()) {
                if (commandTrigger.equalsIgnoreCase(entry.getValue().getDefaultPrefix() + trigger)) {
                    return entry.getValue();
                }
            }
        }
        return null;
    }
    public static boolean register(Command command) {
        for (String trigger : command.getTriggers()) {
            for (Map.Entry<List<String>, CommandContainer> entry : commands.entrySet()) {
                if (entry.getKey().contains(trigger.toLowerCase())) {
                    return false;
                }
            }
        }
        Category category = Category.fromCommand(command);
        if (category == null) {
            return false;
        }
        commands.put(command.getTriggers(), new CommandContainer(command, category));
        return true;
    }
    public static Collection<CommandContainer> getCommands() {
        return commands.values();
    }
}
 | 
	package com.avairebot.orion.commands;
import net.dv8tion.jda.core.entities.Message;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandHandler {
    private static final Map<List<String>, CommandContainer> commands = new HashMap<>();
    public static CommandContainer getCommand(Message message) {
        String commandTrigger = message.getContent().split(" ")[0].toLowerCase();
        for (Map.Entry<List<String>, CommandContainer> entry : commands.entrySet()) {
            for (String trigger : entry.getKey()) {
                if (commandTrigger.equalsIgnoreCase(entry.getValue().getDefaultPrefix() + trigger)) {
                    return entry.getValue();
                }
            }
        }
        return null;
    }
    public static boolean register(Command command) {
        for (String trigger : command.getTriggers()) {
            for (Map.Entry<List<String>, CommandContainer> entry : commands.entrySet()) {
                if (entry.getKey().contains(trigger.toLowerCase())) {
                    return false;
                }
            }
        }
        Category category = Category.fromCommand(command);
        if (category == null) {
            return false;
        }
        commands.put(command.getTriggers(), new CommandContainer(command, category));
        return true;
    }
    public static Collection<CommandContainer> getCommands() {
        return commands.values();
    }
}
 | 
| 
	Allow user to remove sample people | 
	Meteor.methods({
  addSearchSamplePeople: function() {
    var first_names = [
      "Ada",
      "Grace",
      "Marie",
      "Carl",
      "Nikola",
      "Claude",
      "Peter",
      "Stefan",
      "Stephen",
      "Lisa",
      "Christian",
      "Barack"
    ];
    var last_names = [
      "Lovelace",
      "Hopper",
      "Curie",
      "Tesla",
      "Shannon",
      "Muller",
      "Meier",
      "Miller",
      "Gaga",
      "Franklin"
    ];
    var locations = ["Davie", "Fort Lauderdale", "Tampa"];
    var addedList = [];
    for (var i = 0; i < 3; i++) {
      var person = {
        searchSamplePerson: true,
        'member_key': Random.id(),
        firstname: Random.choice(first_names),
        lastname: Random.choice(last_names),
        about: "Random test user created for testing search.",
        location: Random.choice(locations),
      };
      person.email = person.member_key + "@test.t";
      person.fullname = person.firstname + ' ' + person.lastname;
      addedList.push(person.fullname);
      // console.log('for search, adding sample person:', person);
      People.insert(person);
    }
    // console.log('method, addedList:', addedList);
    return addedList; // passed through client callback
  },
  
  removeSearchSamplePeople: function() {
    People.remove({searchSamplePerson: true});
  },
});
 | 
	Meteor.methods({
  addSearchSamplePeople: function() {
    var first_names = [
      "Ada",
      "Grace",
      "Marie",
      "Carl",
      "Nikola",
      "Claude",
      "Peter",
      "Stefan",
      "Stephen",
      "Lisa",
      "Christian",
      "Barack"
    ];
    var last_names = [
      "Lovelace",
      "Hopper",
      "Curie",
      "Tesla",
      "Shannon",
      "Muller",
      "Meier",
      "Miller",
      "Gaga",
      "Franklin"
    ];
    var locations = ["Davie", "Fort Lauderdale", "Tampa"];
    var addedList = [];
    for (var i = 0; i < 3; i++) {
      var person = {
        'member_key': Random.id(),
        firstname: Random.choice(first_names),
        lastname: Random.choice(last_names),
        about: "Random test user created for testing search.",
        location: Random.choice(locations),
      };
      person.email = person.member_key + "@test.t";
      person.fullname = person.firstname + ' ' + person.lastname;
      addedList.push(person.fullname);
      // console.log('for search, adding sample person:', person);
      People.insert(person);
    }
    // console.log('method, addedList:', addedList);
    return addedList; // passed through client callback
  },
});
 | 
| 
	Allow TypeParameters to 'grap' attr from param_dict | 
	from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
    def __init__(self, name, type_kind, param_dict):
        self.name = name
        self.type_kind = type_kind
        self.param_dict = param_dict
    def __getattr__(self, attr):
        try:
            return getattr(self.param_dict, attr)
        except AttributeError:
            raise AttributeError("'{}' object has no attribute "
                                 "'{}'".format(type(self), attr))
    def __getitem__(self, key):
        return self.param_dict[key]
    def __setitem__(self, key, value):
        self.param_dict[key] = value
    @property
    def default(self):
        return self.param_dict.default
    @default.setter
    def default(self, value):
        self.param_dict.default = value
    def attach(self, cpp_obj, sim):
        self.param_dict = AttachedTypeParameterDict(cpp_obj,
                                                    self.name,
                                                    self.type_kind,
                                                    self.param_dict,
                                                    sim)
        return self
    def detach(self):
        self.param_dict = self.param_dict.to_dettached()
        return self
    def to_dict(self):
        return self.param_dict.to_dict()
    def keys(self):
        yield from self.param_dict.keys()
    @property
    def state(self):
        state = self.to_dict()
        if self.param_dict._len_keys > 1:
            state = {str(key): value for key, value in state.items()}
        state['__default'] = self.default
        return state
 | 
	from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
    def __init__(self, name, type_kind, param_dict):
        self.name = name
        self.type_kind = type_kind
        self.param_dict = param_dict
    def __getitem__(self, key):
        return self.param_dict[key]
    def __setitem__(self, key, value):
        self.param_dict[key] = value
    @property
    def default(self):
        return self.param_dict.default
    @default.setter
    def default(self, value):
        self.param_dict.default = value
    def attach(self, cpp_obj, sim):
        self.param_dict = AttachedTypeParameterDict(cpp_obj,
                                                    self.name,
                                                    self.type_kind,
                                                    self.param_dict,
                                                    sim)
        return self
    def detach(self):
        self.param_dict = self.param_dict.to_dettached()
        return self
    def to_dict(self):
        return self.param_dict.to_dict()
    def keys(self):
        yield from self.param_dict.keys()
    @property
    def state(self):
        state = self.to_dict()
        if self.param_dict._len_keys > 1:
            state = {str(key): value for key, value in state.items()}
        state['__default'] = self.default
        return state
 | 
| 
	Select the chunk content on edit. | 
	(function($) {
    $(document).ready(function(){
        $('.edit_chunk').on(
            'click',
            'a',
            function() {
                var key = $(this).parent().data('key');
                var chunk = $(this).parent();
                chunk.empty();
                $.get('/chunks/edit/' + key + '/',
                      {},
                      function(data) {
                          chunk.html(data)
                          $('form', chunk).ajaxForm({
                              dataType: 'text',
                              beforeSubmit: function() { $('button', chunk).prop('disabled', true); },
                              success: function(d, s, x) {
                                  console.log('SUCCESS: ' + x.status);
                                  $('form', chunk).css({
                                      'border': '10px solid green',
                                  }).animate(
                                      {'opacity': 'hide',},
                                      1000, 'linear',
                                      function() {
                                          var txt = $('.edit_chunk form textarea').val();
                                          chunk.empty();
                                          chunk.html(txt + '<a href="#">редактировать</a>')});
                              },
                              error: function(d, s, x) { console.log('ERROR: ' + x.status); }
                          }).find('textarea').select();
                      });
                return false;
            });
    });
})(jQuery);
 | 
	(function($) {
    $(document).ready(function(){
        $('.edit_chunk').on(
            'click',
            'a',
            function() {
                var key = $(this).parent().data('key');
                var chunk = $(this).parent();
                chunk.empty();
                $.get('/chunks/edit/' + key + '/',
                      {},
                      function(data) {
                          chunk.html(data)
                          $('form', chunk).ajaxForm({
                              dataType: 'text',
                              beforeSubmit: function() { $('button', chunk).prop('disabled', true); },
                              success: function(d, s, x) {
                                  console.log('SUCCESS: ' + x.status);
                                  $('form', chunk).css({
                                      'border': '10px solid green',
                                  }).animate(
                                      {'opacity': 'hide',},
                                      1000, 'linear',
                                      function() {
                                          var txt = $('.edit_chunk form textarea').val();
                                          chunk.empty();
                                          chunk.html(txt + '<a href="#">редактировать</a>')
                                      }
                                  );
                              },
                              error: function(d, s, x) { console.log('ERROR: ' + x.status); }
                          });
                      });
                return false;
            });
    });
})(jQuery);
 | 
| 
	Add `key` to payment type selection list | 
	// @flow
import React, { Component } from 'react';
import { FormattedMessage } from 'react-intl';
import PaymentMethodWrapper from '../ExpressDonation/PaymentMethodWrapper';
export default class PaymentTypeSelection extends Component {
  props: {
    disabled?: boolean;
    currentPaymentType?: string;
    onChange: (paymentType: string) => void;
    showDirectDebit: ?boolean;
  };
  render() {
    const { disabled, currentPaymentType, onChange } = this.props;
    const methods = ['card', 'paypal'];
    if (this.props.showDirectDebit) methods.push('gocardless');
    return (
      <div className='ExpressDonation__payment-methods'>
        <PaymentMethodWrapper>
          <span className="ExpressDonation__prompt">
            <FormattedMessage id="fundraiser.payment_type_prompt" />
          </span>
          {methods.map((method, i) => {
            return (
              <div className="PaymentMethod" key={i}>
                <label>
                    <input
                      disabled={disabled}
                      type="radio"
                      checked={currentPaymentType === method}
                      onChange={(e) => onChange(method)}
                    />
                  <FormattedMessage id={`fundraiser.payment_methods.${method}`} />
                </label>
                { currentPaymentType === method && currentPaymentType !== 'card' &&
                  <div className="PaymentMethod__guidance">
                    <FormattedMessage id={`fundraiser.payment_methods.ready_for_${method}`} />
                  </div>
                }
              </div>
            );
          })}
        </PaymentMethodWrapper>
      </div>
    );
  }
}
 | 
	// @flow
import React, { Component } from 'react';
import { FormattedMessage } from 'react-intl';
import PaymentMethodWrapper from '../ExpressDonation/PaymentMethodWrapper';
export default class PaymentTypeSelection extends Component {
  props: {
    disabled?: boolean;
    currentPaymentType?: string;
    onChange: (paymentType: string) => void;
    showDirectDebit: ?boolean;
  };
  render() {
    const { disabled, currentPaymentType, onChange } = this.props;
    const methods = ['card', 'paypal'];
    if (this.props.showDirectDebit) methods.push('gocardless');
    return (
      <div className='ExpressDonation__payment-methods'>
        <PaymentMethodWrapper>
          <span className="ExpressDonation__prompt">
            <FormattedMessage id="fundraiser.payment_type_prompt" />
          </span>
          {methods.map((method) => {
            return (<div className="PaymentMethod">
              <label>
                  <input
                    disabled={disabled}
                    type="radio"
                    checked={currentPaymentType === method}
                    onChange={(e) => onChange(method)}
                  />
                <FormattedMessage id={`fundraiser.payment_methods.${method}`} />
              </label>
              { currentPaymentType === method && currentPaymentType !== 'card' &&
                <div className="PaymentMethod__guidance">
                  <FormattedMessage id={`fundraiser.payment_methods.ready_for_${method}`} />
                </div>
              }
            </div>);
          })}
        </PaymentMethodWrapper>
      </div>
    );
  }
}
 | 
| 
	Add vcrpy to testing-related dependencies | 
	from codecs import open as codecs_open
from setuptools import setup, find_packages
import sentinelsat
# Get the long description from the relevant file
with codecs_open('README.rst', encoding='utf-8') as f:
    long_description = f.read()
setup(name='sentinelsat',
      version=sentinelsat.__version__,
      description="Utility to search and download Sentinel-1 Imagery",
      long_description=long_description,
      classifiers=[
          'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3.4',
          'Programming Language :: Python :: 3.5',
          'Topic :: Scientific/Engineering :: GIS',
          'Topic :: Utilities',
      ],
      keywords='sentinel, esa, satellite, download, GIS',
      author="Wille Marcel",
      author_email='[email protected]',
      url='https://github.com/ibamacsr/sentinelsat',
      license='GPLv3+',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
      include_package_data=True,
      zip_safe=False,
      install_requires=open('requirements.txt').read().splitlines(),
      extras_require={
          'test': [
              'pytest',
              'requests-mock',
              'vcrpy'
          ],
      },
      entry_points="""
      [console_scripts]
      sentinel=sentinelsat.scripts.cli:cli
      """
      )
 | 
	from codecs import open as codecs_open
from setuptools import setup, find_packages
import sentinelsat
# Get the long description from the relevant file
with codecs_open('README.rst', encoding='utf-8') as f:
    long_description = f.read()
setup(name='sentinelsat',
      version=sentinelsat.__version__,
      description="Utility to search and download Sentinel-1 Imagery",
      long_description=long_description,
      classifiers=[
          'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3.4',
          'Programming Language :: Python :: 3.5',
          'Topic :: Scientific/Engineering :: GIS',
          'Topic :: Utilities',
      ],
      keywords='sentinel, esa, satellite, download, GIS',
      author="Wille Marcel",
      author_email='[email protected]',
      url='https://github.com/ibamacsr/sentinelsat',
      license='GPLv3+',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
      include_package_data=True,
      zip_safe=False,
      install_requires=open('requirements.txt').read().splitlines(),
      extras_require={
          'test': [
              'pytest',
              'requests-mock'
          ],
      },
      entry_points="""
      [console_scripts]
      sentinel=sentinelsat.scripts.cli:cli
      """
      )
 | 
| 
	refactor: Set expense to two decimals before saving it to db | 
	import Ember from 'ember';
// import $ from 'jquery';
export default Ember.Component.extend({
  expense: {
    sum: '',
    category: '',
    name: ''
  },
  currency: '£',
  expenseCategories: [
    'Charity',
    'Clothing',
    'Education',
    'Events',
    'Food',
    'Gifts',
    'Healthcare',
    'Household',
    'Leisure',
    'Hobbies',
    'Trasportation',
    'Utilities',
    'Vacation'
  ],
  errorMessagesSum: {
    emRequired: 'This field can\'t be blank',
    emPattern: 'Must be a number!'
  },
  errorMessagesCategory: {
    emRequired: 'Select or add your own category'
  },
  init () {
    this._super();
    Ember.TextSupport.reopen({
      attributeBindings: ['em-required', 'em-min', 'em-max', 'em-pattern']
    });
  },
  didInsertElement () {
    componentHandler.upgradeAllRegistered();
  },
  actions: {
    clearInputs () {
      this.set('expense', {
        sum: '',
        category: '',
        name: ''
      });
      this.$('.mdl-textfield').removeClass('is-dirty is-invalid is-touched');
    },
    addExpense () {
      Ember.run.later(() => {
        if (!this.$().find('.is-invalid').length) {
          let sum = this.get('expense').sum;
          this.set('expense.sum', parseFloat(sum).toFixed(2));
          this.sendAction('action', this.get('expense'));
          this.send('clearInputs');
        }
      }, 200);
    }
  }
});
 | 
	import Ember from 'ember';
// import $ from 'jquery';
export default Ember.Component.extend({
  expense: {
    sum: '',
    category: '',
    name: ''
  },
  currency: '£',
  expenseCategories: [
    'Charity',
    'Clothing',
    'Education',
    'Events',
    'Food',
    'Gifts',
    'Healthcare',
    'Household',
    'Leisure',
    'Hobbies',
    'Trasportation',
    'Utilities',
    'Vacation'
  ],
  errorMessagesSum: {
    emRequired: 'This field can\'t be blank',
    emPattern: 'Must be a number!'
  },
  errorMessagesCategory: {
    emRequired: 'Select or add your own category'
  },
  init () {
    this._super();
    Ember.TextSupport.reopen({
      attributeBindings: ['em-required', 'em-min', 'em-max', 'em-pattern']
    });
  },
  didInsertElement () {
    componentHandler.upgradeAllRegistered();
  },
  actions: {
    clearInputs () {
      this.set('expense', {
        sum: '',
        category: '',
        name: ''
      });
      this.$('.mdl-textfield').removeClass('is-dirty is-invalid is-touched');
    },
    addExpense () {
      Ember.run.later(() => {
        if (!this.$().find('.is-invalid').length) {
          this.sendAction('action', this.get('expense'));
          this.send('clearInputs');
        }
      }, 200);
    }
  }
});
 | 
| 
	Fix Verify endpoint doesn't use user tranformer
Close https://github.com/NamelessMC/Nameless/issues/2714 | 
	<?php
/**
 * @param int $id The NamelessMC user's ID
 * @param string $code The NamelessMC user's reset code, used to verify they own the account
 *
 * @return string JSON Array
 */
class VerifyEndpoint extends KeyAuthEndpoint {
    public function __construct() {
        $this->_route = 'users/{user}/verify';
        $this->_module = 'Core';
        $this->_description = 'Validate/Activate a NamelessMC account by confirming their reset code';
        $this->_method = 'POST';
    }
    public function execute(Nameless2API $api, User $user): void {
        $api->validateParams($_POST, ['code']);
        if ($user->data()->active || $user->data()->reset_code == '') {
            $api->throwError(32, $api->getLanguage()->get('api', 'user_already_active'));
        }
        if ($user->data()->reset_code != $_POST['code']) {
            $api->throwError(28, $api->getLanguage()->get('api', 'invalid_code'));
        }
        $user->update([
            'active' => 1,
            'reset_code' => ''
        ]);
        EventHandler::executeEvent('validateUser', [
            'user_id' => $user->data()->id,
            'username' => $user->data()->username,
            'language' => $api->getLanguage()
        ]);
        $api->returnArray(['message' => $api->getLanguage()->get('api', 'account_validated')]);
    }
} | 
	<?php
/**
 * @param int $id The NamelessMC user's ID
 * @param string $code The NamelessMC user's reset code, used to verify they own the account
 *
 * @return string JSON Array
 */
class VerifyEndpoint extends KeyAuthEndpoint {
    public function __construct() {
        $this->_route = 'verify';
        $this->_module = 'Core';
        $this->_description = 'Validate/Activate a NamelessMC account by confirming their reset code';
        $this->_method = 'POST';
    }
    public function execute(Nameless2API $api): void {
        $api->validateParams($_POST, ['user', 'code']);
        $user = $api->getUser('id', $_POST['user']);
        if ($user->data()->active || $user->data()->reset_code == '') {
            $api->throwError(32, $api->getLanguage()->get('api', 'user_already_active'));
        }
        if ($user->data()->reset_code != $_POST['code']) {
            $api->throwError(28, $api->getLanguage()->get('api', 'invalid_code'));
        }
        $user->update([
            'active' => 1,
            'reset_code' => ''
        ]);
        EventHandler::executeEvent('validateUser', [
            'user_id' => $user->data()->id,
            'username' => $user->data()->username,
            'language' => $api->getLanguage()
        ]);
        $api->returnArray(['message' => $api->getLanguage()->get('api', 'account_validated')]);
    }
}
 | 
| 
	Set JWT expiration date to 30 days | 
	var authRouter = require('express').Router();
var jwt = require('jwt-simple');
var auth = require('../lib/auth');
var User = require('../../db/models/User');
var Promise = require('bluebird');
var bcrypt = require('bcryptjs');
bcrypt.compare = Promise.promisify(bcrypt.compare);
authRouter.post('/login', function(req, res) {
  var email = req.body.email;
  var password = req.body.password;
  if (!email || !password) {
    res.status(400).send('Incomplete email/password');
    return;
  }
  User.query().where('email', email)
    .then(function(user) {
      var user = user[0];
      if (!user) {
        throw 'Error: user does not exist';
      } else {
        return Promise.all([
          bcrypt.compare(password, user.password),
          user
        ]);
      }
    })
    .spread(function(authenticated, user) {
      if (!authenticated) {
        throw 'Invalid password';
      } else {
        var payload = { id: user.id, exp: Math.round((Date.now() + 30 * 24 * 60 * 1000) / 1000) };
        var token = jwt.encode(payload, auth.cfg.jwtSecret);
        res.json({ token: token });
      }
    })
    .catch(function(authError) {
      res.status(401).send(authError);
    })
    .error(function(err) {
      console.error('Auth server error: ', err);
      res.status(500).send('Server error');
    });
});
module.exports = authRouter;
 | 
	var authRouter = require('express').Router();
var jwt = require('jwt-simple');
var auth = require('../lib/auth');
var User = require('../../db/models/User');
var Promise = require('bluebird');
var bcrypt = require('bcryptjs');
bcrypt.compare = Promise.promisify(bcrypt.compare);
authRouter.post('/login', function(req, res) {
  var email = req.body.email;
  var password = req.body.password;
  if (!email || !password) {
    res.status(400).send('Incomplete email/password');
    return;
  }
  User.query().where('email', email)
    .then(function(user) {
      var user = user[0];
      if (!user) {
        throw 'Error: user does not exist';
      } else {
        return Promise.all([
          bcrypt.compare(password, user.password),
          user
        ]);
      }
    })
    .spread(function(authenticated, user) {
      if (!authenticated) {
        throw 'Invalid password';
      } else {
        var payload = { id: user.id };
        var token = jwt.encode(payload, auth.cfg.jwtSecret);
        res.json({ token: token });
      }
    })
    .catch(function(authError) {
      res.status(401).send(authError);
    })
    .error(function(err) {
      console.error('Auth server error: ', err);
      res.status(500).send('Server error');
    });
});
module.exports = authRouter; | 
| 
	Add social events to spring evals 😿 | 
	from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
    # get user data
    user_name = request.headers.get('x-webauth-user')
    members = [
                {
                    'name': "Liam Middlebrook",
                    'committee_meetings': 24,
                    'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
                    'major_project': 'open_container',
                    'major_project_passed': True,
                    'social_events': "",
                    'comments': "please don't fail me",
                    'result': 'Pending'
                },
                {
                    'name': "Julien Eid",
                    'committee_meetings': 69,
                    'house_meetings_missed': [],
                    'major_project': 'wii-u shit',
                    'major_project_passed': True,
                    'social_events': "Manipulation and Opportunism",
                    'comments': "imdabes",
                    'result': 'Passed'
                }
            ]
    # return names in 'first last (username)' format
    return render_template('spring_evals.html',
                            username = user_name,
                            members = members)
 | 
	from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
    # get user data
    user_name = request.headers.get('x-webauth-user')
    members = [
                {
                    'name': "Liam Middlebrook",
                    'committee_meetings': 24,
                    'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
                    'major_project': 'open_container',
                    'major_project_passed': True,
                    'comments': "please don't fail me",
                    'result': 'Pending'
                },
                {
                    'name': "Julien Eid",
                    'committee_meetings': 69,
                    'house_meetings_missed': [],
                    'major_project': 'wii-u shit',
                    'major_project_passed': True,
                    'comments': "imdabes",
                    'result': 'Passed'
                }
            ]
    # return names in 'first last (username)' format
    return render_template('spring_evals.html',
                            username = user_name,
                            members = members)
 | 
| 
	Add support for title next to logo in navbar | 
	<?php defined('C5_EXECUTE') or die("Access Denied.");
?>
<?php
$c = Page::getCurrentPage();
?>
<?php if (is_object($f)): ?>
    <?php
    if ($maxWidth > 0 || $maxHeight > 0) {
        $im = Core::make('helper/image');
        $thumb = $im->getThumbnail(
            $f,
            $maxWidth,
            $maxHeight
        ); //<-- set these 2 numbers to max width and height of thumbnails
        $tag = new \HtmlObject\Image();
        $tag->src($thumb->src)->width($thumb->width)->height($thumb->height);
    } else {
        $image = Core::make('html/image', array($f));
        $tag = $image->getTag();
    }
    $tag->addClass('align-baseline img-fluid');
    if ($altText) {
        $tag->alt($altText);
    }
    if ($linkURL):
        print '<a href="' . $linkURL . '">';
    endif;
    ?>
    <a class="navbar-brand" href="<?php echo $linkURL; ?>"<?php echo ($openLinkInNewWindow ? ' target="_blank"' : ''); ?>>
        <?php echo $tag; ?>
        <?php if ($title): ?>
            <span class="ml-1 text-white"><?php echo h($title); ?></span>
        <?php endif; ?>
    </a>
<?php elseif ($c->isEditMode()): ?>
    <div class="ccm-edit-mode-disabled-item"><?=t('Empty Image Block.')?></div>
<?php endif; ?>
 | 
	<?php defined('C5_EXECUTE') or die("Access Denied.");
?>
<?php
$c = Page::getCurrentPage();
?>
<?php if (is_object($f)): ?>
    <?php
    if ($maxWidth > 0 || $maxHeight > 0) {
        $im = Core::make('helper/image');
        $thumb = $im->getThumbnail(
            $f,
            $maxWidth,
            $maxHeight
        ); //<-- set these 2 numbers to max width and height of thumbnails
        $tag = new \HtmlObject\Image();
        $tag->src($thumb->src)->width($thumb->width)->height($thumb->height);
    } else {
        $image = Core::make('html/image', array($f));
        $tag = $image->getTag();
    }
    $tag->addClass('ccm-image-block img-fluid bID-'.$bID);
    if ($altText) {
        $tag->alt($altText);
    }
    if ($title) {
        $tag->title($title);
    }
    if ($linkURL):
        print '<a href="' . $linkURL . '">';
    endif;
    ?>
    <a class="navbar-brand" href="<?php echo $linkURL; ?>"<?php echo ($openLinkInNewWindow ? ' target="_blank"' : ''); ?>>
        <?php echo $tag; ?>
    </a>
<?php elseif ($c->isEditMode()): ?>
    <div class="ccm-edit-mode-disabled-item"><?=t('Empty Image Block.')?></div>
<?php endif; ?>
 | 
| 
	Correct the function name for better legibility | 
	import React from 'react';
import Dropdown from '../../../src/Dropdown/Dropdown.js';
class DropdownExample extends React.Component {
  onItemSelection(item) {
    console.log(item);
  }
  render() {
    var items = [{
      id: 'a',
      html: <span>Item A</span>,
      selectedHtml: <span>Item A</span>
    },
    {
      id: 'b',
      html: <span>Item B</span>,
      selectedHtml: <span>Item B</span>
    },
    {
      id: 'c',
      html: <span>Item C</span>,
      selectedHtml: <span>Item C</span>
    }];
    return (
      <div>
        <section className="row canvas-pod canvas-pod-light">
          <div className="container container-pod">
            <h2>Here is a simple dropdown.</h2>
            <Dropdown wrapperClassName="dropdown"
              buttonClassName="button dropdown-toggle"
              dropdownMenuClassName="dropdown-menu"
              dropdownMenuListClassName="dropdown-menu-list"
              items={items}
              onItemSelection={this.onItemSelection}
              selectedId="a" />
          </div>
        </section>
      </div>
    );
  }
}
React.render(<DropdownExample />, document.getElementById('dropdown'));
 | 
	import React from 'react';
import Dropdown from '../../../src/Dropdown/Dropdown.js';
class DropdownExample extends React.Component {
  handleItemSelection(item) {
    console.log(item);
  }
  render() {
    var items = [{
      id: 'a',
      html: <span>Item A</span>,
      selectedHtml: <span>Item A</span>
    },
    {
      id: 'b',
      html: <span>Item B</span>,
      selectedHtml: <span>Item B</span>
    },
    {
      id: 'c',
      html: <span>Item C</span>,
      selectedHtml: <span>Item C</span>
    }];
    return (
      <div>
        <section className="row canvas-pod canvas-pod-light">
          <div className="container container-pod">
            <h2>Here is a simple dropdown.</h2>
            <Dropdown wrapperClassName="dropdown"
              buttonClassName="button dropdown-toggle"
              dropdownMenuClassName="dropdown-menu"
              dropdownMenuListClassName="dropdown-menu-list"
              items={items}
              onItemSelection={this.handleItemSelection}
              selectedId="a" />
          </div>
        </section>
      </div>
    );
  }
}
React.render(<DropdownExample />, document.getElementById('dropdown'));
 | 
| 
	Rename Index view to Home | 
	"use strict";
module.exports = function(imports) {
    let express = imports.modules.express;
    let Promise = imports.modules.Promise;
    let fs = require("fs"); // TODO: put this into initImports
    let util = imports.util;
    let handler = util.handler;
    let Team = imports.models.Team;
    let router = express.Router();
    let pages = {
        signup: "Signup",
        login: "Login",
        "": "Home", // this works
        void: "Void",
    };
    for (let page in pages) {
        router.get("/" + page, handler(function*(req, res) {
            if (req.user) {
                req.user.team = yield Team.findOne(req.user.team);
            }
            res.render("../../morteam-web/src/page.html.ejs", {
                userInfo: req.user,
                page: pages[page],
            });
        }));
    }
    router.get("/js/:page", handler(function*(req, res) {
        let page = req.params.page;
        let file = "../morteam-web/build/" + page + ".js";
        // TODO: use the package fs-promise
        fs.exists(file, function(exists) {
            if (!exists) {
                return res.end("fail"); // AHHHH
            }
            fs.createReadStream(file).pipe(res);
        });
    }));
    return router;
};
 | 
	"use strict";
module.exports = function(imports) {
    let express = imports.modules.express;
    let Promise = imports.modules.Promise;
    let fs = require("fs"); // TODO: put this into initImports
    let util = imports.util;
    let handler = util.handler;
    let Team = imports.models.Team;
    let router = express.Router();
    let pages = {
        signup: "Signup",
        login: "Login",
        "": "Index", // this works
        void: "Void",
    };
    for (let page in pages) {
        router.get("/" + page, handler(function*(req, res) {
            if (req.user) {
                req.user.team = yield Team.findOne(req.user.team);
            }
            res.render("../../morteam-web/src/page.html.ejs", {
                userInfo: req.user,
                page: pages[page],
            });
        }));
    }
    router.get("/js/:page", handler(function*(req, res) {
        let page = req.params.page;
        let file = "../morteam-web/build/" + page + ".js";
        // TODO: use the package fs-promise
        fs.exists(file, function(exists) {
            if (!exists) {
                return res.end("fail"); // AHHHH
            }
            fs.createReadStream(file).pipe(res);
        });
    }));
    return router;
};
 | 
| 
	Support gateway initialisation of the custom site name.
Also remove references to the unused (and unnecessary?) CompletePurchaseRequest. | 
	<?php
namespace Omnipay\Gate2shop;
use Omnipay\Common\AbstractGateway;
use Omnipay\Gate2shop\Message\PurchaseRequest;
/**
 * Gate2shop Gateway
 *
 * @link
 */
class Gateway extends AbstractGateway
{
    public function getName()
    {
        return 'Gate2shop';
    }
    public function getDefaultParameters()
    {
        return array(
            'merchantSiteId' => '',
            'merchantId'     => '',
            'secretKey'      => '',
            'customSiteName' => ''
        );
    }
    public function getMerchantSiteId()
    {
        return $this->getParameter('merchantSiteId');
    }
    public function setMerchantSiteId($value)
    {
        return $this->setParameter('merchantSiteId', $value);
    }
    public function getMerchantId()
    {
        return $this->getParameter('merchantId');
    }
    public function setMerchantId($value)
    {
        return $this->setParameter('merchantId', $value);
    }
    public function getSecretKey()
    {
        return $this->getParameter('secretKey');
    }
    public function setSecretKey($value)
    {
        return $this->setParameter('secretKey', $value);
    }
    public function getCustomSiteName()
    {
        return $this->getParameter('customSiteName');
    }
    public function setCustomSiteName($value)
    {
        return $this->setParameter('customSiteName', $value);
    }
    public function purchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Gate2shop\Message\PurchaseRequest', $parameters);
    }
}
 | 
	<?php
namespace Omnipay\Gate2shop;
use Omnipay\Common\AbstractGateway;
use Omnipay\Gate2shop\Message\PurchaseRequest;
use Omnipay\Gate2shop\Message\CompletePurchaseRequest;
/**
 * Gate2shop Gateway
 *
 * @link
 */
class Gateway extends AbstractGateway
{
    public function getName()
    {
        return 'Gate2shop';
    }
    public function getDefaultParameters()
    {
        return array(
            'merchantSiteId' => '',
            'merchantId'     => '',
            'secretKey'      => ''
        );
    }
    public function getMerchantSiteId()
    {
        return $this->getParameter('merchantSiteId');
    }
    public function setMerchantSiteId($value)
    {
        return $this->setParameter('merchantSiteId', $value);
    }
    public function getMerchantId()
    {
        return $this->getParameter('merchantId');
    }
    public function setMerchantId($value)
    {
        return $this->setParameter('merchantId', $value);
    }
    public function getSecretKey()
    {
        return $this->getParameter('secretKey');
    }
    public function setSecretKey($value)
    {
        return $this->setParameter('secretKey', $value);
    }
    public function purchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Gate2shop\Message\PurchaseRequest', $parameters);
    }
    public function completePurchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Gate2shop\Message\CompletePurchaseRequest', $parameters);
    }
}
 | 
| 
	Fix field key in saturn | 
	<?php
namespace App\Sharp;
use App\User;
use Code16\Sharp\Form\Layout\FormLayoutColumn;
use Code16\Sharp\Show\Fields\SharpShowTextField;
use Code16\Sharp\Show\Layout\ShowLayoutSection;
use Code16\Sharp\Show\SharpSingleShow;
class AccountSharpShow extends SharpSingleShow
{
    function buildShowFields()
    {
        $this
            ->addField(
                SharpShowTextField::make("name")
                    ->setLabel("Name:")
            )->addField(
                SharpShowTextField::make("email")
                    ->setLabel("Email:")
            )->addField(
                SharpShowTextField::make("groups")
                    ->setLabel("Groups:")
            );
    }
    function buildShowLayout()
    {
        $this
            ->addSection('Identity', function(ShowLayoutSection $section) {
                $section
                    ->addColumn(7, function(FormLayoutColumn $column) {
                        $column
                            ->withSingleField("name")
                            ->withSingleField("email")
                            ->withSingleField("groups");
                    });
            });
    }
    function findSingle(): array
    {
        return $this->transform(User::findOrFail(auth()->id()));
    }
} | 
	<?php
namespace App\Sharp;
use App\User;
use Code16\Sharp\Form\Layout\FormLayoutColumn;
use Code16\Sharp\Show\Fields\SharpShowTextField;
use Code16\Sharp\Show\Layout\ShowLayoutSection;
use Code16\Sharp\Show\SharpSingleShow;
class AccountSharpShow extends SharpSingleShow
{
    function buildShowFields()
    {
        $this
            ->addField(
                SharpShowTextField::make("name")
                    ->setLabel("Name:")
            )->addField(
                SharpShowTextField::make("email")
                    ->setLabel("Email:")
            )->addField(
                SharpShowTextField::make("group")
                    ->setLabel("Groups:")
            );
    }
    function buildShowLayout()
    {
        $this
            ->addSection('Identity', function(ShowLayoutSection $section) {
                $section
                    ->addColumn(7, function(FormLayoutColumn $column) {
                        $column
                            ->withSingleField("name")
                            ->withSingleField("email")
                            ->withSingleField("groups");
                    });
            });
    }
    function findSingle(): array
    {
        return $this->transform(User::findOrFail(auth()->id()));
    }
} | 
| 
	services.ec2: Add the missing push_notifications args
Signed-off-by: Sayan Chowdhury <[email protected]> | 
	#!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLogger('fedmsg')
def trigger_upload(compose_id, url, push_notifications):
    upload_pool = multiprocessing.pool.ThreadPool(processes=4)
    compose_meta = {'compose_id': compose_id}
    fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta,
            push_notifications=push_notifications)
def get_args():
    parser = argparse.ArgumentParser(
        description="Trigger a manual upload process with the "
                    "specified raw.xz URL")
    parser.add_argument(
        "-u", "--url", type=str, help=".raw.xz URL", required=True)
    parser.add_argument(
        "-c", "--compose-id", type=str, help="compose id of the .raw.xz file",
        required=True)
    parser.add_argument(
        "-p", "--push-notifications",
        help="Bool to check if we need to push fedmsg notifications",
        action="store_true", required=False)
    args = parser.parse_args()
    return args.url, args.compose_id, args.push_notifications
def main():
    url, compose_id, push_notifications = get_args()
    trigger_upload(url, compose_id, push_notifications)
if __name__ == '__main__':
    main()
 | 
	#!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLogger('fedmsg')
def trigger_upload(compose_id, url, push_notifications):
    upload_pool = multiprocessing.pool.ThreadPool(processes=4)
    compose_meta = {'compose_id': compose_id}
    fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta)
def get_args():
    parser = argparse.ArgumentParser(
        description="Trigger a manual upload process with the "
                    "specified raw.xz URL")
    parser.add_argument(
        "-u", "--url", type=str, help=".raw.xz URL", required=True)
    parser.add_argument(
        "-c", "--compose-id", type=str, help="compose id of the .raw.xz file",
        required=True)
    parser.add_argument(
        "-p", "--push-notifications",
        help="Bool to check if we need to push fedmsg notifications",
        action="store_true", required=False)
    args = parser.parse_args()
    return args.url, args.compose_id, args.push_notifications
def main():
    url, compose_id, push_notifications = get_args()
    trigger_upload(url, compose_id, push_notifications)
if __name__ == '__main__':
    main()
 | 
| 
	Fix for_each incorrectly using lazy map operator | 
	from bot.api.api import Api
from bot.storage import Config, State, Cache
from bot.utils.dictionaryobject import DictionaryObject
class Event(DictionaryObject):
    pass
class Update(Event):
    def __init__(self, update, is_pending):
        super().__init__()
        self.update = update
        self.is_pending = is_pending
class Action:
    def __init__(self):
        pass
    def get_name(self):
        return self.__class__.__name__
    def setup(self, api: Api, config: Config, state: State, cache: Cache):
        self.api = api
        self.config = config
        self.state = state
        self.cache = cache
        self.post_setup()
    def post_setup(self):
        pass
    def process(self, event):
        pass
class ActionGroup(Action):
    def __init__(self, *actions):
        super().__init__()
        self.actions = list(actions)
    def add(self, *actions):
        self.actions.extend(actions)
    def setup(self, *args):
        self.for_each(lambda action: action.setup(*args))
        super().setup(*args)
    def process(self, event):
        self.for_each(lambda action: action.process(event._copy()))
    def for_each(self, func):
        for action in self.actions:
            func(action)
class IntermediateAction(ActionGroup):
    def __init__(self):
        super().__init__()
    def then(self, *next_actions):
        self.add(*next_actions)
        return self
    def _continue(self, event):
        super().process(event)
 | 
	from bot.api.api import Api
from bot.storage import Config, State, Cache
from bot.utils.dictionaryobject import DictionaryObject
class Event(DictionaryObject):
    pass
class Update(Event):
    def __init__(self, update, is_pending):
        super().__init__()
        self.update = update
        self.is_pending = is_pending
class Action:
    def __init__(self):
        pass
    def get_name(self):
        return self.__class__.__name__
    def setup(self, api: Api, config: Config, state: State, cache: Cache):
        self.api = api
        self.config = config
        self.state = state
        self.cache = cache
        self.post_setup()
    def post_setup(self):
        pass
    def process(self, event):
        pass
class ActionGroup(Action):
    def __init__(self, *actions):
        super().__init__()
        self.actions = list(actions)
    def add(self, *actions):
        self.actions.extend(actions)
    def setup(self, *args):
        self.for_each(lambda action: action.setup(*args))
        super().setup(*args)
    def process(self, event):
        self.for_each(lambda action: action.process(event._copy()))
    def for_each(self, func):
        map(func, self.actions)
class IntermediateAction(ActionGroup):
    def __init__(self):
        super().__init__()
    def then(self, *next_actions):
        self.add(*next_actions)
        return self
    def _continue(self, event):
        super().process(event)
 | 
| 
	Fix bug of not getting full 60 | 
	import { min } from "date-fns";
export default function queryPlaces (coordinates, radius, service, types) {
    return new Promise(res => {
        let queries = types.reduce((queries, type) => {
            queries.push(queryPlacesByType(coordinates, radius, service, type))
            return queries
        }, [])
        Promise.all(queries).then(result => {
            res(result.reduce((allPlaces, queryResult) => {
                return allPlaces.concat(queryResult)
            }, []))
        })
    });
}
let dict = {"results": []}
const queryPlacesByType = (coordinates, radius, service, type) => {
    var place = new window.google.maps.LatLng(coordinates.lat, coordinates.lng)
    var request = {
        location: place,
        radius: radius,
        types: [type]
    };
    return new Promise((res) => {
        var getNextPage = null;
        service.nearbySearch(request, function (results, status, pagination) {
            if (status === window.google.maps.places.PlacesServiceStatus.OK) {
                dict["results"] = dict["results"].concat(results);
                console.log("type ", type);
                if (pagination.hasNextPage && dict["results"].length < 60) {
                    console.log("getting next page")
                    pagination.nextPage();
                }
                else {
                    res(dict["results"]);
                }
                
            }
            })
        })
        
    
    
}
 | 
	import { min } from "date-fns";
export default function queryPlaces (coordinates, radius, service, types) {
    return new Promise(res => {
        let queries = types.reduce((queries, type) => {
            queries.push(queryPlacesByType(coordinates, radius, service, type))
            return queries
        }, [])
        Promise.all(queries).then(result => {
            res(result.reduce((allPlaces, queryResult) => {
                return allPlaces.concat(queryResult)
            }, []))
        })
    });
}
const queryPlacesByType = (coordinates, radius, service, type) => {
    var place = new window.google.maps.LatLng(coordinates.lat, coordinates.lng)
    var request = {
        location: place,
        radius: radius,
        types: [type]
    };
    var getNextPage = null;
    var results = new Promise(res => {
        service.nearbySearch(request, function (results, status, pagination) {
            if (status === window.google.maps.places.PlacesServiceStatus.OK) {
                getNextPage = null;
                getNextPage = pagination.hasNextPage && function () {
                    console.log("getting next page")
                    pagination.nextPage()
                }
                res(results);
            }
        })
    })
    
    // console.log(results);
    // while (getNextPage !== null) {
    //     console.log("in while loop")
    //     results = results.concat(getNextPage());
    // }
    return results;
}
 | 
			Subsets and Splits
				
	
				
			
				
No community queries yet
The top public SQL queries from the community will appear here once available.