text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add optional argument to the helper function | <?php
/******************************************************************************
* Copyright (c) 2010 Jevon Wright and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* or
*
* LGPL which is available at http://www.gnu.org/licenses/lgpl.html
*
*
* Contributors:
* Jevon Wright - initial API and implementation
****************************************************************************/
/**
* This file is available if you still want to use functions rather than
* autoloading classes.
*/
require_once(__DIR__ . "/src/Html2Text.php");
require_once(__DIR__ . "/src/Html2TextException.php");
function convert_html_to_text($html, $ignore_error = false) {
return Html2Text\Html2Text::convert($html, $ignore_error);
}
function fix_newlines($text) {
return Html2Text\Html2Text::fixNewlines($text);
}
| <?php
/******************************************************************************
* Copyright (c) 2010 Jevon Wright and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* or
*
* LGPL which is available at http://www.gnu.org/licenses/lgpl.html
*
*
* Contributors:
* Jevon Wright - initial API and implementation
****************************************************************************/
/**
* This file is available if you still want to use functions rather than
* autoloading classes.
*/
require_once(__DIR__ . "/src/Html2Text.php");
require_once(__DIR__ . "/src/Html2TextException.php");
function convert_html_to_text($html) {
return Html2Text\Html2Text::convert($html);
}
function fix_newlines($text) {
return Html2Text\Html2Text::fixNewlines($text);
}
|
Enable mutable config in blazar
New releases of oslo.config support a 'mutable' parameter in Opts.
oslo.service provides an option [1] which allows services to tell it
they want mutate_config_files to be called by passing a parameter.
This commit is to use the same approach. This allows Blazar to benefit
from [2], where the 'debug' option (owned by oslo.log) is made mutable.
We should be able to turn debug logging on and off by changing the
config and sending a SIGHUP signal to blazar-manager.
However, please note that blazar-manager currently doesn't work
correctly after receiving a SIGHUP. As a result the mutable config is
not yet usable. Operators should continue restarting blazar-manager
after changing blazar.conf.
TC goal: https://governance.openstack.org/tc/goals/rocky/enable-mutable-configuration.html
[1] https://review.openstack.org/263312/
[2] https://review.openstack.org/254821/
Change-Id: Ieea9043b6f3a28dc92717680585614a68227120e | # Copyright (c) 2013 Mirantis 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.
import eventlet
eventlet.monkey_patch()
import gettext
import sys
from oslo_config import cfg
from oslo_service import service
gettext.install('blazar')
from blazar.db import api as db_api
from blazar.manager import service as manager_service
from blazar.notification import notifier
from blazar.utils import service as service_utils
def main():
cfg.CONF(project='blazar', prog='blazar-manager')
service_utils.prepare_service(sys.argv)
db_api.setup_db()
notifier.init()
service.launch(
cfg.CONF,
manager_service.ManagerService(),
restart_method='mutate'
).wait()
if __name__ == '__main__':
main()
| # Copyright (c) 2013 Mirantis 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.
import eventlet
eventlet.monkey_patch()
import gettext
import sys
from oslo_config import cfg
from oslo_service import service
gettext.install('blazar')
from blazar.db import api as db_api
from blazar.manager import service as manager_service
from blazar.notification import notifier
from blazar.utils import service as service_utils
def main():
cfg.CONF(project='blazar', prog='blazar-manager')
service_utils.prepare_service(sys.argv)
db_api.setup_db()
notifier.init()
service.launch(
cfg.CONF,
manager_service.ManagerService()
).wait()
if __name__ == '__main__':
main()
|
Increase seed length in database to fit default | from django.utils.translation import ugettext_lazy as _
from django.db import models
from django.contrib.auth.models import User
from two_factor import call_gateways, sms_gateways
TOKEN_METHODS = [
('generator', _('Token generator (iPhone/Android App)')),
]
if call_gateways.GATEWAY:
TOKEN_METHODS += [
('call', _('Phone call')),
]
if sms_gateways.GATEWAY:
TOKEN_METHODS += [
('sms', _('Text message')),
]
class VerifiedComputer(models.Model):
user = models.ForeignKey(User, verbose_name=_('verified computer'))
verified_until = models.DateTimeField(_('verified until'))
ip = models.IPAddressField(_('IP address'))
last_used_at = models.DateTimeField(_('last used at'))
class Token(models.Model):
user = models.OneToOneField(User, verbose_name=_('user'))
seed = models.CharField(_('seed'), max_length=32)
method = models.CharField(_('authentication method'),
choices=TOKEN_METHODS, max_length=16)
phone = models.CharField(_('phone number'), max_length=16)
backup_phone = models.CharField(_('backup phone number'), max_length=16,
null=True, blank=True)
| from django.utils.translation import ugettext_lazy as _
from django.db import models
from django.contrib.auth.models import User
from two_factor import call_gateways, sms_gateways
TOKEN_METHODS = [
('generator', _('Token generator (iPhone/Android App)')),
]
if call_gateways.GATEWAY:
TOKEN_METHODS += [
('call', _('Phone call')),
]
if sms_gateways.GATEWAY:
TOKEN_METHODS += [
('sms', _('Text message')),
]
class VerifiedComputer(models.Model):
user = models.ForeignKey(User, verbose_name=_('verified computer'))
verified_until = models.DateTimeField(_('verified until'))
ip = models.IPAddressField(_('IP address'))
last_used_at = models.DateTimeField(_('last used at'))
class Token(models.Model):
user = models.OneToOneField(User, verbose_name=_('user'))
seed = models.CharField(_('seed'), max_length=16)
method = models.CharField(_('authentication method'),
choices=TOKEN_METHODS, max_length=16)
phone = models.CharField(_('phone number'), max_length=16)
backup_phone = models.CharField(_('backup phone number'), max_length=16,
null=True, blank=True)
|
Sort null risk levels correctly
I'm a little surprised that the Tablesort comparator works in the exact
opposite way to pretty much every other comparator, but it's late, and I
could be missing something.
addresses #344 | (function(){
var cleanNumber = function(i) {
var n = parseFloat(i.replace(/[^\-?0-9.]/g, ''));
return isNaN(n) ? null : n;
},
compareNumberReverse = function(a, b) {
// Treat null as always greater
if (a === null) return 1;
if (b === null) return -1;
return a - b;
};
Tablesort.extend('reverse_number', function(item) {
return item.match(/^-?[£\x24Û¢´€]?\d+\s*([,\.]\d{0,2})/) || // Prefixed currency
item.match(/^-?\d+\s*([,\.]\d{0,2})?[£\x24Û¢´€]/) || // Suffixed currency
item.match(/^-?(\d)*-?([,\.]){0,1}-?(\d)+([E,e][\-+][\d]+)?%?$/); // Number
}, function(a, b) {
return compareNumberReverse(cleanNumber(a), cleanNumber(b));
});
}());
| (function(){
var cleanNumber = function(i) {
return i.replace(/[^\-?0-9.]/g, '');
},
compareNumberReverse = function(a, b) {
a = parseFloat(a);
b = parseFloat(b);
a = isNaN(a) ? 0 : a;
b = isNaN(b) ? 0 : b;
return b - a;
};
Tablesort.extend('reverse_number', function(item) {
return item.match(/^-?[£\x24Û¢´€]?\d+\s*([,\.]\d{0,2})/) || // Prefixed currency
item.match(/^-?\d+\s*([,\.]\d{0,2})?[£\x24Û¢´€]/) || // Suffixed currency
item.match(/^-?(\d)*-?([,\.]){0,1}-?(\d)+([E,e][\-+][\d]+)?%?$/); // Number
}, function(a, b) {
a = cleanNumber(a);
b = cleanNumber(b);
return compareNumberReverse(b, a);
});
}());
|
[Instabot] Make example bot react to SIGINT better | #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
try:
bot.run()
except KeyboardInterrupt:
sys.stderr.write('\n')
finally:
bot.close()
if __name__ == '__main__': main()
| #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
bot.run()
if __name__ == '__main__': main()
|
Fix a https url issue
Change-Id: I2d2794209620c823f0aef9549f8ee43aa4c91dff | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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.
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
# solution from: https://bugs.python.org/issue15881#msg170215
try:
import multiprocessing # noqa
except ImportError:
pass
setuptools.setup(
setup_requires=['pbr>=2.0.0'],
pbr=True)
| # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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.
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
# solution from: http://bugs.python.org/issue15881#msg170215
try:
import multiprocessing # noqa
except ImportError:
pass
setuptools.setup(
setup_requires=['pbr>=2.0.0'],
pbr=True)
|
Allow iterable to be output in PHP 7.1 too | <?php
namespace Psalm\Type\Atomic;
class TIterable extends \Psalm\Type\Atomic
{
use HasIntersectionTrait;
/**
* @var string
*/
public $value = 'iterable';
public function __toString()
{
return 'iterable';
}
/**
* @return string
*/
public function getKey()
{
return 'iterable';
}
/**
* @return bool
*/
public function canBeFullyExpressedInPhp()
{
return true;
}
/**
* @param string|null $namespace
* @param array<string> $aliased_classes
* @param string|null $this_class
* @param int $php_major_version
* @param int $php_minor_version
*
* @return string|null
*/
public function toPhpString(
$namespace,
array $aliased_classes,
$this_class,
$php_major_version,
$php_minor_version
) {
return $php_major_version >= 7 && $php_minor_version >= 1 ? 'iterable' : null;
}
}
| <?php
namespace Psalm\Type\Atomic;
class TIterable extends \Psalm\Type\Atomic
{
use HasIntersectionTrait;
/**
* @var string
*/
public $value = 'iterable';
public function __toString()
{
return 'iterable';
}
/**
* @return string
*/
public function getKey()
{
return 'iterable';
}
/**
* @return bool
*/
public function canBeFullyExpressedInPhp()
{
return true;
}
/**
* @param string|null $namespace
* @param array<string> $aliased_classes
* @param string|null $this_class
* @param int $php_major_version
* @param int $php_minor_version
*
* @return string|null
*/
public function toPhpString(
$namespace,
array $aliased_classes,
$this_class,
$php_major_version,
$php_minor_version
) {
return $php_major_version >= 7 && $php_minor_version >= 2 ? 'iterable' : null;
}
}
|
[TwigExtraBundle] Add the return type information in getConfigTreeBuilder() | <?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extra\TwigExtraBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Twig\Extra\TwigExtraBundle\Extensions;
class Configuration implements ConfigurationInterface
{
/**
* @return TreeBuilder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('twig_extra');
$rootNode = $treeBuilder->getRootNode();
foreach (Extensions::getClasses() as $name => $class) {
$rootNode
->children()
->arrayNode($name)
->{class_exists($class) ? 'canBeDisabled' : 'canBeEnabled'}()
->end()
->end()
;
}
return $treeBuilder;
}
}
| <?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extra\TwigExtraBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Twig\Extra\TwigExtraBundle\Extensions;
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('twig_extra');
$rootNode = $treeBuilder->getRootNode();
foreach (Extensions::getClasses() as $name => $class) {
$rootNode
->children()
->arrayNode($name)
->{class_exists($class) ? 'canBeDisabled' : 'canBeEnabled'}()
->end()
->end()
;
}
return $treeBuilder;
}
}
|
Adjust URLs relative to new SW location | #! /usr/bin/env node
"use strict";
const fs = require("fs");
const exec = require("child_process").exec;
const fileName = "src/js/mainSiteURLs.json";
function fileFinder(dir, pattern) {
return new Promise((resolve, reject) => {
var command = `find ${dir} ${pattern}`;
exec(command, (err, stdout) => {
return (err) ? reject(err) : resolve(stdout);
});
});
}
// Find css and JS files
const findJs = fileFinder(`src/js`, `-iname "*.js"`);
const findCss = fileFinder(`src/css`, `-iname "*.css" -or -iname "*.svg" -or -iname "*.png"`);
function processResults(results) {
const paths = results
.reduce((current, next) => next.concat(current), [])
.split("\n")
.filter(item => item)
.map(item => item.replace(/^src\//, "./"))
.sort();
return JSON.stringify(paths, null, 2);
}
function writeFile(template) {
return new Promise((resolve, reject) => {
fs.writeFile(fileName, template, (err) => {
return (err) ? reject(err) : resolve();
});
});
}
// Process and generate file
Promise.all([findJs, findCss])
.then(processResults)
.then(writeFile)
.catch(err => console.error(err));
| #! /usr/bin/env node
"use strict";
const fs = require("fs");
const exec = require("child_process").exec;
const fileName = "src/js/mainSiteURLs.json";
function fileFinder(dir, pattern) {
return new Promise((resolve, reject) => {
var command = `find ${dir} ${pattern}`;
exec(command, (err, stdout) => {
return (err) ? reject(err) : resolve(stdout);
});
});
}
// Find css and JS files
const findJs = fileFinder(`src/js`, `-iname "*.js"`);
const findCss = fileFinder(`src/css`, `-iname "*.css" -or -iname "*.svg" -or -iname "*.png"`);
function processResults(results) {
const paths = results
.reduce((current, next) => next.concat(current), [])
.split("\n")
.filter(item => item)
.map(item => item.replace(/^src\//, "/"))
.sort();
return JSON.stringify(paths.concat(["/"]), null, 2);
}
function writeFile(template) {
return new Promise((resolve, reject) => {
fs.writeFile(fileName, template, (err) => {
return (err) ? reject(err) : resolve();
});
});
}
// Process and generate file
Promise.all([findJs, findCss])
.then(processResults)
.then(writeFile)
.catch(err => console.error(err));
|
Fix the blip autoscrape. Missed an import.
Stupid stupid stupid. Should have tested before pushing. | from vidscraper import errors
from vidscraper.sites import (
vimeo, google_video, youtube, blip)
AUTOSCRAPE_SUITES = [
vimeo.SUITE, google_video.SUITE, youtube.SUITE,
blip.SUITE]
def scrape_suite(url, suite, fields=None):
scraped_data = {}
funcs_map = suite['funcs']
fields = fields or funcs_map.keys()
order = suite.get('order')
if order:
# remove items in the order that are not in the fields
for field in set(order).difference(fields):
order.pop(field)
# add items that may have been missing from the order but
# which are in the fields
order.extend(set(fields).difference(order))
fields = order
shortmem = {}
for field in fields:
func = funcs_map[field]
scraped_data[field] = func(url, shortmem=shortmem)
return scraped_data
def auto_scrape(url, fields=None):
for suite in AUTOSCRAPE_SUITES:
if suite['regex'].match(url):
return scrape_suite(url, suite, fields)
# If we get here that means that none of the regexes matched, so
# throw an error
raise errors.CantIdentifyUrl(
"No video scraping suite was found that can scrape that url")
| from vidscraper import errors
from vidscraper.sites import (
vimeo, google_video, youtube)
AUTOSCRAPE_SUITES = [
vimeo.SUITE, google_video.SUITE, youtube.SUITE,
blip.SUITE]
def scrape_suite(url, suite, fields=None):
scraped_data = {}
funcs_map = suite['funcs']
fields = fields or funcs_map.keys()
order = suite.get('order')
if order:
# remove items in the order that are not in the fields
for field in set(order).difference(fields):
order.pop(field)
# add items that may have been missing from the order but
# which are in the fields
order.extend(set(fields).difference(order))
fields = order
shortmem = {}
for field in fields:
func = funcs_map[field]
scraped_data[field] = func(url, shortmem=shortmem)
return scraped_data
def auto_scrape(url, fields=None):
for suite in AUTOSCRAPE_SUITES:
if suite['regex'].match(url):
return scrape_suite(url, suite, fields)
# If we get here that means that none of the regexes matched, so
# throw an error
raise errors.CantIdentifyUrl(
"No video scraping suite was found that can scrape that url")
|
Check selectedIndex >= 0 before accessing options collection for select elements | /**
* Input controls based on select boxes
*
* @implements v2.FieldElement
* @depends input_element.js
*/
v2.SelectElement = v2.InputElement.extend(/** @scope v2.SelectElement.prototype */{
/**
* Construct a new select field
* @see v2.FieldElement.constructor
*/
constructor: function(select) {
// Regular initialization, add select specific event
this.base([select], 'change');
},
/**
* @see v2.FieldElement.getValue
*
* Returns the value attribute of the currently selected option. For multi
* selects, it returns an array of value attributes for each selected option.
*/
getValue: function() {
var select = this.__elements[0];
if (!select.multiple) {
if (select.options.length > 0 && select.selectedIndex >= 0) {
return select.options[select.selectedIndex].value;
} else {
return null;
}
}
var values = [];
for (var i = 0, option; (option = select.options[i]); i++) {
if (option.selected) {
values.push(option.value);
}
}
return values;
}
});
| /**
* Input controls based on select boxes
*
* @implements v2.FieldElement
* @depends input_element.js
*/
v2.SelectElement = v2.InputElement.extend(/** @scope v2.SelectElement.prototype */{
/**
* Construct a new select field
* @see v2.FieldElement.constructor
*/
constructor: function(select) {
// Regular initialization, add select specific event
this.base([select], 'change');
},
/**
* @see v2.FieldElement.getValue
*
* Returns the value attribute of the currently selected option. For multi
* selects, it returns an array of value attributes for each selected option.
*/
getValue: function() {
var select = this.__elements[0];
if (!select.multiple) {
return select.options.length > 0 && select.options[select.selectedIndex].value;
}
var values = [];
for (var i = 0, option; (option = select.options[i]); i++) {
if (option.selected) {
values.push(option.value);
}
}
return values;
}
});
|
Enable touch use with jQuery element. | $(".up-button").bind("mousedown touchstart", function(){
$.get("/movecam/moveUp");
}).bind("mouseup touchend", function(){
$.get("/movecam/moveStop");
});
$(".left-button").bind("mousedown touchstart", function(){
$.get("/movecam/moveLeft");
}).bind("mouseup touchend", function(){
$.get("/movecam/moveStop");
});
$(".right-button").bind("mousedown touchstart", function(){
$.get("/movecam/moveRight");
}).bind("mouseup touchend", function(){
$.get("/movecam/moveStop");
});
$(".down-button").bind("mousedown touchstart", function(){
$.get("/movecam/moveDown");
}).bind("mouseup touchend", function(){
$.get("/movecam/moveStop");
});
$(".zoom-tele").bind("mousedown touchstart", function(){
$.get("/movecam/zoomTeleStd");
}).bind("mouseup touchend", function(){
$.get("/movecam/zoomStop");
});
$(".zoom-wide").bind("mousedown touchstart", function(){
$.get("/movecam/zoomWideStd");
}).bind("mouseup touchend", function(){
$.get("/movecam/zoomStop");
});
| $(".up-button").mousedown(function(){
$.get("/movecam/moveUp");
}).mouseup(function(){
$.get("/movecam/moveStop");
});
$(".left-button").mousedown(function(){
$.get("/movecam/moveLeft");
}).mouseup(function(){
$.get("/movecam/moveStop");
});
$(".right-button").mousedown(function(){
$.get("/movecam/moveRight");
}).mouseup(function(){
$.get("/movecam/moveStop");
});
$(".down-button").mousedown(function(){
$.get("/movecam/moveDown");
}).mouseup(function(){
$.get("/movecam/moveStop");
});
$(".zoom-tele").mousedown(function(){
$.get("/movecam/zoomTeleStd");
}).mouseup(function(){
$.get("/movecam/zoomStop");
});
$(".zoom-wide").mousedown(function(){
$.get("/movecam/zoomWideStd");
}).mouseup(function(){
$.get("/movecam/zoomStop");
});
|
Fix migration file for new collection kind name | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-12-04 04:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("kolibriauth", "0015_facilitydataset_registered")]
operations = [
migrations.CreateModel(
name="AdHocGroup",
fields=[],
options={"indexes": [], "proxy": True},
bases=("kolibriauth.collection",),
),
migrations.AlterField(
model_name="collection",
name="kind",
field=models.CharField(
choices=[
("facility", "Facility"),
("classroom", "Classroom"),
("learnergroup", "Learner group"),
("adhoclearnersgroup', 'Ad hoc learners group"),
],
max_length=20,
),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-12-04 04:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("kolibriauth", "0015_facilitydataset_registered")]
operations = [
migrations.CreateModel(
name="AdHocGroup",
fields=[],
options={"indexes": [], "proxy": True},
bases=("kolibriauth.collection",),
),
migrations.AlterField(
model_name="collection",
name="kind",
field=models.CharField(
choices=[
("facility", "Facility"),
("classroom", "Classroom"),
("learnergroup", "Learner group"),
("adhoclearnersgroup", "Individual learners group"),
],
max_length=20,
),
),
]
|
Fix - read github issues | "use strict";
let jobModel, campaignModel, tabSequence, serialExecutor, args,
JobModel = require('./models/job'),
CampaignModel = require('./models/campaign'),
TabSequence = require('./tabSequence'),
SerialExecutor = require('./serialExecutor'),
logger = require('./logger')('compatipede'),
async = require('async');
module.exports = function(argv) {
let dbSettings = {
host : argv.couchdbHost,
port : argv.couchdbPort,
auth : {
username : argv.couchdbUser,
password : argv.couchdbPassword
}
};
args = argv;
jobModel = new JobModel(dbSettings, argv.jobsDb);
campaignModel = new CampaignModel(dbSettings, argv.campaignDb);
tabSequence = new TabSequence(argv.masterUrl);
serialExecutor = new SerialExecutor(argv.processId, jobModel,
campaignModel, tabSequence);
jobModel.once('ready', ready);
campaignModel.once('ready', ready);
};
let readyCnt = 0;
function ready() {
readyCnt += 1;
if(readyCnt !== 2) {
return;
}
execute();
}
function execute() {
async.series([
require('./githubDispatcher').bind(null, args),
serialExecutor.loop.bind(serialExecutor)
], (error) => {
if(error) {
logger.error('execute', 'Failed to do loop', error);
throw error;
}
process.exit(0);
});
}
| "use strict";
let jobModel, campaignModel, tabSequence, serialExecutor, args,
JobModel = require('./models/job'),
CampaignModel = require('./models/campaign'),
TabSequence = require('./tabSequence'),
SerialExecutor = require('./serialExecutor'),
logger = require('./logger')('compatipede'),
async = require('async');
module.exports = function(argv) {
let dbSettings = {
host : argv.couchdbHost,
port : argv.couchdbPort,
auth : {
username : argv.couchdbUser,
password : argv.couchdbPassword
}
};
args = argv;
jobModel = new JobModel(dbSettings, argv.jobsDb);
campaignModel = new CampaignModel(dbSettings, argv.campaignDb);
tabSequence = new TabSequence(argv.masterUrl);
serialExecutor = new SerialExecutor(argv.processId, jobModel,
campaignModel, tabSequence);
jobModel.once('ready', ready);
campaignModel.once('ready', ready);
};
let readyCnt = 0;
function ready() {
readyCnt += 1;
if(readyCnt !== 2) {
return;
}
execute();
}
function execute() {
async.series([
// require('./githubDispatcher').bind(null, args),
serialExecutor.loop.bind(serialExecutor)
], (error) => {
if(error) {
logger.error('execute', 'Failed to do loop', error);
throw error;
}
process.exit(0);
});
}
|
Add .git to git url | Package.describe({
git: 'https://github.com/zimme/meteor-collection-timestampable.git',
name: 'zimme:collection-timestampable',
summary: 'Add timestamps to collections',
version: '1.0.3'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use([
'coffeescript',
'underscore'
]);
api.use([
'matb33:collection-hooks@0.7.6',
'zimme:collection-behaviours@1.0.2'
]);
api.use([
'aldeed:autoform@4.0.0',
'aldeed:collection2@2.0.0',
'aldeed:simple-schema@1.0.3'
], ['client', 'server'], {weak: true});
api.imply('zimme:collection-behaviours');
api.addFiles('timestampable.coffee');
});
| Package.describe({
git: 'https://github.com/zimme/meteor-collection-timestampable',
name: 'zimme:collection-timestampable',
summary: 'Add timestamps to collections',
version: '1.0.3'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use([
'coffeescript',
'underscore'
]);
api.use([
'matb33:collection-hooks@0.7.6',
'zimme:collection-behaviours@1.0.2'
]);
api.use([
'aldeed:autoform@4.0.0',
'aldeed:collection2@2.0.0',
'aldeed:simple-schema@1.0.3'
], ['client', 'server'], {weak: true});
api.imply('zimme:collection-behaviours');
api.addFiles('timestampable.coffee');
});
|
Change the command: wonderful_bing -> bing.
Close #15 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from wonderful_bing import wonderful_bing
try:
import pypandoc
long_description = pypandoc.convert('README.md','rst')
except (IOError, ImportError):
with open('README.md') as f:
long_description = f.read()
setup(
name='wonderful_bing',
version=wonderful_bing.__version__,
description="A script download Bing's img and set as wallpaper",
long_description=long_description,
url='https://github.com/lord63/wonderful_bing',
author='lord63',
author_email='lord63.j@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: POSIX',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
keywords='bing wallpaper',
packages=['wonderful_bing'],
install_requires=['requests'],
include_package_data=True,
entry_points={
'console_scripts': [
'bing=wonderful_bing.wonderful_bing:main']
}
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from wonderful_bing import wonderful_bing
try:
import pypandoc
long_description = pypandoc.convert('README.md','rst')
except (IOError, ImportError):
with open('README.md') as f:
long_description = f.read()
setup(
name='wonderful_bing',
version=wonderful_bing.__version__,
description="A script download Bing's img and set as wallpaper",
long_description=long_description,
url='https://github.com/lord63/wonderful_bing',
author='lord63',
author_email='lord63.j@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: POSIX',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
keywords='bing wallpaper',
packages=['wonderful_bing'],
install_requires=['requests'],
include_package_data=True,
entry_points={
'console_scripts': [
'wonderful_bing=wonderful_bing.wonderful_bing:main']
}
)
|
Move to version 1.1.0 for Django 1.7 support. | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'django_atomic_signals',
]
requires = [
'Django>=1.6.0,<1.8',
]
tests_require = [
'flake8',
'django-nose',
'rednose',
]
setup(
name='django-atomic-signals',
version='1.1.0',
description='Signals for atomic transaction blocks in Django 1.6+',
author='Nick Bruun',
author_email='nick@bruun.co',
url='http://bruun.co/',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'django_atomic_signals': 'django_atomic_signals'},
include_package_data=True,
tests_require=tests_require,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
),
)
| #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'django_atomic_signals',
]
requires = [
'Django>=1.6.0,<1.8',
]
tests_require = [
'flake8',
'django-nose',
'rednose',
]
setup(
name='django-atomic-signals',
version='1.0.1',
description='Signals for atomic transaction blocks in Django 1.6+',
author='Nick Bruun',
author_email='nick@bruun.co',
url='http://bruun.co/',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'django_atomic_signals': 'django_atomic_signals'},
include_package_data=True,
tests_require=tests_require,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
),
)
|
Change admin columns for slots | """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
column_list=('day', 'rooms', 'kind', 'start', 'end'),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
| """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = model_view(
models.Day,
'Days',
CATEGORY,
column_default_sort='date',
column_list=('date', 'event'),
form_columns=('event', 'date'),
)
RoomModelView = model_view(
models.Room,
'Rooms',
CATEGORY,
column_default_sort='order',
form_columns=('name', 'order'),
)
SlotModelView = model_view(
models.Slot,
'Slots',
CATEGORY,
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
PresentationModelView = model_view(
models.Presentation,
'Presentations',
CATEGORY,
)
|
Split get_input from set_input in FormTestMixin.
In order to reduce side-effects, this commit moves the @wait_for to
a get_input method and set_input operates immediately. | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from selenium.webdriver.common.by import By
from .utils import wait_for
class FormTestMixin:
# default search element
form_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
(By.XPATH, '//form[@action="{}"]',),
(By.XPATH, '//form[@name="{}"]',),
(By.XPATH, '//form',),
)
@wait_for
def get_form(self, *args, **kwargs):
""" Return form element or None. """
return self.find_element(
self.form_search_list, *args, **kwargs)
input_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
)
@wait_for
def get_input(self, field, **kwargs):
""" Return matching input field. """
return self.find_element(
self.input_search_list, field, **kwargs)
def set_input(self, field, value, **kwargs):
""" Clear the field and enter value. """
element = self.get_input(field, **kwargs)
element.clear()
element.send_keys(value)
return element
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
from selenium.webdriver.common.by import By
from .utils import wait_for
class FormTestMixin:
# default search element
form_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
(By.XPATH, '//form[@action="{}"]',),
(By.XPATH, '//form[@name="{}"]',),
(By.XPATH, '//form/*',),
)
@wait_for
def get_form(self, *args, **kwargs):
""" Return form element or None. """
return self.find_element(
self.form_search_list, *args, **kwargs)
input_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
)
@wait_for
def set_input(self, field, value, **kwargs):
input = self.find_element(
self.input_search_list, field, **kwargs)
input.clear()
input.send_keys(value)
return input
|
Set default world for /ticks
Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com> | package me.nallar.tickthreading.minecraft.commands;
import java.util.List;
import me.nallar.tickthreading.minecraft.TickThreading;
import me.nallar.tickthreading.util.TableFormatter;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
public class TicksCommand extends Command {
public static String name = "ticks";
@Override
public String getCommandName() {
return name;
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender commandSender) {
return !TickThreading.instance.requireOpForTicksCommand || super.canCommandSenderUseCommand(commandSender);
}
@Override
public void processCommand(ICommandSender commandSender, List<String> arguments) {
World world = DimensionManager.getWorld(0);
try {
if (!arguments.isEmpty()) {
try {
world = DimensionManager.getWorld(Integer.valueOf(arguments.get(0)));
} catch (Exception ignored) {
}
} else if (commandSender instanceof Entity) {
world = ((Entity) commandSender).worldObj;
}
} catch (Exception e) {
sendChat(commandSender, "Usage: /ticks [dimensionid]");
return;
}
sendChat(commandSender, String.valueOf(TickThreading.instance.getManager(world).writeDetailedStats(new TableFormatter(commandSender))));
}
}
| package me.nallar.tickthreading.minecraft.commands;
import java.util.List;
import me.nallar.tickthreading.minecraft.TickThreading;
import me.nallar.tickthreading.util.TableFormatter;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
public class TicksCommand extends Command {
public static String name = "ticks";
@Override
public String getCommandName() {
return name;
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender commandSender) {
return !TickThreading.instance.requireOpForTicksCommand || super.canCommandSenderUseCommand(commandSender);
}
@Override
public void processCommand(ICommandSender commandSender, List<String> arguments) {
World world = null;
if (!arguments.isEmpty()) {
try {
world = DimensionManager.getWorld(Integer.valueOf(arguments.get(0)));
} catch (Exception ignored) {
}
} else if (commandSender instanceof Entity) {
world = ((Entity) commandSender).worldObj;
}
if (world == null) {
sendChat(commandSender, "Usage: /ticks [dimensionid]");
return;
}
sendChat(commandSender, String.valueOf(TickThreading.instance.getManager(world).writeDetailedStats(new TableFormatter(commandSender))));
}
}
|
Add a class to color-picker tag | export default ngModule => {
ngModule.config(addColorPickerType);
function addColorPickerType(formlyConfigProvider) {
var ngModelAttrs = {};
function camelize(string) {
string = string.replace(/[\-_\s]+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
// Ensure 1st char is always lowercase
return string.replace(/^([A-Z])/, function(match, chr) {
return chr ? chr.toLowerCase() : '';
});
}
ngModelAttrs = {};
// attributes
angular.forEach([
'color-picker-format',
'color-picker-alpha',
'color-picker-swatch',
'color-picker-swatch-pos',
'color-picker-swatch-only',
'color-picker-pos',
'color-picker-case'
], function(attr) {
ngModelAttrs[camelize(attr)] = {attribute: attr};
});
formlyConfigProvider.setType({
name: 'colorpicker',
template: '<color-picker class="cpStyles" ng-model="model[options.key]"></color-picker>',
wrapper: ['koappLabel', 'koappHasError'],
defaultOptions: {
ngModelAttrs: ngModelAttrs
}
});
}
};
| export default ngModule => {
ngModule.config(addColorPickerType);
function addColorPickerType(formlyConfigProvider) {
var ngModelAttrs = {};
function camelize(string) {
string = string.replace(/[\-_\s]+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
// Ensure 1st char is always lowercase
return string.replace(/^([A-Z])/, function(match, chr) {
return chr ? chr.toLowerCase() : '';
});
}
ngModelAttrs = {};
// attributes
angular.forEach([
'color-picker-format',
'color-picker-alpha',
'color-picker-swatch',
'color-picker-swatch-pos',
'color-picker-swatch-only',
'color-picker-pos',
'color-picker-case'
], function(attr) {
ngModelAttrs[camelize(attr)] = {attribute: attr};
});
formlyConfigProvider.setType({
name: 'colorpicker',
template: '<color-picker ng-model="model[options.key]"></color-picker>',
wrapper: ['koappLabel', 'koappHasError'],
defaultOptions: {
ngModelAttrs: ngModelAttrs
}
});
}
};
|
Fix to handle multiple path segments | # pipeurlbuilder.py
#
import urllib
from pipe2py import util
def pipe_urlbuilder(context, _INPUT, conf, **kwargs):
"""This source builds a url and yields it forever.
Keyword arguments:
context -- pipeline context
_INPUT -- not used
conf:
BASE -- base
PATH -- path elements
PARAM -- query parameters
Yields (_OUTPUT):
url
"""
for item in _INPUT:
#note: we could cache get_value results if item==True
url = util.get_value(conf['BASE'], item, **kwargs)
if not url.endswith('/'):
url += '/'
path = conf['PATH']
if not isinstance(path, list):
path = [path]
path = [util.get_value(p, item, **kwargs) for p in path]
url += "/".join(path)
url = url.rstrip("/")
params = dict([(util.get_value(p['key'], item, **kwargs), util.get_value(p['value'], item, **kwargs)) for p in conf['PARAM']])
if params:
url += "?" + urllib.urlencode(params)
yield url
| # pipeurlbuilder.py
#
import urllib
from pipe2py import util
def pipe_urlbuilder(context, _INPUT, conf, **kwargs):
"""This source builds a url and yields it forever.
Keyword arguments:
context -- pipeline context
_INPUT -- not used
conf:
BASE -- base
PATH -- path elements
PARAM -- query parameters
Yields (_OUTPUT):
url
"""
for item in _INPUT:
#note: we could cache get_value results if item==True
url = util.get_value(conf['BASE'], item, **kwargs)
if not url.endswith('/'):
url += '/'
path = util.get_value(conf['PATH'], item, **kwargs)
if not isinstance(path, list):
path = [path]
url += "/".join(path)
url = url.rstrip("/")
params = dict([(util.get_value(p['key'], item, **kwargs), util.get_value(p['value'], item, **kwargs)) for p in conf['PARAM']])
if params:
url += "?" + urllib.urlencode(params)
yield url
|
Implement UpperCamelCase name check for structs | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase')
def enterEnumCaseName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase')
def enterStructName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Struct names should be in UpperCamelCase')
@staticmethod
def __verify_upper_camel_case(ctx, err_msg):
construct_name = ctx.getText()
if not isUpperCamelCase(construct_name):
print('Line', str(ctx.start.line) + ':', err_msg)
| from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase')
def enterEnumCaseName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase')
def enterStructName(self, ctx):
pass
@staticmethod
def __verify_upper_camel_case(ctx, err_msg):
construct_name = ctx.getText()
if not isUpperCamelCase(construct_name):
print('Line', str(ctx.start.line) + ':', err_msg)
|
Use more modern JS; Add pagination to SE API calls | function getPosts(user, site, page, cb) {
const accessToken = $('#accessToken').val();
const filter = '!0S2A5ipm(pczxWJLGNzYzyy4l';
const key = 'c8aSGAR0rp5RUK)dVriyCA((';
$.getJSON(`https://api.stackexchange.com/2.2/users/${user}/posts?filter=${filter}&key=${key}&access_token=${accessToken}&site=${site}&page=${page}&pagesize=100`, j => {
for (let x = 0; x < j.items.length; x++) {
$('#posts').append(j.items[x].score + ' - <a href="' + j.items[x].link + '">' + j.items[x].title + '</a><br>');
}
if (j.has_more) getPosts(user, site, page + 1, () => console.log('Fetched more posts'));
else return cb();
});
}
$('#go').click(() => {
const accounts = {};
const networkId = $('#networkId').val();
$.getJSON(`http://api.stackexchange.com/2.2/users/${networkId}/associated`, j => {
for (let i = 0; i < j.items.length; i++) {
accounts[j.items[i]['site_url']] = j.items[i]['user_id'];
}
$.each(accounts, (k, v) => {
const site = k.replace(/http.?:\/\//, '');
getPosts(v, site, 1, () => console.log('Fetched all posts'));
});
});
});
| const accounts = {};
$('#go').click(function () {
const networkId = $('#networkId').val();
const accessToken = $('#accessToken').val();
const filter = '!0S2A5ipm(pczxWJLGNzYzyy4l';
const key = 'c8aSGAR0rp5RUK)dVriyCA((';
$.getJSON(`http://api.stackexchange.com/2.2/users/${networkId}/associated`, function (j) {
for (let i = 0; i < j.items.length; i++) {
accounts[j.items[i]['site_url']] = j.items[i]['user_id'];
}
$.each(accounts, function (k, v) {
const site = k.replace(/http.?:\/\//, '');
$.getJSON(`https://api.stackexchange.com/2.2/users/${v}/posts?filter=${filter}&key=${key}&access_token=${accessToken}&site=${site}`, function (j2) {
for (let x = 0; x < j2.items.length; x++) {
$('#posts').append(j2.items[x]['score'] + ' - <a href="' + j2.items[x]['link'] + '">' + j2.items[x]['title'] + '</a><br>');
}
});
});
});
});
|
Update to WADO Image Loader 2.1.3 | Package.describe({
name: 'ohif:cornerstone',
summary: 'Cornerstone Web-based Medical Imaging libraries',
version: '0.0.1'
});
Npm.depends({
hammerjs: '2.0.8',
'cornerstone-core': '2.2.4',
'cornerstone-tools': '2.3.3',
'cornerstone-math': '0.1.6',
'dicom-parser': '1.8.0',
'cornerstone-wado-image-loader': '2.1.3'
});
Package.onUse(function(api) {
api.versionsFrom('1.5');
api.use('ecmascript');
api.addAssets('public/js/cornerstoneWADOImageLoaderCodecs.es5.js', 'client');
api.addAssets('public/js/cornerstoneWADOImageLoaderWebWorker.es5.js', 'client');
api.addAssets('public/js/cornerstoneWADOImageLoaderWebWorker.min.js.map', 'client');
api.mainModule('main.js', 'client');
api.export('cornerstone', 'client');
api.export('cornerstoneMath', 'client');
api.export('cornerstoneTools', 'client');
api.export('cornerstoneWADOImageLoader', 'client');
api.export('dicomParser', 'client');
});
| Package.describe({
name: 'ohif:cornerstone',
summary: 'Cornerstone Web-based Medical Imaging libraries',
version: '0.0.1'
});
Npm.depends({
hammerjs: '2.0.8',
'cornerstone-core': '2.2.4',
'cornerstone-tools': '2.3.3',
'cornerstone-math': '0.1.6',
'dicom-parser': '1.8.0',
'cornerstone-wado-image-loader': '2.1.2'
});
Package.onUse(function(api) {
api.versionsFrom('1.5');
api.use('ecmascript');
api.addAssets('public/js/cornerstoneWADOImageLoaderCodecs.es5.js', 'client');
api.addAssets('public/js/cornerstoneWADOImageLoaderWebWorker.es5.js', 'client');
api.addAssets('public/js/cornerstoneWADOImageLoaderWebWorker.min.js.map', 'client');
api.mainModule('main.js', 'client');
api.export('cornerstone', 'client');
api.export('cornerstoneMath', 'client');
api.export('cornerstoneTools', 'client');
api.export('cornerstoneWADOImageLoader', 'client');
api.export('dicomParser', 'client');
});
|
Update the USER command to take advantage of core capabilities as well | from twisted.words.protocols import irc
from txircd.modbase import Command
class UserCommand(Command):
def onUse(self, user, data):
if not user.username:
user.registered -= 1
user.username = data["ident"]
user.realname = data["gecos"]
if user.registered == 0:
user.register()
def processParams(self, user, params):
if user.registered == 0:
user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)")
return {}
if params and len(params) < 4:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters")
return {}
ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12]
if not ident:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid")
return {}
return {
"user": user,
"ident": ident,
"gecos": params[3]
}
def Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn():
return {
"commands": {
"USER": UserCommand()
}
}
def cleanup():
del self.ircd.commands["USER"] | from twisted.words.protocols import irc
from txircd.modbase import Command
class UserCommand(Command):
def onUse(self, user, params):
if user.registered == 0:
self.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)")
return
if params and len(params) < 4:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters")
if not user.username:
user.registered -= 1
user.username = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12]
if not user.username:
user.registered += 1
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid")
return
user.realname = params[3]
if user.registered == 0:
user.register()
def Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn():
return {
"commands": {
"USER": UserCommand()
}
}
def cleanup():
del self.ircd.commands["USER"] |
Make import dispatcher return one ID | /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.aggregate.imports;
import io.spine.core.EventClass;
import io.spine.server.bus.MessageDispatcher;
/**
* Dispatches imported events to aggregates.
*
* @param <I> the type of aggregate IDs
* @author Alexander Yevsyukov
*/
interface ImportDispatcher<I> extends MessageDispatcher<EventClass, ImportEnvelope, I> {
}
| /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.aggregate.imports;
import io.spine.core.EventClass;
import io.spine.server.bus.MessageDispatcher;
import java.util.Set;
/**
* Dispatches imported events to aggregates.
*
* @param <I> the type of aggregate IDs
* @author Alexander Yevsyukov
*/
interface ImportDispatcher<I> extends MessageDispatcher<EventClass, ImportEnvelope, Set<I>> {
}
|
Add reloadWithReason to Fast Refresh
Summary: This diff adds reload reasons to Fast Refresh. This will help us understand why, for internal Facebook users, Fast Refresh is bailing out to a full reload so that we can improve it for everyone.
Reviewed By: cpojer
Differential Revision: D17499348
fbshipit-source-id: b6e73dc3f396c8531a0872f5572a13928450bb3b | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
if (__DEV__) {
const DevSettings = require('../Utilities/DevSettings');
if (typeof DevSettings.reload !== 'function') {
throw new Error('Could not find the reload() implementation.');
}
// This needs to run before the renderer initializes.
const ReactRefreshRuntime = require('react-refresh/runtime');
ReactRefreshRuntime.injectIntoGlobalHook(global);
const Refresh = {
performFullRefresh(reason: string) {
DevSettings.reload(reason);
},
createSignatureFunctionForTransform:
ReactRefreshRuntime.createSignatureFunctionForTransform,
isLikelyComponentType: ReactRefreshRuntime.isLikelyComponentType,
getFamilyByType: ReactRefreshRuntime.getFamilyByType,
register: ReactRefreshRuntime.register,
performReactRefresh() {
if (ReactRefreshRuntime.hasUnrecoverableErrors()) {
DevSettings.reload('Fast Refresh - Unrecoverable');
return;
}
ReactRefreshRuntime.performReactRefresh();
},
};
(require: any).Refresh = Refresh;
}
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
if (__DEV__) {
const NativeDevSettings = require('../NativeModules/specs/NativeDevSettings')
.default;
if (typeof NativeDevSettings.reload !== 'function') {
throw new Error('Could not find the reload() implementation.');
}
// This needs to run before the renderer initializes.
const ReactRefreshRuntime = require('react-refresh/runtime');
ReactRefreshRuntime.injectIntoGlobalHook(global);
const Refresh = {
performFullRefresh() {
NativeDevSettings.reload();
},
createSignatureFunctionForTransform:
ReactRefreshRuntime.createSignatureFunctionForTransform,
isLikelyComponentType: ReactRefreshRuntime.isLikelyComponentType,
getFamilyByType: ReactRefreshRuntime.getFamilyByType,
register: ReactRefreshRuntime.register,
performReactRefresh() {
if (ReactRefreshRuntime.hasUnrecoverableErrors()) {
NativeDevSettings.reload();
return;
}
ReactRefreshRuntime.performReactRefresh();
},
};
(require: any).Refresh = Refresh;
}
|
Update requests requirement from <2.24,>=2.4.2 to >=2.4.2,<2.25
Updates the requirements on [requests](https://github.com/psf/requests) to permit the latest version.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.4.2...v2.24.0)
Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com> | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.25',
'future>=0.16,<0.19',
'python-magic>=0.4,<0.5',
'redo>=1.7',
'six>=1.9',
],
extras_require={
'testing': [
'mock>=2.0,<4.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
| from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.24',
'future>=0.16,<0.19',
'python-magic>=0.4,<0.5',
'redo>=1.7',
'six>=1.9',
],
extras_require={
'testing': [
'mock>=2.0,<4.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
Fix Undertow static handler package name, as it was renamed | package org.wildfly.swarm.undertow;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Node;
/**
* @author Bob McWhirter
*/
public interface StaticContentContainer<T extends Archive<T>> extends Archive<T> {
default T staticContent() {
return staticContent( "/", "." );
}
default T staticContent(String context) {
return staticContent( context, "." );
}
default T staticContent(String context, String base) {
as(WARArchive.class).addModule("org.wildfly.swarm.undertow", "runtime");
as(WARArchive.class).addAsServiceProvider("io.undertow.server.handlers.builder.HandlerBuilder", "org.wildfly.swarm.undertow.runtime.StaticHandlerBuilder");
Node node = as(WARArchive.class).get("WEB-INF/undertow-handlers.conf");
UndertowHandlersAsset asset = null;
if ( node == null ) {
asset = new UndertowHandlersAsset();
as(WARArchive.class).add( asset, "WEB-INF/undertow-handlers.conf" );
} else {
asset = (UndertowHandlersAsset) node.getAsset();
}
asset.staticContent( context, base );
return (T) this;
}
}
| package org.wildfly.swarm.undertow;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Node;
/**
* @author Bob McWhirter
*/
public interface StaticContentContainer<T extends Archive<T>> extends Archive<T> {
default T staticContent() {
return staticContent( "/", "." );
}
default T staticContent(String context) {
return staticContent( context, "." );
}
default T staticContent(String context, String base) {
as(WARArchive.class).addModule("org.wildfly.swarm.undertow", "runtime");
as(WARArchive.class).addAsServiceProvider("io.undertow.server.handlers.builder.HandlerBuilder", "org.wildfly.swarm.runtime.undertow.StaticHandlerBuilder");
Node node = as(WARArchive.class).get("WEB-INF/undertow-handlers.conf");
UndertowHandlersAsset asset = null;
if ( node == null ) {
asset = new UndertowHandlersAsset();
as(WARArchive.class).add( asset, "WEB-INF/undertow-handlers.conf" );
} else {
asset = (UndertowHandlersAsset) node.getAsset();
}
asset.staticContent( context, base );
return (T) this;
}
}
|
Update test: Simplify, compact formatting | var ACME = require( '..' )
var assert = require( 'assert' )
var nock = require( 'nock' )
suite( 'ACME', function() {
var client = new ACME({
baseUrl: 'https://api.example.com',
})
test( 'throws an error if baseUrl is not a string', function() {
assert.throws( function() { new ACME({ baseUrl: 42 }) })
assert.throws( function() { new ACME({ baseUrl: {} }) })
})
test( '#getDirectory()', function( next ) {
var payload = {
'new-authz': 'https://api.example.com/acme/new-authz',
'new-cert': 'https://api.example.com/acme/new-cert',
'new-reg': 'https://api.example.com/acme/new-reg',
'revoke-cert': 'https://api.example.com/acme/revoke-cert'
}
nock( 'https://api.example.com' )
.get( '/directory' )
.reply( 200, payload )
client.getDirectory( function( error, data ) {
assert.ifError( error )
assert.ok( data )
assert.deepStrictEqual( payload, data )
next()
})
})
})
| var ACME = require( '..' )
var assert = require( 'assert' )
var nock = require( 'nock' )
suite( 'ACME', function() {
var acme = new ACME({
baseUrl: 'https://mock_encrypt.example.com',
})
test( 'throws an error if baseUrl is not a string', function() {
assert.throws( function() {
new ACME({ baseUrl: 42 })
})
assert.throws( function() {
new ACME({ baseUrl: {} })
})
})
test( '#getDirectory()', function( next ) {
var payload = {
'new-authz': 'https://mock_encrypt.example.com/acme/new-authz',
'new-cert': 'https://mock_encrypt.example.com/acme/new-cert',
'new-reg': 'https://mock_encrypt.example.com/acme/new-reg',
'revoke-cert': 'https://mock_encrypt.example.com/acme/revoke-cert'
}
nock( 'https://mock_encrypt.example.com' )
.get( '/directory' )
.reply( 200, payload )
acme.getDirectory( function( error, data ) {
assert.ifError( error )
assert.ok( data )
assert.deepStrictEqual( payload, data )
next()
})
})
})
|
klientctl: Break from loop if requirement is found | package main
// +build linux darwin
import (
"errors"
"github.com/koding/klient/cmd/klientctl/util"
)
// AdminRequired parses through an arg list and requires an admin (sudo)
// for the specified commands.
//
// Note that if the command is required, *and* we failed to get admin
// permission information, let the user run the command anyway.
// Better UX than failing for a possible non-issue.
func AdminRequired(args, reqs []string, p *util.Permissions) error {
// Ignore the permErr in the beginning. If the arg command
isAdmin, permErr := p.IsAdmin()
// If the user is admin, any admin requiring command is already
// satisfied.
if isAdmin {
return nil
}
// At the moment, we're only checking the first level of commands.
// Subcommands are ignored.
if len(args) < 2 {
return nil
}
c := args[1]
var err error
for _, r := range reqs {
if c == r {
// Use sudo terminology, for unix
err = errors.New("Command requires sudo")
break
}
}
// If the command is required, *and* we failed to get admin permission
// information, let the user run the command anyway. Better UX than
// failing for a possible non-issue.
if err != nil && permErr != nil {
return nil
}
return err
}
| package main
// +build linux darwin
import (
"errors"
"github.com/koding/klient/cmd/klientctl/util"
)
// AdminRequired parses through an arg list and requires an admin (sudo)
// for the specified commands.
//
// Note that if the command is required, *and* we failed to get admin
// permission information, let the user run the command anyway.
// Better UX than failing for a possible non-issue.
func AdminRequired(args, reqs []string, p *util.Permissions) error {
// Ignore the permErr in the beginning. If the arg command
isAdmin, permErr := p.IsAdmin()
// If the user is admin, any admin requiring command is already
// satisfied.
if isAdmin {
return nil
}
// At the moment, we're only checking the first level of commands.
// Subcommands are ignored.
if len(args) < 2 {
return nil
}
c := args[1]
var err error
for _, r := range reqs {
if c == r {
// Use sudo terminology, for unix
err = errors.New("Command requires sudo")
}
}
// If the command is required, *and* we failed to get admin permission
// information, let the user run the command anyway. Better UX than
// failing for a possible non-issue.
if err != nil && permErr != nil {
return nil
}
return err
}
|
Send JWT token in HTTP requests only when available. | module.exports = (function() {
var Router = require('router'),
Connection = require('lib/connection');
// App namespace.
window.Boards = {
Models: {},
Collections: {}
};
// Load helpers.
require('lib/helpers');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
var token = _.getModel('User').get('token');
if (token) xhr.setRequestHeader('Authorization', 'JWT ' + token);
}
});
// Register Swag Helpers.
Swag.registerHelpers();
// Initialize Router.
Boards.Router = new Router();
// Create a Connection object to communicate with the server through web sockets.
// The `connection` object will be added to the `Application` object so it's available through
// `window.Application.connection`.
Boards.Connection = new Connection({
type: APPLICATION_CONNECTION,
httpUrl: APPLICATION_HTTP_URL,
socketUrl: APPLICATION_WEBSOCKET_URL
});
// Connect to the server.
Boards.Connection.create().done(function() {
Boards.Router.start();
}).fail(function() {
console.log('Connection Error', arguments);
});
})();
| module.exports = (function() {
var Router = require('router'),
Connection = require('lib/connection');
// App namespace.
window.Boards = {
Models: {},
Collections: {}
};
// Load helpers.
require('lib/helpers');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'JWT ' + _.getModel('User').get('token'));
}
});
// Register Swag Helpers.
Swag.registerHelpers();
// Initialize Router.
Boards.Router = new Router();
// Create a Connection object to communicate with the server through web sockets.
// The `connection` object will be added to the `Application` object so it's available through
// `window.Application.connection`.
Boards.Connection = new Connection({
type: APPLICATION_CONNECTION,
httpUrl: APPLICATION_HTTP_URL,
socketUrl: APPLICATION_WEBSOCKET_URL
});
// Connect to the server.
Boards.Connection.create().done(function() {
Boards.Router.start();
}).fail(function() {
console.log('Connection Error', arguments);
});
})();
|
Append submit button to form | document.getElementById("ayuda").setAttribute("aria-current", "page");
var aside = document.getElementById("complementario");
var form = document.createElement("FORM");
var p = document.createElement("P");
var label = document.createElement("LABEL");
label.setAttribute("for", "repo");
t = document.createTextNode("cuenta/repositorio de GitHub");
label.appendChild(t);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.setAttribute("id", "repo");
input.setAttribute("name", "repo");
var submit = document.createElement("INPUT");
submit.setAttribute("type", "submit");
submit.setAttribute("id", "submit");
p.appendChild(label);
form.appendChild(p);
form.appendChild(submit);
aside.appendChild(form);
/*
$(document).ready(function () {
$"#complementario").append(form);
$("#submit").click(function () {
$.getJSON("https://api.github.com/repos/" + $("#repo").val() + "/releases/latest", function(json) {
var name = json.name);
var p = document.createElement("P");
var t = document.createTextNode(name);
p.appendChild(t);
$("#complementario").append(p);
});
});
});
*/ | document.getElementById("ayuda").setAttribute("aria-current", "page");
var aside = document.getElementById("complementario");
var form = document.createElement("FORM");
var p = document.createElement("P");
var label = document.createElement("LABEL");
label.setAttribute("for", "repo");
t = document.createTextNode("cuenta/repositorio de GitHub");
label.appendChild(t);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.setAttribute("id", "repo");
input.setAttribute("name", "repo");
var submit = document.createElement("INPUT");
submit.setAttribute("type", "submit");
submit.setAttribute("id", "submit");
p.appendChild(label);
form.appendChild(p);
//form.appendChild(submit);
aside.appendChild(form);
/*
$(document).ready(function () {
$"#complementario").append(form);
$("#submit").click(function () {
$.getJSON("https://api.github.com/repos/" + $("#repo").val() + "/releases/latest", function(json) {
var name = json.name);
var p = document.createElement("P");
var t = document.createTextNode(name);
p.appendChild(t);
$("#complementario").append(p);
});
});
});
*/ |
Add link to link to each page | import _ from 'lodash';
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPosts } from '../actions';
class PostsIndex extends React.Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, (post) => {
return (
<li className="list-group-item" key={post.id}>
<Link to={`/posts/${post.id}`}>
{post.title}
</Link>
</li>
);
});
}
render() {
return (
<div className='posts-index'>
<div className='text-xs-right'>
<Link className='btn btn-primary' to='/posts/new'>
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{ this.renderPosts() }
</ul>
</div>
)
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts: fetchPosts })(PostsIndex);
| import _ from 'lodash';
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPosts } from '../actions';
class PostsIndex extends React.Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, (post) => {
return (
<li className="list-group-item" key={post.id}>
{post.title}
</li>
);
});
}
render() {
return (
<div className='posts-index'>
<div className='text-xs-right'>
<Link className='btn btn-primary' to='/posts/new'>
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{ this.renderPosts() }
</ul>
</div>
)
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts: fetchPosts })(PostsIndex);
|
Simplify the book class even more. | package ryhma57.references;
import java.util.EnumSet;
import ryhma57.backend.BibtexReferenceField;
import static ryhma57.backend.BibtexReferenceField.*;
public class Book extends Reference {
private static EnumSet<BibtexReferenceField> existingFields;
private static EnumSet<BibtexReferenceField> requiredFields, optionalFields;
static {
Book.requiredFields = Reference.createFieldSet(AUTHOR,
TITLE, YEAR, PUBLISHER);
Book.optionalFields = Reference.createFieldSet(VOLUME,
NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE);
Book.existingFields = Reference.createExistingSet(
Book.requiredFields, Book.optionalFields);
}
public Book(String id, String author, String title, String year, String publisher) {
super(existingFields, requiredFields, "book");
setID(id);
setField(AUTHOR, author);
setField(TITLE, title);
setField(YEAR, year);
setField(PUBLISHER, publisher);
}
public Book() {
super(existingFields, requiredFields, "book");
}
}
| package ryhma57.references;
import java.util.EnumSet;
import ryhma57.backend.BibtexReferenceField;
import static ryhma57.backend.BibtexReferenceField.*;
public class Book extends Reference {
private static EnumSet<BibtexReferenceField> existingFields;
private static EnumSet<BibtexReferenceField> requiredFields;
static {
EnumSet<BibtexReferenceField> optionals;
Book.requiredFields = Reference.createFieldSet(AUTHOR,
TITLE, YEAR, PUBLISHER);
optionals = Reference.createFieldSet(VOLUME,
NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE);
Book.existingFields = Reference.createExistingSet(
Book.requiredFields, optionals);
}
public Book(String id, String author, String title, String year, String publisher) {
super(existingFields, requiredFields, "book");
setID(id);
setField(AUTHOR, author);
setField(TITLE, title);
setField(YEAR, year);
setField(PUBLISHER, publisher);
}
}
|
Remove trailing comma syntax error | ManageIQ.angular.app.component('verifyButton', {
bindings: {
validate: '<',
enabled: '<',
validateUrl: '@',
restful: '<',
valtype: '<',
buttonLabels: '<',
},
controllerAs: 'vm',
controller: ['$scope', function($scope) {
$scope.__ = __;
var vm = this;
vm.findScope = function() {
var parentScope = $scope;
while (! parentScope.angularForm) {
parentScope = parentScope.$parent;
}
return parentScope.angularForm;
};
vm.chooseValidation = function() {
if (vm.restful) {
vm.validate(
{target: '.validate_button:visible'},
vm.valtype,
true,
vm.findScope,
vm.validateUrl
);
} else {
vm.validate(vm.validateUrl);
}
};
}],
templateUrl: '/static/verify-button.html.haml',
});
| ManageIQ.angular.app.component('verifyButton', {
bindings: {
validate: '<',
enabled: '<',
validateUrl: '@',
restful: '<',
valtype: '<',
buttonLabels: '<',
},
controllerAs: 'vm',
controller: ['$scope', function($scope) {
$scope.__ = __;
var vm = this;
vm.findScope = function() {
var parentScope = $scope;
while (! parentScope.angularForm) {
parentScope = parentScope.$parent;
}
return parentScope.angularForm;
};
vm.chooseValidation = function() {
if (vm.restful) {
vm.validate(
{target: '.validate_button:visible'},
vm.valtype,
true,
vm.findScope,
vm.validateUrl,
);
} else {
vm.validate(vm.validateUrl);
}
};
}],
templateUrl: '/static/verify-button.html.haml',
});
|
Edit spreadsheet is now fixed. | import urllib.request
from io import BytesIO
import pandas as pd
import ujson
from elasticsearch import Elasticsearch
csv = urllib.request.urlopen("https://docs.google.com/spreadsheet/pub?key=1h1udf_H073YaVlZs0fkYUf9dC6KbEZAhF1veeLExyXo&gid=937170620&output=csv").read()
bio = BytesIO(csv)
csv_pd = pd.DataFrame.from_csv(bio)
json_objs = csv_pd.reset_index().to_json(orient='records')
dict_array= ujson.loads(json_objs)
# Edit to point to elasticsearch instance
es = Elasticsearch('ec2-52-10-17-100.us-west-2.compute.amazonaws.com:9200')
# ignore 404 and 400
es.indices.delete(index='datasets_index', ignore=[400, 404])
for d in dict_array:
print(d)
res = es.index(index="datasets_index", doc_type="dataset", body=d)
print(res['created'])
| import urllib.request
from io import BytesIO
import pandas as pd
import ujson
from elasticsearch import Elasticsearch
csv = urllib.request.urlopen("https://docs.google.com/spreadsheet/pub?key=0Ahf71UaPpMOSdGl0NnQtSFgyVFpvSmV3R2JobzVmZHc&output=csv").read()
bio = BytesIO(csv)
csv_pd = pd.DataFrame.from_csv(bio)
json_objs = csv_pd.reset_index().to_json(orient='records')
dict_array= ujson.loads(json_objs)
# Edit to point to elasticsearch instance
es = Elasticsearch('ec2-52-10-17-100.us-west-2.compute.amazonaws.com:9200')
# ignore 404 and 400
es.indices.delete(index='datasets_index', ignore=[400, 404])
for d in dict_array:
res = es.index(index="datasets_index", doc_type="dataset", body=d)
print(res['created'])
|
Add throws to avoid interface clash | package de.danoeh.antennapod.core.util.playback;
import android.content.Context;
import android.view.SurfaceHolder;
import java.io.IOException;
public interface IPlayer {
boolean canSetPitch();
boolean canSetSpeed();
boolean canDownmix();
float getCurrentPitchStepsAdjustment();
int getCurrentPosition();
float getCurrentSpeedMultiplier();
int getDuration();
float getMaxSpeedMultiplier();
float getMinSpeedMultiplier();
boolean isLooping();
boolean isPlaying();
void pause();
void prepare() throws IllegalStateException, IOException;
void prepareAsync();
void release();
void reset();
void seekTo(int msec);
void setAudioStreamType(int streamtype);
void setScreenOnWhilePlaying(boolean screenOn);
void setDataSource(String path) throws IllegalStateException, IOException,
IllegalArgumentException, SecurityException;
void setDisplay(SurfaceHolder sh);
void setEnableSpeedAdjustment(boolean enableSpeedAdjustment);
void setLooping(boolean looping);
void setPitchStepsAdjustment(float pitchSteps);
void setPlaybackPitch(float f);
void setPlaybackSpeed(float f);
void setDownmix(boolean enable);
void setVolume(float left, float right);
void start();
void stop();
void setVideoScalingMode(int mode);
void setWakeMode(Context context, int mode);
}
| package de.danoeh.antennapod.core.util.playback;
import android.content.Context;
import android.view.SurfaceHolder;
import java.io.IOException;
public interface IPlayer {
boolean canSetPitch();
boolean canSetSpeed();
boolean canDownmix();
float getCurrentPitchStepsAdjustment();
int getCurrentPosition();
float getCurrentSpeedMultiplier();
int getDuration();
float getMaxSpeedMultiplier();
float getMinSpeedMultiplier();
boolean isLooping();
boolean isPlaying();
void pause();
void prepare() throws IllegalStateException;
void prepareAsync();
void release();
void reset();
void seekTo(int msec);
void setAudioStreamType(int streamtype);
void setScreenOnWhilePlaying(boolean screenOn);
void setDataSource(String path) throws IllegalStateException,
IllegalArgumentException, SecurityException;
void setDisplay(SurfaceHolder sh);
void setEnableSpeedAdjustment(boolean enableSpeedAdjustment);
void setLooping(boolean looping);
void setPitchStepsAdjustment(float pitchSteps);
void setPlaybackPitch(float f);
void setPlaybackSpeed(float f);
void setDownmix(boolean enable);
void setVolume(float left, float right);
void start();
void stop();
void setVideoScalingMode(int mode);
void setWakeMode(Context context, int mode);
}
|
Fix copy paste typo caused by cloud to butt | # encoding: utf-8
import hashlib
from website import settings
DOMAIN = settings.DOMAIN
UPLOAD_SERVICE_URLS = ['changeme']
PING_TIMEOUT = 5 * 60
SIGNED_REQUEST_KWARGS = {}
# HMAC options
SIGNATURE_HEADER_KEY = 'X-Signature'
URLS_HMAC_SECRET = 'changeme'
URLS_HMAC_DIGEST = hashlib.sha1
WEBHOOK_HMAC_SECRET = 'changeme'
WEBHOOK_HMAC_DIGEST = hashlib.sha1
REVISIONS_PAGE_SIZE = 10
# IDENTITY = {
# 'provider': 's3',
# 'access_key': '',
# 'secret_key': ''
# }
WATERBUTLER_CREDENTIALS = {
'username': 'changeme',
'token': 'changeme',
'region': 'changeme'
}
WATERBUTLER_SETTINGS = {
'provider': 'cloudfiles',
'container': 'changeme',
}
WATERBUTLER_RESOURCE = 'container'
| # encoding: utf-8
import hashlib
from website import settings
DOMAIN = settings.DOMAIN
UPLOAD_SERVICE_URLS = ['changeme']
PING_TIMEOUT = 5 * 60
SIGNED_REQUEST_KWARGS = {}
# HMAC options
SIGNATURE_HEADER_KEY = 'X-Signature'
URLS_HMAC_SECRET = 'changeme'
URLS_HMAC_DIGEST = hashlib.sha1
WEBHOOK_HMAC_SECRET = 'changeme'
WEBHOOK_HMAC_DIGEST = hashlib.sha1
REVISIONS_PAGE_SIZE = 10
# IDENTITY = {
# 'provider': 's3',
# 'access_key': '',
# 'secret_key': ''
# }
WATERBUTLER_CREDENTIALS = {
'username': 'changeme',
'token': 'changeme',
'region': 'changeme'
}
WATERBUTLER_SETTINGS = {
'provider': 'buttfiles',
'container': 'changeme',
}
WATERBUTLER_RESOURCE = 'container'
|
Upgrade to Beats v5.0.0-beta1
- Added comments | package config
import (
"github.com/elastic/beats/libbeat/outputs"
"time"
)
// Defaults for config variables which are not set
const (
DefaultCron string = "@every 1m"
DefaultTimeout time.Duration = 60 * time.Second
DefaultDocumentType string = "httpbeat"
)
/*
Configuration for Httpbeat
*/
type HttpbeatConfig struct {
Urls []UrlConfig
}
/*
Configuration for single URL
*/
type UrlConfig struct {
Cron string
Url string
BasicAuth BasicAuthenticationConfig `config:"basic_auth"`
Method string
Body string
Headers map[string]string
ProxyUrl string `config:"proxy_url"`
Timeout *int64
DocumentType string `config:"document_type"`
Fields map[string]string `config:"fields"`
SSL *outputs.TLSConfig
JsonDotMode string `config:"json_dot_mode"`
}
/*
Configuration for Basic authentication
*/
type BasicAuthenticationConfig struct {
Username string
Password string
}
type ConfigSettings struct {
Httpbeat HttpbeatConfig
}
| package config
import (
"github.com/elastic/beats/libbeat/outputs"
"time"
)
// Defaults for config variables which are not set
const (
DefaultCron string = "@every 1m"
DefaultTimeout time.Duration = 60 * time.Second
DefaultDocumentType string = "httpbeat"
)
type HttpbeatConfig struct {
Urls []UrlConfig
}
type UrlConfig struct {
Cron string
Url string
BasicAuth BasicAuthenticationConfig `config:"basic_auth"`
Method string
Body string
Headers map[string]string
ProxyUrl string `config:"proxy_url"`
Timeout *int64
DocumentType string `config:"document_type"`
Fields map[string]string `config:"fields"`
SSL *outputs.TLSConfig
JsonDotMode string `config:"json_dot_mode"`
}
type BasicAuthenticationConfig struct {
Username string
Password string
}
type ConfigSettings struct {
Httpbeat HttpbeatConfig
}
|
III-893: Fix kansentarif class name casing | <?php
namespace CultuurNet\UDB3\EventExport\Format\HTML\Uitpas\DistributionKey;
use CultureFeed_Uitpas_DistributionKey;
class KansentariefForOtherCardSystemsSpecification implements DistributionKeySpecification
{
public function isSatisfiedBy(
CultureFeed_Uitpas_DistributionKey $distributionKey
) {
$satisfied = false;
foreach ($distributionKey->conditions as $condition) {
if ($condition->definition == $condition::DEFINITION_KANSARM &&
$condition->value == $condition::VALUE_AT_LEAST_ONE_CARDSYSTEM
) {
$satisfied = true;
break;
}
}
return $satisfied;
}
}
| <?php
/**
* @file
*/
namespace CultuurNet\UDB3\EventExport\Format\HTML\Uitpas\DistributionKey;
use CultureFeed_Uitpas_DistributionKey;
class KansenTariefForOtherCardSystemsSpecification implements DistributionKeySpecification
{
public function isSatisfiedBy(
CultureFeed_Uitpas_DistributionKey $distributionKey
) {
$satisfied = false;
foreach ($distributionKey->conditions as $condition) {
if ($condition->definition == $condition::DEFINITION_KANSARM &&
$condition->value == $condition::VALUE_AT_LEAST_ONE_CARDSYSTEM
) {
$satisfied = true;
break;
}
}
return $satisfied;
}
}
|
Allow for override of freemium | <?php
namespace OhMyBrew\ShopifyApp\Observers;
use OhMyBrew\ShopifyApp\Models\Shop;
class ShopObserver
{
/**
* Listen to the shop creating event.
*
* @param Shop $shop
*
* @return void
*/
public function creating(Shop $shop)
{
if (!isset($shop->namespace)) {
// Automatically add the current namespace to new records
$shop->namespace = config('shopify-app.namespace');
}
if (config('shopify-app.billing_freemium_enabled') === true && !isset($shop->freemium)) {
// Add the freemium flag to the shop
$shop->freemium = true;
}
}
}
| <?php
namespace OhMyBrew\ShopifyApp\Observers;
use OhMyBrew\ShopifyApp\Models\Shop;
class ShopObserver
{
/**
* Listen to the shop creating event.
*
* @param Shop $shop
*
* @return void
*/
public function creating(Shop $shop)
{
if (!isset($shop->namespace)) {
// Automatically add the current namespace to new records
$shop->namespace = config('shopify-app.namespace');
}
if (config('shopify-app.billing_freemium_enabled') === true) {
// Add the freemium flag to the shop
$shop->freemium = true;
}
}
}
|
Add the description in the PyPI package | #!/usr/bin/env python
import sys
from setuptools import setup, find_packages
import kamboo
requires = ['boto3']
if sys.version_info[:2] == (2, 6):
# For python2.6 we have to require argparse since it
# was not in stdlib until 2.7.
requires.append('argparse>=1.1')
setup_options = dict(
name='kamboo',
version=kamboo.__version__,
description='To build and distribute AMI images' +
' or EC2 snapshots across accounts and regions',
long_description=open('README.rst').read(),
author='Henry Huang',
author_email='henry.s.huang@gmail.com',
url='https://github.com/henrysher/kamboo',
scripts=[],
packages=find_packages('.', exclude=['tests*']),
package_dir={'kamboo': 'kamboo'},
package_data={'kamboo': []},
install_requires=requires,
license="Apache License 2.0",
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
),
)
setup(**setup_options)
| #!/usr/bin/env python
import sys
from setuptools import setup, find_packages
import kamboo
requires = ['boto3']
if sys.version_info[:2] == (2, 6):
# For python2.6 we have to require argparse since it
# was not in stdlib until 2.7.
requires.append('argparse>=1.1')
setup_options = dict(
name='kamboo',
version=kamboo.__version__,
description='',
long_description=open('README.rst').read(),
author='Henry Huang',
author_email='henry.s.huang@gmail.com',
url='https://github.com/henrysher/kamboo',
scripts=[],
packages=find_packages('.', exclude=['tests*']),
package_dir={'kamboo': 'kamboo'},
package_data={'kamboo': []},
install_requires=requires,
license="Apache License 2.0",
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
),
)
setup(**setup_options)
|
[patch][Button] Add an id attribute to the button component | import React from 'react';
import {Button} from 'apparena-patterns-react';
export default function ButtonExample() {
return (
<div>
<Button type="primary">
Primary
</Button>
<Button type="secondary">
Secondary
</Button>
<Button type="success">
Success
</Button>
<Button type="link">
Link
</Button>
<hr/>
<Button id="withId" type="secondary">
Button with ID
</Button>
</div>
);
} | import React from 'react';
import {Button} from 'apparena-patterns-react';
export default function ButtonExample() {
return (
<div>
<Button type="primary">
Primary
</Button>
<Button type="secondary">
Secondary
</Button>
<Button type="link">
Link
</Button>
<hr/>
<Button id="withId" type="secondary">
Button with ID
</Button>
</div>
);
} |
Include roboto font in app head - DW | import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const sheet = new ServerStyleSheet()
const page = renderPage((App) => (props) =>
sheet.collectStyles(<App {...props} />)
)
const styleTags = sheet.getStyleElement()
return { ...page, styleTags }
}
render() {
return (
<html lang="en">
<Head>
<title>Styled MDL</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700" rel="stylesheet" />
{this.props.styleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
| import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const sheet = new ServerStyleSheet()
const page = renderPage((App) => (props) =>
sheet.collectStyles(<App {...props} />)
)
const styleTags = sheet.getStyleElement()
return { ...page, styleTags }
}
render() {
return (
<html lang="en">
<Head>
<title>Styled MDL</title>
{this.props.styleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
|
Fix bug in CardController when cardId is null and add 'isDisabled' | export default class CardController {
constructor($rootScope, $scope, $log, _, playerModel, cardsApi) {
'ngInject';
this.$rootScope = $rootScope;
this.$scope = $scope;
this.$log = $log;
this._ = _;
this.cardsApi = cardsApi;
this.playerModel = playerModel.model;
this.$log.info('constructor()', this);
}
$onInit() {
let onSuccess = (res => {
this.$log.info('onSuccess()', res, this);
if (res.status === 200) {
this.$scope.cardData = res.data[0];
}
}),
onError = (err => {
this.$log.error(err);
});
this.$log.info('$onInit()', this);
this.$scope.cardData = {};
this.$scope.isDisabled = !this.cardId || this.cardType === 'storage';
if (this.cardId) {
this.cardsApi
.get(this.cardId)
.then(onSuccess, onError);
}
}
$onDestroy() {
return () => {
this.$log.info('$onDestroy()', this);
};
}
onClick($e) {
this.$log.info('onClick()', this);
$e.preventDefault();
}
};
| export default class CardController {
constructor($rootScope, $scope, $log, _, playerModel, cardsApi) {
'ngInject';
this.$rootScope = $rootScope;
this.$scope = $scope;
this.$log = $log;
this._ = _;
this.cardsApi = cardsApi;
this.playerModel = playerModel.model;
this.$log.info('constructor()', this);
}
$onInit() {
let onSuccess = (res => {
this.$log.info('onSuccess()', res, this);
if (res.status === 200) {
this.$scope.cardData = res.data[0];
}
}),
onError = (err => {
this.$log.error(err);
});
this.$log.info('$onInit()', this);
this.$scope.cardData = {};
this.cardsApi
.get(this.cardId)
.then(onSuccess, onError);
}
$onDestroy() {
return () => {
this.$log.info('$onDestroy()', this);
};
}
onClick() {
this.$log.info('onClick()', this);
}
};
|
Revert changes for adding "static" to route
because accessing static is using /api/static instead of /static | /**
* Main application routes
*/
'use strict';
var express = require('express');
var config = require('./config/environment');
import errors from './components/errors';
import path from 'path';
export default function(app) {
// Insert routes below
app.use('/api/achievements', require('./api/achievement'));
app.use('/api/posts', require('./api/post'));
app.use('/api/projects', require('./api/project'));
app.use('/api/commits', require('./api/commit'));
app.use('/api/users', require('./api/user'));
app.use('/api/classyear', require('./api/classyear'));
app.use('/api/smallgroup', require('./api/smallgroup'));
app.use('/api/attendance', require('./api/attendance'));
app.use('/api/static', require('./api/static'));
app.use('/uploads', express.static(config.imageUploadPath));
app.use('/auth', require('./auth'));
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets|uploads)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get((req, res) => {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
}
| /**
* Main application routes
*/
'use strict';
var express = require('express');
var config = require('./config/environment');
import errors from './components/errors';
import path from 'path';
export default function(app) {
// Insert routes below
app.use('/api/achievements', require('./api/achievement'));
app.use('/api/posts', require('./api/post'));
app.use('/api/projects', require('./api/project'));
app.use('/api/commits', require('./api/commit'));
app.use('/api/users', require('./api/user'));
app.use('/api/classyear', require('./api/classyear'));
app.use('/api/smallgroup', require('./api/smallgroup'));
app.use('/api/attendance', require('./api/attendance'));
app.use('/api/static', require('./api/static'));
app.use('/uploads', express.static(config.imageUploadPath));
app.use('/auth', require('./auth'));
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets|uploads|static)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get((req, res) => {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
}
|
Make EtlClass attribute access more robust | """Base EtlClass that all EtlClasses should inherit"""
class EtlClass(object):
def __init__(self, config):
self.config = config
def __setattr__(self, key, value):
"""Set attribute on config if not in EtlClass object"""
if key == "config":
self.__dict__[key] = value
elif "config" in self.__dict__ and hasattr(self.config, key):
setattr(self.config, key, value)
else:
self.__dict__[key] = value
def __getattr__(self, key):
"""Get attribute on config if not in EtlClass object"""
# Get attribute if Config doesnt exist
# we don't need a special call to super here because getattr is only
# called when an attribute is NOT found in the instance's dictionary
config = self.__dict__["config"]
return getattr(config, key)
| """Base EtlClass that all EtlClasses should inherit"""
class EtlClass(object):
def __init__(self, config):
self.config = config
def __setattr__(self, key, value):
"""Set attribute on config if not in EtlClass object"""
if key == "config":
self.__dict__[key] = value
elif hasattr(self.config, key):
setattr(self.config, key, value)
else:
self.__dict__[key] = value
def __getattr__(self, key):
"""Get attribute on config if not in EtlClass object"""
# Get attribute if Config doesnt exist
# we don't need a special call to super here because getattr is only
# called when an attribute is NOT found in the instance's dictionary
config = self.config
return getattr(config, key)
|
Update all configurations to include factories | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Inventory\Factory;
use Doctrine\Common\Collections\ArrayCollection;
use Sylius\Component\Inventory\Model\InventoryUnitInterface;
use Sylius\Component\Inventory\Model\StockableInterface;
use Sylius\Component\Resource\Factory\Factory;
/**
* Default inventory operator.
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
class InventoryUnitFactory extends Factory implements InventoryUnitFactoryInterface
{
/**
* {@inheritdoc}
*/
public function createForStockable(StockableInterface $stockable, $quantity, $state = InventoryUnitInterface::STATE_SOLD)
{
if ($quantity < 1) {
throw new \InvalidArgumentException('Quantity of units must be greater than 1.');
}
$units = new ArrayCollection();
for ($i = 0; $i < $quantity; $i++) {
$inventoryUnit = parent::createNew();
$inventoryUnit->setStockable($stockable);
$inventoryUnit->setInventoryState($state);
$units->add($inventoryUnit);
}
return $units;
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Inventory\Factory;
use Doctrine\Common\Collections\ArrayCollection;
use Sylius\Component\Inventory\Model\InventoryUnitInterface;
use Sylius\Component\Inventory\Model\StockableInterface;
use Sylius\Component\Resource\Factory\Factory;
use Sylius\Component\Resource\Repository\RepositoryInterface;
/**
* Default inventory operator.
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
class InventoryUnitFactory extends Factory implements InventoryUnitFactoryInterface
{
/**
* {@inheritdoc}
*/
public function createForStockable(StockableInterface $stockable, $quantity, $state = InventoryUnitInterface::STATE_SOLD)
{
if ($quantity < 1) {
throw new \InvalidArgumentException('Quantity of units must be greater than 1.');
}
$units = new ArrayCollection();
for ($i = 0; $i < $quantity; $i++) {
$inventoryUnit = parent::createNew();
$inventoryUnit->setStockable($stockable);
$inventoryUnit->setInventoryState($state);
$units->add($inventoryUnit);
}
return $units;
}
}
|
Refactor script to clean up code a bit. | #!/usr/bin/env python3
"""Get a markdown-formatted list of PRs merged since a certain tag."""
import github_tools
Repo = github_tools.get_repo()
# TODO: implement getting date from repo tag.
tagname = '0.8.1'
tags = Repo.get_tags()
for t in tags:
if t.name == tagname:
startdate = t.commit.commit.committer.date
print('Selected tag ' + tagname + ', date: ' + str(startdate))
print('Fetching data...\n\n')
pulls = Repo.get_pulls('closed')
results = []
for p in pulls:
if (p.closed_at > startdate) and p.merged:
results.append({'login': p.user.login,
'number': p.number,
'url': p.html_url,
'title': p.title})
user_maxlength = max([len(entry['login']) for entry in results])
format_string = '{:<' + str(user_maxlength) + '}'
for r in results:
print("* [Nr " + str(r['number']) + "]( "
+ str(r['url']) + " ) by "
+ format_string.format(r['login'])
+ ': ' + str(r['title']))
| #!/usr/bin/env python3
"""Get a markdown-formatted list of PRs merged since a certain tag."""
import github_tools
Repo = github_tools.get_repo()
# TODO: implement getting date from repo tag./
tagname = '0.8.1'
tags = Repo.get_tags()
for t in tags:
if t.name == tagname:
startdate = t.commit.commit.committer.date
print('Tag date: ' + str(startdate))
pulls = Repo.get_pulls('closed')
user_length = 0
for p in pulls:
if (p.closed_at > startdate) and p.merged:
user_length = max(user_length, len(p.user.login))
format_string = '{:<' + str(user_length) + '}'
for p in pulls:
if (p.closed_at > startdate) and p.merged:
print("* [Nr " + str(p.number) + "]( "
+ str(p.html_url) + " ) by " + format_string.format(p.user.login)
+ ': ' + str(p.title))
|
Add error field to expected JSON | from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """"
{
<<<<<<< HEAD
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
| from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class StoriesTestCase(TestCase):
fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json']
def setUp(self):
self.expected_json = """
{
"error": {
"error_status": false,
"error_name": null,
"error_text": null,
"error_level": null
},
"story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..."
}"""
def test_url_endpoint(self):
url = reverse('story-details', kwargs={'id': '1'})
self.assertEqual(url, '/stories/1')
def test_json_equals(self):
c = Client()
response = c.get(reverse('story-details', kwargs={'id': '1'})).content
parsed_answer = json.loads(response)
expected_answer = json.loads(self.expected_json)
self.assertTrue(parsed_answer == expected_answer)
|
Exit with correct code on error | package main
import (
"fmt"
"io"
"os"
)
var ARGV []string
var exitcode int
func main() {
ARGV = os.Args[1:]
exitcode = 0
// If there are no arguments, then we read STDIN
if len(ARGV) == 0 {
ARGV = append(ARGV, "-")
}
// Iterate arguments to read filenames
for _, filename := range ARGV {
// - means read stdin as a special case, we just use /dev/stdin instead
if filename == "-" {
filename = "/dev/stdin"
}
// Time to try and read the file in question
f, err := os.Open(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "cat: %s: No such file or directory\n", filename)
exitcode = 1
continue
}
// Copy our output across!
io.Copy(os.Stdout, f)
}
os.Exit(exitcode)
}
| package main
import (
"fmt"
"io"
"os"
)
var ARGV []string
func main() {
ARGV = os.Args[1:]
// If there are no arguments, then we read STDIN
if len(ARGV) == 0 {
ARGV = append(ARGV, "-")
}
// Iterate arguments to read filenames
for _, filename := range ARGV {
// - means read stdin as a special case, we just use /dev/stdin instead
if filename == "-" {
filename = "/dev/stdin"
}
// Time to try and read the file in question
f, err := os.Open(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "cat: %s: No such file or directory\n", filename)
continue
}
// Copy our output across!
io.Copy(os.Stdout, f)
}
}
|
Improve logic in userRoom removal | const db = require('../db.js');
module.exports = (userId, roomId) => {
const findNumberActiveParticipantsQueryStr = `
SELECT number_active_participants FROM rooms
WHERE id = '${roomId}'
`;
const removeRoomQueryStr = `
DELETE FROM rooms
WHERE id = '${roomId}'
`;
const reduceNumberActiveParticipantsQueryStr = `
UPDATE rooms
SET \`number_active_participants\` = \`number_active_participants\` - 1
WHERE id = '${roomId}'
`;
const removeUserRoomQueryStr = `
DELETE from users_rooms
WHERE room_id = '${roomId}' AND user_id = '${userId}'
`;
return db.query(findNumberActiveParticipantsQueryStr).spread(results => {
if (results[0] == 1) {
return db.query(removeUserRoomQueryStr)
.spread(() => (
db.query(removeRoomQueryStr)
.spread(room => room)
));
}
return db.query(removeUserRoomQueryStr)
.spread(() => (
db.query(reduceNumberActiveParticipantsQueryStr)
.spread(room => room)
));
});
};
| const db = require('../db.js');
module.exports = (userId, roomId) => {
const findNumberActiveParticipantsQueryStr = `
SELECT number_active_participants FROM rooms
WHERE id = '${roomId}'
`;
const removeUserRoomsQueryStr = `
DELETE FROM users_rooms
WHERE room_id = '${roomId}'
`;
const removeRoomQueryStr = `
DELETE FROM rooms
WHERE id = '${roomId}'
`;
const reduceNumberActiveParticipantsQueryStr = `
UPDATE rooms
SET \`number_active_participants\` = \`number_active_participants\` - 1
WHERE id = '${roomId}'
`;
return db.query(findNumberActiveParticipantsQueryStr).spread(results => {
if (results[0] == 1) {
return db.query(removeUserRoomsQueryStr)
.spread(() => (
db.query(removeRoomQueryStr)
.spread(room => room)
));
}
return db.query(reduceNumberActiveParticipantsQueryStr)
.spread(room => room);
});
};
|
Disable native transport by default unless allowed by system property. | package protocolsupport.injector.network;
import net.minecraft.server.v1_8_R3.MinecraftServer;
import net.minecraft.server.v1_8_R3.ServerConnection;
import protocolsupport.ProtocolSupport;
import protocolsupport.utils.Utils;
import protocolsupport.utils.Utils.Converter;
public class NettyInjector {
private static final boolean allowUseEpollChannel = Utils.getJavaPropertyValue("protocolsupport.allowepoll", false, Converter.STRING_TO_BOOLEAN);
private static final boolean useNonBlockingServerConnection = Utils.getJavaPropertyValue("protocolsupport.nonblockingconection", false, Converter.STRING_TO_BOOLEAN);
public static void inject() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
ServerConnection connection = MinecraftServer.getServer().getServerConnection();
if (!allowUseEpollChannel) {
MinecraftServer.getServer().getPropertyManager().setProperty("use-native-transport", false);
}
if (connection == null && useNonBlockingServerConnection) {
NonBlockingServerConnection.inject();
ProtocolSupport.logInfo("Using NonBlockingServerConnection");
} else {
BasicInjector.inject();
ProtocolSupport.logInfo("Using injected ServerConnection");
}
}
}
| package protocolsupport.injector.network;
import net.minecraft.server.v1_8_R3.MinecraftServer;
import net.minecraft.server.v1_8_R3.ServerConnection;
import protocolsupport.ProtocolSupport;
import protocolsupport.utils.Utils;
import protocolsupport.utils.Utils.Converter;
public class NettyInjector {
private static final boolean useNonBlockingServerConnection = Utils.getJavaPropertyValue("protocolsupport.nonblockingconection", false, Converter.STRING_TO_BOOLEAN);
public static void inject() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
ServerConnection connection = MinecraftServer.getServer().getServerConnection();
if (connection == null && useNonBlockingServerConnection) {
NonBlockingServerConnection.inject();
ProtocolSupport.logInfo("Using NonBlockingServerConnection");
} else {
BasicInjector.inject();
ProtocolSupport.logInfo("Using injected ServerConnection");
}
}
}
|
Update ver 0.1 Beta (Build 9)
plg_system examples | <?php
require("bin/fw.php");
define('N', "\n");
define('BR', "<br />");
define('BRN', "<br />\n");
# plg_visitor
echo "You are using ".browserName." ver ".browserVer." on ".platformFamily." ".(is64bit ? "64 bit" : "32 bit")." from ".getIP().BRN;
# plg_dump
$arr = array("Defined Variables"=>get_defined_vars(), "Defined Constants"=>get_defined_constants());
echo dump($arr, TRUE, TRUE).BRN;
# plg_system
echo 'echo clean_number(\'4f32k91025\'); <span style="color: orange; font-style: italic"># will output '.clean_number('4f32k91025').'</span>'.BRN;
echo 'echo decimal_to_fraction(\'.125\'); <span style="color: orange; font-style: italic"># will output '.decimal_to_fraction ('.125').'</span>'.BRN;
echo 'echo fraction_to_decimal(\'1/8\'); <span style="color: orange; font-style: italic"># will output '.fraction_to_decimal ('1/8').'</span>'.BRN;
echo 'echo is_whole_number(\'1/8\'); <span style="color: orange; font-style: italic"># will output '.is_whole_number (45.21).'</span>'.BRN;
| <?php
require("bin/fw.php");
define('N', "\n");
define('BR', "<br />");
define('BRN', "<br />\n");
# plg_visitor
echo "You are using ".browserName." ver ".browserVer." on ".platformFamily." ".(is64bit ? "64 bit" : "32 bit")." from ".getIP().BRN;
# plg_dump
$arr = array("Defined Variables"=>get_defined_vars(), "Defined Constants"=>get_defined_constants());
echo dump($arr, TRUE, TRUE).BRN;
# plg_system
echo 'echo clean_number(\'4f32k91025\'); <span style="color: orange; font-style: italic"># will output '.clean_number('4f32k91025').'</span>'.BRN;
echo 'echo decimal_to_fraction(\'.125\'); <span style="color: orange; font-style: italic"># will output </span>'.decimal_to_fraction ('.125').'</span>'.BRN;
|
Add short/long designation to expiration page subtitle. | window.onload = () => setTimeout(async () => await load());
async function load() {
chrome.windows.getCurrent({}, thisWindow => {
chrome.windows.update(thisWindow.id, { focused: true });
});
let phase = await BackgroundClient.getPhase();
let settings = await BackgroundClient.getSettings();
let start = document.getElementById('start-session');
start.onclick = () => BackgroundClient.startSession();
let title = document.getElementById('session-title');
let subtitle = document.getElementById('session-subtitle');
let action = document.getElementById('session-action');
if (phase === 'focus') {
title.innerText = 'Break finished';
subtitle.innerText = `Start your ${settings.focus.duration} minute focus session when you're ready`;
action.innerText = 'Start Focusing';
} else if (phase == 'short-break') {
title.innerText = 'Take a short break!';
subtitle.innerText = `Start your ${settings.shortBreak.duration} minute short break when you're ready`;
action.innerText = 'Start Short Break';
} else if (phase == 'long-break') {
title.innerText = 'Take a long break!';
subtitle.innerText = `Start your ${settings.longBreak.duration} minute long break when you're ready`;
action.innerText = 'Start Long Break';
}
start.className += ' ' + phase;
};
| window.onload = () => setTimeout(async () => await load());
async function load() {
chrome.windows.getCurrent({}, thisWindow => {
chrome.windows.update(thisWindow.id, { focused: true });
});
let phase = await BackgroundClient.getPhase();
let settings = await BackgroundClient.getSettings();
let start = document.getElementById('start-session');
start.onclick = () => BackgroundClient.startSession();
let title = document.getElementById('session-title');
let subtitle = document.getElementById('session-subtitle');
let action = document.getElementById('session-action');
if (phase === 'focus') {
title.innerText = 'Break finished';
subtitle.innerText = `Start your ${settings.focus.duration} minute focus session when you're ready`;
action.innerText = 'Start Focusing';
} else if (phase == 'short-break') {
title.innerText = 'Take a short break!';
subtitle.innerText = `Start your ${settings.shortBreak.duration} minute break when you're ready`;
action.innerText = 'Start Short Break';
} else if (phase == 'long-break') {
title.innerText = 'Take a long break!';
subtitle.innerText = `Start your ${settings.longBreak.duration} minute break when you're ready`;
action.innerText = 'Start Long Break';
}
start.className += ' ' + phase;
};
|
Fix comment about why we use preload | # Configuration for running the Avalon Music Server under Gunicorn
# http://docs.gunicorn.org
# Note that this configuration omits a bunch of features that Gunicorn
# has (such as running as a daemon, changing users, error and access
# logging) because it is designed to be used when running Gunicorn
# with supervisord and a separate public facing web server (such as
# Nginx).
# Bind the server to an address only accessible locally. We'll be
# running Nginx which will proxy to Gunicorn and act as the public-
# facing web server.
bind = 'localhost:8000'
# Use three workers in addition to the master process. Since the Avalon
# Music Server is largely CPU bound, you can increase the number of
# request that can be handled by increasing this number (up to a point!).
# The Gunicorn docs recommend 2N + 1 where N is the number of CPUs you
# have.
workers = 3
# Make sure to load the application only in the main process before
# spawning the worker processes. This will save us memory when using
# multiple worker processes since the OS will be be able to take advantage
# of copy-on-write optimizations.
preload_app = True
| # Configuration for running the Avalon Music Server under Gunicorn
# http://docs.gunicorn.org
# Note that this configuration omits a bunch of features that Gunicorn
# has (such as running as a daemon, changing users, error and access
# logging) because it is designed to be used when running Gunicorn
# with supervisord and a separate public facing web server (such as
# Nginx).
# Bind the server to an address only accessible locally. We'll be
# running Nginx which will proxy to Gunicorn and act as the public-
# facing web server.
bind = 'localhost:8000'
# Use three workers in addition to the master process. Since the Avalon
# Music Server is largely CPU bound, you can increase the number of
# request that can be handled by increasing this number (up to a point!).
# The Gunicorn docs recommend 2N + 1 where N is the number of CPUs you
# have.
workers = 3
# Make sure to load the application only in the main process before
# spawning the worker processes. Necessary when the server is scanning
# a music collection on start up to prevent multiple workers from
# stomping all over the database at the same time.
preload_app = True
|
Use NodeNG instead of astroid.ALL_NODE_CLASSES | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import astroid
from astroid.node_classes import NodeNG
from . import tools, test_mark_tokens
class TestAstroid(test_mark_tokens.TestMarkTokens):
is_astroid_test = True
module = astroid
nodes_classes = NodeNG
context_classes = [
(astroid.Name, astroid.DelName, astroid.AssignName),
(astroid.Attribute, astroid.DelAttr, astroid.AssignAttr),
]
@staticmethod
def iter_fields(node):
"""
Yield a tuple of ``(fieldname, value)`` for each field
that is present on *node*.
Similar to ast.iter_fields, but for astroid and ignores context
"""
for field in node._astroid_fields + node._other_fields:
if field == 'ctx':
continue
yield field, getattr(node, field)
@classmethod
def create_mark_checker(cls, source):
builder = astroid.builder.AstroidBuilder()
tree = builder.string_build(source)
return tools.MarkChecker(source, tree=tree)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import re
import astroid
from . import tools, test_mark_tokens
class TestAstroid(test_mark_tokens.TestMarkTokens):
is_astroid_test = True
module = astroid
nodes_classes = astroid.ALL_NODE_CLASSES
context_classes = [
(astroid.Name, astroid.DelName, astroid.AssignName),
(astroid.Attribute, astroid.DelAttr, astroid.AssignAttr),
]
@staticmethod
def iter_fields(node):
"""
Yield a tuple of ``(fieldname, value)`` for each field
that is present on *node*.
Similar to ast.iter_fields, but for astroid and ignores context
"""
for field in node._astroid_fields + node._other_fields:
if field == 'ctx':
continue
yield field, getattr(node, field)
@classmethod
def create_mark_checker(cls, source):
builder = astroid.builder.AstroidBuilder()
tree = builder.string_build(source)
return tools.MarkChecker(source, tree=tree)
|
Remove admin.autodiscover() call, it's called automatically in 1.7+ | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, patterns, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = patterns('', # noqa
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name="home"),
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name="about"),
# Django Admin
url(r'^admin/', include(admin.site.urls)),
# User management
url(r'^users/', include("{{ cookiecutter.repo_name }}.users.urls", namespace="users")),
url(r'^accounts/', include('allauth.urls')),
# Your stuff: custom urls includes go here
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
# Comment the next two lines to disable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('', # noqa
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name="home"),
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name="about"),
# Django Admin (Comment the next line to disable the admin)
url(r'^admin/', include(admin.site.urls)),
# User management
url(r'^users/', include("{{ cookiecutter.repo_name }}.users.urls", namespace="users")),
url(r'^accounts/', include('allauth.urls')),
# Your stuff: custom urls includes go here
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
Correct the javadocs about how the id is generated | package org.realityforge.arez.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotate the method that should return the Id for Arez container.
*
* <p>This annotation should appear at most once on a container and should
* not be present if the {@link Container#singleton()} is set to true. The
* annotation should be on a method that accepts no parameters and returns
* a non-null value.</p>
*
* <p>If this annotation is present, it indicates that the Annotation processor
* should call this method to get the ID of the container. This ID should be
* constant and unique (enough) to identify container. It is used when generating
* debug names for observables nested within the container. If this annotation is
* not present the Annotation processor will synthesize an ID as a
* monotonically increasing integer for each instance of the type.</p>
*/
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface ContainerId
{
}
| package org.realityforge.arez.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotate the method that should return the Id for Arez container.
*
* <p>This annotation should appear at most once on a container and should
* not be present if the {@link Container#singleton()} is set to true. The
* annotation should be on a method that accepts no parameters and returns
* a non-null value.</p>
*
* <p>If this annotation is present, it indicates that the Annotation processor
* should call this method to get the ID of the container. This ID should be
* constant and unique (enough) to identify container. It is used when generating
* debug names for observables nested within the container. If this annotation is
* not present the Annotation processor will synthesize an ID by calling
* ArezContext.nextNodeId()</p>
*/
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface ContainerId
{
}
|
Tidy that commit up a bit... | (function($){
$.fn.savetheorphans = function(options) {
var defaults = {
orphansToSave: 1
};
var options = $.extend(defaults, options);
return this.each(function() {
var obj = $(this);
var str = obj.html();
var htmlRegEx = /( )(<[^<]+?>.+<\/[^<]+>)/;
for (var i = 0; i < options.orphansToSave; i++) {
if (htmlRegEx.test(str)) {
// Because the last word is an HTML tag put the in before it else the tag will break
str = str.replace(htmlRegEx, ' $2');
} else {
str = str.replace(/( )([^ ]*)$/,' $2');
}
};
obj.html(str);
});
};
})(jQuery); | (function($){
$.fn.savetheorphans = function(options) {
var defaults = {
orphansToSave: 1
};
var options = $.extend(defaults, options);
return this.each(function() {
var obj = $(this),
str = obj.html(),
htmlRegEx = /( )(<[^<]+?>.+<\/[^<]+>)/;
for (var i = 0; i < options.orphansToSave; i++) {
if (htmlRegEx.test(str)) {
// Because the last word is an HTML tag put the in before it else the tag will break
str = str.replace(htmlRegEx, ' $2');
} else {
str = str.replace(/( )([^ ]*)$/, ' $2');
}
};
obj.html(str);
});
};
})(jQuery); |
Make this a subclass of Thread. | // Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* A special-purpose thread used by Resolvers (both SimpleResolver and
* ExtendedResolver) to perform asynchronous queries.
*
* @author Brian Wellington
*/
class ResolveThread extends Thread {
private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;
/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
ResolverListener listener)
{
this.res = res;
this.query = query;
this.id = id;
this.listener = listener;
}
/**
* Performs the query, and executes the callback.
*/
public void
run() {
try {
Message response = res.send(query);
listener.receiveMessage(id, response);
}
catch (Exception e) {
listener.handleException(id, e);
}
}
}
| // Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* A special-purpose thread used by Resolvers (both SimpleResolver and
* ExtendedResolver) to perform asynchronous queries.
*
* @author Brian Wellington
*/
class ResolveThread implements Runnable {
private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;
/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
ResolverListener listener)
{
this.res = res;
this.query = query;
this.id = id;
this.listener = listener;
}
/**
* Performs the query, and executes the callback.
*/
public void
run() {
try {
Message response = res.send(query);
listener.receiveMessage(id, response);
}
catch (Exception e) {
listener.handleException(id, e);
}
}
}
|
Add instance assertion to table | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Dave Lasley <dave@laslabs.com>
# Copyright: 2015 LasLabs, Inc [https://laslabs.com]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import os
import unittest
import mock
from sqlalchemy.schema import Table
from carepoint.tests.db.db import DatabaseTest
from carepoint.models.cph.address import Address
class ModelCphAddressTest(DatabaseTest):
def test_table_initialization(self, ):
self.assertIsInstance(Address.__table__, Table)
if __name__ == '__main__':
unittest.main()
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Dave Lasley <dave@laslabs.com>
# Copyright: 2015 LasLabs, Inc [https://laslabs.com]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import os
import unittest
import mock
from carepoint.tests.db.db import DatabaseTest
from carepoint.models.cph.address import Address
class ModelCphAddressTest(DatabaseTest):
def test_primary_key(self, ):
print Address.__table__
if __name__ == '__main__':
unittest.main()
|
Use configurable hash_type for general Key fingerprinting | # -*- coding: utf-8 -*-
'''
Functions to view the minion's public key information
'''
from __future__ import absolute_import
# Import python libs
import os
# Import Salt libs
import salt.utils
def finger():
'''
Return the minion's public key fingerprint
CLI Example:
.. code-block:: bash
salt '*' key.finger
'''
return salt.utils.pem_finger(os.path.join(__opts__['pki_dir'], 'minion.pub'),
sum_type=__opts__.get('hash_type', 'md5'))
def finger_master():
'''
Return the fingerprint of the master's public key on the minion.
CLI Example:
.. code-block:: bash
salt '*' key.finger_master
'''
return salt.utils.pem_finger(os.path.join(__opts__['pki_dir'], 'minion_master.pub'),
sum_type=__opts__.get('hash_type', 'md5'))
| # -*- coding: utf-8 -*-
'''
Functions to view the minion's public key information
'''
from __future__ import absolute_import
# Import python libs
import os
# Import Salt libs
import salt.utils
def finger():
'''
Return the minion's public key fingerprint
CLI Example:
.. code-block:: bash
salt '*' key.finger
'''
return salt.utils.pem_finger(
os.path.join(__opts__['pki_dir'], 'minion.pub'),
sum_type=__opts__['hash_type']
)
def finger_master():
'''
Return the fingerprint of the master's public key on the minion.
CLI Example:
.. code-block:: bash
salt '*' key.finger_master
'''
return salt.utils.pem_finger(
os.path.join(__opts__['pki_dir'], 'minion_master.pub'),
sum_type=__opts__['hash_type']
)
|
Remove unused imports in settings fragment | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Abhijit Parida <abhijitparida.me@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.abhijit.iter;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
| /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Abhijit Parida <abhijitparida.me@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.abhijit.iter;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import app.abhijit.iter.R;
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
|
Add tests for disabling ghostMode | 'use strict';
var module = require('../../lib/index');
var setup = module.setup;
var dConfig = require('../fixtures/si-default-config');
var _ = require('lodash');
var defaultConfig;
describe("When a Server arg is given on command line", function () {
var argv = {};
beforeEach(function(){
argv.server = true;
defaultConfig = _.cloneDeep(dConfig);
});
it("should set the server option to true if given on command line", function () {
var config = setup.getConfig(defaultConfig, argv);
expect(config.server).not.toBe(false);
});
it("should set the base dir as current for server if not given", function () {
argv.ghostMode = false;
var config = setup.getConfig(defaultConfig, argv);
expect(config.server.baseDir).toBe("./");
// _todo extract to it's own test
expect(config.ghostMode).toBe(false);
});
it("should set the base dir if given", function () {
argv.server = "app";
var config = setup.getConfig(defaultConfig, argv);
expect(config.server.baseDir).toBe("app");
});
}); | 'use strict';
var module = require('../../lib/index');
var setup = module.setup;
var dConfig = require('../fixtures/si-default-config');
var _ = require('lodash');
var defaultConfig;
describe("When a Server arg is given on command line", function () {
var argv = {};
beforeEach(function(){
argv.server = true;
defaultConfig = _.cloneDeep(dConfig);
});
it("should set the server option to true if given on command line", function () {
var config = setup.getConfig(defaultConfig, argv);
expect(config.server).not.toBe(false);
});
it("should set the base dir as current for server if not given", function () {
var config = setup.getConfig(defaultConfig, argv);
expect(config.server.baseDir).toBe("./");
});
it("should set the base dir if given", function () {
argv.server = "app";
var config = setup.getConfig(defaultConfig, argv);
expect(config.server.baseDir).toBe("app");
});
}); |
Change value of default timeout interval | // /*global jasmine, __karma__, window*/
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;
__karma__.loaded = function () {};
function isSpecFile(path) {
return /\.spec\.js$/.test(path);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile);
System.config({
baseURL: '/base',
packageWithIndex: true
});
System.import('karma.systemjs.conf.js')
.then(function () {
return Promise.all([
System.import('@angular/core/testing'),
System.import('@angular/platform-browser-dynamic/testing')
])
})
.then(function (providers) {
var coreTesting = providers[0];
var browserTesting = providers[1];
coreTesting.TestBed.initTestEnvironment(
browserTesting.BrowserDynamicTestingModule,
browserTesting.platformBrowserDynamicTesting());
})
.then(function() {
return System.import('jquery').then(function($) {
$.noConflict(true);
});
})
.then(function() {
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
}));
})
.then(__karma__.start, __karma__.error);
| // /*global jasmine, __karma__, window*/
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
__karma__.loaded = function () {};
function isSpecFile(path) {
return /\.spec\.js$/.test(path);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile);
System.config({
baseURL: '/base',
packageWithIndex: true
});
System.import('karma.systemjs.conf.js')
.then(function () {
return Promise.all([
System.import('@angular/core/testing'),
System.import('@angular/platform-browser-dynamic/testing')
])
})
.then(function (providers) {
var coreTesting = providers[0];
var browserTesting = providers[1];
coreTesting.TestBed.initTestEnvironment(
browserTesting.BrowserDynamicTestingModule,
browserTesting.platformBrowserDynamicTesting());
})
.then(function() {
return System.import('jquery').then(function($) {
$.noConflict(true);
});
})
.then(function() {
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
}));
})
.then(__karma__.start, __karma__.error);
|
Remove fmt since it's not used | package system
import (
"io/ioutil"
"strconv"
"strings"
)
// parseCPUInfo returns a newline-delimited string slice of '/proc/cpuinfo'.
func parseCPUInfo() []string {
cached, _ := ioutil.ReadFile("/proc/cpuinfo")
return strings.Split(string(cached), "\n")
}
// parseCPUCount returns the number of CPU cores in the system.
func parseCPUCount(cpuinfo []string) int {
cores, _ := strconv.Atoi(strings.Fields(cpuinfo[len(cpuinfo) - 18])[3])
return cores + 1
}
// Model returns the CPU Model
func CPUModel() string {
modelinfo := strings.Fields(parseCPUInfo()[4])[3:]
return modelinfo[0] + " " + modelinfo[1]
}
// CPUTemp sets the temperature of the CPU.
func CPUTemp(cputemp *int, done chan bool) {
*cputemp = getTemperature()
done <- true
}
// Frequencies sets '*cpufreq' with a string containing all core frequencies.
func CPUFrequencies(cpufreqs *string, done chan bool) {
*cpufreqs = "Cores:" + getFrequencyString()
done <- true
}
| package system
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
// parseCPUInfo returns a newline-delimited string slice of '/proc/cpuinfo'.
func parseCPUInfo() []string {
cached, _ := ioutil.ReadFile("/proc/cpuinfo")
return strings.Split(string(cached), "\n")
}
// parseCPUCount returns the number of CPU cores in the system.
func parseCPUCount(cpuinfo []string) int {
cores, _ := strconv.Atoi(strings.Fields(cpuinfo[len(cpuinfo) - 18])[3])
return cores + 1
}
// Model returns the CPU Model
func CPUModel() string {
modelinfo := strings.Fields(parseCPUInfo()[4])[3:]
return modelinfo[0] + " " + modelinfo[1]
}
// CPUTemp sets the temperature of the CPU.
func CPUTemp(cputemp *int, done chan bool) {
*cputemp = getTemperature()
done <- true
}
// Frequencies sets '*cpufreq' with a string containing all core frequencies.
func CPUFrequencies(cpufreqs *string, done chan bool) {
*cpufreqs = "Cores:" + getFrequencyString()
done <- true
}
|
Create fallback for Array.isArray if used as a browser package | var toString = Object.prototype.toString;
/**
* Get the native `typeof` a value.
*
* @param {*} `val`
* @return {*} Native javascript type
*/
module.exports = function kindOf(val) {
if (val === undefined) {
return 'undefined';
}
if (val === null) {
return 'null';
}
if (val === true || val === false || val instanceof Boolean) {
return 'boolean';
}
if (typeof val !== 'object') {
return typeof val;
}
if (Array.isArray && Array.isArray(val)) {
return 'array';
}
var type = toString.call(val);
if (val instanceof RegExp || type === '[object RegExp]') {
return 'regexp';
}
if (val instanceof Date || type === '[object Date]') {
return 'date';
}
if(type === '[object Array]') {
return 'array';
}
if (type === '[object Function]') {
return 'function';
}
if (type === '[object Arguments]') {
return 'arguments';
}
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(val)) {
return 'buffer';
}
return type.slice(8, -1).toLowerCase();
};
| var toString = Object.prototype.toString;
/**
* Get the native `typeof` a value.
*
* @param {*} `val`
* @return {*} Native javascript type
*/
module.exports = function kindOf(val) {
if (val === undefined) {
return 'undefined';
}
if (val === null) {
return 'null';
}
if (val === true || val === false || val instanceof Boolean) {
return 'boolean';
}
if (typeof val !== 'object') {
return typeof val;
}
if (Array.isArray(val)) {
return 'array';
}
var type = toString.call(val);
if (val instanceof RegExp || type === '[object RegExp]') {
return 'regexp';
}
if (val instanceof Date || type === '[object Date]') {
return 'date';
}
if (type === '[object Function]') {
return 'function';
}
if (type === '[object Arguments]') {
return 'arguments';
}
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(val)) {
return 'buffer';
}
return type.slice(8, -1).toLowerCase();
};
|
Allow HTML files to pass through Rewrite filter | package org.aslak.github.merge;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
@WebFilter(filterName= "HTML5RewriteFilter", urlPatterns = {"/*"})
public class HTML5RewriteFilter implements Filter {
public static final Pattern PATTERN = Pattern.compile("(^.*/api/|\\.(css|js|png|jpg|html))");
public static final String APP_INDEX = "/app/index.jsp";
@Override
public void init(FilterConfig filterConfig) throws ServletException { }
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
request.setAttribute("BASE_ROOT", httpRequest.getContextPath());
if(PATTERN.matcher(httpRequest.getRequestURI()).find()) {
chain.doFilter(request, response);
} else {
request.getRequestDispatcher(APP_INDEX).forward(request, response);
}
}
}
| package org.aslak.github.merge;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
@WebFilter(filterName= "HTML5RewriteFilter", urlPatterns = {"/*"})
public class HTML5RewriteFilter implements Filter {
public static final Pattern PATTERN = Pattern.compile("(^.*/api/|\\.(css|js|png|jpg))");
public static final String APP_INDEX = "/app/index.jsp";
@Override
public void init(FilterConfig filterConfig) throws ServletException { }
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
request.setAttribute("BASE_ROOT", httpRequest.getContextPath());
if(PATTERN.matcher(httpRequest.getRequestURI()).find()) {
chain.doFilter(request, response);
} else {
request.getRequestDispatcher(APP_INDEX).forward(request, response);
}
}
}
|
Fix test support in monorepo | module.exports = {
setupFilesAfterEnv: ['./rtl.setup.js'],
verbose: true,
moduleDirectories: ['<rootDir>/node_modules', 'node_modules'],
transform: {
'^.+\\.(js|tsx?)$': '<rootDir>/jest.transform.js',
},
collectCoverage: true,
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
transformIgnorePatterns: ['node_modules/(?!(proton-shared|react-components|mutex-browser|pmcrypto)/)'],
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': 'react-components/__mocks__/fileMock.js',
'\\.(css|scss|less)$': 'react-components/__mocks__/styleMock.js',
'sieve.js': 'react-components/__mocks__/sieve.js',
},
reporters: ['default', ['jest-junit', { outputName: 'test-report.xml' }]],
coverageReporters: ['text', 'lcov', 'cobertura'],
};
| module.exports = {
setupFilesAfterEnv: ['./rtl.setup.js'],
verbose: true,
moduleDirectories: ['<rootDir>/node_modules'],
transform: {
'^.+\\.(js|tsx?)$': '<rootDir>/jest.transform.js',
},
collectCoverage: true,
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
transformIgnorePatterns: ['node_modules/(?!(proton-shared|react-components|mutex-browser|pmcrypto)/)'],
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': 'react-components/__mocks__/fileMock.js',
'\\.(css|scss|less)$': 'react-components/__mocks__/styleMock.js',
'sieve.js': 'react-components/__mocks__/sieve.js',
},
reporters: ['default', ['jest-junit', { outputName: 'test-report.xml' }]],
coverageReporters: ['text', 'lcov', 'cobertura'],
};
|
Add test for getting help for invalid commands | <?php
use Ockcyp\WpTerm\Command\HelpCommand;
class HelpCommandTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->helpCommand = new HelpCommand;
}
public function testReturnsList()
{
$response = $this->helpCommand
->execute();
$this->assertNotEmpty($response);
$this->assertNotEmpty($response['list']);
$this->assertInternalType('array', $response['list']);
}
public function testReturnsItsOwnUsage()
{
$response = $this->helpCommand
->addArguments('help')
->execute();
$this->assertNotEmpty($response);
$this->assertNotEmpty($response['msg']);
}
/**
* @expectedException Ockcyp\WpTerm\Exception\InvalidCommandException
*/
public function testThrowsInvalidCommandException()
{
$this->helpCommand
->addArguments('not-a-command')
->execute();
}
}
| <?php
use Ockcyp\WpTerm\Command\HelpCommand;
class HelpCommandTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->helpCommand = new HelpCommand;
}
public function testReturnsList()
{
$response = $this->helpCommand
->execute();
$this->assertNotEmpty($response);
$this->assertNotEmpty($response['list']);
$this->assertInternalType('array', $response['list']);
}
public function testReturnsItsOwnUsage()
{
$response = $this->helpCommand
->addArguments('help')
->execute();
$this->assertNotEmpty($response);
$this->assertNotEmpty($response['msg']);
}
}
|
Fix ping google / bing functionality so that OkHttp cleans up all resources after itself. | package cz.jiripinkas.jsitemapgenerator;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class HttpClient {
/**
* HTTP GET to URL, return status
*
* @param url URL
* @return status code (for example 200)
* @throws Exception When error
*/
public int get(String url) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new Exception("error sending HTTP GET to this URL: " + url);
}
return response.code();
} finally {
// this will be executed after "return response.code();"
client.connectionPool().evictAll(); // OkHttpClient starts connection pool which needs to be shut down here
}
}
}
| package cz.jiripinkas.jsitemapgenerator;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class HttpClient {
/**
* HTTP GET to URL, return status
*
* @param url URL
* @return status code (for example 200)
* @throws Exception When error
*/
public int get(String url) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new Exception("error sending HTTP GET to this URL: " + url);
}
return response.code();
}
}
}
|
Make script for adding sample feeds more usable | from smoke_signal import app, init_db
from smoke_signal.database.helpers import add_feed
from utils.generate_feed import SampleFeed
import feedparser
from os import walk, makedirs
FEEDS_DIR = app.root_path + "/test_resources/feeds/"
app.config['DATABASE_PATH'] = 'sqlite:///smoke_signal/test_resources/posts.db'
def create_sample_feed_files(num_feeds, num_items):
makedirs(FEEDS_DIR, exist_ok=True)
for i in range(num_feeds):
feed = SampleFeed("Test feed {}".format(i))
for j in range(num_items):
feed.add_item()
filename = FEEDS_DIR + "feed{}.xml".format(i)
with open(filename, "w+") as f:
f.write(feed.__str__())
def add_feeds_to_db():
filenames = next(walk(FEEDS_DIR))[2]
with app.app_context():
init_db()
for filename in filenames:
uri = "file://" + FEEDS_DIR + filename
feed = feedparser.parse(uri).feed
title = feed["title"]
add_feed(title, uri)
if __name__ == "__main__":
create_sample_feed_files(5, 10)
add_feeds_to_db()
| from smoke_signal import app, init_db
from smoke_signal.database.helpers import add_feed
from utils.generate_feed import SampleFeed
from os import walk
feeds_dir = app.root_path + "/test_resources/feeds/"
app.config['DATABASE_PATH'] = 'sqlite:///smoke_signal/test_resources/posts.db'
def create_sample_feed_files(num_feeds, num_items):
for i in range(num_feeds):
feed = SampleFeed("Test feed {}".format(i))
for j in range(num_items):
feed.add_item()
filename = feeds_dir + "feed{}.xml".format(i)
with open(filename, "w+") as f:
f.write(feed.__str__())
def add_feeds_to_db():
filenames = next(walk(feeds_dir))[2]
with app.app_context():
init_db()
for filename in filenames:
add_feed("file://" + feeds_dir + filename)
|
Stop using wires in versions for Firefox test | /*
* (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package io.github.bonigarcia.wdm.test;
import org.junit.Before;
import io.github.bonigarcia.wdm.FirefoxDriverManager;
import io.github.bonigarcia.wdm.base.BaseVersionTst;
/**
* Test asserting Firefox versions.
*
* @author Boni Garcia (boni.gg@gmail.com)
* @since 1.5.0
*/
public class FirefoxVersionTest extends BaseVersionTst {
@Before
public void setup() {
browserManager = FirefoxDriverManager.getInstance();
specificVersions = new String[] { "0.8.0", "0.19.1" };
}
}
| /*
* (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package io.github.bonigarcia.wdm.test;
import org.junit.Before;
import io.github.bonigarcia.wdm.FirefoxDriverManager;
import io.github.bonigarcia.wdm.base.BaseVersionTst;
/**
* Test asserting Firefox versions.
*
* @author Boni Garcia (boni.gg@gmail.com)
* @since 1.5.0
*/
public class FirefoxVersionTest extends BaseVersionTst {
@Before
public void setup() {
browserManager = FirefoxDriverManager.getInstance();
specificVersions = new String[] { "0.3.0", "0.19.1" };
}
}
|
Extend `Albums` to render album images
... when a certain album is selected.
Component `Albums` is not a stateless component like the other components.
The component needs the life cycle method `componentWillMount`, that's why it's stateful.
A stateless component would only require one comment of `eslint-disable-line react/prop-types`.
This component would need three comments to disable linter errors.
That's why `Albums.propTypes` seems better in this case than `setPropTypes` from `recompose`. | import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { setDisplayName } from 'recompose';
import React from 'react';
import R from 'ramda';
import AlbumImages from './album-images';
import AlbumCollection from './album-collection';
import { getAlbums as getAlbumsAction } from 'interactions/albums/actions';
class Albums extends React.Component {
componentWillMount() {
this.props.getAlbums();
}
render() {
let children;
if (this.props.isAlbumSelected) {
children = <AlbumImages id={this.props.selectedAlbum} />;
} else {
children = <AlbumCollection />;
}
return (
children
);
}
}
Albums.propTypes = {
getAlbums: React.PropTypes.func,
isAlbumSelected: React.PropTypes.bool,
selectedAlbum: React.PropTypes.string,
};
const mapStateToProps = (state) => {
const selectedAlbum = state.getIn(['albums', 'selected']);
return ({
isAlbumSelected: !!selectedAlbum,
selectedAlbum,
});
};
const mapDispatchToProps = (dispatch) =>
bindActionCreators({
getAlbums: getAlbumsAction,
}, dispatch);
const enhance = R.pipe(
connect(mapStateToProps, mapDispatchToProps),
setDisplayName('Albums'),
);
export { Albums };
export default enhance(Albums);
| import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { setDisplayName, setPropTypes } from 'recompose';
import React from 'react';
import R from 'ramda';
import AlbumCollection from './album-collection';
import { getAlbums as getAlbumsAction } from 'interactions/albums/actions';
class Albums extends React.Component {
componentWillMount() {
this.props.getAlbums();
}
render() {
return (
<AlbumCollection />
);
}
}
Albums.propTypes = {
getAlbums: React.PropTypes.func,
};
const mapDispatchToProps = (dispatch) =>
bindActionCreators({
getAlbums: getAlbumsAction,
}, dispatch);
const enhance = R.pipe(
setPropTypes({
getAlbums: React.PropTypes.func,
}),
connect(null, mapDispatchToProps),
setDisplayName('Albums'),
);
export { Albums };
export default enhance(Albums);
|
Remove all instances of Prepend
Prepend was removed because it does not strictly contribute to the
creation of Pids; instead it is added to turn Pids into a URL specific
to the organization that created them. | package com.hida.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Type;
/**
*
* @author lruffin
*/
@Entity
@Table(name = "USED_SETTING")
public class UsedSetting extends Setting{
@NotNull
@Column(name="AMOUNT")
@Type(type="long")
private long Amount;
/**
* Constructor; missing javadoc
*
* @param Prefix
* @param TokenType
* @param CharMap
* @param RootLength
* @param SansVowels
* @param Amount
*/
public UsedSetting(String Prefix, TokenType TokenType, String CharMap,
int RootLength, boolean SansVowels, long Amount) {
super(Prefix, TokenType, CharMap, RootLength, SansVowels);
this.Amount = Amount;
}
/**
* Default constructor
*/
public UsedSetting() {
}
public long getAmount() {
return Amount;
}
public void setAmount(long Amount) {
this.Amount = Amount;
}
}
| package com.hida.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Type;
/**
*
* @author lruffin
*/
@Entity
@Table(name = "USED_SETTING")
public class UsedSetting extends Setting{
@NotNull
@Column(name="AMOUNT")
@Type(type="long")
private long Amount;
/**
* Constructor; missing javadoc
*
* @param Prepend
* @param Prefix
* @param TokenType
* @param CharMap
* @param RootLength
* @param SansVowels
* @param Amount
*/
public UsedSetting(String Prepend, String Prefix, TokenType TokenType, String CharMap,
int RootLength, boolean SansVowels, long Amount) {
super(Prefix, TokenType, CharMap, RootLength, SansVowels);
this.Amount = Amount;
}
/**
* Default constructor
*/
public UsedSetting() {
}
public long getAmount() {
return Amount;
}
public void setAmount(long Amount) {
this.Amount = Amount;
}
}
|
Fix Input Iterator Checker for whiteList | module.exports = {
generateQueryString: function (data) {
var ret = []
for (var d in data)
if (data[d])
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]))
return ret.join("&")
},
base64Encoding: function (data) {
return new Buffer(data).toString('base64')
},
base64Decoding: function (data) {
return new Buffer(data, 'base64')
},
getUnixTimeStamp: function () {
return Math.floor((new Date).getTime() / 1000)
},
stringReplace: function (source, find, replace) {
return source.replace(find, replace)
},
inputChecker: function (reqInput, whiteList) {
var input = Object.keys(reqInput)
if (input.length != whiteList.length)
return false
for (var i = 0; i < input.length; i++)
if (whiteList.indexOf(input[i]) <= -1)
return false
return true
}
}
| module.exports = {
generateQueryString: function (data) {
var ret = []
for (var d in data)
if (data[d])
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]))
return ret.join("&")
},
base64Encoding: function (data) {
return new Buffer(data).toString('base64')
},
base64Decoding: function (data) {
return new Buffer(data, 'base64')
},
getUnixTimeStamp: function () {
return Math.floor((new Date).getTime() / 1000)
},
stringReplace: function (source, find, replace) {
return source.replace(find, replace)
},
inputChecker: function (reqInput, whiteList) {
var input = Object.keys(reqInput)
if (input.length != whiteList.length)
return false
for (var i = 0; i < input.length; i++)
if (whiteList.indexOf(whiteList[i]) <= -1)
return false
return true
}
}
|
Change separator with shadow view on ios | import { Platform, StyleSheet } from 'react-native';
import { colors } from '../../styles';
const styles = StyleSheet.create({
root: {
height: 1,
backgroundColor: colors.grey,
opacity: 0.5,
},
shadow: {
backgroundColor: colors.greyOpacity,
...Platform.select({
ios: {
shadowOpacity: 0.9,
shadowRadius: 1,
shadowOffset: {
height: 0.5,
width: 0,
},
},
android: {
elevation: 0.3,
},
}),
},
opacity: {
opacity: 0.3,
},
});
export default styles;
| import { Platform, StyleSheet } from 'react-native';
import { colors } from '../../styles';
const styles = StyleSheet.create({
root: {
height: 1,
backgroundColor: colors.grey,
opacity: 0.5,
},
shadow: {
backgroundColor: colors.greyOpacity,
...Platform.select({
ios: {
shadowOpacity: 0.9,
shadowRadius: 4,
shadowOffset: {
height: 0,
width: 0,
},
},
android: {
elevation: 0.3,
},
}),
},
opacity: {
opacity: 0.3,
},
});
export default styles;
|
Access Google Maps API by https protocol | <?php
namespace kossmoss\GoogleMaps;
/**
* Asset for Gmap3 JavaScript library
* @link https://github.com/kossmoss/yii2-google-maps-api
* @copyright Copyright (c) 2016 kossmoss <radiokoss@gmail.com>
*/
use yii\base\ErrorException;
use yii\web\AssetBundle;
class GoogleMapsAsset extends AssetBundle
{
/**
* @var string Language ID supported by Google Maps API
*/
public $language = 'en';
/**
* @var string Google Developers API key
* @link https://developers.google.com/maps/documentation/javascript/get-api-key
*/
public $apiKey = null;
public function init(){
parent::init();
if($this->apiKey === null){
throw new ErrorException("You must configure GoogleMapsAsset. See README.md for details.");
}
$this->js = [
'https://maps.google.com/maps/api/js?key='.$this->apiKey.'&language='.$this->language,
];
}
} | <?php
namespace kossmoss\GoogleMaps;
/**
* Asset for Gmap3 JavaScript library
* @link https://github.com/kossmoss/yii2-google-maps-api
* @copyright Copyright (c) 2016 kossmoss <radiokoss@gmail.com>
*/
use yii\base\ErrorException;
use yii\web\AssetBundle;
class GoogleMapsAsset extends AssetBundle
{
/**
* @var string Language ID supported by Google Maps API
*/
public $language = 'en';
/**
* @var string Google Developers API key
* @link https://developers.google.com/maps/documentation/javascript/get-api-key
*/
public $apiKey = null;
public function init(){
parent::init();
if($this->apiKey === null){
throw new ErrorException("You must configure GoogleMapsAsset. See README.md for details.");
}
$this->js = [
'http://maps.google.com/maps/api/js?key='.$this->apiKey.'&language='.$this->language,
];
}
} |
Add condition on memcached class to ensure that there is a client available before running this autoconfig class | /*
* Copyright 2013-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.aws.autoconfigure.cache;
import net.spy.memcached.MemcachedClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.aws.autoconfigure.context.ContextCredentialsProviderAutoConfiguration;
import org.springframework.cloud.aws.cache.config.annotation.EnableElastiCache;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* @author Agim Emruli
*/
@Configuration
@Import(ContextCredentialsProviderAutoConfiguration.class)
@EnableElastiCache
@ConditionalOnClass(value = MemcachedClient.class)
public class ElastiCacheAutoConfiguration {
} | /*
* Copyright 2013-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.aws.autoconfigure.cache;
import org.springframework.cloud.aws.autoconfigure.context.ContextCredentialsProviderAutoConfiguration;
import org.springframework.cloud.aws.cache.config.annotation.EnableElastiCache;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* @author Agim Emruli
*/
@Configuration
@Import(ContextCredentialsProviderAutoConfiguration.class)
@EnableElastiCache
public class ElastiCacheAutoConfiguration {
} |
Use null renderer (for ease of testing) and center at (0, 0) | import geojs from 'geojs/geo.js';
import VisComponent from '../../VisComponent';
export default class Geo extends VisComponent {
constructor (el, options) {
super(el);
this.plot = geojs.map({
node: el,
zoom: 6,
center: {x: 0, y: 0}
});
this.plot.createLayer('osm', {
renderer: null
});
if (options.features) {
options.features.forEach(feature => {
this.plot.createLayer('feature', {
renderer: 'd3'
})
.createFeature(feature.type)
.data(feature.data)
.position(d => ({
x: d[feature.x],
y: d[feature.y]
}));
});
this.plot.draw();
}
}
render () {
this.plot.draw();
}
}
| import geojs from 'geojs/geo.js';
import VisComponent from '../../VisComponent';
export default class Geo extends VisComponent {
constructor (el, options) {
super(el);
this.plot = geojs.map({
node: el,
zoom: 6,
center: {x: 28.9550, y: 41.0136}
});
this.plot.createLayer('osm');
if (options.features) {
options.features.forEach(feature => {
this.plot.createLayer('feature', {
renderer: 'd3'
})
.createFeature(feature.type)
.data(feature.data)
.position(d => ({
x: d[feature.x],
y: d[feature.y]
}));
});
this.plot.draw();
}
}
render () {
this.plot.draw();
}
}
|
Fix propTypes warning in FuzzyWrapper | import React from 'react';
import PropTypes from "prop-types";
export default class FuzzyWrapper extends React.Component {
constructor(props) {
super();
this.state = {
isOpen: false,
};
// create a bound function to invoke when keys are pressed on the body.
this.keyEvent = (function(event) {
if (this.props.isKeyPressed(event)) {
event.preventDefault();
this.setState({isOpen: !this.state.isOpen});
}
}).bind(this);
}
componentDidMount() {
document.body.addEventListener('keydown', this.keyEvent);
}
componentWillUnmount() {
document.body.removeEventListener('keydown', this.keyEvent);
}
// Called by the containing fuzzysearcher to close itself.
onClose() {
this.setState({isOpen: false});
}
render() {
return this.props.popup(
this.state.isOpen,
this.onClose.bind(this),
);
}
}
FuzzyWrapper.propTypes = {
isKeyPressed: PropTypes.func.isRequired,
popup: PropTypes.func.isRequired,
};
FuzzyWrapper.defaultProps = {
isKeyPressed: () => false,
popup: () => null,
};
| import React from 'react';
import PropTypes from "prop-types";
export default class FuzzyWrapper extends React.Component {
constructor(props) {
super();
this.state = {
isOpen: false,
};
// create a bound function to invoke when keys are pressed on the body.
this.keyEvent = (function(event) {
if (this.props.isKeyPressed(event)) {
event.preventDefault();
this.setState({isOpen: !this.state.isOpen});
}
}).bind(this);
}
componentDidMount() {
document.body.addEventListener('keydown', this.keyEvent);
}
componentWillUnmount() {
document.body.removeEventListener('keydown', this.keyEvent);
}
// Called by the containing fuzzysearcher to close itself.
onClose() {
this.setState({isOpen: false});
}
render() {
return this.props.popup(
this.state.isOpen,
this.onClose.bind(this),
);
}
}
FuzzyWrapper.PropTypes = {
isKeyPressed: PropTypes.func.isRequired,
popup: PropTypes.func.isRequired,
};
FuzzyWrapper.defaultProps = {
isKeyPressed: () => false,
popup: () => null,
};
|
Add json to accepted celery content
celery.conf.CELERY_ACCEPT_CONTENT accepts only json | from flask import g
from app import app, app_mongo
from celery import Celery
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'], backend=app.config["CELERY_RESULT_BACKEND"])
celery.conf.update(app.config)
task_base = celery.Task
class ContextTask(task_base):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
# Application context for databases
g.mongo = app_mongo
return task_base.__call__(self, *args, **kwargs)
celery.Task = ContextTask
# Security Concerns (http://docs.celeryproject.org/en/latest/faq.html#is-celery-dependent-on-pickle)
celery.conf.CELERY_ACCEPT_CONTENT = ["json", "application/json"]
celery.conf.CELERY_TASK_SERIALIZER = "json"
celery.conf.CELERY_RESULT_SERIALIZER = "json"
| from flask import g
from app import app, app_mongo
from celery import Celery
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'], backend=app.config["CELERY_RESULT_BACKEND"])
celery.conf.update(app.config)
task_base = celery.Task
class ContextTask(task_base):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
# Application context for databases
g.mongo = app_mongo
return task_base.__call__(self, *args, **kwargs)
celery.Task = ContextTask
# Security Concerns (http://docs.celeryproject.org/en/latest/faq.html#is-celery-dependent-on-pickle)
celery.conf.CELERY_TASK_SERIALIZER = "json"
celery.conf.CELERY_RESULT_SERIALIZER = "json"
|
Fix compile errors in main | package eu.programit;
import java.util.ArrayList;
import java.util.List;
import eu.programit.domain.Person;
import eu.programit.domain.Raymond;
import eu.programit.domain.Rik;
import eu.programit.domain.Jeffrey;
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
// feature 1. add your person class
Person raymond = new Raymond();
Person jeffrey = new Jeffrey();
Person rik = new Rik();
// Person remond = new Remond();
// feature 2. add your own Person here
people.add(raymond);
people.add(jeffrey);
people.add(rik);
// people.add(remond);
for (Person p : people) {
System.out.println("Person with firstName " + p.getFirstName() + " has hobbies " + p.getHobbies());
}
}
// feature 3. somebody (who?) whould make this jar runnable with this main class
}
| package eu.programit;
import java.util.ArrayList;
import java.util.List;
import eu.programit.domain.Person;
import eu.programit.domain.Raymond;
import eu.programit.domain.Rik;
import eu.programit.domain.Jeffrey;
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
// feature 1. add your person class
Person raymond = new Raymond();
Person jeffrey = new Jeffrey();
Person rik = new Rik();
Person remond = new Remond();
// feature 2. add your own Person here
people.add(raymond);
people.add(jeffrey);
people.add(rik);
people.add(remond);
for (Person p : people) {
System.out.println("Person with firstName " + p.getFirstName() + " has hobbies " + p.getHobbies());
}
}
// feature 3. somebody (who?) whould make this jar runnable with this main class
}
|
[ReactNative] Replace all the call sites of mergeInto by Object.assign | /**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @providesModule Dimensions
*/
'use strict';
var NativeModules = require('NativeModules');
var invariant = require('invariant');
var dimensions = NativeModules.RKUIManager.Dimensions;
class Dimensions {
/**
* This should only be called from native code.
*
* @param {object} dims Simple string-keyed object of dimensions to set
*/
static set(dims) {
Object.assign(dimensions, dims);
return true;
}
/**
* Initial dimensions are set before `runApplication` is called so they should
* be available before any other require's are run, but may be updated later.
*
* Note: Although dimensions are available immediately, they may change (e.g
* due to device rotation) so any rendering logic or styles that depend on
* these constants should try to call this function on every render, rather
* than caching the value (for example, using inline styles rather than
* setting a value in a `StyleSheet`).
*
* @param {string} dim Name of dimension as defined when calling `set`.
* @returns {Object?} Value for the dimension.
*/
static get(dim) {
invariant(dimensions[dim], 'No dimension set for key ' + dim);
return dimensions[dim];
}
}
module.exports = Dimensions;
| /**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @providesModule Dimensions
*/
'use strict';
var NativeModules = require('NativeModules');
var invariant = require('invariant');
var mergeInto = require('mergeInto');
var dimensions = NativeModules.RKUIManager.Dimensions;
class Dimensions {
/**
* This should only be called from native code.
*
* @param {object} dims Simple string-keyed object of dimensions to set
*/
static set(dims) {
mergeInto(dimensions, dims);
return true;
}
/**
* Initial dimensions are set before `runApplication` is called so they should
* be available before any other require's are run, but may be updated later.
*
* Note: Although dimensions are available immediately, they may change (e.g
* due to device rotation) so any rendering logic or styles that depend on
* these constants should try to call this function on every render, rather
* than caching the value (for example, using inline styles rather than
* setting a value in a `StyleSheet`).
*
* @param {string} dim Name of dimension as defined when calling `set`.
* @returns {Object?} Value for the dimension.
*/
static get(dim) {
invariant(dimensions[dim], 'No dimension set for key ' + dim);
return dimensions[dim];
}
}
module.exports = Dimensions;
|
Update format placeholder to be 2.6 compatible | import pytest
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue import detail_object
@pytest.mark.parametrize('input,expected', [
(1, '1.html'),
(2, '2.html'),
(201, '201.html'),
])
def test_detail_url(input, expected):
epic_object = mock.Mock(epic_id=input)
url_root = 'http://deneb.astro.warwick.ac.uk/phrlbj/k2varcat/objects/{0}'
assert detail_object.DetailObject(epic_object).url == url_root.format(
expected)
def test_open_detail_url():
epic_object = mock.Mock(epic_id=1)
with mock.patch('k2catalogue.detail_object.webbrowser.open') as mock_open:
detail_object.DetailObject(epic_object).open()
mock_open.assert_called_once_with(
'http://deneb.astro.warwick.ac.uk/phrlbj/k2varcat/objects/1.html')
def test_epic_id():
epic_object = mock.Mock(epic_id=1)
assert detail_object.DetailObject(epic_object).epic_id == 1
| import pytest
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue import detail_object
@pytest.mark.parametrize('input,expected', [
(1, '1.html'),
(2, '2.html'),
(201, '201.html'),
])
def test_detail_url(input, expected):
epic_object = mock.Mock(epic_id=input)
url_root = 'http://deneb.astro.warwick.ac.uk/phrlbj/k2varcat/objects/{}'
assert detail_object.DetailObject(epic_object).url == url_root.format(
expected)
def test_open_detail_url():
epic_object = mock.Mock(epic_id=1)
with mock.patch('k2catalogue.detail_object.webbrowser.open') as mock_open:
detail_object.DetailObject(epic_object).open()
mock_open.assert_called_once_with(
'http://deneb.astro.warwick.ac.uk/phrlbj/k2varcat/objects/1.html')
def test_epic_id():
epic_object = mock.Mock(epic_id=1)
assert detail_object.DetailObject(epic_object).epic_id == 1
|
Fix for when views/partials/ doesn't exist. | var fs = require('fs'),
hbs = require('hbs');
module.exports = function(hbs) {
var blocks = {};
hbs.registerHelper('extend', function(name, context) {
var block = blocks[name];
if (!block) {
block = blocks[name] = [];
}
block.push(context.fn(this));
});
hbs.registerHelper('block', function(name) {
var val = (blocks[name] || []).join('\n');
// clear the block
blocks[name] = [];
return val;
});
};
// Register any partials
var partialsDir = __dirname + '/views/partials';
if (fs.existsSync(partialsDir)) {
fs.readdirSync(partialsDir).forEach(function(filename) {
var partial = filename.slice(0, -4);
hbs.registerPartial(partial, fs.readFileSync(__dirname + '/views/partials/' + filename).toString());
});;
}
| var fs = require('fs'),
hbs = require('hbs');
module.exports = function(hbs) {
var blocks = {};
hbs.registerHelper('extend', function(name, context) {
var block = blocks[name];
if (!block) {
block = blocks[name] = [];
}
block.push(context.fn(this));
});
hbs.registerHelper('block', function(name) {
var val = (blocks[name] || []).join('\n');
// clear the block
blocks[name] = [];
return val;
});
}
// Register all the partials
fs.readdirSync(__dirname + '/views/partials').forEach(function(filename) {
var partial = filename.slice(0, -4);
hbs.registerPartial(partial, fs.readFileSync(__dirname + '/views/partials/' + filename).toString());
});;
|
Add null protection for loan records.
Intermittent issue with null loan records being logged. | package bestcoders.library.services.helpers;
import java.util.stream.Stream;
import bestcoders.library.Library;
import bestcoders.library.loans.LoanRecord;
import bestcoders.library.loans.LoanState;
import bestcoders.library.members.LibraryMember;
public class LibraryStreams {
private final Library library;
public LibraryStreams(final Library library) {
this.library = library;
}
public Stream<LoanRecord> getLoansForMember(final Stream<LoanRecord> s, final LibraryMember m) {
return s.filter(lr -> lr != null && lr.getMember().equals(m));
}
Stream<LoanRecord> getLoansStream() {
return library.getLoans().stream();
}
public Stream<LoanRecord> getOpenLoansStream() {
return getLoansStream().filter(lr -> lr != null && lr.getState() == LoanState.OPEN);
}
}
| package bestcoders.library.services.helpers;
import java.util.stream.Stream;
import bestcoders.library.Library;
import bestcoders.library.loans.LoanRecord;
import bestcoders.library.loans.LoanState;
import bestcoders.library.members.LibraryMember;
public class LibraryStreams {
private final Library library;
public LibraryStreams(final Library library) {
this.library = library;
}
public Stream<LoanRecord> getLoansForMember(final Stream<LoanRecord> s, final LibraryMember m) {
return s.filter(lr -> lr.getMember().equals(m));
}
Stream<LoanRecord> getLoansStream() {
return library.getLoans().stream();
}
public Stream<LoanRecord> getOpenLoansStream() {
return getLoansStream().filter(lr -> lr.getState() == LoanState.OPEN);
}
}
|
Implement a test for environment.datetime_format | # -*- coding: utf-8 -*-
import pytest
from freezegun import freeze_time
from jinja2 import Environment, exceptions
@pytest.fixture
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
@pytest.yield_fixture(autouse=True)
def freeze():
freezer = freeze_time("2015-12-09 23:33:01")
freezer.start()
yield
freezer.stop()
def test_tz_is_required(environment):
with pytest.raises(exceptions.TemplateSyntaxError):
environment.from_string('{% now %}')
def test_utc_default_datetime_format(environment):
template = environment.from_string("{% now 'utc' %}")
assert template.render() == "2015-12-09"
@pytest.fixture(params=['utc', 'local', 'Europe/Berlin'])
def valid_tz(request):
return request.param
def test_accept_valid_timezones(environment, valid_tz):
template = environment.from_string(
"{% now '" + valid_tz + "', '%Y-%m' %}"
)
assert template.render() == '2015-12'
def test_environment_datetime_format(environment):
environment.datetime_format = '%a, %d %b %Y %H:%M:%S'
template = environment.from_string("{% now 'utc' %}")
assert template.render() == "Wed, 09 Dec 2015 23:33:01"
| # -*- coding: utf-8 -*-
import pytest
from freezegun import freeze_time
from jinja2 import Environment, exceptions
@pytest.fixture(scope='session')
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
@pytest.yield_fixture(autouse=True)
def freeze():
freezer = freeze_time("2015-12-09 23:33:01")
freezer.start()
yield
freezer.stop()
def test_tz_is_required(environment):
with pytest.raises(exceptions.TemplateSyntaxError):
environment.from_string('{% now %}')
def test_utc_default_datetime_format(environment):
template = environment.from_string("{% now 'utc' %}")
assert template.render() == "2015-12-09"
@pytest.fixture(params=['utc', 'local', 'Europe/Berlin'])
def valid_tz(request):
return request.param
def test_accept_valid_timezones(environment, valid_tz):
template = environment.from_string(
"{% now '" + valid_tz + "', '%Y-%m' %}"
)
assert template.render() == '2015-12'
|
Use new multiple cmd contexts | var coffeeScript = require("coffee-script");
var commands = codebox.require("core/commands");
var File = codebox.require("models/file");
commands.register({
id: "coffeescript.preview",
title: "CoffeeScript: Preview",
context: ["editor"],
shortcuts: [
"ctrl+shift+c"
],
run: function(args, ctx) {
var name = ctx.editor.model.get("name").replace(ctx.editor.model.getExtension(), ".js");
var code, error;
try {
code = coffeeScript.compile(ctx.editor.getContent());
} catch (e) {
error = e;
code = e.toString();
name = "Error at compilation";
}
var f = File.buffer(name, code);
return commands.run("file.open", {
file: f
})
.then(function() {
if (error) throw error;
});
}
});
| var coffeeScript = require("coffee-script");
var commands = codebox.require("core/commands");
var File = codebox.require("models/file");
commands.register({
id: "coffeescript.preview",
title: "CoffeeScript: Preview",
context: ["editor"],
shortcuts: [
"ctrl+shift+c"
],
run: function(args, context) {
var name = context.model.get("name").replace(context.model.getExtension(), ".js");
var code, error;
try {
code = coffeeScript.compile(context.getContent());
} catch (e) {
error = e;
code = e.toString();
name = "Error at compilation";
}
var f = File.buffer(name, code);
return commands.run("file.open", {
file: f
})
.then(function() {
if (error) throw error;
});
}
});
|
Allow autocomplete on non-persisted swift files | from .dependencies import dependencies
dependencies.load()
import sublime, sublime_plugin
from sublime import Region
import subl_source_kitten
# Sublime Text will will call `on_query_completions` itself
class SublCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
offset = locations[0]
file = view.file_name()
if file != None and not file.endswith(".swift"):
return None
project_directory = view.window().folders()[0]
text = view.substr(Region(0, view.size()))
suggestions = subl_source_kitten.complete(offset, file, project_directory, text)
return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
| from .dependencies import dependencies
dependencies.load()
import sublime, sublime_plugin
from sublime import Region
import subl_source_kitten
# Sublime Text will will call `on_query_completions` itself
class SublCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
offset = locations[0]
file = view.file_name()
if not file.endswith(".swift"):
return None
project_directory = view.window().folders()[0]
text = view.substr(Region(0, view.size()))
suggestions = subl_source_kitten.complete(offset, file, project_directory, text)
return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
|
Check to see if session data is expired
Then flush and redirect home | <?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Session;
use Log;
use App\Services\LevelUpApi;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected function LevelUpSetup()
{
$levelup_authentication = Session::get('levelup_authentication');
$levelup_hashcode = Session::get('levelup_hashcode');
if(empty($levelup_authentication) || empty($levelup_hashcode)){
Session::flush();
Session::flash('flash_error', 'Your session has expired');
\Redirect::to('/')->send();;
}
$levelupapi = new LevelUpApi;
$levelupapi->set_token($levelup_authentication->token);
$levelupapi->set_hashcode($levelup_hashcode);
return $levelupapi;
}
}
| <?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Session;
use Log;
use App\Services\LevelUpApi;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected function LevelUpSetup()
{
$levelup_authentication = Session::get('levelup_authentication');
$levelup_hashcode = Session::get('levelup_hashcode');
if(empty($levelup_authentication) || empty($levelup_hashcode)){
//TODO: rewrite
dd($levelup_hashcode);
}
$levelupapi = new LevelUpApi;
$levelupapi->set_token($levelup_authentication->token);
$levelupapi->set_hashcode($levelup_hashcode);
return $levelupapi;
}
}
|
Add another false positive test case
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@6399 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3 | package npe;
public class GuaranteedDereferenceInteractionWithAssertionMethods {
public Object x;
public boolean b;
public int falsePositive() {
if (x == null)
System.out.println("x is null");
if (b) {
x = bar();
checkForError();
}
return x.hashCode();
}
int falsePositive2(Object x) {
if (x == null)
reportError();
return x.hashCode();
}
public void checkForError() {
}
public void reportError() {
}
public Object bar() {
return new Object();
}
public int report(Object x, Object y, Object z) {
if (x == null && y == null)
reportError();
if (z == null)
z = new Object();
return x.hashCode() + z.hashCode();
}
public int report2(Object x, Object y, Object z) {
if (x == null && y == null)
reportError();
if (z == null)
z = new Object();
int result = x.hashCode() + z.hashCode();
checkForError();
return result;
}
}
| package npe;
public class GuaranteedDereferenceInteractionWithAssertionMethods {
public Object x;
public boolean b;
public int falsePositive() {
if (x == null)
System.out.println("x is null");
if (b) {
x = bar();
checkForError();
}
return x.hashCode();
}
public void checkForError() {
}
public void reportError() {
}
public Object bar() {
return new Object();
}
public int report(Object x, Object y, Object z) {
if (x == null && y == null)
reportError();
if (z == null)
z = new Object();
return x.hashCode() + z.hashCode();
}
public int report2(Object x, Object y, Object z) {
if (x == null && y == null)
reportError();
if (z == null)
z = new Object();
int result = x.hashCode() + z.hashCode();
checkForError();
return result;
}
}
|
Add method to get css and jss files for deploy | <?
function cssTags(){
global $config, $css_files;
$css_tags = '';
if($config['env'] == 'prod'){
$css_tags = '<link rel="stylesheet" type="text/css" href="'.$config['address'].'/assets/css/master'.$deploy_id.'.css" media="screen">';
}else{
foreach($css_files as $css_file) {
$css_tags = $css_tags.'<link rel="stylesheet" type="text/css" href="'.$config['address'].'/assets/css/'.$css_file.'.css" media="screen">'."\n";
}
}
return $css_tags;
}
function cssTagsForDeploy(){
global $config, $css_files;
foreach($css_files as $css_file) {
$css_tags = $css_tags.$css_file.'.css ';
}
echo $css_tags;
}
function jsTags(){
global $config, $js_files;
$js_tags = '';
if($config['env'] == 'prod'){
$js_tags = '<script type="text/javascript" src="'.$config['address'].'/assets/js/master'.$deploy_id.'.js"></script>';
}else{
foreach($js_files as $js_file) {
$js_tags = $js_tags.'<script type="text/javascript" src="'.$config['address'].'/assets/js/'.$js_file.'.js"></script>'."\n";
}
}
return $js_tags;
}
function jsTagsForDeploy(){
global $config, $js_files;
foreach($js_files as $js_file) {
$js_tags = $js_tags.$js_file.'.js ';
}
echo $js_tags;
}
?> | <?
function cssTags(){
global $config, $css_files;
$css_tags = '';
if($config['env'] == 'prod'){
$css_tags = '<link rel="stylesheet" type="text/css" href="'.$config['address'].'/assets/css/master'.$deploy_id.'.css" media="screen">';
}else{
foreach($css_files as $css_file) {
$css_tags = $css_tags.'<link rel="stylesheet" type="text/css" href="'.$config['address'].'/assets/css/'.$css_file.'.css" media="screen">'."\n";
}
}
return $css_tags;
}
function jsTags(){
global $config, $js_files;
$js_tags = '';
if($config['env'] == 'prod'){
$js_tags = '<script type="text/javascript" src="'.$config['address'].'/assets/js/master'.$deploy_id.'.js"></script>';
}else{
foreach($js_files as $js_file) {
$js_tags = $js_tags.'<script type="text/javascript" src="'.$config['address'].'/assets/js/'.$js_file.'.js"></script>'."\n";
}
}
return $js_tags;
}
?> |
runtime-field: Make it possible to convert a getter into a function | /**
*
* Copyright (c) 2006-2016, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.runtime.field.method;
import java.util.function.Function;
/**
*
* @param <ENTITY> the entity type
*
* @author Emil Forslund
* @since 3.0.0
*/
public interface Getter<ENTITY> {
/**
* A generic (untyped) get method.
*
* @param entity the entity to get from
* @return the value
*/
Object apply(ENTITY entity);
/**
* Returns this object, typed as a {@code Function} method.
*
* @return this object as a function
*/
default Function<ENTITY, Object> asFunction() {
return this::apply;
}
} | /**
*
* Copyright (c) 2006-2016, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.runtime.field.method;
/**
*
* @param <ENTITY> the entity type
*
* @author Emil Forslund
* @since 3.0.0
*/
public interface Getter<ENTITY> {
/**
* A generic (untyped) get method.
*
* @param entity the entity to get from
* @return the value
*/
Object apply(ENTITY entity);
} |
Fix grammar in front controller comment. | <?php
// Path to the front controller (this file)
define('FCPATH', __DIR__.DIRECTORY_SEPARATOR);
// Location of the Paths config file.
// This is the first of two lines that might need to be changed, depending on your folder structure.
$pathsPath = FCPATH . '../application/Config/Paths.php';
/*
*---------------------------------------------------------------
* BOOTSTRAP THE APPLICATION
*---------------------------------------------------------------
* This process sets up the path constants, loads and registers
* our autoloader, along with Composer's, loads our constants
* and fires up an environment-specific bootstrapping.
*/
// Ensure the current directory is pointing to the front controller's directory
chdir(__DIR__);
// Load our paths config file
require $pathsPath;
$paths = new Config\Paths();
// Location of the framework bootstrap file.
// This is the second of two lines that might need to be changed, depending on your folder structure.
$app = require FCPATH . '../system/bootstrap.php';
/*
*---------------------------------------------------------------
* LAUNCH THE APPLICATION
*---------------------------------------------------------------
* Now that everything is setup, it's time to actually fire
* up the engines and make this app do its thang.
*/
$app->run();
| <?php
// Path to the front controller (this file)
define('FCPATH', __DIR__.DIRECTORY_SEPARATOR);
// Location of the Paths config file.
// This is the first of two lines that might need to be changed, depending on your folder structure.
$pathsPath = FCPATH . '../application/Config/Paths.php';
/*
*---------------------------------------------------------------
* BOOTSTRAP THE APPLICATION
*---------------------------------------------------------------
* This process sets up the path constants, loads and registers
* our autoloader, along with Composer's, loads our constants
* and fires up an environment-specific bootstrapping.
*/
// Ensure the current directory is pointing to the front controller's directory
chdir(__DIR__);
// Load our paths config file
require $pathsPath;
$paths = new Config\Paths();
// Location of the framework bootstrap file.
// This is the second of two lines that might need to be changed, depending on your folder structure.
$app = require FCPATH . '../system/bootstrap.php';
/*
*---------------------------------------------------------------
* LAUNCH THE APPLICATION
*---------------------------------------------------------------
* Now that everything is setup, it's time to actually fire
* up the engines and make this app do it's thang.
*/
$app->run();
|
Add a new generic AWS Error exception | """
The following exceptions may be raised during the course of using
:py:class:`tornado_aws.client.AWSClient` and
:py:class:`tornado_aws.client.AsyncAWSClient`:
"""
class AWSClientException(Exception):
"""Base exception class for AWSClient
:ivar msg: The error message
"""
fmt = 'An error occurred'
def __init__(self, **kwargs):
super(AWSClientException, self).__init__(self.fmt.format(**kwargs))
class AWSError(AWSClientException):
"""Raised when the credentials could not be located."""
fmt = '{message}'
class ConfigNotFound(AWSClientException):
"""The configuration file could not be parsed.
:ivar path: The path to the config file
"""
fmt = 'The config file could not be found ({path})'
class ConfigParserError(AWSClientException):
"""Error raised when parsing a configuration file with
:py:class`configparser.RawConfigParser`
:ivar path: The path to the config file
"""
fmt = 'Unable to parse config file ({path})'
class NoCredentialsError(AWSClientException):
"""Raised when the credentials could not be located."""
fmt = 'Credentials not found'
class NoProfileError(AWSClientException):
"""Raised when the specified profile could not be located.
:ivar path: The path to the config file
:ivar profile: The profile that was specified
"""
fmt = 'Profile ({profile}) not found ({path})'
| """
The following exceptions may be raised during the course of using
:py:class:`tornado_aws.client.AWSClient` and
:py:class:`tornado_aws.client.AsyncAWSClient`:
"""
class AWSClientException(Exception):
"""Base exception class for AWSClient
:ivar msg: The error message
"""
fmt = 'An error occurred'
def __init__(self, **kwargs):
super(AWSClientException, self).__init__(self.fmt.format(**kwargs))
class ConfigNotFound(AWSClientException):
"""The configuration file could not be parsed.
:ivar path: The path to the config file
"""
fmt = 'The config file could not be found ({path})'
class ConfigParserError(AWSClientException):
"""Error raised when parsing a configuration file with
:py:class`configparser.RawConfigParser`
:ivar path: The path to the config file
"""
fmt = 'Unable to parse config file ({path})'
class NoCredentialsError(AWSClientException):
"""Raised when the credentials could not be located."""
fmt = 'Credentials not found'
class NoProfileError(AWSClientException):
"""Raised when the specified profile could not be located.
:ivar path: The path to the config file
:ivar profile: The profile that was specified
"""
fmt = 'Profile ({profile}) not found ({path})'
|
Add tests for search interface plugins | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from flexget import plugin
class TestInterfaces(object):
"""Test that any plugins declaring certain interfaces at least superficially comply with those interfaces."""
def get_plugins(self, interface):
plugins = list(plugin.get_plugins(interface=interface))
assert plugins, 'No plugins for this interface found.'
return plugins
def test_task_interface(self):
for p in self.get_plugins('task'):
assert isinstance(p.schema, dict), 'Task interface requires a schema to be defined.'
assert p.phase_handlers, 'Task plugins should have at least on phase handler (on_task_X) method.'
def test_list_interface(self):
for p in self.get_plugins('list'):
assert isinstance(p.schema, dict), 'List interface requires a schema to be defined.'
assert hasattr(p.instance, 'get_list'), 'List plugins must implement a get_list method.'
def test_search_interface(self):
for p in self.get_plugins('search'):
assert isinstance(p.schema, dict), 'Search interface requires a schema to be defined.'
assert hasattr(p.instance, 'search'), 'Search plugins must implement a search method.'
| from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from flexget import plugin
class TestInterfaces(object):
"""Test that any plugins declaring certain interfaces at least superficially comply with those interfaces."""
def test_task_interface(self):
plugin.load_plugins()
task_plugins = plugin.get_plugins(interface='task')
for p in task_plugins:
assert isinstance(p.schema, dict), 'Task interface requires a schema to be defined.'
assert p.phase_handlers, 'Task plugins should have at least on phase handler (on_task_X) method.'
def test_list_interface(self):
plugin.load_plugins()
task_plugins = plugin.get_plugins(interface='list')
for p in task_plugins:
assert isinstance(p.schema, dict), 'List interface requires a schema to be defined.'
assert hasattr(p.instance, 'get_list'), 'List plugins must implement a get_list method.'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.