text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use basic HTTP authentication instead of headers | var Request = require("request");
function OAuth(clientId, clientSecret, redirectUri, opt_opts) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.redirectUri = redirectUri;
this.opts = Object(opt_opts);
this.credentials = {};
}
OAuth.prototype.getToken = function (opt_callback) {
Request({
url: "https://api.gb1.brightbox.com/token"
, method: "POST"
, form: {
client_id: this.clientId
, grant_type: "none"
}
, auth: {
user: this.clientId
, pass: this.clientSecret
}
, json: true
}, function (err, res, body) {
debugger
});
};
module.exports = OAuth;
| var Request = require("request");
function OAuth(clientId, clientSecret, redirectUri, opt_opts) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.redirectUri = redirectUri;
this.opts = Object(opt_opts);
this.credentials = {};
}
OAuth.prototype.getToken = function (opt_callback) {
var auth = new Buffer(this.clientId + ":" + this.clientSecret).toString("base64");
Request({
url: "https://api.gb1.brightbox.com/token"
, method: "POST"
, form: {
client_id: this.clientId
, grant_type: "none"
}
, headers: {
"Authorization": "Basic " + auth
}
, json: true
}, function (err, res, body) {
debugger
});
};
module.exports = OAuth;
|
Add test cases for brain | <?php
namespace BrainBundle\Tests\Controller;
use Liip\FunctionalTestBundle\Test\WebTestCase;
class WernickeControllerTest extends WebTestCase
{
public function testMarkovAction()
{
// Make new client
$client = $this->makeClient();
// Request for page
$crawler = $client->request('GET', '/brain/markov');
// Check if the request is success
$this->assertStatusCode(200, $client);
// Select a form
$form = $crawler->selectButton('Submit')->form();
// Submit without data
$crawler = $client->submit($form);
// Check if status code is 200
$this->assertStatusCode(200, $client);
// Check if contains error
$this->assertContains('Input text must be provided', $client->getResponse()->getContent());
// Submit the form with data
$form = $crawler->selectButton('Submit')->form();
$form->setValues(['form[input_text]' => 'Lorem Ipsum dolor sit amet', 'form[length]' => '10']);
$client->submit($form);
$this->assertStatusCode(200, $client);
$text = $client->getCrawler()->filter('div.output p')->text();
echo $text;
}
}
| <?php
namespace BrainBundle\Tests\Controller;
use Liip\FunctionalTestBundle\Test\WebTestCase;
class WernickeControllerTest extends WebTestCase
{
public function testMarkovAction()
{
// Make new client
$client = $this->makeClient();
// Request for page
$crawler = $client->request('GET', '/brain/markov');
// Check if the request is success
$this->assertStatusCode(200, $client);
// Select a form
$form = $crawler->selectButton('Submit')->form();
// Submit without data
$crawler = $client->submit($form);
// Check if status code is 200
$this->assertStatusCode(200, $client);
// Check if contains error
$this->assertContains('Input text must be provided', $client->getResponse()->getContent());
// Submit the form with data
$form = $crawler->selectButton('Submit')->form();
$form->setValues(['form[input_text]' => 'Lorem Ipsum dolor sit amet', 'form[length]' => '10']);
$client->submit($form);
$this->assertStatusCode(200, $client);
}
}
|
Update list for transfer recipient | """Script used to define the paystack Transfer Recipient class."""
from paystackapi.base import PayStackBase
class Invoice(PayStackBase):
"""docstring for Transfer Recipient."""
@classmethod
def create(cls, **kwargs):
"""
Method defined to create transfer recipient.
Args:
type: Recipient Type (Only nuban at this time)
name: A name for the recipient
account_number: Required if type is nuban
bank_code: Required if type is nuban.
You can get the list of Bank Codes by calling the List Banks endpoint.
**kwargs
Returns:
Json data from paystack API.
"""
return cls().requests.post('transferrecipient', data=kwargs,)
@classmethod
def list(cls, **kwargs):
"""
Method defined to list transfer recipient.
Args:
perPage: records you want to retrieve per page (Integer)
page: what page you want to retrieve (Integer)
Returns:
Json data from paystack API.
"""
return cls().requests.get('transferrecipient', qs=kwargs,)
| """Script used to define the paystack Transfer Recipient class."""
from paystackapi.base import PayStackBase
class Invoice(PayStackBase):
"""docstring for Transfer Recipient."""
@classmethod
def create(cls, **kwargs):
"""
Method defined to create transfer recipient.
Args:
type: Recipient Type (Only nuban at this time)
name: A name for the recipient
account_number: Required if type is nuban
bank_code: Required if type is nuban.
You can get the list of Bank Codes by calling the List Banks endpoint.
**kwargs
Returns:
Json data from paystack API.
"""
return cls().requests.post('transferrecipient', data=kwargs,)
@classmethod
def list(cls, **kwargs):
"""
Method defined to create transfer recipient.
Args:
perPage: records you want to retrieve per page (Integer)
page: what page you want to retrieve (Integer)
Returns:
Json data from paystack API.
"""
return cls().requests.get('transferrecipient', qs=kwargs,)
|
Remove a “trick babel” hack in analytics
Test plan
* with or without the “Drop IE 11” commit applied
* bin/rspec ./gems/plugins/analytics/spec_canvas/selenium/analytics_account_view_spec.rb:71
Should pass
Or to test manually:
* apply the “drop ie11” commit in canvas-lms
* check out this commit in gems/plugins/analytics
* go to /accounts/x/analytics
* it should load successfully and not die on this error at page load:
“Uncaught TypeError: Cannot read property '0' of null”
Change-Id: Ic402e444e3309028157c12576648c6afdd31cb34
Reviewed-on: https://gerrit.instructure.com/204050
Tested-by: Jenkins
Reviewed-by: Steven Burnett <a0b450117c5d20a22d5c4d52bb8ae13adee003d8@instructure.com>
QA-Review: Steven Burnett <a0b450117c5d20a22d5c4d52bb8ae13adee003d8@instructure.com>
Product-Review: Ryan Shaw <ea3cd978650417470535f3a4725b6b5042a6ab59@instructure.com> | import ComboBox from 'compiled/widget/ComboBox'
import DepartmentRouter from '../Department/DepartmentRouter'
export default class DepartmentFilterBox extends ComboBox {
constructor(model) {
// construct combobox
super(model.get('filters').models, {
value: filter => filter.get('id'),
label: filter => filter.get('label'),
selected: model.get('filter').get('id')
})
this.model = model
// add a router tied to the model
this.router = new DepartmentRouter(this.model)
// connect combobox to model
this.on('change', this.push)
this.model.on('change:filter', this.pull)
}
// #
// Push the current value of the combobox to the URL
push = filter => this.router.select(filter.get('fragment'))
// #
// Pull the current value from the model to the combobox
pull = () => this.select(this.model.get('filter').get('id'))
}
| import ComboBox from 'compiled/widget/ComboBox'
import DepartmentRouter from '../Department/DepartmentRouter'
export default class DepartmentFilterBox extends ComboBox {
constructor(model) {
{
// Hack: trick Babel/TypeScript into allowing this before super.
if (false) { super(); }
let thisFn = (() => { return this; }).toString();
let thisName = thisFn.match(/_this\d*/)[0];
eval(`${thisName} = this;`);
}
this.model = model
// add a router tied to the model
this.router = new DepartmentRouter(this.model)
// construct combobox
super(this.model.get('filters').models, {
value: filter => filter.get('id'),
label: filter => filter.get('label'),
selected: this.model.get('filter').get('id')
})
// connect combobox to model
this.on('change', this.push)
this.model.on('change:filter', this.pull)
}
// #
// Push the current value of the combobox to the URL
push = filter => this.router.select(filter.get('fragment'))
// #
// Pull the current value from the model to the combobox
pull = () => this.select(this.model.get('filter').get('id'))
}
|
Increment version - go ahead and call it 1.0, even. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='geodjango-timezones',
version='1.0',
description='Models to store and scripts to load timezone shapefiles to be usable inside a GeoDjango application.',
author='Adam Fast',
author_email='',
url='https://github.com/adamfast/geodjango_timezones',
packages=find_packages(),
package_data={
},
include_package_data=True,
install_requires=['pytz'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='geodjango-timezones',
version='0.1',
description='Models to store and scripts to load timezone shapefiles to be usable inside a GeoDjango application.',
author='Adam Fast',
author_email='',
url='https://github.com/adamfast/geodjango_timezones',
packages=find_packages(),
package_data={
},
include_package_data=True,
install_requires=['pytz'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
|
Add has and del functions | module.exports = AsyncCache;
var LRU = require('lru-cache');
function AsyncCache(opt) {
if (!opt || typeof opt !== 'object') {
throw new Error('options must be an object');
}
if (!opt.load) {
throw new Error('load function is required');
}
if (!(this instanceof AsyncCache)) {
return new AsyncCache(opt);
}
this._opt = opt;
this._cache = new LRU(opt);
this._load = opt.load;
this._loading = {};
}
AsyncCache.prototype.get = function(key, cb) {
if (this._loading[key]) {
this._loading[key].push(cb);
return;
}
var cached = this._cache.get(key);
if (cached) {
return process.nextTick(function() {
cb(null, cached);
});
}
this._loading[key] = [ cb ];
this._load(key, function(er, res) {
if (!er) this._cache.set(key, res);
var cbs = this._loading[key];
delete this._loading[key];
cbs.forEach(function (cb) {
cb(er, res);
});
}.bind(this));
};
AsyncCache.prototype.set = function(key, val) {
return this._cache.set(key, val);
};
AsyncCache.prototype.reset = function() {
return this._cache.reset();
};
AsyncCache.prototype.has = function(key) {
return this._cache.get(key);
};
AsyncCache.prototype.del = function(key) {
return this._cache.del(key);
};
| module.exports = AsyncCache;
var LRU = require('lru-cache');
function AsyncCache(opt) {
if (!opt || typeof opt !== 'object') {
throw new Error('options must be an object');
}
if (!opt.load) {
throw new Error('load function is required');
}
if (!(this instanceof AsyncCache)) {
return new AsyncCache(opt);
}
this._opt = opt;
this._cache = new LRU(opt);
this._load = opt.load;
this._loading = {};
}
AsyncCache.prototype.get = function(key, cb) {
if (this._loading[key]) {
this._loading[key].push(cb);
return;
}
var cached = this._cache.get(key);
if (cached) {
return process.nextTick(function() {
cb(null, cached);
});
}
this._loading[key] = [ cb ];
this._load(key, function(er, res) {
if (!er) this._cache.set(key, res);
var cbs = this._loading[key];
delete this._loading[key];
cbs.forEach(function (cb) {
cb(er, res);
});
}.bind(this));
};
AsyncCache.prototype.set = function(key, val) {
return this._cache.set(key, val);
};
AsyncCache.prototype.reset = function() {
return this._cache.reset();
};
|
Update print_gcide example to work with latest api changes. | import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import s3g
import serial
import optparse
parser = optparse.OptionParser()
parser.add_option("-p", "--serialport", dest="serialportname",
help="serial port (ex: /dev/ttyUSB0)", default="/dev/ttyACM0")
parser.add_option("-b", "--baud", dest="serialbaud",
help="serial port baud rate", default="115200")
parser.add_option("-f", "--filename", dest="filename",
help="gcode file to print", default=False)
(options, args) = parser.parse_args()
file = serial.Serial(options.serialportname, options.serialbaud, timeout=0)
r = s3g.s3g()
r.writer = s3g.Writer.StreamWriter(file)
parser = s3g.Gcode.GcodeParser()
parser.state.values["build_name"] = 'test'
parser.s3g = r
with open(options.filename) as f:
for line in f:
print line,
parser.ExecuteLine(line)
| import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import s3g
import serial
import optparse
parser = optparse.OptionParser()
parser.add_option("-p", "--serialport", dest="serialportname",
help="serial port (ex: /dev/ttyUSB0)", default="/dev/ttyACM0")
parser.add_option("-b", "--baud", dest="serialbaud",
help="serial port baud rate", default="115200")
parser.add_option("-f", "--filename", dest="filename",
help="gcode file to print", default=False)
(options, args) = parser.parse_args()
file = serial.Serial(options.serialportname, options.serialbaud, timeout=0)
r = s3g.s3g()
r.writer = s3g.StreamWriter(file)
parser = s3g.GcodeParser()
parser.s3g = r
with open(options.filename) as f:
for line in f:
print line
parser.ExecuteLine(line)
|
Update namespace in DIC extension | <?php
namespace Knplabs\TimeBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
class TimeExtension extends Extension
{
public function configLoad(array $configs, ContainerBuilder $container)
{
foreach ($configs as $config) {
$this->doConfigLoad($config, $container);
}
}
public function doConfigLoad(array $config, ContainerBuilder $container)
{
if(!$container->hasDefinition('time.templating.helper.time')) {
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('templating.xml');
$loader->load('twig.xml');
}
}
/**
* Returns the base path for the XSD files.
*
* @return string The XSD base path
*/
public function getXsdValidationBasePath()
{
return null;
}
public function getNamespace()
{
return 'http://www.symfony-project.org/schema/dic/symfony';
}
public function getAlias()
{
return 'time';
}
}
| <?php
namespace Knplabs\TimeBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\FileLocator;
class TimeExtension extends Extension
{
public function configLoad(array $configs, ContainerBuilder $container)
{
foreach ($configs as $config) {
$this->doConfigLoad($config, $container);
}
}
public function doConfigLoad(array $config, ContainerBuilder $container)
{
if(!$container->hasDefinition('time.templating.helper.time')) {
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('templating.xml');
$loader->load('twig.xml');
}
}
/**
* Returns the base path for the XSD files.
*
* @return string The XSD base path
*/
public function getXsdValidationBasePath()
{
return null;
}
public function getNamespace()
{
return 'http://www.symfony-project.org/schema/dic/symfony';
}
public function getAlias()
{
return 'time';
}
}
|
Fix char count for Firefox | // Gets character limit and allows no more
$(function() {
// Creates the character count elements
$(".js-char-count").wrap("<div class='char-count'></div>")
$(".js-char-count").after("<div class='char-text'>Character count: <span class='current-count'>0</span></div>");
// Includes charact limit if there is one
$(".js-char-count").each(function(){
var maxlength = $(this).attr('maxlength');
if (maxlength) {
$(this).closest(".char-count").find(".char-text").append("/<span class='total-count'>" +maxlength+ "</span>")
}
});
// On keydown, gets character count
$(".js-char-count").on('keyup', function () {
// Webkit counts a new line as a two characters
// IE doesn't use maxlength
var newline = " ";
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
// Firefox counts a new line as a singular character
newline = " ";
}
content = $(this).val().replace(/(\r\n|\n|\r)/gm," ");
$(this).closest(".char-count").find(".char-text .current-count").text(content.length);
// If character count is over the limit then show error
if (content.length > $(this).attr('maxlength')) {
$(this).closest(".char-count").addClass("char-over");
} else {
$(this).closest(".char-count").removeClass("char-over");
}
});
});
| // Gets character limit and allows no more
$(function() {
// Creates the character count elements
$(".js-char-count").wrap("<div class='char-count'></div>")
$(".js-char-count").after("<div class='char-text'>Character count: <span class='current-count'>0</span></div>");
// Includes charact limit if there is one
$(".js-char-count").each(function(){
var maxlength = $(this).attr('maxlength');
if (maxlength) {
$(this).closest(".char-count").find(".char-text").append("/<span class='total-count'>" +maxlength+ "</span>")
}
});
// On keydown, gets character count
$(".js-char-count").on('keyup', function () {
content = $(this).val().replace(/(\r\n|\n|\r)/gm," ");
$(this).closest(".char-count").find(".char-text .current-count").text(content.length);
// If character count is over the limit then show error
if (content.length > $(this).attr('maxlength')) {
$(this).closest(".char-count").addClass("char-over");
} else {
$(this).closest(".char-count").removeClass("char-over");
}
});
});
|
Remove pagination from controllers data provider to show more than 20 controllers | <?php
/**
* Created by PhpStorm.
* User: alex
* Date: 20/10/2016
* Time: 15:57
*/
namespace vr\api\doc\widgets;
use yii\bootstrap\Widget;
use yii\data\ArrayDataProvider;
use yii\widgets\ListView;
/**
* Class ControllersListView
* @package vr\api\doc\widgets
*/
class ControllersListView extends Widget
{
/**
* @var null
*/
public $models = null;
/**
* @return string
* @throws \Exception
*/
public function run()
{
return ListView::widget([
'dataProvider' => new ArrayDataProvider([
'allModels' => $this->models,
'pagination' => false,
]),
'layout' => '{items}',
'itemView' => '@api/doc/widgets/views/controller-list-item-view',
]);
}
} | <?php
/**
* Created by PhpStorm.
* User: alex
* Date: 20/10/2016
* Time: 15:57
*/
namespace vr\api\doc\widgets;
use yii\bootstrap\Widget;
use yii\data\ArrayDataProvider;
use yii\widgets\ListView;
/**
* Class ControllersListView
* @package vr\api\doc\widgets
*/
class ControllersListView extends Widget
{
/**
* @var null
*/
public $models = null;
/**
* @return string
* @throws \Exception
*/
public function run()
{
return ListView::widget([
'dataProvider' => new ArrayDataProvider([
'allModels' => $this->models,
]),
'layout' => '{items}',
'itemView' => '@api/doc/widgets/views/controller-list-item-view',
]);
}
} |
Add instructions for bumping the version. | import distutils.core
# Uploading to PyPI
# =================
# The first time only:
# $ python setup.py register -r pypi
#
# Every version bump:
# $ git tag <version>; git push
# $ python setup.py sdist upload -r pypi
version = '1.0'
distutils.core.setup(
name='nonstdlib',
version=version,
author='Kale Kundert',
author='kale@thekunderts.net',
url='https://github.com/kalekundert/nonstdlib',
download_url='https://github.com/kalekundert/nonstdlib/tarball/'+version,
license='MIT',
description="A collection of general-purpose utilities.",
long_description=open('README.rst').read(),
keywords=['utilities', 'library'],
packages=['nonstdlib'],
)
| import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '1.0'
distutils.core.setup(
name='nonstdlib',
version=version,
author='Kale Kundert',
author='kale@thekunderts.net',
url='https://github.com/kalekundert/nonstdlib',
download_url='https://github.com/kalekundert/nonstdlib/tarball/'+version,
license='MIT',
description="A collection of general-purpose utilities.",
long_description=open('README.rst').read(),
keywords=['utilities', 'library'],
packages=['nonstdlib'],
)
|
Change rerun strategy for HHVM (pcntl does not work) | <?php
/*
* This file is part of PhpSpec, A php toolset to drive emergent
* design by specification.
*
* (c) Marcello Duarte <marcello.duarte@gmail.com>
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PhpSpec\Process\ReRunner;
class PcntlReRunner extends PhpExecutableReRunner
{
/**
* @return bool
*/
public function isSupported()
{
return (php_sapi_name() == 'cli')
&& $this->getExecutablePath()
&& function_exists('pcntl_exec')
&& !defined('HHVM_VERSION');
}
/**
* Kills the current process and starts a new one
*/
public function reRunSuite()
{
$args = $_SERVER['argv'];
pcntl_exec($this->getExecutablePath(), $args);
}
}
| <?php
/*
* This file is part of PhpSpec, A php toolset to drive emergent
* design by specification.
*
* (c) Marcello Duarte <marcello.duarte@gmail.com>
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PhpSpec\Process\ReRunner;
class PcntlReRunner extends PhpExecutableReRunner
{
/**
* @return bool
*/
public function isSupported()
{
return (php_sapi_name() == 'cli')
&& $this->getExecutablePath()
&& function_exists('pcntl_exec');
}
/**
* Kills the current process and starts a new one
*/
public function reRunSuite()
{
$args = $_SERVER['argv'];
pcntl_exec($this->getExecutablePath(), $args);
}
}
|
Add debug logging for Travis | import {childProcess} from 'node-promise-es6';
import {path as phantomJsPath} from 'phantomjs-prebuilt';
import PhantomJS from 'phantomjs-promise-es6';
async function sleep(ms) {
await new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function phantomPid() {
try {
const {stdout: pid} = await childProcess.exec(`pgrep -f '${phantomJsPath}'`);
return pid.trim();
} catch (error) {
return null;
}
}
describe('phantomjs-promise-es6', () => {
describe('#exit', () => {
it('kills the phantomjs process', async () => {
const browser = new PhantomJS();
const pid = await phantomPid();
expect(pid).not.toBeNull();
process.stdout.write(`${pid}\n`);
await browser.exit();
await sleep(1000);
expect(await phantomPid()).toBeNull();
});
});
});
| import {childProcess} from 'node-promise-es6';
import {path as phantomJsPath} from 'phantomjs-prebuilt';
import PhantomJS from 'phantomjs-promise-es6';
async function sleep(ms) {
await new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function phantomPid() {
try {
const {stdout: pid} = await childProcess.exec(`pgrep -f '${phantomJsPath}'`);
return pid.trim();
} catch (error) {
return null;
}
}
describe('phantomjs-promise-es6', () => {
describe('#exit', () => {
it('kills the phantomjs process', async () => {
const browser = new PhantomJS();
expect(await phantomPid()).not.toBeNull();
await browser.exit();
await sleep(1000);
expect(await phantomPid()).toBeNull();
});
});
});
|
Fix various bugs in the IndexedCache. | 'use strict';
function IndexedCache(getFunc) {
this._items = {};
this._getFunc = getFunc;
}
IndexedCache.prototype.getNow = function(index) {
var item = this._items[index];
if (!item || !item.data) {
throw new Error('Attempted to getNow an unloaded data resource (' + index + ').');
}
return item.data;
};
IndexedCache.prototype.get = function(index, callback) {
var item = this._items[index];
if (item) {
if (callback) {
if (item.data) {
callback(item.data);
} else {
item.waiters.push(callback);
}
}
return;
}
var newItem = {
data: null,
waiters: callback ? [callback] : []
};
this._items[index] = newItem;
this._getFunc(index, function(data) {
newItem.data = data;
for (var i = 0; i < newItem.waiters.length; ++i) {
newItem.waiters[i](data);
}
newItem.waiters = [];
});
};
// Little helper for dealing with path based indexes.
function DataCache(loader) {
this._cache = new IndexedCache(loader.load);
}
DataCache.prototype.get = function(path, callback) {
var normPath = normalizePath(path);
return this._cache.get(normPath, callback);
};
| 'use strict';
function IndexedCache(getFunc) {
this.items = {};
this.getFunc = getFunc;
}
IndexedCache.prototype.get = function(index, callback) {
var item = this.items[index];
if (item) {
if (item.data) {
callback(item.data);
} else {
item.waiters.push(callback);
}
return;
}
var newItem = {
data: null,
waiters: [callback]
};
this.items[index] = newItem;
this.getFunc(index, function(data) {
newItem.data = data;
for (var i = 0; i < newItem.waiters.length; ++i) {
newItem.waiters[i](data);
}
newItem.waiters = [];
});
};
// Little helper for dealing with path based indexes.
function DataCache(loader) {
this.cache = new IndexedCache(loader.load);
}
DataCache.prototype.get = function(path, callback) {
var normPath = normalizePath(path);
return this.cache.get(normPath, callback);
};
|
Return users that have authed through github | var routes = (passport, mongoose) => {
var express = require('express');
var router = express.Router();
router.get('/auth/github', passport.authenticate('github'));
router.get('/auth/callback/github',
passport.authenticate('github', { failureRedirect: '/' }), (req, res) => {
res.redirect('/#/git/' + req.user.username);
});
router.get('/auth/logout', (req, res, next) => {
req.logout();
res.redirect("/");
});
router.get('/currentuser', (req, res, next) => {
console.log("get user data", req.user);
res.json(req.user);
})
router.get('/userprofile/:username', (req, res, next) => {
let User = require('../models/user');
console.log(req.params.username);
User.findOne({ 'username': new RegExp('^'+req.params.username+'$', "i") }).exec( (err, user) => {
if (err) {
res.status(400);
}
if (user) {
res.json(user)
}
if (!user) {
// hit github api
}
})
});
router.get('/', (req, res, next) => {
console.log(req.user);
res.render('index', { currentUserData: req.user });
});
return router;
}
module.exports = routes;
| var routes = (passport, mongoose) => {
var express = require('express');
var router = express.Router();
router.get('/auth/github', passport.authenticate('github'));
router.get('/auth/callback/github',
passport.authenticate('github', { failureRedirect: '/' }), (req, res) => {
res.redirect('/#/git/' + req.user.username);
});
router.get('/auth/logout', (req, res, next) => {
req.logout();
res.redirect("/");
});
router.get('/currentuser', (req, res, next) => {
console.log("get user data", req.user);
res.json(req.user);
})
router.get('/userprofile/:username', (req, res, next) => {
let User = require('../models/user');
console.log(req.params.username);
User.findOne({ 'username': new RegExp('^'+req.params.username+'$', "i") }).exec( (err, user) => {
console.log(user);
})
res.json({message: "complete"});
});
router.get('/', (req, res, next) => {
console.log(req.user);
res.render('index', { currentUserData: req.user });
});
return router;
}
module.exports = routes;
|
Use pip2pi, not dir2pi for deploys | from fabric.api import *
"""
Overview
========
This fabric file automates the process of pip packaging and
deploying your new pip package to our private pip repository.
Requirements
------------
- Must have fabric installed via `pip install fabric`
- Must have your setup.py working and up to date. Make sure
it works by running `python setup.py test` or do a test install
via `python setup.py install` inside a virtualenv.
Deploying
---------
Run `fab publish` for a one step pip package deploy!
"""
def prep():
local("pip install pip2pi")
def package():
local("python setup.py sdist")
def deploy(pip_repo):
name = local("python setup.py --name", capture=True)
ver = local("python setup.py --version", capture=True)
sdist_name = '{}-{}.tar.gz'.format(name, ver)
local("pip2pi {} dist/{}".format(pip_repo, sdist_name))
def publish():
prep()
package()
deploy() | from fabric.api import *
"""
Overview
========
This fabric file automates the process of pip packaging and
deploying your new pip package to our private pip repository.
Requirements
------------
- Must have fabric installed via `pip install fabric`
- Must have your setup.py working and up to date. Make sure
it works by running `python setup.py test` or do a test install
via `python setup.py install` inside a virtualenv.
Deploying
---------
Run `fab publish` for a one step pip package deploy!
"""
def prep():
local("pip install dir2pi")
def package():
local("python setup.py sdist")
def deploy(pip_repo):
name = local("python setup.py --name", capture=True)
ver = local("python setup.py --version", capture=True)
sdist_name = '{}-{}.tar.gz'.format(name, ver)
local("dir2pi {} dist/{}".format(pip_repo, sdist_name))
def publish():
prep()
package()
deploy() |
Add test for circle geometry | package ol.geom;
import ol.Coordinate;
import ol.GwtOL3BaseTestCase;
import ol.OLFactory;
/**
* A test case for {@link Circle}.
*
* @author Tino Desjardins
*/
public class CircleTest extends GwtOL3BaseTestCase {
public void testCircle() {
injectUrlAndTest(new TestWithInjection() {
@Override
public void test() {
double radius = 5;
Circle circle = OLFactory.createCircle(OLFactory.createCoordinate(10, 10), radius);
assertNotNull(circle);
assertTrue(circle instanceof Geometry);
Coordinate coordinate = circle.getCenter();
assertNotNull(coordinate);
assert(10 == coordinate.getX());
assert(10 == coordinate.getY());
assert(radius == circle.getRadius());
}});
}
}
| package ol.geom;
import ol.BaseTestCase;
import ol.Coordinate;
import ol.OLFactory;
/**
* A test case for {@link Circle}.
*
* @author Tino Desjardins
*/
public class CircleTest extends BaseTestCase {
public void test() {
double radius = 5;
Circle circle = OLFactory.createCircle(OLFactory.createCoordinate(10, 10), radius);
assertNotNull(circle);
assertTrue(circle instanceof Geometry);
Coordinate coordinate = circle.getCenter();
assertNotNull(coordinate);
assert(10 == coordinate.getX());
assert(10 == coordinate.getY());
assert(radius == circle.getRadius());
}
}
|
Make Twig filter test work on PHP 5.3 | <?php
namespace Clippings\ParsedownProvider\Test;
use Pimple\Container;
use Twig_Test_IntegrationTestCase;
use Silex\Provider\TwigServiceProvider;
use Clippings\ParsedownProvider\ParsedownServiceProvider;
class ParsedownTwigFilterTest extends Twig_Test_IntegrationTestCase
{
/**
* @var Pimple\Container
*/
private $container;
public function setUp()
{
parent::setUp();
$this->container = new Container();
$app['twig'] = true;
$this->container->register(new ParsedownServiceProvider());
}
public function getTwigFilters()
{
return array($this->container['parsedown.twig_filter']);
}
public function getFixturesDir()
{
return __DIR__.'/Fixtures/';
}
}
| <?php
namespace Clippings\ParsedownProvider\Test;
use Pimple\Container;
use Twig_Test_IntegrationTestCase;
use Silex\Provider\TwigServiceProvider;
use Clippings\ParsedownProvider\ParsedownServiceProvider;
class ParsedownTwigFilterTest extends Twig_Test_IntegrationTestCase
{
/**
* @var Pimple\Container
*/
private $container;
public function setUp()
{
parent::setUp();
$this->container = new Container();
$app['twig'] = true;
$this->container->register(new ParsedownServiceProvider());
}
public function getTwigFilters()
{
return [$this->container['parsedown.twig_filter']];
}
public function getFixturesDir()
{
return __DIR__.'/Fixtures/';
}
}
|
Fix archive versions for 1.3.0 | package alien4cloud.packager;
import alien4cloud.git.RepositoryManager;
import alien4cloud.utils.FileUtil;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Utility that downloads the archives we want to package.
*/
public class ArchiveDownloader {
public static void main(String[] args) throws IOException {
Path buildDirectory = Paths.get(args[0]);
Path gitDirectory = buildDirectory.resolve("git");
Path zipDirectory = buildDirectory.resolve("archives");
RepositoryManager.cloneOrCheckout(gitDirectory, "https://github.com/alien4cloud/tosca-normative-types.git", "1.2.0", "tosca-normative-types");
RepositoryManager.cloneOrCheckout(gitDirectory, "https://github.com/alien4cloud/alien4cloud-extended-types.git", "1.2.0",
"alien4cloud-extended-types");
// Do we want to initialize alien with sample topology.
// repositoryManager.cloneOrCheckout(gitDirectory, "https://github.com/alien4cloud/samples.git", "master", "samples");
FileUtil.zip(gitDirectory.resolve("tosca-normative-types"), zipDirectory.resolve("tosca-normative-types.zip"));
FileUtil.zip(gitDirectory.resolve("alien4cloud-extended-types/alien-extended-storage-types"), zipDirectory.resolve("alien-extended-storage-types.zip"));
// zip archives
// FileUtil.zip(from, to);
}
}
| package alien4cloud.packager;
import alien4cloud.git.RepositoryManager;
import alien4cloud.utils.FileUtil;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Utility that downloads the archives we want to package.
*/
public class ArchiveDownloader {
public static void main(String[] args) throws IOException {
Path buildDirectory = Paths.get(args[0]);
Path gitDirectory = buildDirectory.resolve("git");
Path zipDirectory = buildDirectory.resolve("archives");
RepositoryManager.cloneOrCheckout(gitDirectory, "https://github.com/alien4cloud/tosca-normative-types.git", "master", "tosca-normative-types");
RepositoryManager.cloneOrCheckout(gitDirectory, "https://github.com/alien4cloud/alien4cloud-extended-types.git", "master",
"alien4cloud-extended-types");
// Do we want to initialize alien with sample topology.
// repositoryManager.cloneOrCheckout(gitDirectory, "https://github.com/alien4cloud/samples.git", "master", "samples");
FileUtil.zip(gitDirectory.resolve("tosca-normative-types"), zipDirectory.resolve("tosca-normative-types.zip"));
FileUtil.zip(gitDirectory.resolve("alien4cloud-extended-types/alien-extended-storage-types"), zipDirectory.resolve("alien-extended-storage-types.zip"));
// zip archives
// FileUtil.zip(from, to);
}
}
|
Make sure initCustomEvent is called properly | /* global chrome */
(function () {
document.addEventListener('window.remoteDebug.getDebugSocket', function (e) {
chrome.runtime.sendMessage({
cmd: 'getDebugSocket'
})
})
var s = document.createElement('script')
s.textContent = '(' + function () {
window.remoteDebug = {}
window.remoteDebug.getDebugSocket = function (requester) {
if (window.confirm('Do you want to allow ' + requester + ' to remote debug this tab?')) { // eslint-disable-line no-alert
var evt = document.createEvent('CustomEvent')
evt.initCustomEvent('window.remoteDebug.getDebugSocket', true, true, {})
document.dispatchEvent(evt)
}
}
} + ')();'
document.documentElement.appendChild(s)
s.parentNode.removeChild(s)
})()
| /* global chrome */
(function () {
document.addEventListener('window.remoteDebug.getDebugSocket', function (e) {
chrome.runtime.sendMessage({
cmd: 'getDebugSocket'
})
})
var s = document.createElement('script')
s.textContent = '(' + function () {
window.remoteDebug = {}
window.remoteDebug.getDebugSocket = function (requester) {
if (window.confirm('Do you want to allow ' + requester + ' to remote debug this tab?')) { // eslint-disable-line no-alert
var evt = document.createEvent('CustomEvent')
evt.initCustomEvent('window.remoteDebug.getDebugSocket', true, true)
document.dispatchEvent(evt)
}
}
} + ')();'
document.documentElement.appendChild(s)
s.parentNode.removeChild(s)
})()
|
Fix HEAD requests for kernelspec resources
Closes gh-7237
Closes gh-7258
StaticFileHandler.get() is a coroutine. When Tornado calls a handler
method, it uses the return value to determine whether or not it's a
coroutine. So when head() calls get(), it needs to pass the return value
on for Tornado to handle it properly. | from tornado import web
from ..base.handlers import IPythonHandler
from ..services.kernelspecs.handlers import kernel_name_regex
class KernelSpecResourceHandler(web.StaticFileHandler, IPythonHandler):
SUPPORTED_METHODS = ('GET', 'HEAD')
def initialize(self):
web.StaticFileHandler.initialize(self, path='')
@web.authenticated
def get(self, kernel_name, path, include_body=True):
ksm = self.kernel_spec_manager
try:
self.root = ksm.get_kernel_spec(kernel_name).resource_dir
except KeyError:
raise web.HTTPError(404, u'Kernel spec %s not found' % kernel_name)
self.log.debug("Serving kernel resource from: %s", self.root)
return web.StaticFileHandler.get(self, path, include_body=include_body)
@web.authenticated
def head(self, kernel_name, path):
return self.get(kernel_name, path, include_body=False)
default_handlers = [
(r"/kernelspecs/%s/(?P<path>.*)" % kernel_name_regex, KernelSpecResourceHandler),
] | from tornado import web
from ..base.handlers import IPythonHandler
from ..services.kernelspecs.handlers import kernel_name_regex
class KernelSpecResourceHandler(web.StaticFileHandler, IPythonHandler):
SUPPORTED_METHODS = ('GET', 'HEAD')
def initialize(self):
web.StaticFileHandler.initialize(self, path='')
@web.authenticated
def get(self, kernel_name, path, include_body=True):
ksm = self.kernel_spec_manager
try:
self.root = ksm.get_kernel_spec(kernel_name).resource_dir
except KeyError:
raise web.HTTPError(404, u'Kernel spec %s not found' % kernel_name)
self.log.debug("Serving kernel resource from: %s", self.root)
return web.StaticFileHandler.get(self, path, include_body=include_body)
@web.authenticated
def head(self, kernel_name, path):
self.get(kernel_name, path, include_body=False)
default_handlers = [
(r"/kernelspecs/%s/(?P<path>.*)" % kernel_name_regex, KernelSpecResourceHandler),
] |
[DashboardBundle] Enable esi by default for the dashboard bundle | <?php
namespace Kunstmaan\DashboardBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class KunstmaanDashboardExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
$loader->load('commands.yml');
}
public function prepend(ContainerBuilder $container)
{
$container->prependExtensionConfig('framework', ['esi' => ['enabled' => true]]);
}
}
| <?php
namespace Kunstmaan\DashboardBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class KunstmaanDashboardExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
$loader->load('commands.yml');
}
}
|
Change synchronization for `get` method in `lazy` module | package storm.lazy;
public class Lazy<T> {
public interface LazyProvider<T> {
T provide();
}
private final LazyProvider<T> mProvider;
private T mCachedValue;
private volatile boolean mIsProviderCalled;
public Lazy(LazyProvider<T> provider) {
if (provider == null) {
throw new NullPointerException("Provider cannot be NULL");
}
this.mProvider = provider;
}
public synchronized T get() {
if (!mIsProviderCalled) {
mCachedValue = mProvider.provide();
mIsProviderCalled = true;
}
return mCachedValue;
}
public boolean isProviderCalled() {
return mIsProviderCalled;
}
}
| package storm.lazy;
public class Lazy<T> {
public interface LazyProvider<T> {
T provide();
}
private final LazyProvider<T> mProvider;
private T mCachedValue;
private volatile boolean mIsProviderCalled;
public Lazy(LazyProvider<T> provider) {
if (provider == null) {
throw new NullPointerException("Provider cannot be NULL");
}
this.mProvider = provider;
}
public T get() {
if (!mIsProviderCalled) {
synchronized (this) {
mCachedValue = mProvider.provide();
mIsProviderCalled = true;
}
}
return mCachedValue;
}
public boolean isProviderCalled() {
return mIsProviderCalled;
}
}
|
Add "parent" field to track topic ids | // NNTP article
//
'use strict';
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;
module.exports = function (N, collectionName) {
let Article = new Schema({
source: Schema.ObjectId,
parent: Schema.ObjectId,
group: Schema.ObjectId,
index: Number
}, {
versionKey: false
});
// Indexes
//////////////////////////////////////////////////////////////////////////////
// find an article by message_id (ARTICLE command)
Article.index({ source: 1 });
// mass-removal of messages
Article.index({ parent: 1 });
// get range of articles inside a group
Article.index({ group: 1, index: 1 });
N.wire.on('init:models', function emit_init_Article() {
return N.wire.emit('init:models.' + collectionName, Article);
});
N.wire.on('init:models.' + collectionName, function init_model_Article(schema) {
N.models[collectionName] = Mongoose.model(collectionName, schema);
});
};
| // NNTP article
//
'use strict';
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;
module.exports = function (N, collectionName) {
let Article = new Schema({
source: Schema.ObjectId,
group: Schema.ObjectId,
index: Number
}, {
versionKey: false
});
// Indexes
//////////////////////////////////////////////////////////////////////////////
// find an article by message_id (ARTICLE command)
Article.index({ source: 1 });
// get range of articles inside a group
Article.index({ group: 1, index: 1 });
N.wire.on('init:models', function emit_init_Article() {
return N.wire.emit('init:models.' + collectionName, Article);
});
N.wire.on('init:models.' + collectionName, function init_model_Article(schema) {
N.models[collectionName] = Mongoose.model(collectionName, schema);
});
};
|
Fix typos in fullscreen methods for IE11
https://bugzilla.redhat.com/show_bug.cgi?id=1520105 | $(function() {
$('#fullscreen').click(function() {
switch (true) {
case document.fullScreenEnabled:
if (document.fullscreenElement) {
document.exitFullscreen();
} else {
document.documentElement.requestFullscreen();
}
break;
case document.webkitFullscreenEnabled:
if (document.webkitFullscreenElement) {
document.webkitExitFullscreen();
} else {
document.documentElement.webkitRequestFullscreen();
}
break;
case document.mozFullScreenEnabled:
if (document.mozFullScreenElement) {
document.mozCancelFullScreen();
} else {
document.documentElement.mozRequestFullScreen();
}
break;
case document.msFullscreenEnabled:
if (document.msFullscreenElement) {
document.msExitFullscreen();
} else {
document.documentElement.msRequestFullscreen();
}
break;
}
});
});
| $(function() {
$('#fullscreen').click(function() {
switch (true) {
case document.fullScreenEnabled:
if (document.fullscreenElement) {
document.exitFullscreen();
} else {
document.documentElement.requestFullscreen();
}
break;
case document.webkitFullscreenEnabled:
if (document.webkitFullscreenElement) {
document.webkitExitFullscreen();
} else {
document.documentElement.webkitRequestFullscreen();
}
break;
case document.mozFullScreenEnabled:
if (document.mozFullScreenElement) {
document.mozCancelFullScreen();
} else {
document.documentElement.mozRequestFullScreen();
}
break;
case document.msFullScreenEnabled:
if (document.msFullScreenElement) {
document.msExitFullScreen();
} else {
document.documentElement.msRequestFullScreen();
}
break;
}
});
});
|
Load new doctrine and swiftmailer bundles | <?php
use Tomahawk\HttpKernel\Kernel;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new \Tomahawk\Bundle\FrameworkBundle\FrameworkBundle(),
new \Tomahawk\Bundle\GeneratorBundle\GeneratorBundle(),
new \Tomahawk\Bundle\MigrationsBundle\MigrationsBundle(),
new \Tomahawk\Bundle\DoctrineBundle\DoctrineBundle(),
new \Tomahawk\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new \Acme\AcmeBundle()
);
if ($this->getEnvironment() === 'dev') {
$bundles[] = new \Tomahawk\Bundle\WebProfilerBundle\WebProfilerBundle();
}
return $bundles;
}
public function registerMiddleware()
{
return array(
new \Tomahawk\HttpCore\Middleware\Response(),
new \Tomahawk\Session\Middleware\Session()
);
}
} | <?php
use Tomahawk\HttpKernel\Kernel;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new \Tomahawk\Bundle\FrameworkBundle\FrameworkBundle(),
new \Tomahawk\Bundle\GeneratorBundle\GeneratorBundle(),
new \Tomahawk\Bundle\MigrationsBundle\MigrationsBundle(),
new \Acme\AcmeBundle()
);
if ($this->getEnvironment() === 'dev') {
$bundles[] = new \Tomahawk\Bundle\WebProfilerBundle\WebProfilerBundle();
}
return $bundles;
}
public function registerMiddleware()
{
return array(
new \Tomahawk\HttpCore\Middleware\Response(),
new \Tomahawk\Session\Middleware\Session()
);
}
} |
Convert foreign modules to try bundling with esbuild | "use strict";
// Alias require to prevent webpack or browserify from actually requiring.
var req = typeof module === "undefined" ? undefined : module.require;
var util = (function() {
try {
return req === undefined ? undefined : req("util");
} catch(e) {
return undefined;
}
})();
export var _trace = function (x, k) {
// node only recurses two levels into an object before printing
// "[object]" for further objects when using console.log()
if (util !== undefined) {
console.log(util.inspect(x, { depth: null, colors: true }));
} else {
console.log(x);
}
return k({});
};
export var _spy = function (tag, x) {
if (util !== undefined) {
console.log(tag + ":", util.inspect(x, { depth: null, colors: true }));
} else {
console.log(tag + ":", x);
}
return x;
};
export var _debugger = function (f) {
debugger;
return f();
};
| "use strict";
// Alias require to prevent webpack or browserify from actually requiring.
var req = typeof module === "undefined" ? undefined : module.require;
var util = (function() {
try {
return req === undefined ? undefined : req("util");
} catch(e) {
return undefined;
}
})();
exports._trace = function (x, k) {
// node only recurses two levels into an object before printing
// "[object]" for further objects when using console.log()
if (util !== undefined) {
console.log(util.inspect(x, { depth: null, colors: true }));
} else {
console.log(x);
}
return k({});
};
exports._spy = function (tag, x) {
if (util !== undefined) {
console.log(tag + ":", util.inspect(x, { depth: null, colors: true }));
} else {
console.log(tag + ":", x);
}
return x;
};
exports._debugger = function (f) {
debugger;
return f();
};
|
Add some delay to the dev api to better represent reality | // To use it create some files under `routes/`
// e.g. `server/routes/ember-hamsters.js`
//
// module.exports = function(app) {
// app.get('/ember-hamsters', function(req, res) {
// res.send('hello');
// });
// };
module.exports = function(app) {
var globSync = require('glob').sync;
var bodyParser = require('body-parser');
var mocks = globSync('./mocks/**/*.js', { cwd: __dirname }).map(require);
var proxies = globSync('./proxies/**/*.js', { cwd: __dirname }).map(require);
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function(req,res,next){
setTimeout(next,1000);
});
// Uncomment to log proxy requests
// var morgan = require('morgan');
// app.use(morgan('dev'));
mocks.forEach(function(route) { route(app); });
proxies.forEach(function(route) { route(app); });
};
| // To use it create some files under `routes/`
// e.g. `server/routes/ember-hamsters.js`
//
// module.exports = function(app) {
// app.get('/ember-hamsters', function(req, res) {
// res.send('hello');
// });
// };
module.exports = function(app) {
var globSync = require('glob').sync;
var bodyParser = require('body-parser');
var mocks = globSync('./mocks/**/*.js', { cwd: __dirname }).map(require);
var proxies = globSync('./proxies/**/*.js', { cwd: __dirname }).map(require);
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Uncomment to log proxy requests
// var morgan = require('morgan');
// app.use(morgan('dev'));
mocks.forEach(function(route) { route(app); });
proxies.forEach(function(route) { route(app); });
};
|
Change that was unintended to implement with the data was removed | import { percentPovertyLevel,
percentStateMedianIncome } from '../../../helpers/helperFunctions';
function getHousingEligibility(client) {
let percentPov = parseInt(percentPovertyLevel(parseInt(client.annualIncome), client.householdSize));
if (client.annualIncome == 0 || percentPov < 70) {
return {result: 'good', details: 'All good!', benefitValue: 800};
} else if (percentPov > 70 && percentPov < 80) {
return {result: 'information', details: `Your income puts you at ${percentPov.toFixed()}% of the federal poverty level, which is close to the 80% limit.`, benefitValue: 800};
} else {
return {result: 'warning', details: `Your income puts you at ${percentPov.toFixed()}% of the federal poverty level, which is above the 80% limit.`, benefitValue: 0};
}
}
export {getHousingEligibility}; | import { percentPovertyLevel,
percentStateMedianIncome } from '../../../helpers/helperFunctions';
function getHousingEligibility(client) {
let percentPov = parseInt(percentStateMedianIncome(parseInt(client.annualIncome), client.householdSize));
if (client.annualIncome == 0 || percentPov < 70) {
return {result: 'good', details: 'All good!', benefitValue: 800};
} else if (percentPov > 70 && percentPov < 80) {
return {result: 'information', details: `Your income puts you at ${percentPov.toFixed()}% of the federal poverty level, which is close to the 80% limit.`, benefitValue: 800};
} else {
return {result: 'warning', details: `Your income puts you at ${percentPov.toFixed()}% of the federal poverty level, which is above the 80% limit.`, benefitValue: 0};
}
}
export {getHousingEligibility}; |
Comment out bootstrap to make test suite pass | import React, { Component, PropTypes } from 'react'
import classnames from 'classnames'
import { jsdom } from 'jsdom'
import OrganisationListRow from './OrganisationListRow'
//Snippet taken from https://www.npmjs.com/package/jquery
// require("jsdom").env("", function(err, window) {
// if (err) {
// console.error(err);
// return;
// }
//
// var $ = require("jquery")(window);
// require('bootstrap');
// });
class OrganisationList extends Component {
render() {
var numberOfOrgs = this.props.organisations.length;
var rows = [];
var counter = 0;
for(var i=0; i<numberOfOrgs; i++) {
rows.push(<OrganisationListRow name={this.props.organisations[i].name} id={this.props.organisations[i].id} key={counter}/>);
counter++;
};
return(
<table className="table table-striped table-bordered table-hover">
<thead className="thead">
<th>Name</th>
<th>Id</th>
</thead>
<tbody className="tbody">
{rows}
//<OrganisationListRow name={this.props.organisations[0].name} id={this.props.organisations[0].id}/>
</tbody>
</table>
);
}
}
export default OrganisationList
| import React, { Component, PropTypes } from 'react'
import classnames from 'classnames'
import { jsdom } from 'jsdom'
import OrganisationListRow from './OrganisationListRow'
//Snippet taken from https://www.npmjs.com/package/jquery
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
require('bootstrap');
});
class OrganisationList extends Component {
render() {
var numberOfOrgs = this.props.organisations.length;
var rows = [];
var counter = 0;
for(var i=0; i<numberOfOrgs; i++) {
rows.push(<OrganisationListRow name={this.props.organisations[i].name} id={this.props.organisations[i].id} key={counter}/>);
counter++;
};
return(
<table className="table table-striped table-bordered table-hover">
<thead className="thead">
<th>Name</th>
<th>Id</th>
</thead>
<tbody className="tbody">
{rows}
//<OrganisationListRow name={this.props.organisations[0].name} id={this.props.organisations[0].id}/>
</tbody>
</table>
);
}
}
export default OrganisationList |
[Python] Complete 'About Triangle Project 2' koans | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' if no sides are equal
#
# The tests for this method can be found in
# about_triangle_project.py
# and
# about_triangle_project_2.py
#
def triangle(a, b, c):
# Check input
if a <= 0 or b <= 0 or c <= 0:
raise TriangleError(AttributeError("Negative values"))
if a + b + c <= 2 * max(a, b, c):
raise TriangleError(AttributeError("Imposible triangle"))
if a == b == c:
return 'equilateral'
elif a == b or a == c or b == c:
return 'isosceles'
else:
return 'scalene'
# Error class used in part 2. No need to change this code.
class TriangleError(Exception):
pass
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' if no sides are equal
#
# The tests for this method can be found in
# about_triangle_project.py
# and
# about_triangle_project_2.py
#
def triangle(a, b, c):
# DELETE 'PASS' AND WRITE THIS CODE
# pass
if a == b == c:
return 'equilateral'
elif a == b or a == c or b == c:
return 'isosceles'
else:
return 'scalene'
# Error class used in part 2. No need to change this code.
class TriangleError(Exception):
pass
|
Add meta refresh in wrapper instead of vdom | const h = require('virtual-dom/h');
module.exports = function (data) {
const {gameID, game} = data;
return h('div', {className: 'room'}, [
game.playing ? null : h('form', {method: 'post', action: `/${gameID}`}, [
h('button', {type: 'button', id: 'min'}, '-'),
h('input', {type: 'number', name: 'max-score', min: '1', value: game.maxScore}),
h('button', {type: 'button', id: 'max'}, '+'),
h('button', {type: 'submit'}, 'Start')
]),
h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'),
h('div', {id: 'players'}, [
h('ul', Object.keys(game.players).map(playerID => {
const player = game.players[playerID];
return h('li', {
style: {
backgroundColor: `rgb(${player.color[1]}, ${player.color[0]}, ${player.color[2]})`
},
dataPlayerId: playerID
}, 'Score: ' + player.score)
}))
])
]);
};
| const h = require('virtual-dom/h');
module.exports = function (data) {
const {gameID, game} = data;
return h('div', {className: 'room'}, [
game.playing ? h('meta', {httpEquiv: 'refresh', content: '1'}) : h('form', {method: 'post', action: `/${gameID}`}, [
h('button', {type: 'button', id: 'min'}, '-'),
h('input', {type: 'number', name: 'max-score', min: '1', value: game.maxScore}),
h('button', {type: 'button', id: 'max'}, '+'),
h('button', {type: 'submit'}, 'Start')
]),
h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'),
h('div', {id: 'players'}, [
h('ul', Object.keys(game.players).map(playerID => {
const player = game.players[playerID];
return h('li', {
style: {
backgroundColor: `rgb(${player.color[1]}, ${player.color[0]}, ${player.color[2]})`
},
dataPlayerId: playerID
}, 'Score: ' + player.score)
}))
])
]);
};
|
Implement COMMIT and ROLLBACK actions | import mobx from 'mobx';
import { stringify, parse } from 'jsan';
import { setValue } from './utils';
export const isMonitorAction = (store) => store.__isRemotedevAction === true;
export const dispatchMonitorAction = (store, devTools) => {
let intermValue;
const initValue = mobx.toJS(store);
devTools.init(initValue);
return (message) => {
if (message.type === 'DISPATCH') {
switch (message.payload.type) {
case 'RESET':
setValue(store, initValue);
devTools.init(initValue);
return;
case 'COMMIT':
intermValue = mobx.toJS(store);
devTools.init(intermValue);
return;
case 'ROLLBACK':
setValue(store, intermValue);
devTools.init(intermValue);
return;
case 'JUMP_TO_STATE':
setValue(store, parse(message.state));
return;
}
}
};
};
| import mobx from 'mobx';
import { stringify, parse } from 'jsan';
import { setValue } from './utils';
export const isMonitorAction = (store) => store.__isRemotedevAction === true;
export const dispatchMonitorAction = (store, devTools) => {
const initValue = mobx.toJS(store);
devTools.init(initValue);
return (message) => {
if (message.type === 'DISPATCH') {
switch (message.payload.type) {
case 'RESET':
setValue(store, initValue);
devTools.init(initValue);
return;
case 'JUMP_TO_STATE':
setValue(store, parse(message.state));
return;
}
}
};
};
|
Allow legend to represent numbers < 1 | import { t } from './i18n'
export function capitalizeFirstLetter (string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
export function shortenNumber (number, decimals, abbreviate) {
decimals = (decimals === undefined) ? 0 : decimals
abbreviate = (abbreviate === undefined) ? true : abbreviate
let k = t('K')
let m = t('M')
let b = t('B')
if (!abbreviate) {
k = t('Thousand')
m = t('Million')
b = t('Billion')
}
if (Math.abs(number) >= 1000000000) {
return `${Number((number / 1000000000).toFixed(decimals))} ${b}`
} else if (Math.abs(number) >= 1000000) {
return `${Number((number / 1000000).toFixed(decimals))} ${m}`
} else if (Math.abs(number) >= 1000) {
return `${Number((number / 1000).toFixed(decimals))} ${k}`
} else if (Math.abs(number) < 1) {
return Number(Math.abs(number).toFixed(6))
} else {
return Math.round(number)
}
}
| import { t } from './i18n'
export function capitalizeFirstLetter (string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
export function shortenNumber (number, decimals, abbreviate) {
decimals = (decimals === undefined) ? 0 : decimals
abbreviate = (abbreviate === undefined) ? true : abbreviate
let k = t('K')
let m = t('M')
let b = t('B')
if (!abbreviate) {
k = t('Thousand')
m = t('Million')
b = t('Billion')
}
if (Math.abs(number) >= 1000000000) {
return `${Number((number / 1000000000).toFixed(decimals))} ${b}`
} else if (Math.abs(number) >= 1000000) {
return `${Number((number / 1000000).toFixed(decimals))} ${m}`
} else if (Math.abs(number) >= 1000) {
return `${Number((number / 1000).toFixed(decimals))} ${k}`
} else {
return Math.round(number)
}
}
|
Replace HttpComponent Request mocks with test data | <?php
/*
* This file is part of the Omnipay package.
*
* (c) Adrian Macneil <adrian@adrianmacneil.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Omnipay\Stripe;
use Omnipay\Common\AbstractResponse;
/**
* Stripe Response
*/
class Response extends AbstractResponse
{
public function isSuccessful()
{
return !isset($this->data['error']);
}
public function getGatewayReference()
{
if ($this->isSuccessful()) {
return $this->data['id'];
}
return $this->data['error']['charge'];
}
public function getMessage()
{
if (!$this->isSuccessful()) {
return $this->data['error']['message'];
}
}
}
| <?php
/*
* This file is part of the Omnipay package.
*
* (c) Adrian Macneil <adrian@adrianmacneil.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Omnipay\Stripe;
use Omnipay\Common\AbstractResponse;
use Omnipay\Exception;
/**
* Stripe Response
*/
class Response extends AbstractResponse
{
public function isSuccessful()
{
return !isset($this->data['error']);
}
public function getGatewayReference()
{
if ($this->isSuccessful()) {
return $this->data['id'];
}
return $this->data['error']['charge'];
}
public function getMessage()
{
if (!$this->isSuccessful()) {
return $this->data['error']['message'];
}
}
}
|
Add logging when netty channels are closed due to inactivity. | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.worker.netty;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Closes the channel if it has been idle for too long.
*/
public class IdleReadHandler extends ChannelDuplexHandler {
private static final Logger LOG = LoggerFactory.getLogger(IdleReadHandler.class);
/**
* Creates a new idle read handler.
*/
public IdleReadHandler() {}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
LOG.warn("Closing netty channel to {} due to inactivity.", ctx.channel().remoteAddress());
ctx.close();
}
}
}
}
| /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.worker.netty;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
/**
* Closes the channel if it has been idle for too long.
*/
public class IdleReadHandler extends ChannelDuplexHandler {
/**
* Creates a new idle read handler.
*/
public IdleReadHandler() {}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
ctx.close();
}
}
}
}
|
Add support for using multiple aliases | package clc
import (
"github.com/CenturyLinkCloud/clc-sdk/aa"
"github.com/CenturyLinkCloud/clc-sdk/alert"
"github.com/CenturyLinkCloud/clc-sdk/api"
"github.com/CenturyLinkCloud/clc-sdk/dc"
"github.com/CenturyLinkCloud/clc-sdk/group"
"github.com/CenturyLinkCloud/clc-sdk/lb"
"github.com/CenturyLinkCloud/clc-sdk/server"
"github.com/CenturyLinkCloud/clc-sdk/status"
)
type Client struct {
client *api.Client
Server *server.Service
Status *status.Service
AA *aa.Service
Alert *alert.Service
LB *lb.Service
Group *group.Service
DC *dc.Service
}
func New(config api.Config) *Client {
c := &Client{
client: api.New(config),
}
c.Server = server.New(c.client)
c.Status = status.New(c.client)
c.AA = aa.New(c.client)
c.Alert = alert.New(c.client)
c.LB = lb.New(c.client)
c.Group = group.New(c.client)
c.DC = dc.New(c.client)
return c
}
func (c *Client) Alias(alias string) *Client {
c.client.Config().Alias = alias
return c
}
| package clc
import (
"github.com/CenturyLinkCloud/clc-sdk/aa"
"github.com/CenturyLinkCloud/clc-sdk/alert"
"github.com/CenturyLinkCloud/clc-sdk/api"
"github.com/CenturyLinkCloud/clc-sdk/dc"
"github.com/CenturyLinkCloud/clc-sdk/group"
"github.com/CenturyLinkCloud/clc-sdk/lb"
"github.com/CenturyLinkCloud/clc-sdk/server"
"github.com/CenturyLinkCloud/clc-sdk/status"
)
type Client struct {
client *api.Client
Server *server.Service
Status *status.Service
AA *aa.Service
Alert *alert.Service
LB *lb.Service
Group *group.Service
DC *dc.Service
}
func New(config api.Config) *Client {
c := &Client{
client: api.New(config),
}
c.Server = server.New(c.client)
c.Status = status.New(c.client)
c.AA = aa.New(c.client)
c.Alert = alert.New(c.client)
c.LB = lb.New(c.client)
c.Group = group.New(c.client)
c.DC = dc.New(c.client)
return c
}
|
Add feature for setting and getting folder | #!/usr/bin/env node
const tilde = require('tilde-expansion');
const chalk = require('chalk');
const init = require('./init');
const list = require('./list');
const newTodoMonth = require('./newTodoMonth');
const newTodo = require('./newTodo');
const setConfigProp = require('./setConfigProp');
const config = require('./config');
const argv = require('yargs')
.command('init', '[options] -dir | -d, initialize a new todo workbook', (yargs) => {
return yargs.option('dir', {
alias: 'd',
default: './'
})
}, init)
.command('get-folder', `get the folder for your todos`, () => {}, () => {
console.log(chalk.blue(config.todoRoot));
})
.command('set-folder', `[options] -dir | -d, set the folder for your todos`, (yargs) => {
return yargs.option('dir', {
alias: 'd',
default: './'
})
}, ({dir}) => {
tilde(dir, (expandedDir) => {
setConfigProp({ todoRoot: expandedDir });
});
})
.command('list', `list all the todo's`, () => {}, list)
.command('new-day', `create a new .md for today`, () => {}, newTodoMonth)
.command('add', `[options] -item | -i, create a new todo in today's file`, (yargs) => {
return yargs.option('item', {
alias: 'i',
default: 'foo'
})
}, newTodo)
.demandCommand()
.help()
.argv; | #!/usr/bin/env node
const init = require('./init');
const list = require('./list');
const newTodoMonth = require('./newTodoMonth');
const newTodo = require('./newTodo');
const argv = require('yargs')
.command('init', '[options] -dir | -d, initialize a new todo workbook', (yargs) => {
return yargs.option('dir', {
alias: 'd',
default: './'
})
}, init)
.command('list', `list all the todo's`, () => {}, list)
.command('new-day', `create a new .md for today`, () => {}, newTodoMonth)
.command('add', `[options] -item | -i, create a new todo in today's file`, (yargs) => {
return yargs.option('item', {
alias: 'i',
default: 'foo'
})
}, newTodo)
.demandCommand()
.help()
.argv; |
Add pkg_resources back, working forward | import pkg_resources
import json
resource_package = __name__
resource_path_format = 'datasource/{}.json'
class DatasourceRepository:
def __init__(self):
self.availableSources = json.loads(pkg_resources.resource_string(resource_package, resource_path_format.format('all')))['available']
self.data = {}
for source in availableSources:
self.data[source] = json.loads(pkg_resources.resource_string(resource_package, resource_path_format.format(source)))
def listDatasources(self):
return self.availableSources
def getDatasource(self, sourceId):
if sourceId in self.data:
return self.data[sourceId]
else:
return None
| import json
resource_package = __name__
resource_path_format = 'datasource/{}.json'
class DatasourceRepository:
def __init__(self):
self.availableSources = json.loads(pkg_resources.resource_string(resource_package, resource_path_format.format('all')))['available']
self.data = {}
for source in availableSources:
self.data[source] = json.loads(pkg_resources.resource_string(resource_package, resource_path_format.format(source)))
def listDatasources(self):
return self.availableSources
def getDatasource(self, sourceId):
if sourceId in self.data:
return self.data[sourceId]
else:
return None
|
Add @Override annotations to PeerEventListener. | /**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import java.util.List;
/**
* Convenience implementation of {@link PeerEventListener}.
*/
public class AbstractPeerEventListener implements PeerEventListener {
@Override
public void onBlocksDownloaded(Peer peer, Block block, int blocksLeft) {
}
@Override
public void onChainDownloadStarted(Peer peer, int blocksLeft) {
}
@Override
public void onPeerConnected(Peer peer, int peerCount) {
}
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
}
@Override
public Message onPreMessageReceived(Peer peer, Message m) {
// Just pass the message right through for further processing.
return m;
}
@Override
public void onTransaction(Peer peer, Transaction t) {
}
@Override
public List<Message> getData(Peer peer, GetDataMessage m) {
return null;
}
@Override
public void onException(Throwable throwable) {
}
}
| /**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import java.util.List;
/**
* Convenience implementation of {@link PeerEventListener}.
*/
public class AbstractPeerEventListener implements PeerEventListener {
public void onBlocksDownloaded(Peer peer, Block block, int blocksLeft) {
}
public void onChainDownloadStarted(Peer peer, int blocksLeft) {
}
public void onPeerConnected(Peer peer, int peerCount) {
}
public void onPeerDisconnected(Peer peer, int peerCount) {
}
public Message onPreMessageReceived(Peer peer, Message m) {
// Just pass the message right through for further processing.
return m;
}
public void onTransaction(Peer peer, Transaction t) {
}
public List<Message> getData(Peer peer, GetDataMessage m) {
return null;
}
@Override
public void onException(Throwable throwable) {
}
}
|
Rename admin to core (seeing as that's what it's currently called | export const services = {
signup: {
consumes: ['branch-created', 'branch-removed', 'branch-edited'],
publishes: ['member-registered', 'send-email'],
},
core: {
consumes: [
'member-registered', 'member-removed', 'member-edited',
'branch-created', 'branch-removed', 'branch-edited',
'group-created', 'group-removed', 'group-edited',
'admin-created', 'admin-removed', 'admin-edited',
],
publishes: [
'member-removed', 'member-edited',
'branch-created', 'branch-removed', 'branch-edited',
'group-created', 'group-removed', 'group-edited',
'admin-created', 'admin-removed', 'admin-edited',
],
},
mailer: {
consumes: ['send-email'],
publishes: ['email-sent', 'email-failed'],
},
'group-mailer': {
consumes: [
'member-registered', 'member-removed', 'member-edited',
'group-created', 'group-removed', 'group-edited',
],
publishes: ['send-email'],
}
};
export const eventTypes = [];
const pushEventType = eventType => {
if (!eventTypes.includes(eventType)) {
eventTypes.push(eventType);
}
}
Object.keys(services).forEach(serviceName => {
services[serviceName].consumes.forEach(pushEventType);
services[serviceName].publishes.forEach(pushEventType);
});
eventTypes.sort();
| export const services = {
signup: {
consumes: ['branch-created', 'branch-removed', 'branch-edited'],
publishes: ['member-registered', 'send-email'],
},
admin: {
consumes: [
'member-registered', 'member-removed', 'member-edited',
'branch-created', 'branch-removed', 'branch-edited',
'group-created', 'group-removed', 'group-edited',
'admin-created', 'admin-removed', 'admin-edited',
],
publishes: [
'member-removed', 'member-edited',
'branch-created', 'branch-removed', 'branch-edited',
'group-created', 'group-removed', 'group-edited',
'admin-created', 'admin-removed', 'admin-edited',
],
},
mailer: {
consumes: ['send-email'],
publishes: ['email-sent', 'email-failed'],
},
'group-mailer': {
consumes: [
'member-registered', 'member-removed', 'member-edited',
'group-created', 'group-removed', 'group-edited',
],
publishes: ['send-email'],
}
};
export const eventTypes = [];
const pushEventType = eventType => {
if (!eventTypes.includes(eventType)) {
eventTypes.push(eventType);
}
}
Object.keys(services).forEach(serviceName => {
services[serviceName].consumes.forEach(pushEventType);
services[serviceName].publishes.forEach(pushEventType);
});
eventTypes.sort();
|
Fix breaking change for RN 0.47 | package com.barefootcoders.android.react.KDSocialShare;
import android.app.Activity;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class KDSocialShare implements ReactPackage {
public KDSocialShare(Activity activity) {
} // backwards compatability
public KDSocialShare() {
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new KDSocialShareModule(reactContext));
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
| package com.barefootcoders.android.react.KDSocialShare;
import android.app.Activity;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class KDSocialShare implements ReactPackage {
public KDSocialShare(Activity activity) {
} // backwards compatability
public KDSocialShare() {
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new KDSocialShareModule(reactContext));
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
Convert backslashes to forward slashes in spl_autoload_register | <?php
// Don't allow direct access to the boostrap
//if(basename($_SERVER['REQUEST_URI']) == 'bootstrap.php'){
/// exit('bootstrap.php does nothing on its own. Please see the examples provided');
//}
// Set error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 'On');
// Register a simple autoload function
spl_autoload_register(function($class){
$class = str_replace('\\', '/', $class);
require_once('../' . $class . '.php');
});
// Set your consumer key, secret and callback URL
$key = 'XXXXXXXXXXXXXXX';
$secret = 'XXXXXXXXXXXXXXX';
$callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Instantiate the required Dropbox objects
$storage = new \Dropbox\OAuth\Storage\Session;
$OAuth = new \Dropbox\OAuth\Consumer\Curl($key, $secret, $storage, $callback);
$dropbox = new \Dropbox\API($OAuth);
| <?php
// Don't allow direct access to the boostrap
if(basename($_SERVER['REQUEST_URI']) == 'bootstrap.php'){
exit('bootstrap.php does nothing on its own. Please see the examples provided');
}
// Set error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 'On');
// Register a simple autoload function
spl_autoload_register(function($class){
require_once('../' . $class . '.php');
});
// Set your consumer key, secret and callback URL
$key = 'XXXXXXXXXXXXXXX';
$secret = 'XXXXXXXXXXXXXXX';
$callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Instantiate the required Dropbox objects
$storage = new \Dropbox\OAuth\Storage\Session;
$OAuth = new \Dropbox\OAuth\Consumer\Curl($key, $secret, $storage, $callback);
$dropbox = new \Dropbox\API($OAuth);
|
Remove the dbLocation as we do this within plugin.py | ###
# Copyright (c) 2012-2013, spline
# All rights reserved.
#
#
###
import os
import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('MLB')
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified himself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('MLB', True)
MLB = conf.registerPlugin('MLB')
conf.registerGlobalValue(MLB, 'usatApiKey', registry.String('', """api key for developer.usatoday.com""", private=True))
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=250:
| ###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###
import os
import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('MLB')
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified himself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('MLB', True)
MLB = conf.registerPlugin('MLB')
# This is where your configuration variables (if any) should go. For example:
conf.registerGlobalValue(MLB, 'dbLocation', registry.String(os.path.abspath(os.path.dirname(__file__)) + '/mlb.db', _("""Absolute path for mlb.db sqlite3 database file location.""")))
conf.registerGlobalValue(MLB, 'ffApiKey', registry.String('', """api key for fanfeedr.com""", private=True))
conf.registerGlobalValue(MLB, 'usatApiKey', registry.String('', """api key for developer.usatoday.com""", private=True))
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=250:
|
Use eslint inside of webpack | var webpack = require("webpack");
/* eslint-disable no-undef */
var environment = process.env["NODE_ENV"] || "development";
module.exports = {
entry: "./src/game",
output: {
path: __dirname + "/build",
filename: "index.js"
},
module: {
preLoaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: "eslint-loader" }
],
loaders: [
{ test: /\.json$/, loader: "json" },
{
test: /src\/images\/.*\.(jpe?g|png|gif|svg)$/i,
loaders: [
"file?hash=sha512&digest=hex&name=images/[name].[ext]",
"image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false"
]
},
{
test: /src\/sounds\/.*\.(mp3|ogg|wav)$/i,
loader: "file?hash=sha512&digest=hex&name=sounds/[name].[ext]"
},
{
test: /src\/index.html$/i,
loader: "file?hash=sha512&digest=hex&name=[name].[ext]"
}
]
},
plugins: [
new webpack.DefinePlugin({
__PRODUCTION__: environment === "production",
__TEST__: environment === "test",
__DEVELOPMENT__: environment === "development"
})
]
};
| var webpack = require("webpack");
/* eslint-disable no-undef */
var environment = process.env["NODE_ENV"] || "development";
module.exports = {
entry: "./src/game",
output: {
path: __dirname + "/build",
filename: "index.js"
},
module: {
preLoaders: [
// { test: /\.js$/, exclude: /node_modules/, loader: "eslint" }
],
loaders: [
{ test: /\.json$/, loader: "json" },
{
test: /src\/images\/.*\.(jpe?g|png|gif|svg)$/i,
loaders: [
"file?hash=sha512&digest=hex&name=images/[name].[ext]",
"image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false"
]
},
{
test: /src\/sounds\/.*\.(mp3|ogg|wav)$/i,
loader: "file?hash=sha512&digest=hex&name=sounds/[name].[ext]"
},
{
test: /src\/index.html$/i,
loader: "file?hash=sha512&digest=hex&name=[name].[ext]"
}
]
},
plugins: [
new webpack.DefinePlugin({
__PRODUCTION__: environment === "production",
__TEST__: environment === "test",
__DEVELOPMENT__: environment === "development"
})
]
};
|
Fix last migration for some MySQL servers | <?php
use Movim\Migration;
use Illuminate\Database\Schema\Blueprint;
class ChangeMessagesPrimaryKey extends Migration
{
public function up()
{
$this->schema->table('messages', function(Blueprint $table) {
$table->dropForeign(['user_id']);
$table->dropPrimary('messages_pkey');
$table->primary(['user_id', 'jidfrom', 'id']);
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
}
public function down()
{
$this->schema->table('messages', function(Blueprint $table) {
$table->dropForeign(['user_id']);
$table->dropPrimary('messages_pkey');
$table->primary(['user_id', 'id']);
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
}
}
| <?php
use Movim\Migration;
use Illuminate\Database\Schema\Blueprint;
class ChangeMessagesPrimaryKey extends Migration
{
public function up()
{
$this->disableForeignKeyCheck();
$this->schema->table('messages', function(Blueprint $table) {
$table->dropPrimary('messages_pkey');
$table->primary(['user_id', 'jidfrom', 'id']);
});
$this->enableForeignKeyCheck();
}
public function down()
{
$this->disableForeignKeyCheck();
$this->schema->table('messages', function(Blueprint $table) {
$table->dropPrimary('messages_pkey');
$table->primary(['user_id', 'id']);
});
$this->enableForeignKeyCheck();
}
}
|
Fix typo in websocket example | var messageTxt;
var messages;
$(function () {
messageTxt = $("#messageTxt");
messages = $("#messages");
w = new Ws("ws://" + HOST + "/my_endpoint");
w.OnConnect(function () {
console.log("Websocket connection established");
});
w.OnDisconnect(function () {
appendMessage($("<div><center><h3>Disconnected</h3></center></div>"));
});
w.On("chat", function (message) {
appendMessage($("<div>" + message + "</div>"));
});
$("#sendBtn").click(function () {
w.Emit("chat", messageTxt.val().toString());
messageTxt.val("");
});
})
function appendMessage(messageDiv) {
var theDiv = messages[0];
var doScroll = theDiv.scrollTop == theDiv.scrollHeight - theDiv.clientHeight;
messageDiv.appendTo(messages);
if (doScroll) {
theDiv.scrollTop = theDiv.scrollHeight - theDiv.clientHeight;
}
}
| var messageTxt;
var messages;
$(function () {
messageTxt = $("#messageTxt");
messages = $("#messages");
w = new Ws("ws://" + HOST + "/my_endpoint");
w.OnConnect(function () {
console.log("Websocket connection enstablished");
});
w.OnDisconnect(function () {
appendMessage($("<div><center><h3>Disconnected</h3></center></div>"));
});
w.On("chat", function (message) {
appendMessage($("<div>" + message + "</div>"));
});
$("#sendBtn").click(function () {
w.Emit("chat", messageTxt.val().toString());
messageTxt.val("");
});
})
function appendMessage(messageDiv) {
var theDiv = messages[0];
var doScroll = theDiv.scrollTop == theDiv.scrollHeight - theDiv.clientHeight;
messageDiv.appendTo(messages);
if (doScroll) {
theDiv.scrollTop = theDiv.scrollHeight - theDiv.clientHeight;
}
}
|
Add event field when editing posts | from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
list_display = (
'title',
'slug',
'event',
'created_at',
'updated_at',
'author',
'is_sponsored',
)
search_fields = ('title', 'lead', 'body')
list_filter = ('event', 'created_at')
fields = ('event', 'title', 'slug', 'lead', 'body', 'is_sponsored')
ordering = ('-created_at',)
prepopulated_fields = {'slug': ('title',)}
def save_model(self, request, obj, form, change):
"""When creating a new object, set the author field."""
if not change:
obj.author = request.user
obj.save()
admin.site.register(Post, PostAdmin)
| from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
list_display = (
'title',
'slug',
'event',
'created_at',
'updated_at',
'author',
'is_sponsored',
)
search_fields = ('title', 'lead', 'body')
list_filter = ('event', 'created_at')
fields = ('title', 'slug', 'lead', 'body', 'is_sponsored')
ordering = ('-created_at',)
prepopulated_fields = {'slug': ('title',)}
def save_model(self, request, obj, form, change):
"""When creating a new object, set the author field."""
if not change:
obj.author = request.user
obj.save()
admin.site.register(Post, PostAdmin)
|
Determine glowscript version from file name | from __future__ import print_function
import os
from glob import glob
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
glowscript_file = glob(os.path.join(data_dir, 'glow.*.min.js'))
glowscript_name = glowscript_file[0]
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('glow\.(.+?)\.min\.js', glowscript_name)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
| from __future__ import print_function
import os
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
glowscript_name = 'glow.2.1.min.js'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
with open(os.path.join(data_dir, glowscript_name)) as f:
contents = f.read()
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('var glowscript=\{version:"(.+?)"\}', contents)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
|
Fix PHP OOM error while processing test coverage | <?php
use Desk\Test\Helper\TestCase;
use Guzzle\Service\Builder\ServiceBuilder;
ini_set('memory_limit', '256M');
error_reporting(-1);
$ds = DIRECTORY_SEPARATOR;
$autoloader = dirname(__DIR__) . "{$ds}vendor{$ds}autoload.php";
// Ensure that Composer dependencies have been installed locally
if (!file_exists($autoloader)) {
die(
"Dependencies must be installed using Composer:\n\n" .
"composer.phar install --dev\n\n" .
"See https://github.com/composer/composer/blob/master/README.md " .
"for help with installing composer\n"
);
}
// Include the Composer autoloader
require_once $autoloader;
// Configure Guzzle service builder
if (isset($_SERVER['DESK_TEST_CONFIG'])) {
$config = $_SERVER['DESK_TEST_CONFIG'];
} else {
$config = __DIR__ . '/service/mock.json';
}
TestCase::setServiceBuilder(ServiceBuilder::factory($config));
TestCase::setTestsBasePath(__DIR__);
TestCase::setMockBasePath(__DIR__ . '/mock');
| <?php
use Desk\Test\Helper\TestCase;
use Guzzle\Service\Builder\ServiceBuilder;
error_reporting(-1);
$ds = DIRECTORY_SEPARATOR;
$autoloader = dirname(__DIR__) . "{$ds}vendor{$ds}autoload.php";
// Ensure that Composer dependencies have been installed locally
if (!file_exists($autoloader)) {
die(
"Dependencies must be installed using Composer:\n\n" .
"composer.phar install --dev\n\n" .
"See https://github.com/composer/composer/blob/master/README.md " .
"for help with installing composer\n"
);
}
// Include the Composer autoloader
require_once $autoloader;
// Configure Guzzle service builder
if (isset($_SERVER['DESK_TEST_CONFIG'])) {
$config = $_SERVER['DESK_TEST_CONFIG'];
} else {
$config = __DIR__ . '/service/mock.json';
}
TestCase::setServiceBuilder(ServiceBuilder::factory($config));
TestCase::setTestsBasePath(__DIR__);
TestCase::setMockBasePath(__DIR__ . '/mock');
|
Test that some exceptions are converted before rendering | <?php
namespace Nord\ImageManipulationService\Tests\Exceptions;
use League\Flysystem\FileNotFoundException;
use Nord\ImageManipulationService\Exceptions\Handler;
use Nord\ImageManipulationService\Tests\TestCase;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Class HandlerTest
* @package Nord\ImageManipulationService\Tests\Exceptions
*/
class HandlerTest extends TestCase
{
/**
* Tests that the exception is converted
*/
public function testFileNotFoundException()
{
$handler = new Handler();
$response = $handler->render(null, new FileNotFoundException('/'));
$data = json_decode((string)$response->getContent(), true);
$this->assertEquals(NotFoundHttpException::class, $data['exception']);
}
/**
* Tests that exceptions are rendered as JSON
*/
public function testHandleRender()
{
$handler = new Handler();
$response = $handler->render(null, new \InvalidArgumentException('The message', 23));
$data = json_decode((string)$response->getContent(), true);
$this->assertArraySubset([
'exception' => 'InvalidArgumentException',
'message' => 'The message',
'code' => 23,
], $data);
$this->assertEquals(env('APP_DEBUG'), array_key_exists('trace', $data));
}
}
| <?php
namespace Nord\ImageManipulationService\Tests\Exceptions;
use Nord\ImageManipulationService\Exceptions\Handler;
use Nord\ImageManipulationService\Tests\TestCase;
/**
* Class HandlerTest
* @package Nord\ImageManipulationService\Tests\Exceptions
*/
class HandlerTest extends TestCase
{
public function testHandle()
{
$handler = new Handler();
$response = $handler->render(null, new \InvalidArgumentException('The message', 23));
$data = json_decode((string)$response->getContent(), true);
$this->assertArraySubset([
'exception' => 'InvalidArgumentException',
'message' => 'The message',
'code' => 23,
], $data);
$this->assertEquals(env('APP_DEBUG'), array_key_exists('trace', $data));
}
}
|
Support negative and positive timezones. | 'use strict';
const moment = require('moment');
/**
* Given a date return a date ISO string.
* @param {String} dateString The date string to format.
* @param {String} dateFormat The date format.
* @param {String} offset A timezone offset.
* @param {Function} startOf A function to manipulate the moment object.
*/
const isoString = (dateString, dateFormat = 'YYYY-MM-DD', offset = '+0:00', manipulationFn) => {
let date = moment(dateString, dateFormat);
if (manipulationFn) {
date = manipulationFn(date);
}
// Take into consideration the client-side timezone.
// MongoDB stores dates in UTC.
date.zone(offset);
// Add the timezone in minutes to the date.
const [, plusOrMinus, hours, minutes] = offset.match(/^(\+|-)([0-9]{1,2}):([0-9]{2})$/);
let total = Number(hours)*60 + Number(minutes);
// Support positive and negative timezones.
if (plusOrMinus === '+') {
total = -(total);
}
// Add the value of the offset, back to the time in minutes.
// This will ensure when an `endOf('day')` date is rendered client side, it will be accurate.
date.add(total, 'm');
// Return as an ISOString.
return date.toISOString();
}
module.exports = {
isoString,
};
| 'use strict';
const moment = require('moment');
/**
* Given a date return a date ISO string.
* @param {String} dateString The date string to format.
* @param {String} dateFormat The date format.
* @param {String} offset A timezone offset.
* @param {Function} startOf A function to manipulate the moment object.
*/
const isoString = (dateString, dateFormat = 'YYYY-MM-DD', offset = '+0:00', manipulationFn) => {
let date = moment(dateString, dateFormat);
if (manipulationFn) {
date = manipulationFn(date);
}
// Take into consideration the client-side timezone.
// MongoDB stores dates in UTC.
date.zone(offset);
// Add the timezone in minutes to the date.
const [, plusOrMinus, hours, minutes] = offset.match(/^(\+|-)([0-9]{1,2}):([0-9]{2})$/);
let total = Number(hours)*60 + Number(minutes);
// Add the value of the offset, back to the time in minutes.
// This will ensure when an `endOf('day')` date is rendered client side, it will be accurate.
date.subtract(total, 'm');
// Return as an ISOString.
return date.toISOString();
}
module.exports = {
isoString,
};
|
Allow running separate test files
With e.g.:
./runtests.py tests.tests_transactions | #!/usr/bin/env python
import os, sys, re, shutil
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.core.management import call_command
names = next((a for a in sys.argv[1:] if not a.startswith('-')), None)
if not names:
names = 'tests'
elif re.search(r'^\d+$', names):
names = 'tests.tests.IssueTests.test_' + names
elif not names.startswith('tests.'):
names = 'tests.tests.' + names
django.setup()
# NOTE: we create migrations each time since they depend on type of database,
# python and django versions
try:
shutil.rmtree('tests/migrations', True)
call_command('makemigrations', 'tests', verbosity=2 if '-v' in sys.argv else 0)
call_command('test', names, failfast='-x' in sys.argv, verbosity=2 if '-v' in sys.argv else 1)
finally:
shutil.rmtree('tests/migrations')
| #!/usr/bin/env python
import os, sys, re, shutil
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.core.management import call_command
names = next((a for a in sys.argv[1:] if not a.startswith('-')), None)
if names and re.search(r'^\d+$', names):
names = 'tests.tests.IssueTests.test_' + names
elif names and not names.startswith('tests.'):
names = 'tests.tests.' + names
else:
names = 'tests'
django.setup()
# NOTE: we create migrations each time since they depend on type of database,
# python and django versions
try:
shutil.rmtree('tests/migrations', True)
call_command('makemigrations', 'tests', verbosity=2 if '-v' in sys.argv else 0)
call_command('test', names, failfast='-x' in sys.argv, verbosity=2 if '-v' in sys.argv else 1)
finally:
shutil.rmtree('tests/migrations')
|
Fix minute count in logs | var sessionStart = new Date().getTime();
function zeroPad(num, places) {
places = places || 2;
var str = num+'';
while (str.length < 2) {
str = '0'+str;
}
return str;
}
function log(str) {
var milliseconds = new Date().getTime() - sessionStart;
var dateStr = log.getTime(milliseconds, true);
var args = Array.prototype.slice.call(arguments);
args.splice(0, 1, '['+dateStr+'] '+str);
console.log.apply(console, args);
}
log.getTime = function(milliseconds, alwaysIncludeHours) {
var seconds = Math.round(milliseconds / 1000);
var minutes = Math.round(seconds / 60);
var hours = Math.round(minutes / 60);
seconds = seconds % 60;
minutes = minutes % 60;
var dateStr = '';
if (hours || alwaysIncludeHours) {
dateStr += zeroPad(hours)+':';
}
dateStr += zeroPad(minutes)+':'+zeroPad(seconds);
return dateStr;
};
module.exports = log;
| var sessionStart = new Date().getTime();
function zeroPad(num, places) {
places = places || 2;
var str = num+'';
while (str.length < 2) {
str = '0'+str;
}
return str;
}
function log(str) {
var milliseconds = new Date().getTime() - sessionStart;
var dateStr = log.getTime(milliseconds, true);
var args = Array.prototype.slice.call(arguments);
args.splice(0, 1, '['+dateStr+'] '+str);
console.log.apply(console, args);
}
log.getTime = function(milliseconds, alwaysIncludeHours) {
var seconds = Math.round(milliseconds / 1000);
var minutes = Math.round(seconds / 60);
var hours = Math.round(minutes / 60);
seconds = seconds % 60;
var dateStr = '';
if (hours || alwaysIncludeHours) {
dateStr += zeroPad(hours)+':';
}
dateStr += zeroPad(minutes)+':'+zeroPad(seconds);
return dateStr;
};
module.exports = log;
|
Use this. notation instead of expecting things to autocomplete to ivs | package org.usfirst.frc.team2503.r2016.component;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.SpeedController;
public class Intake extends SpeedControllerComponent {
public enum IntakeMode {
UNKNOWN,
STOPPED,
INBOUND,
OUTBOUND,
FIRE
}
public DigitalInput limitSwitch;
private IntakeMode mode = IntakeMode.UNKNOWN;
public void setMode(IntakeMode mode) { this.mode = mode; }
public IntakeMode getMode() { return this.mode; }
public void tick() {
switch(this.mode) {
case STOPPED:
this.controller.set(0.0);
break;
case INBOUND:
if(this.limitSwitch.get()) {
this.controller.set(0.0);
} else {
this.controller.set(1.0);
}
break;
case OUTBOUND:
this.controller.set(-1.0);
break;
case FIRE:
this.controller.set(1.0);
break;
case UNKNOWN:
default:
break;
}
}
public Intake(SpeedController controller, DigitalInput limitSwitch) {
super(controller);
this.limitSwitch = limitSwitch;
}
}
| package org.usfirst.frc.team2503.r2016.component;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.SpeedController;
public class Intake extends SpeedControllerComponent {
public enum IntakeMode {
UNKNOWN,
STOPPED,
INBOUND,
OUTBOUND,
FIRE
}
public DigitalInput limitSwitch;
private IntakeMode mode = IntakeMode.UNKNOWN;
public void setMode(IntakeMode mode) { this.mode = mode; }
public IntakeMode getMode() { return this.mode; }
public void tick() {
switch(mode) {
case STOPPED:
this.controller.set(0.0);
break;
case INBOUND:
if(limitSwitch.get()) {
this.controller.set(0.0);
} else {
this.controller.set(1.0);
}
break;
case OUTBOUND:
this.controller.set(-1.0);
break;
case FIRE:
this.controller.set(1.0);
break;
case UNKNOWN:
default:
break;
}
}
public Intake(SpeedController controller, DigitalInput limitSwitch) {
super(controller);
this.limitSwitch = limitSwitch;
}
}
|
[babel] Move default plugins to before | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var babelPluginModules = require('./rewrite-modules');
var babelPluginAutoImporter = require('./auto-importer');
var inlineRequires = require('./inline-requires');
var plugins = [
{
position: 'before',
transformer: babelPluginAutoImporter,
},
{
position: 'before',
transformer: babelPluginModules,
},
];
if (process.env.NODE_ENV === 'test') {
plugins.push({
position: 'after',
transformer: inlineRequires,
});
}
module.exports = {
nonStandard: true,
blacklist: [
'spec.functionName'
],
loose: [
'es6.classes'
],
stage: 1,
plugins: plugins,
_moduleMap: {
'core-js/library/es6/map': 'core-js/library/es6/map',
'promise': 'promise',
'ua-parser-js': 'ua-parser-js',
'whatwg-fetch': 'whatwg-fetch'
}
};
| /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var babelPluginModules = require('./rewrite-modules');
var babelPluginAutoImporter = require('./auto-importer');
var inlineRequires = require('./inline-requires');
var plugins = [
{
position: 'after',
transformer: babelPluginAutoImporter,
},
{
position: 'after',
transformer: babelPluginModules,
},
];
if (process.env.NODE_ENV === 'test') {
plugins.push({
position: 'after',
transformer: inlineRequires,
});
}
module.exports = {
nonStandard: true,
blacklist: [
'spec.functionName'
],
loose: [
'es6.classes'
],
stage: 1,
plugins: plugins,
_moduleMap: {
'core-js/library/es6/map': 'core-js/library/es6/map',
'promise': 'promise',
'ua-parser-js': 'ua-parser-js',
'whatwg-fetch': 'whatwg-fetch'
}
};
|
Allow constraint getter to take parameter dict | from __future__ import absolute_import
import theano
import theano.tensor as T
import numpy as np
class Constraint(object):
def __call__(self, p):
return p
def get_config(self):
return {"name":self.__class__.__name__}
class MaxNorm(Constraint):
def __init__(self, m=2):
self.m = m
def __call__(self, p):
norms = T.sqrt(T.sum(T.sqr(p), axis=0))
desired = T.clip(norms, 0, self.m)
p = p * (desired / (1e-7 + norms))
return p
def get_config(self):
return {"name":self.__class__.__name__,
"m":self.m}
class NonNeg(Constraint):
def __call__(self, p):
p *= T.ge(p, 0)
return p
class UnitNorm(Constraint):
def __call__(self, p):
return p / T.sqrt(T.sum(p**2, axis=-1, keepdims=True))
identity = Constraint
maxnorm = MaxNorm
nonneg = NonNeg
unitnorm = UnitNorm
from .utils.generic_utils import get_from_module
def get(identifier, kwargs=None):
return get_from_module(identifier, globals(), 'constraint', instantiate=True, kwargs=kwargs) | from __future__ import absolute_import
import theano
import theano.tensor as T
import numpy as np
class Constraint(object):
def __call__(self, p):
return p
def get_config(self):
return {"name":self.__class__.__name__}
class MaxNorm(Constraint):
def __init__(self, m=2):
self.m = m
def __call__(self, p):
norms = T.sqrt(T.sum(T.sqr(p), axis=0))
desired = T.clip(norms, 0, self.m)
p = p * (desired / (1e-7 + norms))
return p
def get_config(self):
return {"name":self.__class__.__name__,
"m":self.m}
class NonNeg(Constraint):
def __call__(self, p):
p *= T.ge(p, 0)
return p
class UnitNorm(Constraint):
def __call__(self, p):
return p / T.sqrt(T.sum(p**2, axis=-1, keepdims=True))
identity = Constraint
maxnorm = MaxNorm
nonneg = NonNeg
unitnorm = UnitNorm
from .utils.generic_utils import get_from_module
def get(identifier):
return get_from_module(identifier, globals(), 'constraint', instantiate=True) |
[SWIK-675_remaking_user_profile_page] Delete user context and doing refresh of page after user was deleted | import { userSignOut } from '../userSignOut.js';
import { navigateAction } from 'fluxible-router';
import UserProfileStore from '../../../stores/UserProfileStore';
//import notFoundError from '../../error/notFoundError';
import methodNotAllowedError from '../../error/methodNotAllowedError';
export default function removeUser(context, payload, done) {
payload.params = {};
payload.params.id = context.getStore(UserProfileStore).userid;
payload.params.jwt = context.getStore(UserProfileStore).jwt;
context.service.delete('userProfile.remove', payload, { timeout: 20 * 1000 }, (err, res) => {
if (err) {
if (err.statusCode === 404) {
context.dispatch('DELETE_USER_FAILURE', err);
} else if (err.statusCode === 401) {
context.executeAction(methodNotAllowedError, {}, done);
return;
} else
context.dispatch('DELETE_USER_FAILURE', err);
} else {
context.deleteUser();
context.dispatch('DELETE_USER_SUCCESS', null);
context.executeAction(navigateAction, { url: '/' });
location.reload();
}
done();
});
}
| import { userSignOut } from '../userSignOut.js';
import { navigateAction } from 'fluxible-router';
import UserProfileStore from '../../../stores/UserProfileStore';
//import notFoundError from '../../error/notFoundError';
import methodNotAllowedError from '../../error/methodNotAllowedError';
export default function removeUser(context, payload, done) {
payload.params = {};
payload.params.id = context.getStore(UserProfileStore).userid;
payload.params.jwt = context.getStore(UserProfileStore).jwt;
context.service.delete('userProfile.remove', payload, { timeout: 20 * 1000 }, (err, res) => {
if (err) {
if (err.statusCode === 404) {
context.dispatch('DELETE_USER_FAILURE', err);
} else if (err.statusCode === 401) {
context.executeAction(methodNotAllowedError, {}, done);
return;
} else
context.dispatch('DELETE_USER_FAILURE', err);
} else {
//TODO logout user - context.executeAction(userSignOut, {}); throws an error
context.executeAction(navigateAction, { url: '/' });
}
done();
});
}
|
Fix filter for fields when displaying OpenStack select | import template from './appstore-field-select-openstack-tenant.html';
class AppstoreFieldSelectOpenstackTenantController {
// @ngInject
constructor(ncUtilsFlash, openstackTenantsService, currentStateService) {
this.ncUtilsFlash = ncUtilsFlash;
this.openstackTenantsService = openstackTenantsService;
this.currentStateService = currentStateService;
}
$onInit() {
this.loading = true;
this.currentStateService.getProject().then(project => {
this.openstackTenantsService.getAll({
field: ['name', 'backend_id'],
project_uuid: project.uuid,
}).then(tenants => {
this.choices = tenants.map(tenant => ({
display_name: tenant.name,
value: `Tenant UUID: ${tenant.backend_id}. Name: ${tenant.name}`
}));
this.loading = false;
this.loaded = true;
})
.catch(response => {
this.ncUtilsFlash.errorFromResponse(response, gettext('Unable to get list of OpenStack tenants.'));
this.loading = false;
this.loaded = false;
});
});
}
}
const appstoreFieldSelectOpenstackTenant = {
template,
bindings: {
field: '<',
model: '<'
},
controller: AppstoreFieldSelectOpenstackTenantController,
};
export default appstoreFieldSelectOpenstackTenant;
| import template from './appstore-field-select-openstack-tenant.html';
class AppstoreFieldSelectOpenstackTenantController {
// @ngInject
constructor(ncUtilsFlash, openstackTenantsService, currentStateService) {
this.ncUtilsFlash = ncUtilsFlash;
this.openstackTenantsService = openstackTenantsService;
this.currentStateService = currentStateService;
}
$onInit() {
this.loading = true;
this.currentStateService.getProject().then(project => {
this.openstackTenantsService.getAll({
field: ['name', 'uuid'],
project_uuid: project.uuid,
}).then(tenants => {
this.choices = tenants.map(tenant => ({
display_name: tenant.name,
value: `Tenant UUID: ${tenant.backend_id}. Name: ${tenant.name}`
}));
this.loading = false;
this.loaded = true;
})
.catch(response => {
this.ncUtilsFlash.errorFromResponse(response, gettext('Unable to get list of OpenStack tenants.'));
this.loading = false;
this.loaded = false;
});
});
}
}
const appstoreFieldSelectOpenstackTenant = {
template,
bindings: {
field: '<',
model: '<'
},
controller: AppstoreFieldSelectOpenstackTenantController,
};
export default appstoreFieldSelectOpenstackTenant;
|
Add delay to the dialog story to make sure the open animation has finished | import React from 'react';
import { IconWarningBadgedMediumOutline } from '@teamleader/ui-icons';
import { Dialog, Box, TextBody } from '../..';
export default {
component: Dialog,
title: 'Dialog',
};
export const Main = () => (
<Dialog
headerIcon={<IconWarningBadgedMediumOutline />}
active
onCloseClick={() => {}}
onEscKeyDown={() => {}}
onOverlayClick={() => {}}
primaryAction={{
label: 'Confirm',
}}
secondaryAction={{
label: 'Cancel',
}}
tertiaryAction={{
children: 'Read more',
}}
title="Dialog title"
>
<Box padding={4}>
<TextBody>Here you can add arbitrary content.</TextBody>
</Box>
</Dialog>
);
Main.parameters = {
// add a delay to make sure the dialog animation is finished
chromatic: { delay: 300 },
};
| import React from 'react';
import { IconWarningBadgedMediumOutline } from '@teamleader/ui-icons';
import { Dialog, Box, TextBody } from '../..';
export default {
component: Dialog,
title: 'Dialog',
};
export const Main = () => (
<Dialog
headerIcon={<IconWarningBadgedMediumOutline />}
active
onCloseClick={() => {}}
onEscKeyDown={() => {}}
onOverlayClick={() => {}}
primaryAction={{
label: 'Confirm',
}}
secondaryAction={{
label: 'Cancel',
}}
tertiaryAction={{
children: 'Read more',
}}
title="Dialog title"
>
<Box padding={4}>
<TextBody>Here you can add arbitrary content.</TextBody>
</Box>
</Dialog>
);
|
Enable a websockets config option | var Web3 = require("web3");
var wrapper = require('./wrapper');
module.exports = {
wrap: function(provider, options) {
return wrapper.wrap(provider, options);
},
create: function(options) {
var provider;
if (options.provider && typeof options.provider == "function") {
provider = options.provider();
} else if (options.provider) {
provider = options.provider;
} else if (options.websockets) {
provider = new Web3.providers.WebsocketProvider("ws://" + options.host + ":" + options.port);
} else {
provider = new Web3.providers.HttpProvider("http://" + options.host + ":" + options.port);
}
return this.wrap(provider, options);
},
test_connection: function(provider, callback) {
var web3 = new Web3();
var fail = new Error("Could not connect to your RPC client. Please check your RPC configuration.");
web3.setProvider(provider);
web3
.eth
.getCoinbase()
.then(coinbase => callback(null, coinbase))
.catch(e => callback(fail, null));
}
};
| var Web3 = require("web3");
var wrapper = require('./wrapper');
module.exports = {
wrap: function(provider, options) {
return wrapper.wrap(provider, options);
},
create: function(options) {
var provider;
if (options.provider && typeof options.provider == "function") {
provider = options.provider();
} else if (options.provider) {
provider = options.provider;
} else {
provider = new Web3.providers.HttpProvider("http://" + options.host + ":" + options.port);
}
return this.wrap(provider, options);
},
test_connection: function(provider, callback) {
var web3 = new Web3();
var fail = new Error("Could not connect to your RPC client. Please check your RPC configuration.");
web3.setProvider(provider);
web3
.eth
.getCoinbase()
.then(coinbase => callback(null, coinbase))
.catch(e => callback(fail, null));
}
};
|
Fix test so that it works with Junit 4.6
git-svn-id: 38b70485df25d5e096a1845b40b72a0bf0ca9ea6@2409 6a4a4fef-ff2a-56b0-fee9-946765563393 | package org.apache.ibatis.parsing;
import org.apache.ibatis.io.Resources;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.io.Reader;
public class XPathParserTest {
@Test
public void shouldTestXPathParserMethods() throws Exception {
String resource = "resources/nodelet_test.xml";
Reader reader = Resources.getResourceAsReader(resource);
XPathParser parser = new XPathParser(reader, false, null, null);
assertEquals((Long)1970l, parser.evalLong("/employee/birth_date/year"));
assertEquals((short) 6, (short) parser.evalShort("/employee/birth_date/month"));
assertEquals((Integer) 15, parser.evalInteger("/employee/birth_date/day"));
assertEquals((Float) 5.8f, parser.evalFloat("/employee/height"));
assertEquals((Double) 5.8d, parser.evalDouble("/employee/height"));
assertEquals("${id_var}", parser.evalString("/employee/@id"));
assertEquals(Boolean.TRUE, parser.evalBoolean("/employee/active"));
assertEquals("<id>${id_var}</id>", parser.evalNode("/employee/@id").toString().trim());
assertEquals(7, parser.evalNodes("/employee/*").size());
XNode node = parser.evalNode("/employee/height");
assertEquals("employee/height", node.getPath());
assertEquals("employee[${id_var}]_height", node.getValueBasedIdentifier());
}
}
| package org.apache.ibatis.parsing;
import org.apache.ibatis.io.Resources;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.io.Reader;
public class XPathParserTest {
@Test
public void shouldTestXPathParserMethods() throws Exception {
String resource = "resources/nodelet_test.xml";
Reader reader = Resources.getResourceAsReader(resource);
XPathParser parser = new XPathParser(reader, false, null, null);
assertEquals((long)1970, parser.evalLong("/employee/birth_date/year"));
assertEquals((short)6, parser.evalShort("/employee/birth_date/month"));
assertEquals(15, parser.evalInteger("/employee/birth_date/day"));
assertEquals(5.8f, parser.evalFloat("/employee/height"));
assertEquals(5.8d, parser.evalDouble("/employee/height"));
assertEquals("${id_var}", parser.evalString("/employee/@id"));
assertEquals(Boolean.TRUE, parser.evalBoolean("/employee/active"));
assertEquals("<id>${id_var}</id>", parser.evalNode("/employee/@id").toString().trim());
assertEquals(7, parser.evalNodes("/employee/*").size());
XNode node = parser.evalNode("/employee/height");
assertEquals("employee/height", node.getPath());
assertEquals("employee[${id_var}]_height", node.getValueBasedIdentifier());
}
}
|
Revert "Fix for possible deref of cleaned up source component"
This reverts commit 2b35e47816edb0f655fca21d108d651a6a218b2c. | /*
* Copyright (C) 2012 salesforce.com, 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.
*/
{
handleSearch : function(cmp,event){
var searchTerm = event.getParam('searchTerm') || event.getSource().getElement().value;
if (searchTerm.length > 0) {
var results_location = "#help?topic=searchResults&searchTerm=" + escape(searchTerm);
window.location = results_location;
}
}
} | /*
* Copyright (C) 2012 salesforce.com, 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.
*/
{
handleSearch : function(cmp,event){
var searchTerm = event.getParam('searchTerm') || (event.getSource() && event.getSource().getElement().value);
if (searchTerm.length > 0) {
var results_location = "#help?topic=searchResults&searchTerm=" + escape(searchTerm);
window.location = results_location;
}
}
} |
Make it into single statement. | <?php
namespace Adldap\Laravel\Validation\Rules;
use Adldap\Laravel\Events\AuthenticatedModelTrashed;
use Illuminate\Support\Facades\Event;
class DenyTrashed extends Rule
{
/**
* {@inheritdoc}
*/
public function isValid()
{
if ($this->isTrashed()) {
Event::dispatch(
new AuthenticatedModelTrashed($this->user, $this->model)
);
return false;
}
return true;
}
/**
* Determines if the current model is trashed.
*
* @return bool
*/
protected function isTrashed()
{
return $this->model
? method_exists($this->model, 'trashed') && $this->model->trashed()
: false;
}
}
| <?php
namespace Adldap\Laravel\Validation\Rules;
use Adldap\Laravel\Events\AuthenticatedModelTrashed;
use Illuminate\Support\Facades\Event;
class DenyTrashed extends Rule
{
/**
* {@inheritdoc}
*/
public function isValid()
{
if ($this->isTrashed()) {
Event::dispatch(
new AuthenticatedModelTrashed($this->user, $this->model)
);
return false;
}
return true;
}
/**
* Determines if the current model is trashed.
*
* @return bool
*/
protected function isTrashed()
{
if ($this->model) {
return method_exists($this->model, 'trashed') && $this->model->trashed();
}
return false;
}
}
|
Load viz and place on goal |
//When page loadded, read data and URL state, if any
$( document ).ready(load_data());
function page_main(){
add_goals_sidebar();
add_goals();
load_vizrefs();
}
function add_goals_sidebar(){
$('#sidebar').addClass("active");
var sdgList = document.getElementById("sidebar");
var goals=sdgs.goals.goals;
for (var i in goals){
var goal= goals[i];
append('a',sdgList,"",""," "+goal.goal+": "+goal.short+".","#goal-"+goal.goal,"");
}
}
function add_goals(){
var sdgList = document.getElementById("dashboard-content");
var goals=sdgs.goals.goals;
for (var i in goals){
var goal= goals[i];
append('div',sdgList,"goal-"+goal.goal,"h3"," "+goal.goal+": "+goal.title+".");
}
}
var visualizations={};
function load_vizrefs(){
// Load Visualizations references from the json file
d3.json("/web/assets/viz-101.json", function (error, data) {
var viz=data.visualizations[0];
var vizHook = document.getElementById("goal-"+viz.goal);
console.log(viz,vizHook);
if (vizHook === null){
throw new Error("Something went badly wrong!");
}
//append(htype,hookElement,id,classes,value,link)
append('div',vizHook,"viz-"+viz.goal,"",viz["viz-title"]);
});
}
|
//When page loadded, read data and URL state, if any
$( document ).ready(load_data());
function page_main(){
add_goals_sidebar();
add_goals();
}
function add_goals_sidebar(){
$('#sidebar').addClass("active");
var sdgList = document.getElementById("sidebar");
var goals=sdgs.goals.goals;
for (var i in goals){
var goal= goals[i];
append('a',sdgList,"",""," "+goal.goal+": "+goal.short+".","#goal-"+goal.goal,"");
}
}
function add_goals(){
var sdgList = document.getElementById("dashboard-content");
var goals=sdgs.goals.goals;
for (var i in goals){
var goal= goals[i];
append('div',sdgList,"goal-"+goal.goal,"h3"," "+goal.goal+": "+goal.title+".");
}
}
|
Add in a missing change from r67143 for print preview options.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/5334002
git-svn-id: http://src.chromium.org/svn/trunk/src@67155 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 216c5805aff5e437ba09b83c309b46a0806d2ecf | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
$('cancel-button').addEventListener('click', function(e) {
window.close();
});
chrome.send('getPrinters');
};
/**
* Fill the printer list drop down.
*/
function setPrinters(printers) {
if (printers.length > 0) {
for (var i = 0; i < printers.length; ++i) {
var option = document.createElement('option');
option.textContent = printers[i];
$('printer-list').add(option);
}
} else {
var option = document.createElement('option');
option.textContent = localStrings.getString('noPrinter');
$('printer-list').add(option);
$('printer-list').disabled = true;
$('print-button').disabled = true;
}
}
window.addEventListener('DOMContentLoaded', load);
| // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
$('cancel-button').addEventListener('click', function(e) {
window.close();
});
chrome.send('getPrinters');
};
/**
* Fill the printer list drop down.
*/
function setPrinters(printers) {
if (printers.length > 0) {
for (var i = 0; i < printers.length; ++i) {
var option = document.createElement('option');
option.textContent = printers[i];
$('printer-list').add(option);
}
} else {
var option = document.createElement('option');
option.textContent = localStrings.getString('no-printer');
$('printer-list').add(option);
$('printer-list').disabled = true;
$('print-button').disabled = true;
}
}
window.addEventListener('DOMContentLoaded', load);
|
Add family history and pathology client-side | from radar.lib.models.cohorts import *
from radar.lib.models.common import *
from radar.lib.models.comorbidities import *
from radar.lib.models.diagnosis import *
from radar.lib.models.dialysis import *
from radar.lib.models.data_sources import *
from radar.lib.models.family_history import *
from radar.lib.models.genetics import *
from radar.lib.models.hospitalisations import *
from radar.lib.models.results import *
from radar.lib.models.medications import *
from radar.lib.models.organisations import *
from radar.lib.models.posts import *
from radar.lib.models.pathology import *
from radar.lib.models.patients import *
from radar.lib.models.patient_addresses import *
from radar.lib.models.patient_aliases import *
from radar.lib.models.patient_demographics import *
from radar.lib.models.patient_numbers import *
from radar.lib.models.plasmapheresis import *
from radar.lib.models.renal_imaging import *
from radar.lib.models.salt_wasting import *
from radar.lib.models.transplants import *
from radar.lib.models.users import *
| from radar.lib.models.cohorts import *
from radar.lib.models.common import *
from radar.lib.models.comorbidities import *
from radar.lib.models.diagnosis import *
from radar.lib.models.dialysis import *
from radar.lib.models.data_sources import *
from radar.lib.models.genetics import *
from radar.lib.models.hospitalisations import *
from radar.lib.models.results import *
from radar.lib.models.medications import *
from radar.lib.models.organisations import *
from radar.lib.models.posts import *
from radar.lib.models.pathology import *
from radar.lib.models.patients import *
from radar.lib.models.patient_addresses import *
from radar.lib.models.patient_aliases import *
from radar.lib.models.patient_demographics import *
from radar.lib.models.patient_numbers import *
from radar.lib.models.plasmapheresis import *
from radar.lib.models.renal_imaging import *
from radar.lib.models.salt_wasting import *
from radar.lib.models.transplants import *
from radar.lib.models.users import *
|
Allow passing arguments to another screen module | import { $, $$, bind } from 'util/dom';
import splashScreen from 'screens/splash';
import mainMenu from 'screens/main-menu';
var screens = {
'splash-screen': splashScreen,
'main-menu': mainMenu,
};
export function showScreen (id) {
var activeScreen = $$('#game .screen.active')[0];
var screen = $(id);
var args = [].slice.call(arguments, 1);
if (activeScreen) {
activeScreen.classList.remove('active');
}
screens[id].run.apply(screens[id], args);
screen.classList.add('active');
}
export function setup () {
bind(document, 'touchmove', function (e) {
e.preventDefault();
});
// hide the address bar on Android devices
if (/Android/.test(navigator.userAgent)) {
$$('html')[0].style.height = '200%';
setTimeout(function () { window.scrollTo(0,1); }, 0);
}
}
| import { $, $$, bind } from 'util/dom';
import splashScreen from 'screens/splash';
import mainMenu from 'screens/main-menu';
var screens = {
'splash-screen': splashScreen,
'main-menu': mainMenu,
};
export function showScreen (id) {
var activeScreen = $$('#game .screen.active')[0],
screen = $(id);
if (activeScreen) {
activeScreen.classList.remove('active');
}
screens[id].run();
screen.classList.add('active');
}
export function setup () {
bind(document, 'touchmove', function (e) {
e.preventDefault();
});
// hide the address bar on Android devices
if (/Android/.test(navigator.userAgent)) {
$$('html')[0].style.height = '200%';
setTimeout(function () { window.scrollTo(0,1); }, 0);
}
}
|
Use binary file name instead of full path
Signed-off-by: Radek Simko <c0f89f684c2e56811603206eabe5a4cea7f58f3e@gmail.com> | package main
import (
"os"
"path"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
)
func main() {
for _, f := range os.Args {
if f == "-D" || f == "--debug" || f == "-debug" {
os.Setenv("DEBUG", "1")
initLogging(log.DebugLevel)
}
}
app := cli.NewApp()
app.Name = path.Base(os.Args[0])
app.Commands = Commands
app.CommandNotFound = cmdNotFound
app.Usage = "Create and manage machines running Docker."
app.Version = VERSION
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug, D",
Usage: "Enable debug mode",
},
cli.StringFlag{
EnvVar: "MACHINE_STORAGE_PATH",
Name: "storage-path",
Usage: "Configures storage path",
},
cli.StringFlag{
EnvVar: "MACHINE_AUTH_CA",
Name: "auth-ca",
Usage: "CA to verify remotes against",
},
cli.StringFlag{
EnvVar: "MACHINE_AUTH_PRIVATE_KEY",
Name: "auth-key",
Usage: "Private key to generate certificates",
},
}
app.Run(os.Args)
}
| package main
import (
"os"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
)
func main() {
for _, f := range os.Args {
if f == "-D" || f == "--debug" || f == "-debug" {
os.Setenv("DEBUG", "1")
initLogging(log.DebugLevel)
}
}
app := cli.NewApp()
app.Name = os.Args[0]
app.Commands = Commands
app.CommandNotFound = cmdNotFound
app.Usage = "Create and manage machines running Docker."
app.Version = VERSION
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug, D",
Usage: "Enable debug mode",
},
cli.StringFlag{
EnvVar: "MACHINE_STORAGE_PATH",
Name: "storage-path",
Usage: "Configures storage path",
},
cli.StringFlag{
EnvVar: "MACHINE_AUTH_CA",
Name: "auth-ca",
Usage: "CA to verify remotes against",
},
cli.StringFlag{
EnvVar: "MACHINE_AUTH_PRIVATE_KEY",
Name: "auth-key",
Usage: "Private key to generate certificates",
},
}
app.Run(os.Args)
}
|
Enable nickname extension by default | configuration = {
node_name: "default", // ensure this is unique in your cluster
redis: {
ip: '127.0.0.1',
port: 6379,
db: 1
},
servers: [
{ type: 'tcp', ip: '127.0.0.1', port: 8080 },
{ type: 'ws', ip: '127.0.0.1', port: 8081 }
],
extensions: [
{
name: "basic",
type: "node",
module: "../lib/ext/basic"
},
{
name: "metadata",
type: "node",
module: "../lib/ext/metadata"
},
{
name: "pubsub",
type: "node",
module: "../lib/ext/pubsub",
options: { db: 1 }
},
{
name: "nickname",
type: "node",
module: "../lib/ext/nickname",
}
],
max_clients: 50000,
max_request_size: 50240,
max_queued_requests: 100
};
| configuration = {
node_name: "default", // ensure this is unique in your cluster
redis: {
ip: '127.0.0.1',
port: 6379,
db: 1
},
servers: [
{ type: 'tcp', ip: '127.0.0.1', port: 8080 },
{ type: 'ws', ip: '127.0.0.1', port: 8081 }
],
extensions: [
{
name: "basic",
type: "node",
module: "../lib/ext/basic"
},
{
name: "metadata",
type: "node",
module: "../lib/ext/metadata"
},
{
name: "pubsub",
type: "node",
module: "../lib/ext/pubsub",
options: { db: 1 }
}
],
max_clients: 50000,
max_request_size: 50240,
max_queued_requests: 100
};
|
Remove dots from method descriptions | <?php
namespace Juy\ActiveMenu;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
/**
* Register the application services
*
* @return void
*/
public function register()
{
// Default package configuration
$this->mergeConfigFrom(
__DIR__ . '/../config/activemenu.php', 'activemenu'
);
$this->app->singleton('active', function($app) {
return new Active($app['router']->current()->getName());
});
}
/**
* Perform post-registration booting of services
*
* @return void
*/
public function boot()
{
// Add custom blade directive @ifActiveUrl
\Blade::directive('ifActiveRoute', function($expression) {
return "<?php if (Active::route({$expression})): ?>";
});
// Publish the config file
$this->publishConfig();
}
/**
* Publish the config file
*/
protected function publishConfig()
{
$this->publishes([
__DIR__ . '/../config/activemenu.php' => config_path('activemenu.php')
], 'config');
}
}
| <?php
namespace Juy\ActiveMenu;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
/**
* Register the application services
*
* @return void
*/
public function register()
{
// Default package configuration
$this->mergeConfigFrom(
__DIR__ . '/../config/activemenu.php', 'activemenu'
);
$this->app->singleton('active', function($app) {
return new Active($app['router']->current()->getName());
});
}
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
// Add custom blade directive @ifActiveUrl
\Blade::directive('ifActiveRoute', function($expression) {
return "<?php if (Active::route({$expression})): ?>";
});
// Publish the config file
$this->publishConfig();
}
/**
* Publish the config file.
*/
protected function publishConfig()
{
$this->publishes([
__DIR__ . '/../config/activemenu.php' => config_path('activemenu.php')
], 'config');
}
}
|
Fix big text after insertion (not pure function) | /*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import {
calculateFitTextFontSize,
calculateTextHeight,
} from '../../utils/textMeasurements';
import { dataPixels } from '../../units';
function updateForResizeEvent(element, direction, newWidth, newHeight) {
const isResizingWidth = direction[0] !== 0;
const isResizingHeight = direction[1] !== 0;
// Vertical or diagonal resizing w/keep ratio.
if (isResizingHeight) {
const { fontSize, marginOffset } = calculateFitTextFontSize(
element,
newWidth || element.width,
newHeight
);
return {
fontSize: dataPixels(fontSize),
marginOffset,
};
}
// Width-only resize: recalc height.
if (isResizingWidth) {
return { height: dataPixels(calculateTextHeight(element, newWidth)) };
}
return null;
}
export default updateForResizeEvent;
| /*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import {
calculateFitTextFontSize,
calculateTextHeight,
} from '../../utils/textMeasurements';
import { dataPixels } from '../../units';
function updateForResizeEvent(element, direction, newWidth, newHeight) {
const isResizingWidth = direction[0] !== 0;
const isResizingHeight = direction[1] !== 0;
const { fontSize, marginOffset } = calculateFitTextFontSize(
element,
newWidth || element.width,
newHeight
);
// Vertical or diagonal resizing w/keep ratio.
if (isResizingHeight) {
return {
fontSize: dataPixels(fontSize),
marginOffset,
};
}
// Width-only resize: recalc height.
if (isResizingWidth) {
return { height: dataPixels(calculateTextHeight(element, newWidth)) };
}
return null;
}
export default updateForResizeEvent;
|
Use TM_BUNDLE_SUPPORT over the deprecated TM_BUNDLE_PATH variable. | /* Git JS gateway */
/* Tim Harper (tim.harper at leadmediapartners.org) */
function e_sh(str) {
return '"' + (str.toString().gsub('"', '\\"')) + '"';
}
function exec(command, params) {
params = params.map(function(a) { return e_sh(a) }).join(" ")
return TextMate.system(command + " " + params, null)
}
function ENV(var_name) {
return TextMate.system("echo $" + var_name, null).outputString.strip();
}
function gateway_command(command, params) {
// var cmd = arguments.shift
// var params = arguments
try {
command = "ruby " + e_sh(TM_BUNDLE_SUPPORT) + "/gateway/" + command
return exec(command, params).outputString
}
catch(err) {
return "ERROR!" + err;
}
}
function dispatch(params) {
try {
params = $H(params).map(function(pair) { return(pair.key + "=" + pair.value.toString())})
command = "ruby " + e_sh(TM_BUNDLE_SUPPORT) + "/dispatch.rb";
// return params.map(function(a) { return e_sh(a) }).join(" ")
return exec(command, params).outputString
}
catch(err) {
return "ERROR!" + err;
}
}
TM_BUNDLE_SUPPORT = ENV('TM_BUNDLE_SUPPORT') | /* Git JS gateway */
/* Tim Harper (tim.harper at leadmediapartners.org) */
function e_sh(str) {
return '"' + (str.toString().gsub('"', '\\"')) + '"';
}
function exec(command, params) {
params = params.map(function(a) { return e_sh(a) }).join(" ")
return TextMate.system(command + " " + params, null)
}
function ENV(var_name) {
return TextMate.system("echo $" + var_name, null).outputString.strip();
}
function gateway_command(command, params) {
// var cmd = arguments.shift
// var params = arguments
try {
command = "ruby " + e_sh(TM_BUNDLE_PATH) + "/Support/gateway/" + command
return exec(command, params).outputString
}
catch(err) {
return "ERROR!" + err;
}
}
function dispatch(params) {
try {
params = $H(params).map(function(pair) { return(pair.key + "=" + pair.value.toString())})
command = "ruby " + e_sh(TM_BUNDLE_PATH) + "/Support/dispatch.rb";
// return params.map(function(a) { return e_sh(a) }).join(" ")
return exec(command, params).outputString
}
catch(err) {
return "ERROR!" + err;
}
}
TM_BUNDLE_PATH = ENV('TM_BUNDLE_PATH') |
Revert "Python tests now return an error code on fail." | #!/usr/bin/python
import os
import optparse
import sys
import unittest
USAGE = """%prog SDK_PATH TEST_PATH
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation.
TEST_PATH Path to package containing test modules.
WEBTEST_PATH Path to the webtest library."""
def main(sdk_path, test_path, webtest_path):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
sys.path.append(webtest_path)
suite = unittest.loader.TestLoader().discover(test_path,
pattern="*test.py")
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) != 3:
print 'Error: Exactly 3 arguments required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0]
TEST_PATH = args[1]
WEBTEST_PATH = args[2]
main(SDK_PATH, TEST_PATH, WEBTEST_PATH)
| #!/usr/bin/python
import os
import optparse
import sys
import unittest
USAGE = """%prog SDK_PATH TEST_PATH
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation.
TEST_PATH Path to package containing test modules.
WEBTEST_PATH Path to the webtest library."""
def main(sdk_path, test_path, webtest_path):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
sys.path.append(webtest_path)
suite = unittest.loader.TestLoader().discover(test_path,
pattern="*test.py")
return unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) != 3:
print 'Error: Exactly 3 arguments required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0]
TEST_PATH = args[1]
WEBTEST_PATH = args[2]
sys.exit(not main(SDK_PATH, TEST_PATH, WEBTEST_PATH))
|
Remove comment about client_instance script
The script attribute of a client_instance is tested in the view,
for example in body-end.html:
<% if (model.get('script')) { %>
It can be set to false to disable including of our rather large
JavaScript assets. | var requirejs = require('requirejs');
var PageConfig = requirejs('page_config');
var get_dashboard_and_render = require('./server/mixins/get_dashboard_and_render');
var renderContent = function (req, res, model) {
model.set(PageConfig.commonConfig(req));
var ControllerClass = model.get('controller');
var controller = new ControllerClass({
model: model,
url: req.originalUrl
});
controller.once('ready', function () {
res.set('Cache-Control', 'public, max-age=600');
if (model.get('published') !== true) {
res.set('X-Robots-Tag', 'none');
}
req['spotlight-dashboard-slug'] = model.get('slug');
res.send(controller.html);
});
controller.render({ init: true });
return controller;
};
var setup = function (req, res) {
var client_instance = setup.get_dashboard_and_render(req, res, setup.renderContent);
client_instance.set('script', true);
client_instance.setPath(req.url.replace('/performance', ''));
};
setup.renderContent = renderContent;
setup.get_dashboard_and_render = get_dashboard_and_render;
module.exports = setup;
| var requirejs = require('requirejs');
var PageConfig = requirejs('page_config');
var get_dashboard_and_render = require('./server/mixins/get_dashboard_and_render');
var renderContent = function (req, res, model) {
model.set(PageConfig.commonConfig(req));
var ControllerClass = model.get('controller');
var controller = new ControllerClass({
model: model,
url: req.originalUrl
});
controller.once('ready', function () {
res.set('Cache-Control', 'public, max-age=600');
if (model.get('published') !== true) {
res.set('X-Robots-Tag', 'none');
}
req['spotlight-dashboard-slug'] = model.get('slug');
res.send(controller.html);
});
controller.render({ init: true });
return controller;
};
var setup = function (req, res) {
var client_instance = setup.get_dashboard_and_render(req, res, setup.renderContent);
//I have no idea what this does, can't find anything obvious in the docs or this app.
client_instance.set('script', true);
client_instance.setPath(req.url.replace('/performance', ''));
};
setup.renderContent = renderContent;
setup.get_dashboard_and_render = get_dashboard_and_render;
module.exports = setup;
|
Add don't move the file if he'snt uploaded | <?php
namespace Keosu\Gadget\PushNotificationBundle\EventListener;
use Keosu\CoreBundle\KeosuEvents;
use Keosu\CoreBundle\Event\PackageSaveAppEvent;
use Keosu\Gadget\PushNotificationBundle\KeosuGadgetPushNotificationBundle;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Listener responsible to gadget action
*/
class AppConfListener implements EventSubscriberInterface
{
private $container;
public function __construct($container)
{
$this->container = $container;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
KeosuEvents::PACKAGE_GLOBAL_CONFIG_SAV_FORM.KeosuGadgetPushNotificationBundle::PACKAGE_NAME => 'onAppSave',
);
}
public function onAppSave(PackageSaveAppEvent $event)
{
$app = $event->getApp();
$form = $event->getForm();
$appData = $this->container->get('keosu_core.packagemanager')->getAppDataFolder($app->getId());
$iosPem = $form['configPackages']['keosu-push']['iosPem']->getData();
if($iosPem !== null) {
$iosPem->move($appData,'ios.pem');
$configPackage = $app->getConfigPackages();
$configPackage[KeosuGadgetPushNotificationBundle::PACKAGE_NAME]['iosPem'] = $appData.'ios.pem';
$app->setConfigPackages($configPackage);
}
}
}
| <?php
namespace Keosu\Gadget\PushNotificationBundle\EventListener;
use Keosu\CoreBundle\KeosuEvents;
use Keosu\CoreBundle\Event\PackageSaveAppEvent;
use Keosu\Gadget\PushNotificationBundle\KeosuGadgetPushNotificationBundle;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Listener responsible to gadget action
*/
class AppConfListener implements EventSubscriberInterface
{
private $container;
public function __construct($container)
{
$this->container = $container;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
KeosuEvents::PACKAGE_GLOBAL_CONFIG_SAV_FORM.KeosuGadgetPushNotificationBundle::PACKAGE_NAME => 'onAppSave',
);
}
public function onAppSave(PackageSaveAppEvent $event)
{
$app = $event->getApp();
$form = $event->getForm();
$appData = $this->container->get('keosu_core.packagemanager')->getAppDataFolder($app->getId());
$form['configPackages']['keosu-push']['iosPem']->getData()->move($appData,'ios.pem');
$configPackage = $app->getConfigPackages();
$configPackage[KeosuGadgetPushNotificationBundle::PACKAGE_NAME]['iosPem'] = $appData.'ios.pem';
$app->setConfigPackages($configPackage);
}
}
|
Put some Session examples into other types | package gockle
import (
"fmt"
"github.com/maraino/go-mock"
)
var mySession = &SessionMock{}
func ExampleBatch() {
var b = mySession.QueryBatch(BatchLogged)
b.Query("insert into users (id, name) values (123, 'me')")
b.Query("insert into users (id, name) values (456, 'you')")
b.Exec()
}
func ExampleIterator() {
var i = mySession.QueryIterator("select * from users")
for done := false; !done; {
var m = map[string]interface{}{}
done = i.ScanMap(m)
fmt.Println(m)
}
}
func ExampleSession() {
var rows, _ = mySession.QuerySliceMap("select * from users")
for _, row := range rows {
fmt.Println(row)
}
}
func init() {
var i = &IteratorMock{}
i.When("ScanMap", mock.Any).Call(func(m map[string]interface{}) bool {
m["id"] = 123
m["name"] = "me"
return false
})
i.When("Close").Return(nil)
mySession.When("QueryExec", mock.Any).Return(nil)
mySession.When("QueryIterator", mock.Any).Return(i)
mySession.When("QueryScanMap", mock.Any).Return(map[string]interface{}{"id": 1, "name": "me"}, nil)
}
| package gockle
import (
"fmt"
"github.com/maraino/go-mock"
)
var mySession = &SessionMock{}
func Example_dump() {
var rows, _ = mySession.QuerySliceMap("select * from users")
for _, row := range rows {
fmt.Println(row)
}
}
func Example_insert() {
mySession.QueryExec("insert into users (id, name) values (123, 'me')")
}
func Example_print() {
var i = mySession.QueryIterator("select * from users")
for done := false; !done; {
var m = map[string]interface{}{}
done = i.ScanMap(m)
fmt.Println(m)
}
}
func init() {
var i = &IteratorMock{}
i.When("ScanMap", mock.Any).Call(func(m map[string]interface{}) bool {
m["id"] = 123
m["name"] = "me"
return false
})
i.When("Close").Return(nil)
mySession.When("QueryExec", mock.Any).Return(nil)
mySession.When("QueryIterator", mock.Any).Return(i)
mySession.When("QueryScanMap", mock.Any).Return(map[string]interface{}{"id": 1, "name": "me"}, nil)
}
|
Use foundation stylesheet and js on every page | <?php
/*
* Dit is een standaardpagina voor op de website. Voor het includen van deze
* pagina moet een aantal variabelen geïnitialiseerd worden:
* $title: bevat de paginatitel.
* $head: bevat extra inhoud voor binnen de head tag. Optioneel.
* $body: bevat de inhoud van de pagina, binnen de body tag.
*/
if (!isset($title)) {
trigger_error('Paginatitel niet geïnitialiseerd!', E_USER_WARNING);
}
if (!isset($body)) {
trigger_error('Deze pagina is leeg!', E_USER_NOTICE);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="resources/css/foundation.min.css" type="text/css">
<title><?php echo $title; ?></title>
<?php echo $head; ?>
</head>
<body>
<h1><?php echo $title; ?></h1>
<?php echo $body; ?>
<script src="resources/js/vendor/jquery.min.js"></script>
<script src="resources/js/foundation.min.js"></script>
<script>$(document).foundation();</script>
</body>
</html>
| <?php
/*
* Dit is een standaardpagina voor op de website. Voor het includen van deze
* pagina moet een aantal variabelen geïnitialiseerd worden:
* $title: bevat de paginatitel.
* $head: bevat extra inhoud voor binnen de head tag. Optioneel.
* $body: bevat de inhoud van de pagina, binnen de body tag.
*/
if (!isset($title)) {
trigger_error('Paginatitel niet geïnitialiseerd!', E_USER_WARNING);
}
if (!isset($body)) {
trigger_error('Deze pagina is leeg!', E_USER_NOTICE);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $title; ?></title>
<?php echo $head; ?>
</head>
<body>
<h1><?php echo $title; ?></h1>
<?php echo $body; ?>
</body>
</html>
|
Add imports to init with noqa comments | #!/usr/bin/python
# coding: utf8
"""
Geocoder
~~~~~~~~
Geocoder is a geocoding library, written in python, simple and consistent.
Many online providers such as Google & Bing have geocoding services,
these providers do not include Python libraries and have different
JSON responses between each other.
Consistant JSON responses from various providers.
>>> g = geocoder.google('New York City')
>>> g.latlng
[40.7127837, -74.0059413]
>>> g.state
'New York'
>>> g.json
...
"""
__title__ = 'geocoder'
__author__ = 'Denis Carriere'
__author_email__ = 'carriere.denis@gmail.com'
__version__ = '1.2.2'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2013-2015 Denis Carriere'
# CORE
from .api import get, yahoo, bing, geonames, mapquest # noqa
from .api import nokia, osm, tomtom, geolytica, arcgis, opencage # noqa
from .api import maxmind, freegeoip, ottawa, here, baidu, w3w, yandex # noqa
# EXTRAS
from .api import timezone, elevation, ip, canadapost, reverse # noqa
# CLI
from .cli import cli # noqa
| #!/usr/bin/python
# coding: utf8
# TODO: Move imports to specific modules that need them
# CORE
from .api import get, yahoo, bing, geonames, google, mapquest # noqa
from .api import nokia, osm, tomtom, geolytica, arcgis, opencage # noqa
from .api import maxmind, freegeoip, ottawa, here, baidu, w3w, yandex # noqa
# EXTRAS
from .api import timezone, elevation, ip, canadapost, reverse # noqa
# CLI
from .cli import cli # noqa
"""
Geocoder
~~~~~~~~
Geocoder is a geocoding library, written in python, simple and consistent.
Many online providers such as Google & Bing have geocoding services,
these providers do not include Python libraries and have different
JSON responses between each other.
Consistant JSON responses from various providers.
>>> g = geocoder.google('New York City')
>>> g.latlng
[40.7127837, -74.0059413]
>>> g.state
'New York'
>>> g.json
...
"""
__title__ = 'geocoder'
__author__ = 'Denis Carriere'
__author_email__ = 'carriere.denis@gmail.com'
__version__ = '1.2.2'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2013-2015 Denis Carriere'
|
Allow the stream reader to be set
git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@659 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba | package org.codehaus.xfire.exchange;
import javax.xml.stream.XMLStreamReader;
/**
* A "in" message. These arrive at endpoints.
* @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
*/
public class InMessage
extends AbstractMessage
{
private XMLStreamReader xmlStreamReader;
public InMessage()
{
}
public InMessage(XMLStreamReader xmlStreamReader)
{
this.xmlStreamReader = xmlStreamReader;
setUri(ANONYMOUS_URI);
}
public InMessage(XMLStreamReader xmlStreamReader, String uri)
{
this.xmlStreamReader = xmlStreamReader;
setUri(uri);
}
public void setXMLStreamReader(XMLStreamReader xmlStreamReader)
{
this.xmlStreamReader = xmlStreamReader;
}
public XMLStreamReader getXMLStreamReader()
{
return xmlStreamReader;
}
} | package org.codehaus.xfire.exchange;
import javax.xml.stream.XMLStreamReader;
/**
* A "in" message. These arrive at endpoints.
* @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
*/
public class InMessage
extends AbstractMessage
{
private XMLStreamReader xmlStreamReader;
public InMessage()
{
}
public InMessage(XMLStreamReader xmlStreamReader)
{
this.xmlStreamReader = xmlStreamReader;
setUri(ANONYMOUS_URI);
}
public InMessage(XMLStreamReader xmlStreamReader, String uri)
{
this.xmlStreamReader = xmlStreamReader;
setUri(uri);
}
public XMLStreamReader getXMLStreamReader()
{
return xmlStreamReader;
}
} |
PyChan: Simplify callback creation with a functional utility function. | # coding: utf-8
### Functools ###
def applyOnlySuitable(func,**kwargs):
"""
This nifty little function takes another function and applies it to a dictionary of
keyword arguments. If the supplied function does not expect one or more of the
keyword arguments, these are silently discarded. The result of the application is returned.
This is useful to pass information to callbacks without enforcing a particular signature.
"""
if hasattr(func,'im_func'):
code = func.im_func.func_code
varnames = code.co_varnames[1:code.co_argcount]#ditch bound instance
else:
code = func.func_code
varnames = code.co_varnames[0:code.co_argcount]
#http://docs.python.org/lib/inspect-types.html
if code.co_flags & 8:
return func(**kwargs)
for name,value in kwargs.items():
if name not in varnames:
del kwargs[name]
return func(**kwargs)
def callbackWithArguments(callback,*args,**kwargs):
"""
Curries a function with extra arguments to
create a suitable callback.
If you don't know what this means, don't worry.
It is designed for the case where you need
different buttons to execute basically the same code
with different argumnets.
Usage::
# The target callback
def printStuff(text):
print text
# Mapping the events
gui.mapEvents({
'buttonHello' : callbackWithArguments(printStuff,"Hello"),
'buttonBye' : callbackWithArguments(printStuff,"Adieu")
})
"""
def real_callback():
callback(*args,**kwargs)
return real_callback
| # coding: utf-8
### Functools ###
def applyOnlySuitable(func,**kwargs):
"""
This nifty little function takes another function and applies it to a dictionary of
keyword arguments. If the supplied function does not expect one or more of the
keyword arguments, these are silently discarded. The result of the application is returned.
This is useful to pass information to callbacks without enforcing a particular signature.
"""
if hasattr(func,'im_func'):
code = func.im_func.func_code
varnames = code.co_varnames[1:code.co_argcount]#ditch bound instance
else:
code = func.func_code
varnames = code.co_varnames[0:code.co_argcount]
#http://docs.python.org/lib/inspect-types.html
if code.co_flags & 8:
return func(**kwargs)
for name,value in kwargs.items():
if name not in varnames:
del kwargs[name]
return func(**kwargs)
|
Fix styl/img watching in gulp tasks | import gulp from 'gulp';
import requireDir from 'require-dir';
import runSequence from 'run-sequence';
// Require individual tasks
requireDir('./gulp/tasks', { recurse: true });
gulp.task('default', ['dev']);
gulp.task('dev', () =>
runSequence('clean', 'set-development', 'set-watch-js', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'cached-lintjs-watch'
], ['webpack', 'watch'])
);
gulp.task('hot-dev', () =>
runSequence('clean', 'set-development', [
'i18n',
'copy-static',
'bower',
'stylesheets-livereload',
'cached-lintjs-watch'
], ['webpack', 'watch'])
);
gulp.task('build', cb =>
runSequence('clean', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'lintjs'
], 'webpack', 'minify', cb)
);
| import gulp from 'gulp';
import requireDir from 'require-dir';
import runSequence from 'run-sequence';
// Require individual tasks
requireDir('./gulp/tasks', { recurse: true });
gulp.task('default', ['dev']);
gulp.task('dev', () =>
runSequence('clean', 'set-development', 'set-watch-js', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'webpack',
'cached-lintjs-watch'
], 'watch')
);
gulp.task('hot-dev', () =>
runSequence('clean', 'set-development', [
'i18n',
'copy-static',
'bower',
'stylesheets-livereload',
'cached-lintjs-watch'
], ['webpack', 'watch'])
);
gulp.task('build', cb =>
runSequence('clean', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'lintjs'
], 'webpack', 'minify', cb)
);
|
Apply masonry once images are loaded | jQuery(function ($) {
'use strict';
var content = $('#content');
function applyMasonry() {
if ($(document).width() >= 768) {
content.masonry({
itemSelector: 'article',
isAnimated: false,
columnWidth: function (containerWidth) {
return containerWidth / 6;
}
});
} else if ($(document).width() < 768 && content.hasClass("masonry")) {
content.masonry("destroy");
}
}
content.imagesLoaded(applyMasonry);
$(window).resize(applyMasonry);
$(document.body).bind("post-load", function () {
if (content.hasClass("masonry")) {
content.masonry('option', { isAnimated: true});
content.masonry("appended", content.find("article:not(.masonry-brick)"), true);
}
});
});
| jQuery(function ($) {
'use strict';
var content = $('#content');
function applyMasonry() {
if ($(document).width() >= 768) {
content.masonry({
itemSelector: 'article',
isAnimated: false,
columnWidth: function (containerWidth) {
return containerWidth / 6;
}
});
} else if ($(document).width() < 768 && content.hasClass("masonry")) {
content.masonry("destroy");
}
}
applyMasonry();
$(window).resize(applyMasonry);
$(document.body).bind("post-load", function () {
if (content.hasClass("masonry")) {
content.masonry('option', { isAnimated: true});
content.masonry("appended", content.find("article:not(.masonry-brick)"), true);
}
});
});
|
Add explicit dependency on mongo for tests | Package.describe({
name: "mizzao:autocomplete",
summary: "Client/server autocompletion designed for Meteor's collections and reactivity",
version: "0.4.10",
git: "https://github.com/mizzao/meteor-autocomplete.git"
});
Package.onUse(function (api) {
api.versionsFrom("0.9.4");
api.use(['blaze', 'templating', 'jquery'], 'client');
api.use(['coffeescript', 'underscore']); // both
api.use(['mongo', 'ddp']);
api.use("dandv:caret-position@2.1.0-3", 'client');
// Our files
api.addFiles([
'autocomplete.css',
'inputs.html',
'autocomplete-client.coffee',
'templates.coffee'
], 'client');
api.addFiles([
'autocomplete-server.coffee'
], 'server');
api.export('Autocomplete', 'server');
api.export('AutocompleteTest', {testOnly: true});
});
Package.onTest(function(api) {
api.use("mizzao:autocomplete");
api.use('coffeescript');
api.use('mongo');
api.use('tinytest');
api.addFiles('tests/rule_tests.coffee', 'client');
api.addFiles('tests/regex_tests.coffee', 'client');
api.addFiles('tests/param_tests.coffee', 'client');
api.addFiles('tests/security_tests.coffee');
});
| Package.describe({
name: "mizzao:autocomplete",
summary: "Client/server autocompletion designed for Meteor's collections and reactivity",
version: "0.4.10",
git: "https://github.com/mizzao/meteor-autocomplete.git"
});
Package.onUse(function (api) {
api.versionsFrom("0.9.4");
api.use(['blaze', 'templating', 'jquery'], 'client');
api.use(['coffeescript', 'underscore']); // both
api.use(['mongo', 'ddp']);
api.use("dandv:caret-position@2.1.0-3", 'client');
// Our files
api.addFiles([
'autocomplete.css',
'inputs.html',
'autocomplete-client.coffee',
'templates.coffee'
], 'client');
api.addFiles([
'autocomplete-server.coffee'
], 'server');
api.export('Autocomplete', 'server');
api.export('AutocompleteTest', {testOnly: true});
});
Package.onTest(function(api) {
api.use("mizzao:autocomplete");
api.use('coffeescript');
api.use('tinytest');
api.addFiles('tests/rule_tests.coffee', 'client');
api.addFiles('tests/regex_tests.coffee', 'client');
api.addFiles('tests/param_tests.coffee', 'client');
api.addFiles('tests/security_tests.coffee');
});
|
636: Update case progress query to include name | const config = require('../../../knexfile').web
const knex = require('knex')(config)
const orgUnitFinder = require('../helpers/org-unit-finder')
module.exports = function (id, type) {
var orgUnit = orgUnitFinder('name', type)
var table = orgUnit.caseProgressView
return knex(table)
.where('id', id)
.select('name',
'community_last_16_weeks AS communityLast16Weeks',
'license_last_16_weeks AS licenseLast16Weeks',
'total_cases AS totalCases',
'warrants_total AS warrantsTotal',
'overdue_terminations_total AS overdueTerminationsTotal',
'unpaid_work_total AS unpaidWorkTotal')
.then(function (results) {
return results
})
}
| const config = require('../../../knexfile').web
const knex = require('knex')(config)
const orgUnitFinder = require('../helpers/org-unit-finder')
module.exports = function (id, type) {
var orgUnit = orgUnitFinder('name', type)
var table = orgUnit.caseProgressView
return knex(table)
.where(table + '.id', id)
.select(table + '.community_last_16_weeks AS communityLast16Weeks',
table + '.license_last_16_weeks AS licenseLast16Weeks',
table + '.total_cases AS totalCases',
table + '.warrants_total AS warrantsTotal',
table + '.overdue_terminations_total AS overdueTerminationsTotal',
table + '.unpaid_work_total AS unpaidWorkTotal')
.then(function (results) {
return results
})
}
|
Allow components and sections to be used in parallel | import React from 'react';
import ReactDOM from 'react-dom';
import { setComponentsNames, globalizeComponents, promoteInlineExamples, flattenChildren } from './utils/utils';
import StyleGuide from 'rsg-components/StyleGuide';
import 'highlight.js/styles/tomorrow.css';
import './styles.css';
global.React = React;
if (module.hot) {
module.hot.accept();
}
// Load style guide
let { config, components, sections } = require('styleguide!');
function processComponents(cs) {
cs = flattenChildren(cs);
cs = promoteInlineExamples(cs);
cs = setComponentsNames(cs);
globalizeComponents(cs);
return cs;
}
function processSections(ss) {
return ss.map(section => {
section.components = processComponents(section.components || []);
section.sections = processSections(section.sections || []);
return section;
});
}
components = processComponents(components);
sections = processSections(sections || []);
ReactDOM.render(<StyleGuide config={config} components={components} sections={sections} />, document.getElementById('app'));
| import React from 'react';
import ReactDOM from 'react-dom';
import { setComponentsNames, globalizeComponents, promoteInlineExamples, flattenChildren } from './utils/utils';
import StyleGuide from 'rsg-components/StyleGuide';
import 'highlight.js/styles/tomorrow.css';
import './styles.css';
global.React = React;
if (module.hot) {
module.hot.accept();
}
// Load style guide
let { config, components, sections } = require('styleguide!');
function processComponents(cs) {
cs = flattenChildren(cs);
cs = promoteInlineExamples(cs);
cs = setComponentsNames(cs);
globalizeComponents(cs);
return cs;
}
function processSections(ss) {
return ss.map(section => {
section.components = processComponents(section.components || []);
section.sections = processSections(section.sections || []);
return section;
});
}
// Components are required unless sections are provided
if (sections) {
sections = processSections(sections);
components = [];
}
else {
components = processComponents(components);
sections = [];
}
ReactDOM.render(<StyleGuide config={config} components={components} sections={sections} />, document.getElementById('app'));
|
Fix crash in intercom on server navigation events | const esbuild = require("esbuild");
const isProduction = false;
esbuild.buildSync({
entryPoints: ['./src/platform/current/server/serverStartup.ts'],
bundle: true,
outfile: './build/server/js/bundle2.js',
platform: "node",
sourcemap: true,
minify: false,
define: {
"process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"",
"webpackIsServer": true,
},
external: [
"akismet-api", "mongodb", "canvas", "express", "mz", "pg", "pg-promise",
"mathjax", "mathjax-node", "mathjax-node-page", "jsdom", "@sentry/node", "node-fetch", "later", "turndown",
"apollo-server", "apollo-server-express", "graphql",
"bcrypt", "node-pre-gyp", "@lesswrong", "intercom-client",
],
})
esbuild.buildSync({
entryPoints: ['./src/platform/current/client/clientStartup.ts'],
bundle: true,
target: "es6",
sourcemap: true,
outfile: "./build/client/js/bundle.js",
minify: false,
define: {
"process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"",
"webpackIsServer": false,
"global": "window",
},
});
| const esbuild = require("esbuild");
const isProduction = false;
esbuild.buildSync({
entryPoints: ['./src/platform/current/server/serverStartup.ts'],
bundle: true,
outfile: './build/server/js/bundle2.js',
platform: "node",
sourcemap: true,
minify: false,
define: {
"process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"",
"webpackIsServer": true,
},
external: [
"akismet-api", "mongodb", "canvas", "express", "mz", "pg", "pg-promise",
"mathjax", "mathjax-node", "jsdom", "@sentry/node", "node-fetch", "later", "turndown",
"apollo-server", "apollo-server-express", "graphql",
"bcrypt", "node-pre-gyp", "@lesswrong",
],
})
esbuild.buildSync({
entryPoints: ['./src/platform/current/client/clientStartup.ts'],
bundle: true,
target: "es6",
sourcemap: true,
outfile: "./build/client/js/bundle.js",
minify: false,
define: {
"process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"",
"webpackIsServer": false,
"global": "window",
},
});
|
Increment minor version once again | import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='parserutils',
description='A collection of performant parsing utilities',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml',
version='1.2.2',
packages=[
'parserutils', 'parserutils.tests'
],
install_requires=[
'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/parserutils',
license='BSD',
cmdclass={'test': RunTests}
)
| import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='parserutils',
description='A collection of performant parsing utilities',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml',
version='1.2.1',
packages=[
'parserutils', 'parserutils.tests'
],
install_requires=[
'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/parserutils',
license='BSD',
cmdclass={'test': RunTests}
)
|
Set one line tab titles to default false | import PhotonColors from 'static/lib/photon.css';
const {
blue60: tabColor,
yellow50: otherWindowTabColor,
red60: recentlyClosedTabColor,
ink70: bookmarkColor,
purple70: historyColor,
} = PhotonColors[':root'];
export { defaultCommands } from 'core/keyboard';
export const initialFuzzySettings = {
enableFuzzySearch: true,
shouldSort: true,
threshold: 0.5,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: ['title', 'url'],
};
export const initialGeneralSettings = {
oneLineTabTitles: false,
showVisualDeleteTabButton: true,
showHistory: false,
showBookmarks: false,
showTabCountBadgeText: true,
searchAllWindows: true,
enableOverlay: false,
showRecentlyClosed: true,
alwaysShowRecentlyClosedAtTheBottom: true,
recentlyClosedLimit: 5,
useFallbackFont: false,
showLastQueryOnPopup: false,
shouldSortByMostRecentlyUsedOnPopup: false,
shouldSortByMostRecentlyUsedAll: false,
tabUrlSize: 11,
tabTitleSize: 13,
};
export const initialState = {
lastQuery: '',
};
export const initialColorSettings = {
tabColor,
otherWindowTabColor,
recentlyClosedTabColor,
bookmarkColor,
historyColor,
};
| import PhotonColors from 'static/lib/photon.css';
const {
blue60: tabColor,
yellow50: otherWindowTabColor,
red60: recentlyClosedTabColor,
ink70: bookmarkColor,
purple70: historyColor,
} = PhotonColors[':root'];
export { defaultCommands } from 'core/keyboard';
export const initialFuzzySettings = {
enableFuzzySearch: true,
shouldSort: true,
threshold: 0.5,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: ['title', 'url'],
};
export const initialGeneralSettings = {
oneLineTabTitles: true,
showVisualDeleteTabButton: true,
showHistory: false,
showBookmarks: false,
showTabCountBadgeText: true,
searchAllWindows: true,
enableOverlay: false,
showRecentlyClosed: true,
alwaysShowRecentlyClosedAtTheBottom: true,
recentlyClosedLimit: 5,
useFallbackFont: false,
showLastQueryOnPopup: false,
shouldSortByMostRecentlyUsedOnPopup: false,
shouldSortByMostRecentlyUsedAll: false,
tabUrlSize: 11,
tabTitleSize: 13,
};
export const initialState = {
lastQuery: '',
};
export const initialColorSettings = {
tabColor,
otherWindowTabColor,
recentlyClosedTabColor,
bookmarkColor,
historyColor,
};
|
Sort term frequency results by frequency | class WordCloudOp:
def run(self, data):
terms = { }
results = [ ]
try:
for corpus in data:
tokens = corpus.tokenized_contents
for token in tokens:
if token in terms:
terms[token]+=1
else:
terms[token]=1
for term in terms:
results.append({ "term" : term, "frequency" : terms[term]})
#sort results by term frequency
results.sort(key=lambda results: results['frequency'], reverse=False)
return results
except LookupError:
raise TransactionException('NLTK \'Punkt\' Model not installed.', 500)
except TypeError:
raise TransactionException('Corpus contents does not exist.')
| class WordCloudOp:
def run(self, data):
terms = { }
results = [ ]
try:
for corpus in data:
tokens = corpus.tokenized_contents
for token in tokens:
if token in terms:
terms[token]+=1
else:
terms[token]=1
for term in terms:
results.append({ "term" : term, "frequency" : terms[term]})
return results
except LookupError:
raise TransactionException('NLTK \'Punkt\' Model not installed.', 500)
except TypeError:
raise TransactionException('Corpus contents does not exist.')
|
Remove some chars from dictionary | <?php
namespace Aysheka\Password\Type;
/**
* Base password generator
*/
abstract class Generator
{
protected $numbers = '23456789';
protected $chars = 'qwertyupasdfghjkzxcvbnm';
protected $specialChars = '!@#$%^&&*()-_+=:;';
/**
* generate password
* @param $length
* @return string
*/
function generate($length)
{
$dictionary = $this->getDictionary();
$dictionaryLength = strlen($dictionary) - 1;
$password = '';
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $dictionaryLength);
$password .= $dictionary[$index];
}
while (!$this->check($password)) {
$password = $this->generate($length);
}
return $password;
}
/**
* get password dictionary
* @return string
*/
abstract protected function getDictionary();
/**
* Check password strong
* @param string $password
* @return bool
*/
abstract protected function check($password);
}
| <?php
namespace Aysheka\Password\Type;
/**
* Base password generator
*/
abstract class Generator
{
protected $numbers = '1234567890';
protected $chars = 'qwertyuiopasdfghjklzxcvbnm';
protected $specialChars = '!@#$%^&&*()-_+=:;';
/**
* generate password
* @param $length
* @return string
*/
function generate($length)
{
$dictionary = $this->getDictionary();
$dictionaryLength = strlen($dictionary) - 1;
$password = '';
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $dictionaryLength);
$password .= $dictionary[$index];
}
while (!$this->check($password)) {
$password = $this->generate($length);
}
return $password;
}
/**
* get password dictionary
* @return string
*/
abstract protected function getDictionary();
/**
* Check password strong
* @param string $password
* @return bool
*/
abstract protected function check($password);
}
|
Validate the Subscription policy is made up of Subscription objects | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
'Protocol': (basestring, True),
}
class TopicPolicy(AWSObject):
props = {
'PolicyDocument': (dict, True),
'Topics': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::TopicPolicy"
sup = super(TopicPolicy, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
class Topic(AWSObject):
props = {
'DisplayName': (basestring, False),
'Subscription': ([Subscription], True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::Topic"
sup = super(Topic, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
| # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
'Protocol': (basestring, True),
}
class TopicPolicy(AWSObject):
props = {
'PolicyDocument': (dict, True),
'Topics': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::TopicPolicy"
sup = super(TopicPolicy, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
class Topic(AWSObject):
props = {
'DisplayName': (basestring, False),
'Subscription': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::Topic"
sup = super(Topic, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
|
Load other resources into exist-db | # coding=utf-8
#
# Must be called in roche root dir
#
import sys
import os
sys.path.append('.')
import roche.settings
from os import walk
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.createCollection('docker/texts', True)
os.chdir('../dublin-store')
for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'):
xmldb.createCollection('docker/texts' + '/' + dirpath, True)
if filenames:
for filename in filenames:
with open(dirpath + '/' + filename) as f:
xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True)
#
# Load resources
#
for (dirpath, dirnames, filenames) in walk('resources'):
xmldb.createCollection('docker' + '/' + dirpath, True)
if filenames:
for filename in filenames:
with open(dirpath + '/' + filename) as f:
xmldb.load(f, 'docker' + '/' + dirpath + '/' + filename, True)
| # coding=utf-8
#
# Must be called in roche root dir
#
import sys
import os
sys.path.append('.')
import roche.settings
from os import walk
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.createCollection('docker/texts', True)
os.chdir('../dublin-store')
for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'):
xmldb.createCollection('docker/texts' + '/' + dirpath, True)
if filenames:
for filename in filenames:
with open(dirpath + '/' + filename) as f:
xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True)
|
Switch to google app engine | package main
import (
"html/template"
"net/http"
"sort"
"github.com/eknkc/amber"
"google.golang.org/appengine"
)
//template map
var templateMap map[string]*template.Template
//initialization of the template map
func init() {
templateMap, _ = amber.CompileDir("views",
amber.DirOptions{Ext: ".amber", Recursive: true},
amber.Options{PrettyPrint: false, LineNumbers: false})
}
//complete web server function
func webServer() {
//Sets path handler funcions
http.HandleFunc("/", animeHandler)
http.HandleFunc("/static/", staticHandler)
appengine.Main()
}
// /anime path handler
func animeHandler(w http.ResponseWriter, r *http.Request) {
data := getAnimeList()
sort.Sort(data)
templateMap["aList"].Execute(w, data)
}
// /static/* file server
func staticHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
}
| package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"sort"
"github.com/eknkc/amber"
)
//template map
var templateMap map[string]*template.Template
//initialization of the template map
func init() {
templateMap, _ = amber.CompileDir("views",
amber.DirOptions{Ext: ".amber", Recursive: true},
amber.Options{PrettyPrint: false, LineNumbers: false})
}
//complete web server function
func webServer() {
//Sets path handler funcions
http.HandleFunc("/", animeHandler)
http.HandleFunc("/static/", staticHandler)
//Sets url and port
bind := fmt.Sprintf("%s:%s", "127.0.0.1", "422")
if os.Getenv("OPENSHIFT_GO_IP") != "" &&
os.Getenv("OPENSHIFT_GO_PORT") != "" {
bind = fmt.Sprintf("%s:%s", os.Getenv("OPENSHIFT_GO_IP"),
os.Getenv("OPENSHIFT_GO_PORT"))
}
//Listen and sert to port
log.Printf("Web server listening on %s", bind)
err := http.ListenAndServe(bind, nil)
if err != nil {
log.Fatal("webServer() => ListenAndServer() error:\t", err)
}
}
// /anime path handler
func animeHandler(w http.ResponseWriter, r *http.Request) {
data := getAnimeList()
sort.Sort(data)
templateMap["aList"].Execute(w, data)
}
// /static/* file server
func staticHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
}
|
Check err not nil before calling clusterDialer | package ref
import (
"fmt"
"strings"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
)
var NodeNotFound = "can not build dialer to"
func IsNodeNotFound(err error) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), NodeNotFound)
}
func FromStrings(namespace, name string) string {
return fmt.Sprintf("%s:%s", namespace, name)
}
func Ref(obj runtime.Object) string {
objMeta, _ := meta.Accessor(obj)
if objMeta.GetNamespace() == "" {
return objMeta.GetName()
}
return FromStrings(objMeta.GetNamespace(), objMeta.GetName())
}
func Parse(ref string) (namespace string, name string) {
parts := strings.SplitN(ref, ":", 2)
if len(parts) == 1 {
return "", parts[0]
}
return parts[0], parts[1]
}
| package ref
import (
"fmt"
"strings"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
)
var NodeNotFound = "can not build dialer to"
func IsNodeNotFound(err error) bool {
return strings.Contains(err.Error(), NodeNotFound)
}
func FromStrings(namespace, name string) string {
return fmt.Sprintf("%s:%s", namespace, name)
}
func Ref(obj runtime.Object) string {
objMeta, _ := meta.Accessor(obj)
if objMeta.GetNamespace() == "" {
return objMeta.GetName()
}
return FromStrings(objMeta.GetNamespace(), objMeta.GetName())
}
func Parse(ref string) (namespace string, name string) {
parts := strings.SplitN(ref, ":", 2)
if len(parts) == 1 {
return "", parts[0]
}
return parts[0], parts[1]
}
|
Change Proxy class used to Doctrine\Common\Persistence\Proxy | <?php
/*
* Copyright 2013 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* 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.
*/
namespace JMS\Serializer\Tests\Fixtures;
use Doctrine\Common\Persistence\Proxy;
class SimpleObjectProxy extends SimpleObject implements Proxy
{
public $__isInitialized__ = false;
private $baz = 'baz';
public function __load()
{
if (!$this->__isInitialized__) {
$this->camelCase = 'proxy-boo';
$this->__isInitialized__ = true;
}
}
public function __isInitialized()
{
return $this->__isInitialized__;
}
}
| <?php
/*
* Copyright 2013 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* 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.
*/
namespace JMS\Serializer\Tests\Fixtures;
use Doctrine\ORM\Proxy\Proxy;
class SimpleObjectProxy extends SimpleObject implements Proxy
{
public $__isInitialized__ = false;
private $baz = 'baz';
public function __load()
{
if (!$this->__isInitialized__) {
$this->camelCase = 'proxy-boo';
$this->__isInitialized__ = true;
}
}
public function __isInitialized()
{
return $this->__isInitialized__;
}
}
|
Add tips to error message | #!/usr/bin/env node
'use strict';
var minimist = require('minimist');
var npmDoctor = require('../lib/npm-doctor');
var issueLogger = require('../lib/issue-logger');
var options = minimist(process.argv.slice(2));
var query = options._[0];
var depth = options.depth;
var limit = options.limit;
if (!query) {
console.log([
'',
'Usage: npm-doctor [options] [query]',
'',
'Examples: npm-doctor "An issue that I need to search for"',
' npm-doctor --depth 2 "An issue that I need to search for"',
' npm-doctor --depth 2 --limit 10 "An issue that I need to search for"',
'',
'Options:',
'--depth [int] The maximum depth of your local node modules that should be included in the search',
'--limit [int] The maximum number of results you would like logged to console'
].join('\n'));
return;
}
npmDoctor.searchIssues(query, depth)
.then(function (issues) {
issueLogger.log(issues, limit);
})
.catch(function (err) {
console.error([
'GitHub rate limits requests, so you may have to wait a minute to try again',
'If you keep seeing this message, try with a smaller depth (ie: npm-doctor --depth 1)',
'If you still keep seeing this, report a bug at https://github.com/seanzarrin/npm-doctor/issues'
].join('\n'));
});
| #!/usr/bin/env node
'use strict';
var minimist = require('minimist');
var npmDoctor = require('../lib/npm-doctor');
var issueLogger = require('../lib/issue-logger');
var options = minimist(process.argv.slice(2));
var query = options._[0];
var depth = options.depth;
var limit = options.limit;
if (!query) {
console.log([
'',
'Usage: npm-doctor [options] [query]',
'',
'Examples: npm-doctor "An issue that I need to search for"',
' npm-doctor --depth 2 "An issue that I need to search for"',
' npm-doctor --depth 2 --limit 10 "An issue that I need to search for"',
'',
'Options:',
'--depth [int] The maximum depth of your local node modules that should be included in the search',
'--limit [int] The maximum number of results you would like logged to console'
].join('\n'));
return;
}
npmDoctor.searchIssues(query, depth)
.then(function (issues) {
issueLogger.log(issues, limit);
})
.catch(function (err) {
console.error('GitHub rate limits requests, so you may have to wait a minute to try again');
});
|
Add new fields to match DEA
[#96142924] | package cc_messages
import "time"
type LRPInstanceState string
const (
LRPInstanceStateStarting LRPInstanceState = "STARTING"
LRPInstanceStateRunning LRPInstanceState = "RUNNING"
LRPInstanceStateCrashed LRPInstanceState = "CRASHED"
LRPInstanceStateUnknown LRPInstanceState = "UNKNOWN"
)
type LRPInstance struct {
ProcessGuid string `json:"process_guid"`
InstanceGuid string `json:"instance_guid"`
Index uint `json:"index"`
State LRPInstanceState `json:"state"`
Details string `json:"details,omitempty"`
Host string `json:"host,omitempty"`
Port uint16 `json:"port,omitempty"`
Since int64 `json:"since"`
Stats *LRPInstanceStats `json:"stats,omitempty"`
}
type LRPInstanceStats struct {
Time time.Time `json:"time"`
CpuPercentage float64 `json:"cpu"`
MemoryBytes uint64 `json:"mem"`
DiskBytes uint64 `json:"disk"`
}
| package cc_messages
type LRPInstanceState string
const (
LRPInstanceStateStarting LRPInstanceState = "STARTING"
LRPInstanceStateRunning LRPInstanceState = "RUNNING"
LRPInstanceStateCrashed LRPInstanceState = "CRASHED"
LRPInstanceStateUnknown LRPInstanceState = "UNKNOWN"
)
type LRPInstance struct {
ProcessGuid string `json:"process_guid"`
InstanceGuid string `json:"instance_guid"`
Index uint `json:"index"`
State LRPInstanceState `json:"state"`
Details string `json:"details,omitempty"`
Since int64 `json:"since_in_ns"`
Stats *LRPInstanceStats `json:"stats,omitempty"`
}
type LRPInstanceStats struct {
CpuPercentage float64 `json:"cpu"`
MemoryBytes uint64 `json:"mem"`
DiskBytes uint64 `json:"disk"`
}
|
Correct URL for settings page | (function(Pebble, window) {
var settings = {};
Pebble.addEventListener("ready", function(e) {
settings = window.localStorage.getItem("settings");
if(settings !== '') {
var options = JSON.parse(settings);
Pebble.sendAppMessage(options);
}
});
Pebble.addEventListener("showConfiguration", function() {
settings = window.localStorage.getItem("settings");
if(!settings) {
settings = {};
}
Pebble.openURL("http://rexmac.com/projects/pebble/chronocode/settings.html");
});
Pebble.addEventListener("webviewclosed", function(e) {
var options = JSON.parse(decodeURIComponent(e.response));
if(Object.keys(options).length > 0) {
window.localStorage.setItem("settings", JSON.stringify(options));
Pebble.sendAppMessage(options);
}
})
})(Pebble, window);
| (function(Pebble, window) {
var settings = {};
Pebble.addEventListener("ready", function(e) {
settings = window.localStorage.getItem("settings");
if(settings !== '') {
var options = JSON.parse(settings);
Pebble.sendAppMessage(options);
}
});
Pebble.addEventListener("showConfiguration", function() {
settings = window.localStorage.getItem("settings");
if(!settings) {
settings = {};
}
//Pebble.openURL("http://pebble.rexmac.com/pebble-wordsquare/settings.html");
Pebble.openURL("http://rexmac.dev/pws/settings.html#" + encodeURIComponent(JSON.stringify(settings)));
});
Pebble.addEventListener("webviewclosed", function(e) {
var options = JSON.parse(decodeURIComponent(e.response));
if(Object.keys(options).length > 0) {
window.localStorage.setItem("settings", JSON.stringify(options));
Pebble.sendAppMessage(options);
}
})
})(Pebble, window);
|
Add variant extension in example script | #!/usr/bin/env python
# -*- coding: utf8 - *-
from __future__ import print_function, unicode_literals
from cihai.bootstrap import bootstrap_unihan
from cihai.core import Cihai
def variant_list(unihan, field):
for char in unihan.with_fields(field):
print("Character: {}".format(char.char))
for var in char.untagged_vars(field):
print(var)
def script(unihan_options={}):
"""Wrapped so we can test in tests/test_examples.py"""
print("This example prints variant character data.")
c = Cihai()
c.add_dataset('cihai.unihan.Unihan', namespace='unihan')
if not c.sql.is_bootstrapped: # download and install Unihan to db
bootstrap_unihan(c.sql.metadata, options=unihan_options)
c.sql.reflect_db() # automap new table created during bootstrap
c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants')
print("## ZVariants")
variant_list(c.unihan, "kZVariant")
print("## kSemanticVariant")
variant_list(c.unihan, "kSemanticVariant")
print("## kSpecializedSemanticVariant")
variant_list(c.unihan, "kSpecializedSemanticVariant")
if __name__ == '__main__':
script()
| #!/usr/bin/env python
# -*- coding: utf8 - *-
from __future__ import print_function, unicode_literals
from cihai.bootstrap import bootstrap_unihan
from cihai.core import Cihai
def variant_list(unihan, field):
for char in unihan.with_fields(field):
print("Character: {}".format(char.char))
for var in char.untagged_vars(field):
print(var)
def script(unihan_options={}):
"""Wrapped so we can test in tests/test_examples.py"""
print("This example prints variant character data.")
c = Cihai()
c.add_dataset('cihai.unihan.Unihan', namespace='unihan')
if not c.sql.is_bootstrapped: # download and install Unihan to db
bootstrap_unihan(c.sql.metadata, options=unihan_options)
c.sql.reflect_db() # automap new table created during bootstrap
print("## ZVariants")
variant_list(c.unihan, "kZVariant")
print("## kSemanticVariant")
variant_list(c.unihan, "kSemanticVariant")
print("## kSpecializedSemanticVariant")
variant_list(c.unihan, "kSpecializedSemanticVariant")
if __name__ == '__main__':
script()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.