text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Add NetBandwith & CPUUsage in Container struct | package dockerguard
type DockerInfo struct {
// Infos from docker api /version
APIVersion string `json:"ApiVersion"`
Arch string `json:"Arch"`
Experimental bool `json:"Experimental"`
GitCommit string `json:"GitCommit"`
GoVersion string `json:"GoVersion"`
KernelVersion string `json:"KernelVersion"`
Os string `json:"Os"`
Version string `json:"Version"`
// Infos from docker api /info
ID string `json:"ID"`
Name string `json:"Name"`
Containers int `json:"Containers"`
Images int `json:"Images"`
Driver string `json:"Driver"`
SystemTime string `json:"SystemTime"`
OperatingSystem string `json:"OperatingSystem"`
NCPU int `json:"NCPU"`
MemTotal int `json:"MemTotal"`
}
type Container struct {
ID string `json:"Id"`
Hostname string `json:"Hostname"`
Image string `json:"Image"`
IPAddress string `json:"IPAddress"`
MacAddress string `json:"MacAddress"`
SizeRootFs float64 `json:"SizeRootFs"`
SizeRw float64 `json:"SizeRw"`
MemoryUsed float64 `json:"MemoryUsed"`
NetBandwith float64 `json:"NetBandwith"`
CPUUsage float64 `json:"CPUUsage"`
Running bool `json:"Running"`
Time float64 `json:"Time"`
}
| package dockerguard
type DockerInfo struct {
// Infos from docker api /version
APIVersion string `json:"ApiVersion"`
Arch string `json:"Arch"`
Experimental bool `json:"Experimental"`
GitCommit string `json:"GitCommit"`
GoVersion string `json:"GoVersion"`
KernelVersion string `json:"KernelVersion"`
Os string `json:"Os"`
Version string `json:"Version"`
// Infos from docker api /info
ID string `json:"ID"`
Name string `json:"Name"`
Containers int `json:"Containers"`
Images int `json:"Images"`
Driver string `json:"Driver"`
SystemTime string `json:"SystemTime"`
OperatingSystem string `json:"OperatingSystem"`
NCPU int `json:"NCPU"`
MemTotal int `json:"MemTotal"`
}
type Container struct {
ID string `json:"Id"`
Hostname string `json:"Hostname"`
Image string `json:"Image"`
IPAddress string `json:"IPAddress"`
MacAddress string `json:"MacAddress"`
SizeRootFs float64 `json:"SizeRootFs"`
SizeRw float64 `json:"SizeRw"`
MemoryUsed float64 `json:"MemoryUsed"`
Running bool `json:"Running"`
Time float64 `json:"Time"`
}
|
Clear command default answer changed to no | <?php
/*
* This file is part of the Subway package.
*
* (c) Eymen Gunay <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Subway\Command;
use Subway\Factory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Clear command
*/
class ClearCommand extends RedisAwareCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('clear')
->setDescription('Clear subway database')
;
parent::configure();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($input->getOption('no-interaction') === false) {
$dialog = $this->getHelperSet()->get('dialog');
if (!$dialog->askConfirmation(
$output,
'<question>This action will erase entire subway database. Are you sure you want to continue? (y/N)</question>',
false
)) {
return $output->writeln('<comment>Command aborted by user</comment>');
}
}
$factory = new Factory($this->redis);
$factory->clear();
$output->writeln('<info>Database cleared successfully</info>');
}
}
| <?php
/*
* This file is part of the Subway package.
*
* (c) Eymen Gunay <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Subway\Command;
use Subway\Factory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Clear command
*/
class ClearCommand extends RedisAwareCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('clear')
->setDescription('Clear subway database')
;
parent::configure();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($input->getOption('no-interaction') === false) {
$dialog = $this->getHelperSet()->get('dialog');
if (!$dialog->askConfirmation(
$output,
'<question>This action will erase entire subway database. Are you sure you want to continue? (Y/n)</question>',
true
)) {
return;
}
}
$factory = new Factory($this->redis);
$factory->clear();
$output->writeln('<info>Database cleared successfully</info>');
}
}
|
Add stopwatch as auth protected route | import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Switch
} from 'react-router-dom';
import MonthDetail from './components/pages/History/MonthDetail';
import HomePage from './components/pages/Home';
import SignupPage from './components/pages/Signup';
import LoginPage from './components/pages/Login';
import StopWatchPage from './components/pages/StopWatch';
import HistoryPage from './components/pages/History';
import PrivateRoute from './components/PrivateRoute';
import NotFoundPage from './components/NotFoundPage';
import NavBar from './components/NavBar';
import './styles.css';
class App extends Component {
render () {
return (
<Router>
<div>
<NavBar />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/signup" component={SignupPage} />
<Route path="/login" component={LoginPage} />
<PrivateRoute path="/stopwatch" component={StopWatchPage} />
<PrivateRoute exact path="/history" component={HistoryPage} />
<PrivateRoute path="/history/:month" component={MonthDetail} />
<Route component={NotFoundPage} />
</Switch>
</div>
</Router>
);
}
}
export default App;
| import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Switch
} from 'react-router-dom';
import MonthDetail from './components/pages/History/MonthDetail';
import HomePage from './components/pages/Home';
import SignupPage from './components/pages/Signup';
import LoginPage from './components/pages/Login';
import StopWatchPage from './components/pages/StopWatch';
import HistoryPage from './components/pages/History';
import PrivateRoute from './components/PrivateRoute';
import NotFoundPage from './components/NotFoundPage';
import NavBar from './components/NavBar';
import './styles.css';
class App extends Component {
render () {
return (
<Router>
<div>
<NavBar />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/signup" component={SignupPage} />
<Route path="/login" component={LoginPage} />
<Route path="/stopwatch" component={StopWatchPage} />
<PrivateRoute exact path="/history" component={HistoryPage} />
<PrivateRoute path="/history/:month" component={MonthDetail} />
<Route component={NotFoundPage} />
</Switch>
</div>
</Router>
);
}
}
export default App;
|
Print out errors to log. | #!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError(RuntimeError):
def __init__(self, string=''):
# Get the username
try:
from getpass import getuser
username = getuser()
except Exception:
username = 'Dave'
# Put in HAL error text.
text = 'I\'m sorry {0}. I\'m afraid I can\'t do that. {1}'.format(
username, string)
# Init base class
RuntimeError.__init__(self, text)
def halraiser(e):
''' Function to re-raise an exception with a Hal message. '''
import logging
# Get the log and write the error to the log file
log = logging.getLogger(__name__)
log.error(e)
# Get the username
try:
from getpass import getuser
username = getuser()
except Exception:
username = 'Humanoid'
# Put in HAL error text.
text = 'I\'m sorry {0}. I\'m afraid I can\'t do that.'.format(username)
# Append to exception
if len(e.args) == 0:
e.args = (text,)
elif len(e.args) == 1:
e.args = (text + ' ' + e.args[0],)
else:
e.args = (text,) + e.args
# Reraise the exception
raise
| #!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError(RuntimeError):
def __init__(self, string=''):
# Get the username
try:
from getpass import getuser
username = getuser()
except Exception:
username = 'Dave'
# Put in HAL error text.
text = 'I\'m sorry {0}. I\'m afraid I can\'t do that. {1}'.format(
username, string)
# Init base class
RuntimeError.__init__(self, text)
def halraiser(e):
''' Function to re-raise an exception with a Hal message. '''
# Get the username
try:
from getpass import getuser
username = getuser()
except Exception:
username = 'Humanoid'
# Put in HAL error text.
text = 'I\'m sorry {0}. I\'m afraid I can\'t do that.'.format(username)
# Append to exception
if len(e.args) == 0:
e.args = (text,)
elif len(e.args) == 1:
e.args = (text + ' ' + e.args[0],)
else:
e.args = (text,) + e.args
# Reraise the exception
raise
|
Fix try-except-finally statement for python 2.4 support | # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.log = logging.getLogger('diamond')
# Initialize Data
self.config = config
# Initialize Lock
self.lock = threading.Condition(threading.Lock())
def _process(self, metric):
"""
Decorator for processing handlers with a lock, catching exceptions
"""
try:
try:
self.log.debug("Running Handler %s locked" % (self))
self.lock.acquire()
self.process(metric)
self.lock.release()
except Exception:
self.log.error(traceback.format_exc())
finally:
self.lock.release()
self.log.debug("Unlocked Handler %s" % (self))
def process(self, metric):
"""
Process a metric
Should be overridden in subclasses
"""
raise NotImplementedError
def flush(self):
"""
Flush metrics
Optional: Should be overridden in subclasses
"""
pass
| # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.log = logging.getLogger('diamond')
# Initialize Data
self.config = config
# Initialize Lock
self.lock = threading.Condition(threading.Lock())
def _process(self, metric):
"""
Decorator for processing handlers with a lock, catching exceptions
"""
try:
self.log.debug("Running Handler %s locked" % (self))
self.lock.acquire()
self.process(metric)
self.lock.release()
except Exception:
self.log.error(traceback.format_exc())
finally:
self.lock.release()
self.log.debug("Unlocked Handler %s" % (self))
def process(self, metric):
"""
Process a metric
Should be overridden in subclasses
"""
raise NotImplementedError
def flush(self):
"""
Flush metrics
Optional: Should be overridden in subclasses
"""
pass
|
CRM-1648: Adjust EmailType form type to use email templates selector
- update unit tests | <?php
namespace Oro\Bundle\EmailBundle\Tests\Unit\Form\Model;
use Oro\Bundle\EmailBundle\Entity\EmailTemplate;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Oro\Bundle\EmailBundle\Form\Model\Email;
class EmailTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider propertiesDataProvider
* @param string $property
* @param mixed $value
*/
public function testSettersAndGetters($property, $value)
{
$obj = new Email();
$accessor = PropertyAccess::createPropertyAccessor();
$accessor->setValue($obj, $property, $value);
$this->assertEquals($value, $accessor->getValue($obj, $property));
}
public function propertiesDataProvider()
{
return [
['gridName', 'testGridName'],
['entityClass', 'testEntityClass'],
['entityId', 123],
['from', '[email protected]'],
['to', ['testGridName']],
['subject', 'testSubject'],
['body', 'testBody'],
['gridName', 'testGridName'],
['template', new EmailTemplate('test')],
];
}
public function testHasEntity()
{
$obj = new Email();
$this->assertFalse($obj->hasEntity());
$obj->setEntityClass('Test\Entity');
$this->assertFalse($obj->hasEntity());
$obj->setEntityId(123);
$this->assertTrue($obj->hasEntity());
$obj->setEntityClass(null);
$this->assertFalse($obj->hasEntity());
}
}
| <?php
namespace Oro\Bundle\EmailBundle\Tests\Unit\Form\Model;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Oro\Bundle\EmailBundle\Form\Model\Email;
class EmailTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider propertiesDataProvider
* @param string $property
* @param mixed $value
*/
public function testSettersAndGetters($property, $value)
{
$obj = new Email();
$accessor = PropertyAccess::createPropertyAccessor();
$accessor->setValue($obj, $property, $value);
$this->assertEquals($value, $accessor->getValue($obj, $property));
}
public function propertiesDataProvider()
{
return [
['gridName', 'testGridName'],
['entityClass', 'testEntityClass'],
['entityId', 123],
['from', '[email protected]'],
['to', ['testGridName']],
['subject', 'testSubject'],
['body', 'testBody'],
['gridName', 'testGridName'],
['gridName', 'testGridName'],
['gridName', 'testGridName'],
['gridName', 'testGridName'],
];
}
public function testHasEntity()
{
$obj = new Email();
$this->assertFalse($obj->hasEntity());
$obj->setEntityClass('Test\Entity');
$this->assertFalse($obj->hasEntity());
$obj->setEntityId(123);
$this->assertTrue($obj->hasEntity());
$obj->setEntityClass(null);
$this->assertFalse($obj->hasEntity());
}
}
|
Fix LIST command crashing (again) on certain input | from twisted.words.protocols import irc
from txircd.modbase import Mode
class SecretMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "NAMES":
return data
remove = []
for chan in data["targetchan"]:
if "s" in chan.mode and chan.name not in user.channels:
user.sendMessage(irc.ERR_NOSUCHNICK, chan, ":No such nick/channel")
remove.append(chan)
for chan in remove:
data["targetchan"].remove(chan)
return data
def listOutput(self, command, data):
if command != "LIST":
return data
if "cdata" not in data:
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"].clear()
# other +s stuff is hiding in other modules.
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_s = None
def spawn(self):
self.mode_s = SecretMode()
return {
"modes": {
"cns": self.mode_s
},
"actions": {
"commandextra": [self.mode_s.listOutput]
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cns")
self.ircd.actions["commandextra"].remove(self.mode_s.listOutput) | from twisted.words.protocols import irc
from txircd.modbase import Mode
class SecretMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "NAMES":
return data
remove = []
for chan in data["targetchan"]:
if "s" in chan.mode and chan.name not in user.channels:
user.sendMessage(irc.ERR_NOSUCHNICK, chan, ":No such nick/channel")
remove.append(chan)
for chan in remove:
data["targetchan"].remove(chan)
return data
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"].clear()
# other +s stuff is hiding in other modules.
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_s = None
def spawn(self):
self.mode_s = SecretMode()
return {
"modes": {
"cns": self.mode_s
},
"actions": {
"commandextra": [self.mode_s.listOutput]
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cns")
self.ircd.actions["commandextra"].remove(self.mode_s.listOutput) |
Fix directory creation by view assistant creator | <?php
namespace Knp\RadBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
class AssistantController extends Controller
{
public function missingViewAction($viewName, $viewParams)
{
$viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);
$viewBody = $this->renderView(
'KnpRadBundle:Assistant:_viewBody.twig.twig',
array(
'viewParams' => $viewParams
)
);
return $this->render(
'KnpRadBundle:Assistant:missingView.html.twig',
array(
'viewName' => $viewName,
'viewBody' => $viewBody,
'viewParams' => $viewParams,
'viewPath' => $viewPath,
)
);
}
public function createViewAction(Request $request)
{
$viewName = $request->request->get('viewName');
$viewBody = $request->request->get('viewBody');
$viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);
// in case directory does not exist
$this->get('filesystem')->mkdir(dirname($viewPath));
file_put_contents($viewPath, $viewBody);
return new Response(null, 201);
}
}
| <?php
namespace Knp\RadBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
class AssistantController extends Controller
{
public function missingViewAction($viewName, $viewParams)
{
$viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);
$viewBody = $this->renderView(
'KnpRadBundle:Assistant:_viewBody.twig.twig',
array(
'viewParams' => $viewParams
)
);
return $this->render(
'KnpRadBundle:Assistant:missingView.html.twig',
array(
'viewName' => $viewName,
'viewBody' => $viewBody,
'viewParams' => $viewParams,
'viewPath' => $viewPath,
)
);
}
public function createViewAction(Request $request)
{
$viewName = $request->request->get('viewName');
$viewBody = $request->request->get('viewBody');
$viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);
// in case directory does not exist
$this->get('filesystem')->touch($viewPath);
file_put_contents($viewPath, $viewBody);
return new Response(null, 201);
}
}
|
Fix of loading chosen options on Lead timeline filter without need to refresh the page | <?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
?>
<!-- filter form -->
<form action="" class="panel" id="timeline-filters">
<div class="form-control-icon pa-xs">
<input type="text" class="form-control bdr-w-0" name="search" id="search" placeholder="<?php echo $view['translator']->trans('mautic.core.search.placeholder'); ?>">
<span class="the-icon fa fa-search text-muted mt-xs"></span>
<?php if (isset($eventTypes) && is_array($eventTypes)) : ?>
<select name="eventFilters[]" multiple="multiple" class="form-control bdr-w-0" data-placeholder="<?php echo $view['translator']->trans('mautic.lead.lead.filter.bundles.placeholder'); ?>">
<?php foreach ($eventTypes as $typeKey => $typeName) : ?>
<option value="<?php echo $typeKey; ?>"<?php echo in_array($typeKey, $eventFilter) ? ' selected' : ''; ?> >
<?php echo $typeName; ?>
</option>
<?php endforeach; ?>
</select>
<?php endif; ?>
</div>
<input type="hidden" name="leadId" id="leadId" value="<?php echo $lead->getId(); ?>" />
</form>
<!--/ filter form -->
| <?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
?>
<!-- filter form -->
<form action="" class="panel" id="timeline-filters">
<div class="form-control-icon pa-xs">
<input type="text" class="form-control bdr-w-0" name="search" id="search" placeholder="<?php echo $view['translator']->trans('mautic.core.search.placeholder'); ?>">
<span class="the-icon fa fa-search text-muted mt-xs"></span>
<?php if (isset($eventTypes) && is_array($eventTypes)) : ?>
<select name="eventFilters[]" multiple class="form-control bdr-w-0" data-placeholder="<?php echo $view['translator']->trans('mautic.lead.lead.filter.bundles.placeholder'); ?>">
<?php foreach ($eventTypes as $typeKey => $typeName) : ?>
<option value="<?php echo $typeKey; ?>"<?php echo in_array($typeKey, $eventFilter) ? ' selected' : ''; ?> />
<?php echo $typeName; ?>
</option>
<?php endforeach; ?>
</select>
<?php endif; ?>
</div>
<input type="hidden" name="leadId" id="leadId" value="<?php echo $lead->getId(); ?>" />
</form>
<!--/ filter form -->
|
Add valueAttr to the application module | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.dataSource = this.model.get('data-source');
options.dataSource['query-params'] = _.extend({flatten:true}, options.dataSource['query-params']);
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
valueAttr: this.model.get('value-attribute'),
maxBars: this.model.get('max-bars'),
target: this.model.get('target'),
pinTo: this.model.get('pin-to')
};
}
};
}); | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.dataSource = this.model.get('data-source');
options.dataSource['query-params'] = _.extend({flatten:true}, options.dataSource['query-params']);
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
maxBars: this.model.get('max-bars'),
target: this.model.get('target'),
pinTo: this.model.get('pin-to')
};
}
};
}); |
Mark runserver as a plumbing command | """Command-line utilities for HTTP service subsystem."""
import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(BaseCommand):
"""
Run a debug server.
**This is for debug, local use only, not production.**
This command is named to mirror its equivalent in Django. It configures
the WSGI app and serves it through Werkzeug's simple serving mechanism,
with a debugger attached, and auto-reloading.
"""
plumbing = True
help = "run a (local, debug) server"
def add_arguments(self, parser):
"""Add argparse arguments."""
parser.add_argument(
'-p',
'--port',
type=int,
default=1212,
help="port to bind to",
)
parser.add_argument(
'-b',
'--bind',
type=str,
default='::1',
help="address to bind to",
)
def handle(self, config, options):
"""Run command."""
app = get_wsgi_app(config)
werkzeug.serving.run_simple(
options.bind,
options.port,
app,
use_reloader=True,
use_debugger=True,
use_evalex=True,
threaded=False,
processes=1,
)
| """Command-line utilities for HTTP service subsystem."""
import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(BaseCommand):
"""
Run a debug server.
**This is for debug, local use only, not production.**
This command is named to mirror its equivalent in Django. It configures
the WSGI app and serves it through Werkzeug's simple serving mechanism,
with a debugger attached, and auto-reloading.
"""
help = "run a (local, debug) server"
def add_arguments(self, parser):
"""Add argparse arguments."""
parser.add_argument(
'-p',
'--port',
type=int,
default=1212,
help="port to bind to",
)
parser.add_argument(
'-b',
'--bind',
type=str,
default='::1',
help="address to bind to",
)
def handle(self, config, options):
"""Run command."""
app = get_wsgi_app(config)
werkzeug.serving.run_simple(
options.bind,
options.port,
app,
use_reloader=True,
use_debugger=True,
use_evalex=True,
threaded=False,
processes=1,
)
|
Change the constraints for dateTime class | package seedu.emeraldo.model.task;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
/**
* Represents a Task's date and time in Emeraldo.
* Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)}
*/
public class DateTime {
public static final String MESSAGE_ADDRESS_CONSTRAINTS = "Task date and time must follow this format YY/MM/DD HH:MM";
public static final String ADDRESS_VALIDATION_REGEX = "(.+)?";
public final String value;
/**
* Validates given date and time.
*
* @throws IllegalValueException if given address string is invalid.
*/
public DateTime(String dateTime) throws IllegalValueException {
assert dateTime != null;
if (!isValidDateTime(dateTime)) {
throw new IllegalValueException(MESSAGE_ADDRESS_CONSTRAINTS);
}
this.value = dateTime;
}
private static boolean isValidDateTime(String test) {
return test.matches(ADDRESS_VALIDATION_REGEX);
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof DateTime // instanceof handles nulls
&& this.value.equals(((DateTime) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
} | package seedu.emeraldo.model.task;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
/**
* Represents a Task's date and time in Emeraldo.
* Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)}
*/
public class DateTime {
public static final String MESSAGE_ADDRESS_CONSTRAINTS = "Task date and time can be in any format";
public static final String ADDRESS_VALIDATION_REGEX = "(.+)?";
public final String value;
/**
* Validates given date and time.
*
* @throws IllegalValueException if given address string is invalid.
*/
public DateTime(String dateTime) throws IllegalValueException {
assert dateTime != null;
if (!isValidDateTime(dateTime)) {
throw new IllegalValueException(MESSAGE_ADDRESS_CONSTRAINTS);
}
this.value = dateTime;
}
private static boolean isValidDateTime(String test) {
return test.matches(ADDRESS_VALIDATION_REGEX);
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof DateTime // instanceof handles nulls
&& this.value.equals(((DateTime) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
} |
Update jwtauth service provider @ fix namespace error. | <?php namespace JwtAuth;
use ReflectionClass;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
class JwtAuthServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
// Find path to the package
$componenentsFileName = with(new ReflectionClass('\JwtAuth\JwtAuthServiceProvider'))->getFileName();
$componenentsPath = dirname($componenentsFileName);
$this->loadViewsFrom($componenentsPath . '/../views', 'jwtauth');
// include $componenentsPath . '/../routes.php';
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->register(\Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);
$loader = AliasLoader::getInstance();
$loader->alias('JWTAuth', \Tymon\JWTAuth\Facades\JWTAuth::class);
$loader->alias('JWTFactory', \Tymon\JWTAuth\Facades\JWTFactory::class);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [];
}
}
| <?php namespace JwtAuth;
use Illuminate\Support\ServiceProvider;
class JwtAuthServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
// Find path to the package
$componenentsFileName = with(new ReflectionClass('\JwtAuth\JwtAuthServiceProvider'))->getFileName();
$componenentsPath = dirname($componenentsFileName);
$this->loadViewsFrom($componenentsPath . '/../views', 'jwtauth');
// include $componenentsPath . '/../routes.php';
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->register(\Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);
$loader = AliasLoader::getInstance();
$loader->alias('JWTAuth', \Tymon\JWTAuth\Facades\JWTAuth::class);
$loader->alias('JWTFactory', \Tymon\JWTAuth\Facades\JWTFactory::class);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [];
}
}
|
Remove any leading '*.' that may be present in the suffix list. | package org.bouncycastle.test.est.examples;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
class SuffixList
{
static Set<String> loadSuffixes(String file)
throws Exception
{
FileInputStream fin = new FileInputStream(file);
String line = null;
BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
ArrayList<String> suffixes = new ArrayList<String>();
while ((line = bin.readLine()) != null)
{
if (line.length() == 0 || (line.startsWith("//") && !line.startsWith("// xn--")))
{
continue;
}
if (line.startsWith("!"))
{
continue;
}
line = line.trim();
if (line.startsWith("// xn--"))
{
String[] j = line.split(" ");
suffixes.add(j[1]);
}
else
{
suffixes.add(line);
}
}
bin.close();
for (int t = 0; t < suffixes.size(); t++)
{
String j = suffixes.get(t);
if (j.startsWith("*.")) {
j = j.substring(2);
}
suffixes.set(t, j);
}
HashSet<String> set = new HashSet<String>();
for (String s : suffixes)
{
set.add(s);
}
return set;
}
}
| package org.bouncycastle.test.est.examples;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
class SuffixList
{
static Set<String> loadSuffixes(String file)
throws Exception
{
FileInputStream fin = new FileInputStream(file);
String line = null;
BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
ArrayList<String> suffixes = new ArrayList<String>();
while ((line = bin.readLine()) != null)
{
if (line.length() == 0 || (line.startsWith("//") && !line.startsWith("// xn--")))
{
continue;
}
if (line.startsWith("!"))
{
continue;
}
line = line.trim();
if (line.startsWith("// xn--"))
{
String[] j = line.split(" ");
suffixes.add(j[1]);
}
else
{
suffixes.add(line);
}
}
bin.close();
for (int t = 0; t < suffixes.size(); t++)
{
String j = suffixes.get(t);
if (!j.startsWith("*."))
{
j = "*." + j;
}
suffixes.set(t, j);
}
HashSet<String> set = new HashSet<String>();
for (String s : suffixes)
{
set.add(s);
}
return set;
}
}
|
Change module.exports to export default | import { isFunction } from 'lodash';
import { setHeader } from 'focus-core/application';
const cartridgeBehaviour = {
/**
* Updates the cartridge using the cartridgeConfiguration.
*/
_registerCartridge(props = this.props) {
const cartridgeConfiguration = this.cartridgeConfiguration || props.cartridgeConfiguration;
const hasCartridge = isFunction(cartridgeConfiguration);
if (!hasCartridge) {
console.warn(`
Your detail page does not have any cartrige configuration, this is not mandarory but recommended.
It should be a component attribute return by a function.
function cartridgeConfiguration(){
var cartridgeConfiguration = {
summary: {component: "A React Component", props: {id: this.props.id}},
cartridge: {component: "A React Component"},
actions: {components: "react actions"}
};
return cartridgeConfiguration;
}
`);
}
const config = hasCartridge ? cartridgeConfiguration() : {};
setHeader(config);
},
/**
* Registers the cartridge upon mounting.
*/
componentWillMount() {
this._registerCartridge();
},
componentWillReceiveProps(nextProps) {
this._registerCartridge(nextProps);
}
};
export default cartridgeBehaviour; | import { isFunction } from 'lodash';
import { setHeader } from 'focus-core/application';
module.exports = {
/**
* Updates the cartridge using the cartridgeConfiguration.
*/
_registerCartridge(props = this.props) {
const cartridgeConfiguration = this.cartridgeConfiguration || props.cartridgeConfiguration;
const hasCartridge = isFunction(cartridgeConfiguration);
if (!hasCartridge) {
console.warn(`
Your detail page does not have any cartrige configuration, this is not mandarory but recommended.
It should be a component attribute return by a function.
function cartridgeConfiguration(){
var cartridgeConfiguration = {
summary: {component: "A React Component", props: {id: this.props.id}},
cartridge: {component: "A React Component"},
actions: {components: "react actions"}
};
return cartridgeConfiguration;
}
`);
}
const config = hasCartridge ? cartridgeConfiguration() : {};
setHeader(config);
},
/**
* Registers the cartridge upon mounting.
*/
componentWillMount() {
this._registerCartridge();
},
componentWillReceiveProps(nextProps) {
this._registerCartridge(nextProps);
}
};
|
Make sure `multi` returns a promise | 'use strict';
var Pipeline = require('./pipeline');
var utils = require('./utils');
exports.addTransactionSupport = function (redis) {
redis.pipeline = function () {
var pipeline = new Pipeline(this);
return pipeline;
};
var multi = redis.multi;
redis.multi = function (options) {
if (options && options.pipeline === false) {
return multi.call(this);
}
var pipeline = new Pipeline(this);
pipeline.multi();
var exec = pipeline.exec;
pipeline.exec = function (callback) {
exec.call(pipeline);
var promise = exec.call(pipeline);
return promise.then(function (result) {
var execResult = result[result.length - 1];
if (execResult[0]) {
execResult[0].previousErrors = [];
for (var i = 0; i < result.length - 1; ++i) {
if (result[i][0]) {
execResult[0].previousErrors.push(result[i][0]);
}
}
throw execResult[0];
}
return utils.wrapMultiResult(execResult[1]);
}).nodeify(callback);
};
return pipeline;
};
var exec = redis.exec;
redis.exec = function (callback) {
var wrapper = function (err, results) {
if (Array.isArray(results)) {
results = utils.wrapMultiResult(results);
}
callback(err, results);
};
exec.call(this, wrapper);
};
};
| 'use strict';
var Pipeline = require('./pipeline');
var utils = require('./utils');
exports.addTransactionSupport = function (redis) {
redis.pipeline = function () {
var pipeline = new Pipeline(this);
return pipeline;
};
var multi = redis.multi;
redis.multi = function (options) {
if (options && options.pipeline === false) {
multi.call(this);
} else {
var pipeline = new Pipeline(this);
pipeline.multi();
var exec = pipeline.exec;
pipeline.exec = function (callback) {
exec.call(pipeline);
var promise = exec.call(pipeline);
return promise.then(function (result) {
var execResult = result[result.length - 1];
if (execResult[0]) {
execResult[0].previousErrors = [];
for (var i = 0; i < result.length - 1; ++i) {
if (result[i][0]) {
execResult[0].previousErrors.push(result[i][0]);
}
}
throw execResult[0];
}
return utils.wrapMultiResult(execResult[1]);
}).nodeify(callback);
};
return pipeline;
}
};
var exec = redis.exec;
redis.exec = function (callback) {
var wrapper = function (err, results) {
if (Array.isArray(results)) {
results = utils.wrapMultiResult(results);
}
callback(err, results);
};
exec.call(this, wrapper);
};
};
|
Fix log for grunt tasks | (function() {
'use strict';
var yeoman = require('yeoman-generator'),
scaffold = {};
module.exports = yeoman.generators.Base.extend({
constructor: function() {
yeoman.generators.Base.apply(this, arguments);
this.option('skip-welcome');
this.argument('runType', {
type: String,
required: false
});
scaffold = require('../../scaffold')(this);
this.isBuild = typeof this.runType !== 'undefined' && this.runType.toLowerCase() === 'build';
},
initializing: function() {
var message = 'Starting development mode. I will start a server with BrowserSync support. :)';
if (this.isBuild) {
message = 'Starting build view. I will start a server with BrowserSync support. :)';
}
if (!this.options['skip-welcome']) {
scaffold.welcomeMessage(' Running project ', message);
}
},
install: function() {
scaffold.log('Installing Bower dependencies...\n', 'yellow');
this.bowerInstall('', this.async);
},
end: function() {
scaffold.log('Running...\n', 'yellow');
if (this.isBuild) {
this.spawnCommand('grunt', ['serve'], {
stdio: 'inherit'
});
return false;
}
this.spawnCommand('grunt', ['default'], {
stdio: 'inherit'
});
}
});
})();
| (function() {
'use strict';
var yeoman = require('yeoman-generator'),
scaffold = {};
module.exports = yeoman.generators.Base.extend({
constructor: function() {
yeoman.generators.Base.apply(this, arguments);
this.option('skip-welcome');
this.argument('runType', {
type: String,
required: false
});
scaffold = require('../../scaffold')(this);
this.isBuild = typeof this.runType !== 'undefined' && this.runType.toLowerCase() === 'build';
},
initializing: function() {
var message = 'Starting development mode. I will start a server with BrowserSync support. :)';
if (this.isBuild) {
message = 'Starting build view. I will start a server with BrowserSync support. :)';
}
if (!this.options['skip-welcome']) {
scaffold.welcomeMessage(' Running project ', message);
}
},
install: function() {
scaffold.log('Installing Bower dependencies...\n', 'yellow');
this.bowerInstall('', this.async);
},
end: function() {
scaffold.log('Running...\n', 'yellow');
if (this.isBuild) {
this.spawnCommand('grunt', ['serve']);
return false;
}
this.spawnCommand('grunt', ['default']);
}
});
})();
|
Return instead of throw the exception | <?php
declare(strict_types = 1);
namespace Speicher210\Estimote;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use JMS\Serializer\SerializerInterface;
use Speicher210\Estimote\Exception\ApiException;
use Speicher210\Estimote\Exception\ApiKeyInvalidException;
/**
* Abstract resource.
*/
abstract class AbstractResource
{
/**
* The API client.
*
* @var Client
*/
protected $client;
/**
* Serializer interface to serialize / deserialize the request / responses.
*
* @var SerializerInterface
*/
protected $serializer;
/**
* @param Client $client The API client.
* @param SerializerInterface $serializer Serializer interface to serialize / deserialize the request / responses.
*/
public function __construct(Client $client, SerializerInterface $serializer)
{
$this->client = $client;
$this->serializer = $serializer;
}
/**
* Create an ApiException from a client exception.
*
* @param ClientException $e The client exception.
* @return ApiException
*/
protected function createApiException(ClientException $e): ApiException
{
$response = $e->getResponse();
if (\in_array($response->getStatusCode(), [401, 403], true)) {
throw new ApiKeyInvalidException();
}
return new ApiException((string)$response->getBody());
}
}
| <?php
namespace Speicher210\Estimote;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use JMS\Serializer\SerializerInterface;
use Speicher210\Estimote\Exception\ApiException;
use Speicher210\Estimote\Exception\ApiKeyInvalidException;
use Speicher210\Estimote\Model\Beacon as BeaconModel;
/**
* Abstract resource.
*/
abstract class AbstractResource
{
/**
* The API client.
*
* @var Client
*/
protected $client;
/**
* Serializer interface to serialize / deserialize the request / responses.
*
* @var SerializerInterface
*/
protected $serializer;
/**
* @param Client $client The API client.
* @param SerializerInterface $serializer Serializer interface to serialize / deserialize the request / responses.
*/
public function __construct(Client $client, SerializerInterface $serializer)
{
$this->client = $client;
$this->serializer = $serializer;
}
/**
* Create an ApiException from a client exception.
*
* @param ClientException $e The client exception.
* @return ApiException
*/
protected function createApiException(ClientException $e)
{
$response = $e->getResponse();
if (in_array($response->getStatusCode(), [401, 403], true)) {
throw new ApiKeyInvalidException();
}
throw new ApiException((string)$response->getBody());
}
}
|
Use the `web` middleware group by default in the web config | <?php
return [
/*
|--------------------------------------------------------------------------
| User Model
|--------------------------------------------------------------------------
|
| Set your eloquent model for your users.
|
*/
'user' => App\User::class,
/*
|--------------------------------------------------------------------------
| Group Mode
|--------------------------------------------------------------------------
|
| Set the group mode to either "nested" or "flat" for a different forum
| experience.
|
*/
'group_mode' => 'nested',
/*
|--------------------------------------------------------------------------
| Discussion Group Limit
|--------------------------------------------------------------------------
|
| Set the maximum number of groups that a discussion can be created in.
| Only applicable if group_mode is set to 'flat'.
|
*/
'discussion_group_limit' => 3,
/*
|--------------------------------------------------------------------------
| Pagination Limits
|--------------------------------------------------------------------------
|
| Set the maximum number of resources that will be shown per page.
|
*/
'pagination' => [
'discussions' => 20,
'posts' => 15,
],
/*
|--------------------------------------------------------------------------
| API and Web
|--------------------------------------------------------------------------
|
| Include whichever middleware and namespace(s) you want here.
|
*/
'api' => [
'enabled' => false,
'prefix' => 'api/forum',
'namespace' => '\Bitporch\Forum\Controllers\Api',
'middleware' => 'auth:api',
],
'web' => [
'enabled' => true,
'prefix' => 'forum',
'namespace' => '\Bitporch\Forum\Controllers',
'middleware' => 'web',
],
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| User Model
|--------------------------------------------------------------------------
|
| Set your eloquent model for your users.
|
*/
'user' => App\User::class,
/*
|--------------------------------------------------------------------------
| Group Mode
|--------------------------------------------------------------------------
|
| Set the group mode to either "nested" or "flat" for a different forum
| experience.
|
*/
'group_mode' => 'nested',
/*
|--------------------------------------------------------------------------
| Discussion Group Limit
|--------------------------------------------------------------------------
|
| Set the maximum number of groups that a discussion can be created in.
| Only applicable if group_mode is set to 'flat'.
|
*/
'discussion_group_limit' => 3,
/*
|--------------------------------------------------------------------------
| Pagination Limits
|--------------------------------------------------------------------------
|
| Set the maximum number of resources that will be shown per page.
|
*/
'pagination' => [
'discussions' => 20,
'posts' => 15,
],
/*
|--------------------------------------------------------------------------
| API and Web
|--------------------------------------------------------------------------
|
| Include whichever middleware and namespace(s) you want here.
|
*/
'api' => [
'enabled' => false,
'prefix' => 'api/forum',
'namespace' => '\Bitporch\Forum\Controllers\Api',
'middleware' => 'auth:api',
],
'web' => [
'enabled' => true,
'prefix' => 'forum',
'namespace' => '\Bitporch\Forum\Controllers',
'middleware' => [
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
],
],
];
|
Revise elif to if due to continue | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def valid_parentheses(s):
"""Balance parentheses in a string."""
open_close_d = {
'(': ')',
'[': ']',
'{': '}'
}
# Use stack to collect open parentheses.
stack = []
for c in s:
if c in '([{':
# If c is open parenthesis, push to stack.
stack.append(c)
continue
if c in ')]}':
# Check if there is still open parenthesis.
if not stack:
return False
# If yes, compare open parenthesis and current char.
open_c = stack.pop()
if c != open_close_d[open_c]:
return False
# Finally check if there is open remaining.
if not stack:
return True
else:
return False
def main():
s = '(abcd)' # Ans: True.
print(valid_parentheses(s))
s = '([(a)bcd]{ef}g)' # Ans: True.
print(valid_parentheses(s))
s = '(ab{c}d]' # Ans: False.
print(valid_parentheses(s))
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def valid_parentheses(s):
"""Balance parentheses in a string."""
open_close_d = {
'(': ')',
'[': ']',
'{': '}'
}
# Use stack to collect open parentheses.
stack = []
for c in s:
if c in '([{':
# If c is open parenthesis, push to stack.
stack.append(c)
continue
elif c in ')]}':
# Check if there is still open parenthesis.
if not stack:
return False
# If yes, compare open parenthesis and current char.
open_c = stack.pop()
if c != open_close_d[open_c]:
return False
# Finally check if there is open remaining.
if not stack:
return True
else:
return False
def main():
s = '(abcd)' # Ans: True.
print(valid_parentheses(s))
s = '([(a)bcd]{ef}g)' # Ans: True.
print(valid_parentheses(s))
s = '(ab{c}d]' # Ans: False.
print(valid_parentheses(s))
if __name__ == '__main__':
main()
|
Allow shared container to store empty, but not null values. | <?php
/**
*
*/
namespace Mvc5\Resolver;
use RuntimeException;
trait Initializer
{
/**
* @var array
*/
protected $pending = [];
/**
* @param string $name
* @param callable $callback
* @param array $args
* @return callable|null|object
*/
protected abstract function plugin($name, array $args = [], callable $callback = null);
/**
* @param string $name
* @param null $config
* @return null|object|callable
*/
protected function initialize($name, $config = null)
{
return $this->initializing($name) ?? $this->initialized($name, $this->plugin($config ?? $name));
}
/**
* @param string $name
* @param callable|null|object $service
* @return callable|null|object
*/
protected function initialized($name, $service = null)
{
$this->pending[$name] = false;
null !== $service && $this->set($name, $service);
return $service;
}
/**
* @param string $name
* @return bool
*/
protected function initializing($name)
{
if (!empty($this->pending[$name])) {
throw new RuntimeException('Circular dependency: ' . $name);
}
$this->pending[$name] = true;
return null;
}
/**
* @param string $name
* @param mixed $service
* @return void
*/
protected abstract function set($name, $service);
}
| <?php
/**
*
*/
namespace Mvc5\Resolver;
use RuntimeException;
trait Initializer
{
/**
* @var array
*/
protected $pending = [];
/**
* @param string $name
* @param callable $callback
* @param array $args
* @return callable|null|object
*/
protected abstract function plugin($name, array $args = [], callable $callback = null);
/**
* @param string $name
* @param null $config
* @return null|object|callable
*/
protected function initialize($name, $config = null)
{
return $this->initializing($name) ?? $this->initialized($name, $this->plugin($config ?? $name));
}
/**
* @param string $name
* @param callable|null|object $service
* @return callable|null|object
*/
protected function initialized($name, $service = null)
{
$this->pending[$name] = false;
null !== $service && $service && $this->set($name, $service);
return $service;
}
/**
* @param string $name
* @return bool
*/
protected function initializing($name)
{
if (!empty($this->pending[$name])) {
throw new RuntimeException('Circular dependency: ' . $name);
}
$this->pending[$name] = true;
return null;
}
/**
* @param string $name
* @param mixed $service
* @return void
*/
protected abstract function set($name, $service);
}
|
Fix condition for when keys for self can be generated | import { ADDRESS_STATUS, ADDRESS_TYPE, MEMBER_PRIVATE, RECEIVE_ADDRESS } from 'proton-shared/lib/constants';
const { TYPE_ORIGINAL, TYPE_CUSTOM_DOMAIN, TYPE_PREMIUM } = ADDRESS_TYPE;
const { READABLE } = MEMBER_PRIVATE;
export const getStatus = ({ address: { Status, Receive, DomainID, HasKeys }, i }) => {
const isActive = ADDRESS_STATUS.STATUS_ENABLED && Receive === RECEIVE_ADDRESS.RECEIVE_YES;
const isDisabled = Status === ADDRESS_STATUS.STATUS_DISABLED;
const isOrphan = DomainID === null;
const isMissingKeys = !HasKeys;
return {
isDefault: i === 0,
isActive,
isDisabled,
isOrphan,
isMissingKeys
};
};
export const getPermissions = ({
member: { Private, Self },
address: { Status, HasKeys, Type },
user: { isAdmin },
organizationKey
}) => {
const isSpecialAddress = Type === TYPE_ORIGINAL && Type === TYPE_PREMIUM;
const canGenerateMember = organizationKey && isAdmin && Private === READABLE;
return {
canGenerate: !HasKeys && (canGenerateMember || Self),
canDisable: Status === ADDRESS_STATUS.STATUS_ENABLED && isAdmin && !isSpecialAddress,
canEnable: Status === ADDRESS_STATUS.STATUS_DISABLED && isAdmin && !isSpecialAddress,
canDelete: Type === TYPE_CUSTOM_DOMAIN,
canEdit: !!Self
};
};
| import { ADDRESS_STATUS, ADDRESS_TYPE, MEMBER_PRIVATE, RECEIVE_ADDRESS } from 'proton-shared/lib/constants';
const { TYPE_ORIGINAL, TYPE_CUSTOM_DOMAIN, TYPE_PREMIUM } = ADDRESS_TYPE;
const { READABLE, UNREADABLE } = MEMBER_PRIVATE;
export const getStatus = ({ address: { Status, Receive, DomainID, HasKeys }, i }) => {
const isActive = ADDRESS_STATUS.STATUS_ENABLED && Receive === RECEIVE_ADDRESS.RECEIVE_YES;
const isDisabled = Status === ADDRESS_STATUS.STATUS_DISABLED;
const isOrphan = DomainID === null;
const isMissingKeys = !HasKeys;
return {
isDefault: i === 0,
isActive,
isDisabled,
isOrphan,
isMissingKeys
};
};
export const getPermissions = ({
member: { Private, Self },
address: { Status, HasKeys, Type },
user: { isAdmin },
organizationKey
}) => {
const isSpecialAddress = Type === TYPE_ORIGINAL && Type === TYPE_PREMIUM;
return {
canGenerate:
!HasKeys && organizationKey && ((isAdmin && Private === READABLE) || (Private === UNREADABLE && Self)),
canDisable: Status === ADDRESS_STATUS.STATUS_ENABLED && isAdmin && !isSpecialAddress,
canEnable: Status === ADDRESS_STATUS.STATUS_DISABLED && isAdmin && !isSpecialAddress,
canDelete: Type === TYPE_CUSTOM_DOMAIN,
canEdit: !!Self
};
};
|
Fix typo in parameter name. | <?php
namespace Slim\Middleware;
/**
* HTTP Basic Authentication
*
* Provides HTTP Basic Authentication on given routes
*
* @package Slim
* @author Mika Tuupola <[email protected]>
*/
class HttpBasicAuth extends \Slim\Middleware {
public $options;
public function __construct($options = null) {
/* Default options. */
$this->options = array(
"users" => array(),
"path" => "/",
"realm" => "Protected"
);
if ($options) {
$this->options = array_merge($this->options, (array)$options);
}
}
public function call() {
$request = $this->app->request;
/* If path matches what is given on initialization. */
if (false !== strpos($request->getPath(), $this->options["path"])) {
$user = $request->headers("PHP_AUTH_USER");
$pass = $request->headers("PHP_AUTH_PW");
/* Check if user and passwords matches. */
if (isset($this->options["users"][$user]) && $this->options["users"][$user] === $pass) {
$this->next->call();
} else {
$this->app->response->status(401);
$this->app->response->header("WWW-Authenticate", sprintf('Basic realm="%s"', $this->options["realm"]));;
return;
}
} else {
$this->next->call();
}
}
}
| <?php
namespace Slim\Middleware;
/**
* HTTP Basic Authentication
*
* Provides HTTP Basic Authentication on given routes
*
* @package Slim
* @author Mika Tuupola <[email protected]>
*/
class HttpBasicAuth extends \Slim\Middleware {
public $options;
public function __construct($options = null) {
/* Default options. */
$this->options = array(
"users" => array(),
"path" => "/",
"real" => "Protected"
);
if ($options) {
$this->options = array_merge($this->options, (array)$options);
}
}
public function call() {
$request = $this->app->request;
/* If path matches what is given on initialization. */
if (false !== strpos($request->getPath(), $this->options["path"])) {
$user = $request->headers("PHP_AUTH_USER");
$pass = $request->headers("PHP_AUTH_PW");
/* Check if user and passwords matches. */
if (isset($this->options["users"][$user]) && $this->options["users"][$user] === $pass) {
$this->next->call();
} else {
$this->app->response->status(401);
$this->app->response->header("WWW-Authenticate", sprintf('Basic realm="%s"', $this->options["realm"]));;
return;
}
} else {
$this->next->call();
}
}
}
|
Change username to osf uid | from .apps import OsfOauth2AdapterConfig
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class OSFAccount(ProviderAccount):
def to_str(self):
# default ... reserved word?
dflt = super(OSFAccount, self).to_str()
return next(
value
for value in (
# try the name first, then the id, then the super value
'{} {}'.format(
self.account.extra_data.get('first_name', None),
self.account.extra_data.get('last_name', None)
),
self.account.extra_data.get('id', None),
dflt
)
if value is not None
)
class OSFProvider(OAuth2Provider):
id = 'osf'
name = 'Open Science Framework'
account_class = OSFAccount
def extract_common_fields(self, data):
attributes = data.get('data').get('attributes')
return dict(
# we could put more fields here later
# the api has much more available, just not sure how much we need right now
username=self.extract_uid(data),
first_name=attributes.get('given_name'),
last_name=attributes.get('family_name'),
)
def extract_uid(self, data):
return str(data.get('data').get('id'))
def get_default_scope(self):
return OsfOauth2AdapterConfig.default_scopes
providers.registry.register(OSFProvider) | from .apps import OsfOauth2AdapterConfig
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class OSFAccount(ProviderAccount):
def to_str(self):
# default ... reserved word?
dflt = super(OSFAccount, self).to_str()
return next(
value
for value in (
# try the name first, then the id, then the super value
'{} {}'.format(
self.account.extra_data.get('first_name', None),
self.account.extra_data.get('last_name', None)
),
self.account.extra_data.get('id', None),
dflt
)
if value is not None
)
class OSFProvider(OAuth2Provider):
id = 'osf'
name = 'Open Science Framework'
account_class = OSFAccount
def extract_common_fields(self, data):
attributes = data.get('data').get('attributes')
return dict(
# we could put more fields here later
# the api has much more available, just not sure how much we need right now
username=data.get('id'),
first_name=attributes.get('given_name'),
last_name=attributes.get('family_name'),
)
def extract_uid(self, data):
return str(data.get('data').get('id'))
def get_default_scope(self):
return OsfOauth2AdapterConfig.default_scopes
providers.registry.register(OSFProvider) |
Revert "Swallow proxy exception from requests"
This reverts commit 8d9ccbb2bbde7c2f8dbe60b90f730d87b924d86e. | """
Some code to manage the Amazon Certificate Service.
"""
import logging
import boto3
import botocore
class DiscoACM(object):
"""
A class to manage the Amazon Certificate Service
"""
def __init__(self, connection=None):
self._acm = connection
@property
def acm(self):
"""
Lazily creates ACM connection
NOTE!!! As of 2016-02-11 ACM is not supported outside the us-east-1 region.
Return None if service does not exist in current region
"""
if not self._acm:
try:
self._acm = boto3.client('acm', region_name='us-east-1')
except Exception:
logging.warning("ACM service does not exist in current region")
return None
return self._acm
def get_certificate_arn(self, dns_name):
"""Returns a Certificate ARN from the Amazon Certificate Service given the DNS name"""
if not self.acm:
return None
try:
certs = self.acm.list_certificates()["CertificateSummaryList"]
cert = [cert['CertificateArn'] for cert in certs if cert['DomainName'] == dns_name]
return cert[0] if cert else None
except botocore.exceptions.EndpointConnectionError:
# some versions of botocore(1.3.26) will try to connect to acm even if outside us-east-1
return None
| """
Some code to manage the Amazon Certificate Service.
"""
import logging
import boto3
import botocore
class DiscoACM(object):
"""
A class to manage the Amazon Certificate Service
"""
def __init__(self, connection=None):
self._acm = connection
@property
def acm(self):
"""
Lazily creates ACM connection
NOTE!!! As of 2016-02-11 ACM is not supported outside the us-east-1 region.
Return None if service does not exist in current region
"""
if not self._acm:
try:
self._acm = boto3.client('acm', region_name='us-east-1')
except Exception:
logging.warning("ACM service does not exist in current region")
return None
return self._acm
def get_certificate_arn(self, dns_name):
"""Returns a Certificate ARN from the Amazon Certificate Service given the DNS name"""
if not self.acm:
return None
try:
certs = self.acm.list_certificates()["CertificateSummaryList"]
cert = [cert['CertificateArn'] for cert in certs if cert['DomainName'] == dns_name]
return cert[0] if cert else None
except (botocore.exceptions.EndpointConnectionError, botocore.vendored.requests.exceptions.ConnectionError):
# some versions of botocore(1.3.26) will try to connect to acm even if outside us-east-1
return None
|
Convert time to JS format
JS uses ms instead of s provided by the API. | var async = require('async');
var pingdom = require('./pingdom');
function checks(config, limit, done) {
var api = pingdom(config);
api.checks(function(err, checks) {
if(err) return console.error(err);
async.map(checks, function(check, cb) {
api.results(function(err, results) {
if(err) return cb(err);
cb(null, {
name: check.name,
host: check.hostname,
type: check.type,
lastresponse: check.lastresponsetime,
data: results.map(function(result) {
return {
x: result.time * 1000, // s to ms
y: result.responsetime
};
})
});
}, {
target: check.id,
qs: {
limit: limit
}
});
}, done);
});
}
exports.checks = checks;
| var async = require('async');
var pingdom = require('./pingdom');
function checks(config, limit, done) {
var api = pingdom(config);
api.checks(function(err, checks) {
if(err) return console.error(err);
async.map(checks, function(check, cb) {
api.results(function(err, results) {
if(err) return cb(err);
cb(null, {
name: check.name,
host: check.hostname,
type: check.type,
lastresponse: check.lastresponsetime,
data: results.map(function(result) {
return {
x: result.time,
y: result.responsetime
};
})
});
}, {
target: check.id,
qs: {
limit: limit
}
});
}, done);
});
}
exports.checks = checks;
|
Tweak layout of export component | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
const exampleQuery = (slug) => `query {
organization(slug: "${slug}") {
auditEvents(first: 500) {
edges {
node {
type
occurredAt
actor {
name
}
subject {
name
type
}
data
}
}
}
}
}`;
class AuditLogExport extends React.PureComponent {
static propTypes = {
organization: PropTypes.shape({
slug: PropTypes.string.isRequired
}).isRequired
};
render() {
const linkClassName = 'text-decoration-none semi-bold lime hover-lime hover-underline';
return (
<div>
<p>
Your organizationʼs audit log can be queried and exported using the <a href="/docs/graphql-api" className={linkClassName}>GraphQL API</a>.
</p>
<p>For example:</p>
<pre className="border border-gray rounded bg-silver overflow-auto p2 monospace">
{exampleQuery(this.props.organization.slug)}
</pre>
<p>
See the <a href="/docs/graphql-api" className={linkClassName}>GraphQL Documentation</a> for more information.
</p>
</div>
);
}
}
export default Relay.createContainer(AuditLogExport, {
fragments: {
organization: () => Relay.QL`
fragment on Organization {
slug
}
`
}
});
| import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
const exampleQuery = (slug) => `query {
organization(slug: "${slug}") {
auditEvents(first: 500) {
edges {
node {
type
occurredAt
actor {
name
}
subject {
name
type
}
data
}
}
}
}
}`;
class AuditLogExport extends React.PureComponent {
static propTypes = {
organization: PropTypes.shape({
slug: PropTypes.string.isRequired
}).isRequired
};
render() {
const linkClassName = 'text-decoration-none semi-bold lime hover-lime hover-underline';
return (
<div>
<p>Your organizationʼs audit log can be queried and exported using the <a href="/docs/graphql-api" className={linkClassName}>GraphQL API</a>.</p>
<p>For example:</p>
<pre className="border border-gray rounded bg-silver overflow-auto p2 monospace">
{exampleQuery(this.props.organization.slug)}
</pre>
<p>See the <a href="/docs/graphql-api" className={linkClassName}>GraphQL Documentation</a> for more information.</p>
</div>
);
}
}
export default Relay.createContainer(AuditLogExport, {
fragments: {
organization: () => Relay.QL`
fragment on Organization {
slug
}
`
}
});
|
Fix SVG load with spaces in filename | var server = require('webserver').create(),
fs = require('fs');
var serverUrl = '127.0.0.1:8888';
var workingDirectory = fs.workingDirectory.replace(/\//g, fs.separator);
function create() {
var serverCreated = server.listen(serverUrl, function (request, response) {
var cleanedUrl = decodeURIComponent(request.url
.replace(/\//g, fs.separator)
.replace(/\?.*$/g, '')
.replace(/js\/js\//,'js/'));
//console.log('Requesting ' + request.url + ', loading ' + cleanedUrl);
var pagePath = workingDirectory + cleanedUrl;
var extension = pagePath.replace(/^.*\.(.*)$/,'$1');
switch (extension) {
case 'svg':
response.setHeader("Content-Type", "image/svg+xml");
break;
}
response.statusCode = 200;
try {
response.write(fs.read(pagePath));
} catch(err) {
console.error('Error while reading ' + cleanedUrl + '(requested URL : '+request.url+')');
response.close();
phantom.exit(1);
}
response.close();
});
if (!serverCreated) {
console.error('Error while creating HTTP server');
phantom.exit(1);
}
}
function close() {
server.close();
}
module.exports = {
create: create,
url: serverUrl,
close: close
}; | var server = require('webserver').create(),
fs = require('fs');
var serverUrl = '127.0.0.1:8888';
var workingDirectory = fs.workingDirectory.replace(/\//g, fs.separator);
function create() {
var serverCreated = server.listen(serverUrl, function (request, response) {
var cleanedUrl = request.url
.replace(/\//g, fs.separator)
.replace(/\?.*$/g, '')
.replace(/js\/js\//,'js/');
//console.log('Requesting ' + request.url + ', loading ' + cleanedUrl);
var pagePath = workingDirectory + cleanedUrl;
var extension = pagePath.replace(/^.*\.(.*)$/,'$1');
switch (extension) {
case 'svg':
response.setHeader("Content-Type", "image/svg+xml");
break;
}
response.statusCode = 200;
try {
response.write(fs.read(pagePath));
} catch(err) {
console.error('Error while reading ' + cleanedUrl + '(requested URL : '+request.url+')');
response.close();
phantom.exit(1);
}
response.close();
});
if (!serverCreated) {
console.error('Error while creating HTTP server');
phantom.exit(1);
}
}
function close() {
server.close();
}
module.exports = {
create: create,
url: serverUrl,
close: close
}; |
Make the SSH configuration more resilient.
If you don't have certain values specified in your ~/.ssh/config, use
the defaults instead of erroring out. | # -*- coding: utf-8 -*-
__author__ = 'John Moylan'
import sys
from paramiko import SSHClient, SSHConfig, AutoAddPolicy
from pyvarnish.settings import SSH_CONFIG
class Varnish_admin():
def __init__(self, server=''):
self.server = server
self.conf = {
'hostname': server,
'port': 22,
# If these are None, Paramiko will figure out the correct values.
'user': None,
'identityfile': None,
}
self.conf.update(self.config())
def config(self):
sshconfig = SSHConfig()
try:
sshconfig.parse(open(SSH_CONFIG))
except IOError:
print "your app needs to have a valid " \
"ssh config file location in settings.py"
sys.exit(1)
conf = sshconfig.lookup(self.server)
if 'port' in conf:
conf['port'] = int(conf['port'])
return conf
def runcmd(self, cmd):
try:
client = SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(self.conf['hostname'],
port = self.conf['port'],
username = self.conf['user'],
key_filename = self.conf['identityfile'],)
stdin, stdout, stderr = client.exec_command(cmd)
return ''.join([i.rstrip('\r\n ').lstrip() for i in stdout.readlines()])
finally:
client.close()
| # -*- coding: utf-8 -*-
__author__ = 'John Moylan'
import sys
from paramiko import SSHClient, SSHConfig, AutoAddPolicy
from pyvarnish.settings import SSH_CONFIG
class Varnish_admin():
def __init__(self, server=''):
self.server = server
self.conf = self.config()
def config(self):
sshconfig = SSHConfig()
try:
sshconfig.parse(open(SSH_CONFIG))
except IOError:
print "your app needs to have a valid " \
"ssh config file location in settings.py"
sys.exit(1)
return sshconfig.lookup(self.server)
def runcmd(self, cmd):
try:
client = SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(self.conf['hostname'],
port = int(self.conf['port']),
username = self.conf['user'],
key_filename = self.conf['identityfile'],
password = None,)
stdin, stdout, stderr = client.exec_command(cmd)
return ''.join([i.rstrip('\r\n ').lstrip() for i in stdout.readlines()])
finally:
client.close() |
Allow MarkdownDirectory events to specify author. | from been.core import DirectorySource, source_registry
from hashlib import sha1
import re
import unicodedata
import time
import markdown
# slugify from Django source (BSD license)
def slugify(value):
value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return re.sub('[-\s]+', '-', value)
class MarkdownDirectory(DirectorySource):
kind = 'markdown'
def process_event(self, event):
md = markdown.Markdown(extensions=['meta'])
event['content'] = md.convert(event['raw'])
event['title'] = ' '.join(md.Meta.get('title', [event['filename']]))
event['author'] = ' '.join(md.Meta.get('author', ['']))
event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])]))
event['summary'] = ' '.join(md.Meta.get('summary', [event['raw'][:100]]))
if md.Meta.get('published'):
# Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT)
event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S')))
event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest()
if time.gmtime() < event['timestamp']:
return None
else:
return event
source_registry.add(MarkdownDirectory)
| from been.core import DirectorySource, source_registry
from hashlib import sha1
import re
import unicodedata
import time
import markdown
# slugify from Django source (BSD license)
def slugify(value):
value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return re.sub('[-\s]+', '-', value)
class MarkdownDirectory(DirectorySource):
kind = 'markdown'
def process_event(self, event):
md = markdown.Markdown(extensions=['meta'])
event['content'] = md.convert(event['raw'])
event['title'] = ' '.join(md.Meta.get('title', [event['filename']]))
event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])]))
event['summary'] = ' '.join(md.Meta.get('summary', [event['raw'][:100]]))
if md.Meta.get('published'):
# Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT)
event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S')))
event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest()
if time.gmtime() < event['timestamp']:
return None
else:
return event
source_registry.add(MarkdownDirectory)
|
Add response logging for upload of image | package xyz.igorgee.shapejs;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class ShapeJS {
private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpg");
private static final String ENDPOINT = "http://52.90.86.247/image";
public static final String SHAPE_JS_IMAGE_KEY = "shapeJS_img";
private final OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)
.build();
public InputStream uploadImage(File image) throws IOException {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(SHAPE_JS_IMAGE_KEY, image.getName(),
RequestBody.create(MEDIA_TYPE_JPG, image))
.build();
Request request = new Request.Builder()
.url(ENDPOINT)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
Log.d("RESPONSE HEAD", String.valueOf(response.code()));
Log.d("RESPONSE MESSAGE", response.message());
if (!response.isSuccessful()) throw new IOException("Unsuccessful response");
return response.body().byteStream();
}
}
| package xyz.igorgee.shapejs;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class ShapeJS {
private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpg");
private static final String ENDPOINT = "http://52.90.86.247/image";
public static final String SHAPE_JS_IMAGE_KEY = "shapeJS_img";
private final OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)
.build();
public InputStream uploadImage(File image) throws IOException {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(SHAPE_JS_IMAGE_KEY, image.getName(),
RequestBody.create(MEDIA_TYPE_JPG, image))
.build();
Request request = new Request.Builder()
.url(ENDPOINT)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unsuccessful response");
return response.body().byteStream();
}
}
|
Allow specific migrations to be run | """
Run all migrations
"""
import imp
import os
import re
import sys
from os.path import join
import logging
from backdrop.core.database import Database
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')
fp = None
try:
sys.path.append(config_path)
fp, pathname, description = imp.find_module(
"backdrop/write/config/%s" % env)
return imp.load_module(env, fp, pathname, description)
finally:
sys.path.pop()
if fp:
fp.close()
def get_database(config):
return Database(
config.MONGO_HOSTS, config.MONGO_PORT, config.DATABASE_NAME)
def get_migrations(migration_files):
migrations_path = join(ROOT_PATH, 'migrations')
for migration_file in os.listdir(migrations_path):
if migration_files is None or migration_file in migration_files:
migration_path = join(migrations_path, migration_file)
yield imp.load_source('migration', migration_path)
if __name__ == '__main__':
config = load_config(os.getenv('GOVUK_ENV', 'development'))
database = get_database(config)
migration_files = sys.argv[1:] or None
for migration in get_migrations(migration_files):
log.info("Running migration %s" % migration)
migration.up(database)
| """
Run all migrations
"""
import imp
import os
import sys
import pymongo
from os.path import join
import logging
from backdrop.core.database import Database
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')
fp = None
try:
sys.path.append(config_path)
fp, pathname, description = imp.find_module(
"backdrop/write/config/%s" % env)
return imp.load_module(env, fp, pathname, description)
finally:
sys.path.pop()
if fp:
fp.close()
def get_database(config):
return Database(
config.MONGO_HOSTS, config.MONGO_PORT, config.DATABASE_NAME)
def get_migrations():
migrations_path = join(ROOT_PATH, 'migrations')
for migration_file in os.listdir(migrations_path):
if migration_file.endswith('.py'):
migration_path = join(migrations_path, migration_file)
yield imp.load_source('migration', migration_path)
if __name__ == '__main__':
config = load_config(os.getenv('GOVUK_ENV', 'development'))
database = get_database(config)
for migration in get_migrations():
log.info("Running migration %s" % migration)
migration.up(database)
|
Use Buffer.from() instead of new Buffer()
new Buffer() is now deprecated | /*
* Whitespace-JS / utils.js
* copyright (c) 2016 Susisu
*/
"use strict";
function end() {
module.exports = Object.freeze({
SPACE,
TAB,
LF,
intToWhitespace,
labelToWhitespace
});
}
const SPACE = " ";
const TAB = "\t";
const LF = "\n";
function intToWhitespace(n) {
n = n | 0;
let sign;
if (n >= 0) {
sign = SPACE;
}
else {
sign = TAB;
n = -n;
}
let bits = "";
while (n > 0) {
bits = ((n & 1) === 0 ? SPACE : TAB) + bits;
n = n >> 1;
}
return sign + bits + LF;
}
function labelToWhitespace(label) {
let buf = Buffer.from(label, "utf8");
let len = buf.length;
let ws = "";
for (let offset = 0; offset < len; offset++) {
let n = buf.readUInt8(offset);
let c = "";
for (let i = 0; i < 8; i++) {
c = (n & 1 ? TAB : SPACE) + c;
n = n >>> 1;
}
ws += c;
}
return ws + LF;
}
end();
| /*
* Whitespace-JS / utils.js
* copyright (c) 2016 Susisu
*/
"use strict";
function end() {
module.exports = Object.freeze({
SPACE,
TAB,
LF,
intToWhitespace,
labelToWhitespace
});
}
const SPACE = " ";
const TAB = "\t";
const LF = "\n";
function intToWhitespace(n) {
n = n | 0;
let sign;
if (n >= 0) {
sign = SPACE;
}
else {
sign = TAB;
n = -n;
}
let bits = "";
while (n > 0) {
bits = ((n & 1) === 0 ? SPACE : TAB) + bits;
n = n >> 1;
}
return sign + bits + LF;
}
function labelToWhitespace(l) {
let buf = new Buffer(l, "utf8");
let len = buf.length;
let ws = "";
for (let offset = 0; offset < len; offset++) {
let n = buf.readUInt8(offset);
let c = "";
for (let i = 0; i < 8; i++) {
c = (n & 1 ? TAB : SPACE) + c;
n = n >>> 1;
}
ws += c;
}
return ws + LF;
}
end();
|
Load a schedule on start | 'use strict';
var fs = require('fs');
var Mustache = require('mustache');
import * as schedule from './schedule/schedule.js';
function readForm() {
return {
school: schedule.schools['Globala gymnasiet'],
id: document.getElementById('select-id').value,
week: 38,
width: 600,
height: 400
}
}
function setSchedule(url) {
document.getElementById('schedule-img').src = url;
}
function idView(ids) {
return ids.map(function(id) {
return { id: id };
});
}
function injectContent() {
return new Promise(function(resolve, reject) {
fs.readFile(__dirname + '/app.mst.html', 'utf-8', function(err, data) {
if (err) {
reject(err);
}
let view = { ids: idView(schedule.ids) };
let rendered = Mustache.render(data, view);
document.getElementById('container').innerHTML = rendered;
resolve();
});
});
}
function afterLoad() {
setSchedule(schedule.url(readForm()));
document.getElementById('form-button').addEventListener('click', function() {
setSchedule(schedule.url(readForm()));
});
}
injectContent()
.then(afterLoad);
| 'use strict';
var fs = require('fs');
var Mustache = require('mustache');
import * as schedule from './schedule/schedule.js';
function readForm() {
return {
school: schedule.schools['Globala gymnasiet'],
id: document.getElementById('select-id').value,
week: 38,
width: 600,
height: 400
}
}
function setSchedule(url) {
document.getElementById('schedule-img').src = url;
}
function idView(ids) {
return ids.map(function(id) {
return { id: id };
});
}
function injectContent() {
return new Promise(function(resolve, reject) {
fs.readFile(__dirname + '/app.mst.html', 'utf-8', function(err, data) {
if (err) {
reject(err);
}
let view = { ids: idView(schedule.ids) };
let rendered = Mustache.render(data, view);
document.getElementById('container').innerHTML = rendered;
resolve();
});
});
}
function afterLoad() {
console.log('afterLoad');
document.getElementById('form-button').addEventListener('click', function() {
setSchedule(schedule.url(readForm()));
});
}
injectContent()
.then(afterLoad);
|
Fix typo in upgrade script
git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@1647 af82e41b-90c4-0310-8c96-b1721e28e2e2 | import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
name text PRIMARY KEY,
time integer,
description text
);
INSERT INTO version(name,time,description)
SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>'';
-- Add a description column to the component table, and remove unnamed components
CREATE TEMP TABLE component_old AS SELECT * FROM component;
DROP TABLE component;
CREATE TABLE component (
name text PRIMARY KEY,
owner text,
description text
);
INSERT INTO component(name,owner,description)
SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>'';
"""
def do_upgrade(env, ver, cursor):
cursor.execute(sql)
# Copy the new default wiki macros over to the environment
from trac.siteconfig import __default_macros_dir__ as macros_dir
for f in os.listdir(macros_dir):
if not f.endswith('.py'):
continue
src = os.path.join(macros_dir, f)
dst = os.path.join(env.path, 'wiki-macros', f)
if not os.path.isfile(dst):
shutil.copy2(src, dst)
| import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
name text PRIMARY KEY,
time integer,
description text
);
INSERT INTO version(name,time,description)
SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>'';
-- Add a description column to the component table, and remove unnamed components
CREATE TEMP TABLE component_old AS SELECT * FROM component;
DROP TABLE component;
CREATE TABLE component (
name text PRIMARY KEY,
owner text,
description text
);
INSERT INTO component(name,owner,description)
SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>'';
"""
def do_upgrade(env, ver, cursor):
cursor.execute(sql)
# Copy the new default wiki macros over to the environment
from trac.siteconfig import __default_macro_dir__ as macro_dir
for f in os.listdir(macro_dir):
if not f.endswith('.py'):
continue
src = os.path.join(macro_dir, f)
dst = os.path.join(env.path, 'wiki-macros', f)
if not os.path.isfile(dst):
shutil.copy2(src, dst)
|
Add new properties to ignore due to matrix.org protocol changes | package com.dmytrobilokha.disturber.network.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The matrix Joined Room DTO
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class JoinedRoomDto {
@JsonProperty(value = "unread_notifications", required = true)
private UnreadNotificationCountsDto unreadNotificationCounts;
@JsonProperty(value = "timeline", required = true)
private TimelineDto timeline;
@JsonProperty(value = "state", required = true)
private StateDto state;
@JsonProperty(value = "account_data", required = true)
private AccountDataDto accountData;
@JsonProperty(value = "ephemeral", required = true)
private EphemeralDto ephemeral;
public UnreadNotificationCountsDto getUnreadNotificationCounts() {
return unreadNotificationCounts;
}
public void setUnreadNotificationCounts(UnreadNotificationCountsDto unreadNotificationCounts) {
this.unreadNotificationCounts = unreadNotificationCounts;
}
public TimelineDto getTimeline() {
return timeline;
}
public void setTimeline(TimelineDto timeline) {
this.timeline = timeline;
}
public StateDto getState() {
return state;
}
public void setState(StateDto state) {
this.state = state;
}
public AccountDataDto getAccountData() {
return accountData;
}
public void setAccountData(AccountDataDto accountData) {
this.accountData = accountData;
}
public EphemeralDto getEphemeral() {
return ephemeral;
}
public void setEphemeral(EphemeralDto ephemeral) {
this.ephemeral = ephemeral;
}
}
| package com.dmytrobilokha.disturber.network.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The matrix Joined Room DTO
*/
public class JoinedRoomDto {
@JsonProperty(value = "unread_notifications", required = true)
private UnreadNotificationCountsDto unreadNotificationCounts;
@JsonProperty(value = "timeline", required = true)
private TimelineDto timeline;
@JsonProperty(value = "state", required = true)
private StateDto state;
@JsonProperty(value = "account_data", required = true)
private AccountDataDto accountData;
@JsonProperty(value = "ephemeral", required = true)
private EphemeralDto ephemeral;
public UnreadNotificationCountsDto getUnreadNotificationCounts() {
return unreadNotificationCounts;
}
public void setUnreadNotificationCounts(UnreadNotificationCountsDto unreadNotificationCounts) {
this.unreadNotificationCounts = unreadNotificationCounts;
}
public TimelineDto getTimeline() {
return timeline;
}
public void setTimeline(TimelineDto timeline) {
this.timeline = timeline;
}
public StateDto getState() {
return state;
}
public void setState(StateDto state) {
this.state = state;
}
public AccountDataDto getAccountData() {
return accountData;
}
public void setAccountData(AccountDataDto accountData) {
this.accountData = accountData;
}
public EphemeralDto getEphemeral() {
return ephemeral;
}
public void setEphemeral(EphemeralDto ephemeral) {
this.ephemeral = ephemeral;
}
}
|
Add test for transfer control disable otp | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/balance"),
content_type='text/json',
body='{"status": true, "message": "Balances retrieved"}',
status=201,
)
response = TransferControl.check_balance()
self.assertTrue(response['status'])
@httpretty.activate
def test_resend_otp(self):
"""Method defined to test resend_otp."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/transfer/resend_otp"),
content_type='text/json',
body='{"status": true, "message": "OTP has been resent"}',
status=201,
)
response = TransferControl.resend_otp(
transfer_code="TRF_vsyqdmlzble3uii",
reason="Just do it."
)
self.assertTrue(response['status'])
@httpretty.activate
def test_disable_otp(self):
"""Method defined to test disable_otp."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/transfer/disable_otp"),
content_type='text/json',
body='{"status": true,\
"message": "OTP has been sent to mobile number ending with 4321"}',
status=201,
)
response = TransferControl.disable_otp()
self.assertTrue(response['status'])
| import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/balance"),
content_type='text/json',
body='{"status": true, "message": "Balances retrieved"}',
status=201,
)
response = TransferControl.check_balance()
self.assertTrue(response['status'])
@httpretty.activate
def test_resend_otp(self):
"""Method defined to test resend_otp."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/transfer/resend_otp"),
content_type='text/json',
body='{"status": true, "message": "OTP has been resent"}',
status=201,
)
response = TransferControl.resend_otp(
transfer_code="TRF_vsyqdmlzble3uii",
reason="Just do it."
)
self.assertTrue(response['status'])
|
Fix the inclusion of the TODO.rst file. | import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='utinypass',
version='0.1.0',
description='Parse and split PEM files painlessly.',
long_description=(read('README.rst') + '\n\n' +
read('HISTORY.rst') + '\n\n' +
read('AUTHORS.rst') + '\n\n' +
read('TODO.rst')),
url='http://github.com/gfranxman/utinypass/',
license='MIT',
author='Glenn Franxman',
author_email='[email protected]',
py_modules=['utinypass'],
include_package_data=True,
packages=find_packages(exclude=['tests*']),
install_requires=['pprp',],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='utinypass',
version='0.1.0',
description='Parse and split PEM files painlessly.',
long_description=(read('README.rst') + '\n\n' +
read('HISTORY.rst') + '\n\n' +
read('AUTHORS.rst') + '\n\n' +
read(('TODO.rst')),
url='http://github.com/gfranxman/utinypass/',
license='MIT',
author='Glenn Franxman',
author_email='[email protected]',
py_modules=['utinypass'],
include_package_data=True,
packages=find_packages(exclude=['tests*']),
install_requires=['pprp',],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Fix redirect after delete element | <?php
namespace OuterEdge\Layout\Controller\Adminhtml\Elements;
use Magento\Backend\App\Action;
class Delete extends \Magento\Backend\App\Action
{
/**
* @param Action\Context $context
*/
public function __construct(Action\Context $context)
{
parent::__construct($context);
}
/**
* Delete action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$id = $this->getRequest()->getParam('id_element');
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if ($id) {
try {
$model = $this->_objectManager->create('OuterEdge\Layout\Model\Elements');
$model->load($id);
$model->delete();
$this->messageManager->addSuccess(__('You deleted the element.'));
return $resultRedirect->setPath('layout/groups/edit', ['id_group' => $model->getFkGroup()]);
} catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
return $resultRedirect->setPath('*/*/edit', ['id_element' => $id]);
}
}
$this->messageManager->addError(__('We can\'t find a element to delete.'));
return $resultRedirect->setPath('*/*/');
}
} | <?php
namespace OuterEdge\Layout\Controller\Adminhtml\Elements;
use Magento\Backend\App\Action;
class Delete extends \Magento\Backend\App\Action
{
/**
* @param Action\Context $context
*/
public function __construct(Action\Context $context)
{
parent::__construct($context);
}
/**
* Delete action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$id = $this->getRequest()->getParam('id_element');
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if ($id) {
try {
$model = $this->_objectManager->create('OuterEdge\Layout\Model\Elements');
$model->load($id);
$model->delete();
$this->messageManager->addSuccess(__('You deleted the element.'));
return $resultRedirect->setPath('*/*/');
} catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
return $resultRedirect->setPath('*/*/edit', ['id_element' => $id]);
}
}
$this->messageManager->addError(__('We can\'t find a element to delete.'));
return $resultRedirect->setPath('*/*/');
}
} |
Add missing SVN eol-style property to text files. | import sys, unittest
from ctypes import *
structures = []
byteswapped_structures = []
if sys.byteorder == "little":
SwappedStructure = BigEndianStructure
else:
SwappedStructure = LittleEndianStructure
for typ in [c_short, c_int, c_long, c_longlong,
c_float, c_double,
c_ushort, c_uint, c_ulong, c_ulonglong]:
class X(Structure):
_pack_ = 1
_fields_ = [("pad", c_byte),
("value", typ)]
class Y(SwappedStructure):
_pack_ = 1
_fields_ = [("pad", c_byte),
("value", typ)]
structures.append(X)
byteswapped_structures.append(Y)
class TestStructures(unittest.TestCase):
def test_native(self):
for typ in structures:
## print typ.value
self.failUnlessEqual(typ.value.offset, 1)
o = typ()
o.value = 4
self.failUnlessEqual(o.value, 4)
def test_swapped(self):
for typ in byteswapped_structures:
## print >> sys.stderr, typ.value
self.failUnlessEqual(typ.value.offset, 1)
o = typ()
o.value = 4
self.failUnlessEqual(o.value, 4)
if __name__ == '__main__':
unittest.main()
| import sys, unittest
from ctypes import *
structures = []
byteswapped_structures = []
if sys.byteorder == "little":
SwappedStructure = BigEndianStructure
else:
SwappedStructure = LittleEndianStructure
for typ in [c_short, c_int, c_long, c_longlong,
c_float, c_double,
c_ushort, c_uint, c_ulong, c_ulonglong]:
class X(Structure):
_pack_ = 1
_fields_ = [("pad", c_byte),
("value", typ)]
class Y(SwappedStructure):
_pack_ = 1
_fields_ = [("pad", c_byte),
("value", typ)]
structures.append(X)
byteswapped_structures.append(Y)
class TestStructures(unittest.TestCase):
def test_native(self):
for typ in structures:
## print typ.value
self.failUnlessEqual(typ.value.offset, 1)
o = typ()
o.value = 4
self.failUnlessEqual(o.value, 4)
def test_swapped(self):
for typ in byteswapped_structures:
## print >> sys.stderr, typ.value
self.failUnlessEqual(typ.value.offset, 1)
o = typ()
o.value = 4
self.failUnlessEqual(o.value, 4)
if __name__ == '__main__':
unittest.main()
|
Move includes dir and copy all files by default
Partial fix for #4 | var Async = require('async'),
Fs = require('fs'),
Glob = require('glob'),
Path = require('path'),
RawSource = require('webpack-core/lib/RawSource');
module.exports = function(options) {
this.options = options;
};
module.exports.prototype.apply = function(compiler) {
var options = this.options;
compiler.plugin('compilation', function(compilation) {
compilation.plugin('additional-assets', function(callback) {
// Copy over any include files to the build output target
var includesDir = options.includesDir || './styles/includes/**/*';
includesDir = Path.resolve(compiler.options.context, includesDir);
Glob.glob(includesDir, function(err, files) {
if (err) {
return callback(err);
}
Async.forEach(files, function(file, callback) {
Fs.readFile(file, function(err, data) {
if (err) {
// If the file suddenly disappeared, then the error should be fatal as this
// is unexpected, being previously returned from the glob API.
return callback(err);
}
file = Path.relative(compiler.options.context, file);
compilation.assets[options.remap ? options.remap(file) : file] = new RawSource(data);
callback();
});
},
callback);
});
});
});
};
| var Async = require('async'),
Fs = require('fs'),
Glob = require('glob'),
Path = require('path'),
RawSource = require('webpack-core/lib/RawSource');
module.exports = function(options) {
this.options = options;
};
module.exports.prototype.apply = function(compiler) {
var options = this.options;
compiler.plugin('compilation', function(compilation) {
compilation.plugin('additional-assets', function(callback) {
// Copy over any include files to the build output target
var includesDir = options.includesDir || './src/client/styles/includes/**/*.styl';
includesDir = Path.resolve(compiler.options.context, includesDir);
Glob.glob(includesDir, function(err, files) {
if (err) {
return callback(err);
}
Async.forEach(files, function(file, callback) {
Fs.readFile(file, function(err, data) {
if (err) {
// If the file suddenly disappeared, then the error should be fatal as this
// is unexpected, being previously returned from the glob API.
return callback(err);
}
file = Path.relative(compiler.options.context, file);
compilation.assets[options.remap ? options.remap(file) : file] = new RawSource(data);
callback();
});
},
callback);
});
});
});
};
|
Fix the drag'n drop when entering a fipe. | (function() {
App.Views.Fipe = Backbone.View.extend({
events: {
// Classic file selection
'click .upload a' : 'browseFiles',
'change input[type="file"]' : 'selectFiles',
// Drag'n drop
'dragover .widget' : 'dragOver',
'drop .widget' : 'dropFiles'
},
browseFiles: function(event) {
var fileInput = $(this.el).find('input[type="file"]')[0];
fileInput.click();
},
selectFiles: function(event) {
this.enterTheFipe(event.target.files);
},
dragOver: function(event) {
return false;
},
dropFiles: function(event) {
this.enterTheFipe(event.dataTransfer.files);
},
enterTheFipe: function(files) {
this.addFiles(files);
// Only redirect when we are on the home page.
if (App.Fipe === undefined) {
this.redirect();
}
},
addFiles: function(files) {
files = _.map(files, function(file) {
return new App.Models.File({
obj : file,
name : file.name,
type : file.type,
size : file.size
});
});
App.Files.add(files).save();
},
redirect: function() {
var fipe = new App.Models.Fipe;
fipe.save({}, {
success: function() {
App.Routes.navigate(fipe.url(), true);
}
});
}
});
})();
| (function() {
App.Views.Fipe = Backbone.View.extend({
events: {
// Classic file selection
'click .upload a' : 'browseFiles',
'change input[type="file"]' : 'enterTheFipe',
// Drag'n drop
'dragover .widget' : 'dragOver',
'drop .widget' : 'drop'
},
browseFiles: function(event) {
var fileInput = $(this.el).find('input[type="file"]')[0];
fileInput.click();
},
enterTheFipe: function(event) {
this.addFiles(event.target.files);
// Only redirect when we are on the home page.
if (App.Fipe === undefined) {
this.redirect();
}
},
dragOver: function(event) {
return false;
},
drop: function(event) {
this.addFiles(event.dataTransfer.files);
},
addFiles: function(files) {
files = _.map(files, function(file) {
return new App.Models.File({
obj : file,
name : file.name,
type : file.type,
size : file.size
});
});
App.Files.add(files).save();
},
redirect: function() {
var fipe = new App.Models.Fipe;
fipe.save({}, {
success: function() {
App.Routes.navigate(fipe.url(), true);
}
});
}
});
})();
|
Raise exception on not found ticker | import requests
from bs4 import BeautifulSoup
try:
from urllib.parse import urlparse
except ImportError:
from urllib2 import urlparse
urlparse = urlparse.urlparse
try:
ConnectionError
except NameError:
ConnectionError = ValueError
YAHOO_ENDPOINT = "http://finance.yahoo.com/q/pr?s={}"
CLEARBIT_ENDPOINT = "https://logo.clearbit.com/{}?format=png&size=438"
def get_endpoint(ticker):
return YAHOO_ENDPOINT.format(ticker).lower()
def get_response(target):
return requests.get(target)
def handle_response(response):
if not response.ok:
raise ConnectionError("Yahoo didn't like that")
soup = BeautifulSoup(response.text, "html5lib")
pool = []
for anchor in soup.find_all("a", href=True):
link = anchor['href'].lower()
if link.startswith("http://") or link.startswith("https://"):
if link in pool:
return link
if "yahoo" not in link:
pool.append(link)
raise ValueError("Invalid Ticker")
def get_domain(url):
return urlparse(url).netloc
def get_logo(domain):
return CLEARBIT_ENDPOINT.format(domain)
def main(ticker):
target = get_endpoint(ticker)
response = get_response(target)
url = handle_response(response)
domain = get_domain(url)
return get_logo(domain)
| import requests
from bs4 import BeautifulSoup
try:
from urllib.parse import urlparse
except ImportError:
from urllib2 import urlparse
urlparse = urlparse.urlparse
try:
ConnectionError
except NameError:
ConnectionError = ValueError
YAHOO_ENDPOINT = "http://finance.yahoo.com/q/pr?s={}"
CLEARBIT_ENDPOINT = "https://logo.clearbit.com/{}?format=png&size=438"
def get_endpoint(ticker):
return YAHOO_ENDPOINT.format(ticker).lower()
def get_response(target):
return requests.get(target)
def handle_response(response):
if not response.ok:
raise ConnectionError("Yahoo didn't like that")
soup = BeautifulSoup(response.text, "html5lib")
pool = []
for anchor in soup.find_all("a", href=True):
link = anchor['href'].lower()
if link.startswith("http://") or link.startswith("https://"):
if link in pool:
return link
if "yahoo" not in link:
pool.append(link)
def get_domain(url):
return urlparse(url).netloc
def get_logo(domain):
return CLEARBIT_ENDPOINT.format(domain)
def main(ticker):
target = get_endpoint(ticker)
response = get_response(target)
url = handle_response(response)
domain = get_domain(url)
return get_logo(domain)
|
Add alert and logout when no login details given
Former-commit-id: 78b396c1adfca2470a9e0f44a36e91513779f424 | /**
* Generic error handler method for ajax responses.
* Apply your specific requirements for an error response and then call this method to take care of the rest.
* @param response
*/
function handleApiError(response) {
if (!response || response.status === 200)
return;
if (response.status === 403 || response.status === 401) {
//sweetAlert('You are not logged in', 'Please refresh Florence and log back in.');
logout();
} else if (response.status === 504) {
sweetAlert('This task is taking longer than expected', "It will continue to run in the background.", "info");
} else {
var message = 'An error has occurred, please contact an administrator.';
if (response.responseJSON) {
message = response.responseJSON.message;
}
console.log(message);
sweetAlert("Error", message, "error");
}
}
/* Unique error handling for the login screen */
function handleLoginApiError(response) {
if (!response || response.status === 200)
return;
if (response.status === 400) {
sweetAlert("Please enter a valid username and password");
logout();
} else if (response.status === 403 || response.status === 401) {
sweetAlert('Incorrect login details', 'These login credentials were not recognised. Please try again.', 'error');
logout();
} else {
var message = 'An error has occurred, please contact an administrator.';
if (response.responseJSON) {
message = response.responseJSON.message;
}
console.log(message);
sweetAlert("Error", message, "error");
}
}
| /**
* Generic error handler method for ajax responses.
* Apply your specific requirements for an error response and then call this method to take care of the rest.
* @param response
*/
function handleApiError(response) {
if (!response || response.status === 200)
return;
if (response.status === 403 || response.status === 401) {
//sweetAlert('You are not logged in', 'Please refresh Florence and log back in.');
logout();
} else if (response.status === 504) {
sweetAlert('This task is taking longer than expected', "It will continue to run in the background.", "info");
} else {
var message = 'An error has occurred, please contact an administrator.';
if (response.responseJSON) {
message = response.responseJSON.message;
}
console.log(message);
sweetAlert("Error", message, "error");
}
}
/* Unique error handling for the login screen */
function handleLoginApiError(response) {
if (!response || response.status === 200)
return;
if (response.status === 403 || response.status === 401) {
sweetAlert('Incorrect login details', 'These login credentials were not recognised. Please try again.', 'error');
logout();
} else {
var message = 'An error has occurred, please contact an administrator.';
if (response.responseJSON) {
message = response.responseJSON.message;
}
console.log(message);
sweetAlert("Error", message, "error");
}
}
|
Move datatype editor to the right | import React, { PropTypes } from 'react'
import {
changeDatatypeName, changeDatatypeParam
} from '../actions/response-format'
import DatatypePicker from './datatype-picker';
import NumericDatatypeEditor from './numeric-datatype-editor';
import TextDatatypeEditor from './text-datatype-editor';
import DateDatatypeEditor from './date-datatype-editor';
import { connect } from 'react-redux'
import { DATATYPE_NAME } from '../constants/pogues-constants'
const datatypeEditors = {
[DATATYPE_NAME.TEXT]: TextDatatypeEditor,
[DATATYPE_NAME.NUMERIC]: NumericDatatypeEditor
// no additional parameters for date and boolean datatype types
}
function SimpleResponseFormatEditor(
{ id, format, changeDatatypeName, changeDatatypeParam, locale }) {
const { typeName } = format
const DatatypeEditor = datatypeEditors[typeName]
return (
<div>
<DatatypePicker typeName={typeName}
select={typeName => changeDatatypeName(id, typeName)}
locale={locale} />
<div className="col-sm-offset-2">
{ DatatypeEditor &&
<DatatypeEditor datatype={format}
edit={update => changeDatatypeParam(id, update)} locale={locale} />
}
</div>
</div>
)
}
const mapStateToProps = () => ({})
const mapDispatchToProps = {
changeDatatypeParam,
changeDatatypeName
}
SimpleResponseFormatEditor.propTypes = {
locale: PropTypes.object.isRequired,
changeDatatypeName: PropTypes.func.isRequired,
changeDatatypeParam: PropTypes.func.isRequired
}
export default connect(mapStateToProps, mapDispatchToProps)(SimpleResponseFormatEditor)
| import React, { PropTypes } from 'react'
import {
changeDatatypeName, changeDatatypeParam
} from '../actions/response-format'
import DatatypePicker from './datatype-picker';
import NumericDatatypeEditor from './numeric-datatype-editor';
import TextDatatypeEditor from './text-datatype-editor';
import DateDatatypeEditor from './date-datatype-editor';
import { connect } from 'react-redux'
import { DATATYPE_NAME } from '../constants/pogues-constants'
const datatypeEditors = {
[DATATYPE_NAME.TEXT]: TextDatatypeEditor,
[DATATYPE_NAME.NUMERIC]: NumericDatatypeEditor
// no additional parameters for date and boolean datatype types
}
function SimpleResponseFormatEditor(
{ id, format, changeDatatypeName, changeDatatypeParam, locale }) {
const { typeName } = format
const DatatypeEditor = datatypeEditors[typeName]
return (
<div>
<DatatypePicker typeName={typeName}
select={typeName => changeDatatypeName(id, typeName)}
locale={locale} />
<div className="col-sm-offset-1">
{ DatatypeEditor &&
<DatatypeEditor datatype={format}
edit={update => changeDatatypeParam(id, update)} locale={locale} />
}
</div>
</div>
)
}
const mapStateToProps = () => ({})
const mapDispatchToProps = {
changeDatatypeParam,
changeDatatypeName
}
SimpleResponseFormatEditor.propTypes = {
locale: PropTypes.object.isRequired,
changeDatatypeName: PropTypes.func.isRequired,
changeDatatypeParam: PropTypes.func.isRequired
}
export default connect(mapStateToProps, mapDispatchToProps)(SimpleResponseFormatEditor)
|
Switch basic app back to using perspective camera | window.addEvent("domready", function() {
var BasicApp = new Class({
Extends: App,
initialize: function(element, options) {
this.parent(element, options);
this.renderer = new BasicRenderer('basic-renderer-vert',
'basic-renderer-frag');
this.camera = new Camera();
this.camera.perspective(45, this.options.width/this.options.height,
0.1, 100);
this.camera.lookAt([0, 0, 5],
[0, 0, 0],
[0, 1, 0]);
this.triangle = new Mesh(3, gl.TRIANGLES, gl.STATIC_DRAW,
gl.STATIC_DRAW);
this.triangle.vertexBuffer.setValues([ 0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0]);
this.triangle.colorBuffer.setValues([1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0]);
},
draw: function() {
this.clear();
this.renderer.render([this.triangle], this.camera);
}
});
var app = new BasicApp(document.body);
app.run();
});
| window.addEvent("domready", function() {
var BasicApp = new Class({
Extends: App,
initialize: function(element, options) {
this.parent(element, options);
this.renderer = new BasicRenderer('basic-renderer-vert',
'basic-renderer-frag');
this.camera = new Camera();
/*
this.camera.perspective(45, this.options.width/this.options.height,
0.1, 100);
this.camera.lookAt([0, 0, 5],
[0, 0, 0],
[0, 1, 0]);
*/
this.camera.ortho(0, 1, 0, 1, -1, 1);
mat4.translate(this.camera.modelview.matrix, [0, 0, 1],
this.camera.modelview.matrix);
this.triangle = new Mesh(3, gl.TRIANGLES, gl.STATIC_DRAW,
gl.STATIC_DRAW);
this.triangle.vertexBuffer.setValues([ 0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0]);
this.triangle.colorBuffer.setValues([1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0]);
},
draw: function() {
this.clear();
this.renderer.render([this.triangle], this.camera);
}
});
var app = new BasicApp(document.body);
app.run();
});
|
Remove the convenience functions, reorganize around the SQLAlchemy class | from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback() | from __future__ import unicode_literals
import os
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
db = SQLAlchemy()
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
def save(self):
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
Base = declarative_base(cls=Model)
Base.metadata.bind = db.engine
Base.query = db.session.query_property()
metadata = MetaData()
metadata.bind = db.engine
all = [Base, db, metadata]
def rollback(*_):
db.session.rollback() |
Use token in github hook | <?php
namespace Criterion\UI\Controller;
class HookController
{
public function github(\Silex\Application $app)
{
$query_token = $app['request']->query->get('token');
$token = new \Criterion\Model\Token($query_token);
if ( ! $token->exists)
{
return $app->abort(404, 'Page does not exist');
}
$payload = json_decode($app['request']->get('payload'), true);
if ( ! isset($payload['repository']['url']))
{
return $app->json(array(
'success' => false
));
}
$repo = $payload['repository']['url'];
// Detect if its an private repository, if so then we need to use SSH
if ($payload['repository']['private'])
{
$repo = \Criterion\Helper\Github::toSSHUrl($repo);
}
$project = new \Criterion\Model\Project(array(
'repo' => $repo
));
if ( ! $project->exists)
{
$project->save();
}
$test = new \Criterion\Model\Test();
$test->project_id = $project->id;
$test->branch = str_replace('refs/heads/', null, $payload['ref']);
$test->save();
return $app->json(array(
'success' => true,
'test' => (string) $test->id
));
}
}
| <?php
namespace Criterion\UI\Controller;
class HookController
{
public function github(\Silex\Application $app)
{
$payload = json_decode($app['request']->get('payload'), true);
if ( ! isset($payload['repository']['url']))
{
return $app->json(array(
'success' => false
));
}
$repo = $payload['repository']['url'];
// Detect if its an private repository, if so then we need to use SSH
if ($payload['repository']['private'])
{
$repo = \Criterion\Helper\Github::toSSHUrl($repo);
}
$project = new \Criterion\Model\Project(array(
'repo' => $repo
));
if ( ! $project->exists)
{
$project->save();
}
$test = new \Criterion\Model\Test();
$test->project_id = $project->id;
$test->branch = str_replace('refs/heads/', null, $payload['ref']);
$test->save();
return $app->json(array(
'success' => true,
'test' => (string) $test->id
));
}
}
|
[FEATURE] Update user links in angular to get resources. | 'use strict';
angular.module('publicApp')
.controller('UsersCtrl', ['$scope', '$http', '$location', '$route', '$routeParams', 'UserService', function ($scope, $http, $location, $route, $routeParams, $user) {
$scope.user = $user;
if ($user.isLogged) {
if (($user.id == $routeParams.id) || $user.admin) {
$scope.user.balances = [];
$scope.user.ripple_transactions = [];
$scope.user.external_transaction = [];
$scope.user.external_accounts = [];
$scope.user.ripple_addresses = [];
getExternalTransactions();
getRippleTransactions();
getBalances();
console.log($scope.user);
} else {
$location.path('/users/'+$user.id);
}
} else {
$location.path('/login');
}
function getExternalTransactions() {
$http.get('/api/v1/external_transactions').success(function(resp){
$scope.user.external_transactions = resp.external_transactions;
});
}
function getRippleTransactions() {
$http.get('/api/v1/ripple_transactions').success(function(resp){
$scope.user.ripple_transactions = resp.ripple_transactions;
});
}
function getBalances() {
$http.get('/api/v1/balances').success(function(resp){
$scope.user.balances = resp.balances;
});
}
}]);
| 'use strict';
angular.module('publicApp')
.controller('UsersCtrl', ['$scope', '$http', '$location', '$route', '$routeParams', 'UserService', function ($scope, $http, $location, $route, $routeParams, $user) {
$scope.user = $user;
if ($user.isLogged) {
if (($user.id == $routeParams.id) || $user.admin) {
$scope.user.balances = [];
$scope.user.ripple_transactions = [];
$scope.user.external_transaction = [];
$scope.user.external_accounts = [];
$scope.user.ripple_addresses = [];
getExternalTransactions();
getRippleTransactions();
getBalances();
console.log($scope.user);
} else {
$location.path('/users/'+$user.id);
}
} else {
$location.path('/login');
}
function getExternalTransactions() {
$http.get('/api/v1/users/'+$user.id+'/external_transactions').success(function(resp){
$scope.user.external_transactions = resp.external_transactions;
});
}
function getRippleTransactions() {
$http.get('/api/v1/users/'+$user.id+'/ripple_transactions').success(function(resp){
$scope.user.ripple_transactions = resp.ripple_transactions;
});
}
function getBalances() {
$http.get('/api/v1/users/'+$user.id+'/balances').success(function(resp){
$scope.user.balances = resp.balances;
});
}
}]);
|
Stop relying on `ts-node` from the global scope | const childProcess = require("child_process");
const fs = require("fs");
if (process.argv.length !== 3) {
throw new Error("Requires the base path as argument.");
}
const basePath = process.argv[2];
if (!basePath.match(/[\\\/]$/)) {
throw new Error("Path must end with a slash - any slash will do.");
}
else if (!fs.existsSync(basePath)) {
throw new Error(`Invalid path, '${basePath}' does not exist or is not readable.`);
}
fs.readdirSync(basePath)
.filter(directory => {
if (directory.indexOf('.') !== 0 && fs.statSync(basePath + directory).isDirectory()) {
// filter by known repository name patterns
if (directory === "WCF" || directory.indexOf("com.woltlab.") === 0) {
return true;
}
}
return false;
})
.forEach(directory => {
console.log(`##### Building ${directory} #####\n`);
let path = basePath + directory;
if (directory === "WCF") {
childProcess.execSync(`node _buildCore.js`, {
stdio: [0, 1, 2]
});
}
else {
childProcess.execSync(`node _buildExternal.js ${path}`, {
stdio: [0, 1, 2]
});
}
childProcess.execSync(`npx ts-node syncTemplates.ts ${path}`, {
stdio: [0, 1, 2]
});
console.log("\n");
});
| const childProcess = require("child_process");
const fs = require("fs");
if (process.argv.length !== 3) {
throw new Error("Requires the base path as argument.");
}
const basePath = process.argv[2];
if (!basePath.match(/[\\\/]$/)) {
throw new Error("Path must end with a slash - any slash will do.");
}
else if (!fs.existsSync(basePath)) {
throw new Error(`Invalid path, '${basePath}' does not exist or is not readable.`);
}
fs.readdirSync(basePath)
.filter(directory => {
if (directory.indexOf('.') !== 0 && fs.statSync(basePath + directory).isDirectory()) {
// filter by known repository name patterns
if (directory === "WCF" || directory.indexOf("com.woltlab.") === 0) {
return true;
}
}
return false;
})
.forEach(directory => {
console.log(`##### Building ${directory} #####\n`);
let path = basePath + directory;
if (directory === "WCF") {
childProcess.execSync(`node _buildCore.js`, {
stdio: [0, 1, 2]
});
}
else {
childProcess.execSync(`node _buildExternal.js ${path}`, {
stdio: [0, 1, 2]
});
}
childProcess.execSync(`ts-node syncTemplates.ts ${path}`, {
stdio: [0, 1, 2]
});
console.log("\n");
});
|
Return the parameter for channel mode +l as a list
This fixes a bug where every digit was handled as a separate parameter, causing
"MODE #channel +l 10" to turn into "MODE #channel +ll 1 0" | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "LimitMode"
core = True
affectedActions = [ "joinpermission" ]
def hookIRCd(self, ircd):
self.ircd = ircd
def channelModes(self):
return [ ("l", ModeType.Param, self) ]
def actions(self):
return [ ("modeactioncheck-channel-l-joinpermission", 10, self.isModeSet) ]
def isModeSet(self, channel, alsoChannel, user):
if "l" in channel.modes:
return channel.modes["l"]
return None
def checkSet(self, channel, param):
if param.isdigit():
return [param]
return None
def apply(self, actionType, channel, param, alsoChannel, user):
try: # There may be cases when the parameter we're passed is in string form still (e.g. from modules other than this one)
param = int(param)
except ValueError:
return None
if len(channel.users) >= param:
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
return False
return None
limitMode = LimitMode() | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "LimitMode"
core = True
affectedActions = [ "joinpermission" ]
def hookIRCd(self, ircd):
self.ircd = ircd
def channelModes(self):
return [ ("l", ModeType.Param, self) ]
def actions(self):
return [ ("modeactioncheck-channel-l-joinpermission", 10, self.isModeSet) ]
def isModeSet(self, channel, alsoChannel, user):
if "l" in channel.modes:
return channel.modes["l"]
return None
def checkSet(self, channel, param):
if param.isdigit():
return param
return None
def apply(self, actionType, channel, param, alsoChannel, user):
try: # There may be cases when the parameter we're passed is in string form still (e.g. from modules other than this one)
param = int(param)
except ValueError:
return None
if len(channel.users) >= param:
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
return False
return None
limitMode = LimitMode() |
Use AutoVersionClient to fix client incompatibity issues
Fixes #35 | # -*- coding: utf-8 -*-
import docker
import os
import sys
import requests
DEFAULT_TIMEOUT_SECONDS = 600
def docker_client():
# Default timeout 10 minutes
try:
timeout = int(os.getenv('DOCKER_TIMEOUT', 600))
except ValueError as e:
print("Provided timeout value: %s cannot be parsed as integer, exiting." %
os.getenv('DOCKER_TIMEOUT'))
sys.exit(1)
if not timeout > 0:
print(
"Provided timeout value needs to be greater than zero, currently: %s, exiting." % timeout)
sys.exit(1)
# Default base url for the connection
base_url = os.getenv('DOCKER_CONNECTION', 'unix://var/run/docker.sock')
try:
client = docker.AutoVersionClient(base_url=base_url, timeout=timeout)
except docker.errors.DockerException as e:
print("Error while creating the Docker client: %s" % e)
print(
"Please make sure that you specified valid parameters in the 'DOCKER_CONNECTION' environment variable.")
sys.exit(1)
if client and valid_docker_connection(client):
return client
else:
print(
"Could not connect to the Docker daemon, please make sure the Docker daemon is running.")
if os.environ.get('DOCKER_CONNECTION'):
print(
"If Docker daemon is running, please make sure that you specified valid parameters in the 'DOCKER_CONNECTION' environment variable.")
sys.exit(1)
def valid_docker_connection(client):
try:
return client.ping()
except requests.exceptions.ConnectionError:
return False
| # -*- coding: utf-8 -*-
import docker
import os
import sys
import requests
DEFAULT_TIMEOUT_SECONDS = 600
def docker_client():
# Default timeout 10 minutes
try:
timeout = int(os.getenv('DOCKER_TIMEOUT', 600))
except ValueError as e:
print("Provided timeout value: %s cannot be parsed as integer, exiting." %
os.getenv('DOCKER_TIMEOUT'))
sys.exit(1)
if not timeout > 0:
print(
"Provided timeout value needs to be greater than zero, currently: %s, exiting." % timeout)
sys.exit(1)
# Default base url for the connection
base_url = os.getenv('DOCKER_CONNECTION', 'unix://var/run/docker.sock')
try:
client = docker.Client(base_url=base_url, timeout=timeout)
except docker.errors.DockerException as e:
print("Error while creating the Docker client: %s" % e)
print(
"Please make sure that you specified valid parameters in the 'DOCKER_CONNECTION' environment variable.")
sys.exit(1)
if client and valid_docker_connection(client):
return client
else:
print(
"Could not connect to the Docker daemon, please make sure the Docker daemon is running.")
if os.environ.get('DOCKER_CONNECTION'):
print(
"If Docker daemon is running, please make sure that you specified valid parameters in the 'DOCKER_CONNECTION' environment variable.")
sys.exit(1)
def valid_docker_connection(client):
try:
return client.ping()
except requests.exceptions.ConnectionError:
return False
|
Add check to ensure hook exists before deleting it | <?php
namespace BrainMaestro\GitHooks;
class Hook
{
private static $hooks;
/**
* Add valid git hooks.
*/
public static function add($hook, $script)
{
$filename = ".git/hooks/{$hook}";
if (array_key_exists($hook, self::getHooks())) {
file_put_contents($filename, $script);
chmod($filename, 0755);
echo "Added '{$hook}' hook" . PHP_EOL;
}
}
/**
* Remove valid git hooks.
*/
public static function remove($hook)
{
$filename = ".git/hooks/{$hook}";
if (array_key_exists($hook, self::getHooks()) && is_file($filename)) {
unlink(".git/hooks/{$hook}");
echo "Removed '{$hook}' hook" . PHP_EOL;
}
}
/**
* Get all valid git hooks
*/
private static function getHooks()
{
if (! isset(self::$hooks)) {
self::$hooks = array_flip([
'applypatch-msg',
'commit-msg',
'post-applypatch',
'post-checkout',
'post-commit',
'post-merge',
'post-receive',
'post-rewrite',
'post-update',
'pre-applypatch',
'pre-auto-gc',
'pre-commit',
'pre-push',
'pre-rebase',
'pre-receive',
'prepare-commit-msg',
'push-to-checkout',
'update',
]);
}
return self::$hooks;
}
}
| <?php
namespace BrainMaestro\GitHooks;
class Hook
{
private static $hooks;
/**
* Add valid git hooks.
*/
public static function add($hook, $script)
{
if (array_key_exists($hook, self::getHooks())) {
$filename = ".git/hooks/{$hook}";
file_put_contents($filename, $script);
chmod($filename, 0755);
echo "Added '{$hook}' hook" . PHP_EOL;
}
}
/**
* Remove valid git hooks.
*/
public static function remove($hook)
{
if (array_key_exists($hook, self::getHooks())) {
unlink(".git/hooks/{$hook}");
echo "Removed '{$hook}' hook" . PHP_EOL;
}
}
/**
* Get all valid git hooks
*/
private static function getHooks()
{
if (! isset(self::$hooks)) {
self::$hooks = array_flip([
'applypatch-msg',
'commit-msg',
'post-applypatch',
'post-checkout',
'post-commit',
'post-merge',
'post-receive',
'post-rewrite',
'post-update',
'pre-applypatch',
'pre-auto-gc',
'pre-commit',
'pre-push',
'pre-rebase',
'pre-receive',
'prepare-commit-msg',
'push-to-checkout',
'update',
]);
}
return self::$hooks;
}
}
|
Move $locale closer to usage | <?php
namespace App\Handlers\Events;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\NewBooking;
use Notifynder;
use Log;
use Mail;
use App;
class SendBookingNotification
{
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param NewBooking $event
* @return void
*/
public function handle(NewBooking $event)
{
Log::info('Handle NewBooking.SendBookingNotification()');
$business_name = $event->appointment->business->name;
Notifynder::category('appointment.reserve')
->from('App\User', $event->user->id)
->to('App\Business', $event->appointment->business->id)
->url('http://localhost')
->extra(compact('business_name'))
->send();
$locale = App::getLocale();
Mail::send("emails.{$locale}.appointments._new", ['user' => $event->user, 'appointment' => $event->appointment], function ($m) use ($event) {
$m->to($event->user->email, $event->user->name)->subject(trans('emails.appointment.reserved.subject'));
});
}
}
| <?php
namespace App\Handlers\Events;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\NewBooking;
use Notifynder;
use Log;
use Mail;
use App;
class SendBookingNotification
{
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param NewBooking $event
* @return void
*/
public function handle(NewBooking $event)
{
Log::info('Handle NewBooking.SendBookingNotification()');
$locale = App::getLocale();
$business_name = $event->appointment->business->name;
Notifynder::category('appointment.reserve')
->from('App\User', $event->user->id)
->to('App\Business', $event->appointment->business->id)
->url('http://localhost')
->extra(compact('business_name'))
->send();
Mail::send("emails.{$locale}.appointments._new", ['user' => $event->user, 'appointment' => $event->appointment], function ($m) use ($event) {
$m->to($event->user->email, $event->user->name)->subject(trans('emails.appointment.reserved.subject'));
});
}
}
|
Remove hard coded experiment description. Remove done field and add status field since that is what we get from the backend. | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = '';
this.aim = '';
this.status = 'in-progress';
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
| export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = 'Look at grain size as it relates to hardness';
this.aim = '';
this.done = false;
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
|
Check for all exceptions to main method | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import sys
import argparse
import tmux_wrapper as tmux
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def load_session_presets():
try:
file_path = os.environ["TM_SESSIONS"]
except KeyError:
return None
try:
with open(file_path) as f:
config = json.load(f)
except IOError:
print("Invalid TM_SESSIONS environmental variable: cannot open file {}".format(file_path))
def main(argv):
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument("session",
metavar="session",
type=str,
nargs="?",
help="the name of the tmux session to start or attach")
parser.add_argument("-l", "--list",
action="store_true",
help="list all open sessions and session presets")
parser.add_argument("-k", "--kill",
metavar="session",
action="store",
help="kill a session")
args = parser.parse_args()
if len(argv) == 0:
parser.print_help()
if args.kill:
try:
tmux.kill(args.kill)
except (tmux.ServerConnectionError, tmux.SessionDoesNotExist), e:
print(e.description)
elif args.list:
try:
print tmux.list()
except tmux.ServerConnectionError, e:
print(e.description)
elif args.session:
tmux.create_or_attach(args.session)
if __name__ == "__main__":
main(sys.argv[1:]) | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import sys
import argparse
import tmux_wrapper as tmux
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def load_session_presets():
try:
file_path = os.environ["TM_SESSIONS"]
except KeyError:
return None
try:
with open(file_path) as f:
config = json.load(f)
except IOError:
print("Invalid TM_SESSIONS environmental variable: cannot open file {}".format(file_path))
def main(argv):
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument("session",
metavar="session",
type=str,
nargs="?",
help="the name of the tmux session to start or attach")
parser.add_argument("-l", "--list",
action="store_true",
help="list all open sessions and session presets")
parser.add_argument("-k", "--kill",
metavar="session",
action="store",
help="kill a session")
args = parser.parse_args()
if len(argv) == 0:
parser.print_help()
if args.kill:
try:
tmux.kill(args.kill)
except tmux.ServerConnectionError, e:
print(e.description)
elif args.list:
print tmux.list()
elif args.session:
tmux.create_or_attach(args.session)
if __name__ == "__main__":
main(sys.argv[1:]) |
Change delegate to make it safer
Up till now the delegate would've failed without any error if there was no response or if the middleware it was supposed to trigger was null (end of stack) | <?php
declare(strict_types=1);
namespace Onion\Framework\Http\Middleware;
use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message;
final class Delegate implements DelegateInterface
{
/**
* @var ServerMiddlewareInterface
*/
protected $middleware;
/**
* @var Message\ResponseInterface
*/
protected $response;
/**
* MiddlewareDelegate constructor.
*
* @param ServerMiddlewareInterface[] $middleware Middleware of the frame
*/
public function __construct(array $middleware, Message\ResponseInterface $response = null)
{
$this->middleware = $middleware;
$this->response = $response;
}
/**
* @param Message\RequestInterface $request
*
* @throws Exceptions\MiddlewareException if returned response is not instance of ResponseInterface
* @return Message\ResponseInterface
*/
public function process(Message\ServerRequestInterface $request): Message\ResponseInterface
{
if ($this->middleware !== []) {
$middleware = array_shift($this->middleware);
if ($middleware !== null) {
if (!$middleware instanceof ServerMiddlewareInterface) {
throw new \TypeError(
'All members of middleware must implement ServerMiddlewareInterface'
);
}
return $middleware->process($request, $this);
}
}
if (null === $this->response) {
throw new \RuntimeException('No response template provide');
}
return $this->response;
}
}
| <?php
declare(strict_types=1);
namespace Onion\Framework\Http\Middleware;
use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message;
final class Delegate implements DelegateInterface
{
/**
* @var ServerMiddlewareInterface
*/
protected $middleware;
/**
* @var Message\ResponseInterface
*/
protected $response;
/**
* MiddlewareDelegate constructor.
*
* @param ServerMiddlewareInterface[] $middleware Middleware of the frame
*/
public function __construct(array $middleware, Message\ResponseInterface $response = null)
{
$this->middleware = $middleware;
$this->response = $response;
}
/**
* @param Message\RequestInterface $request
*
* @throws Exceptions\MiddlewareException if returned response is not instance of ResponseInterface
* @return Message\ResponseInterface
*/
public function process(Message\ServerRequestInterface $request): Message\ResponseInterface
{
if ($this->middleware !== []) {
$middleware = array_shift($this->middleware);
if ($middleware !== null) {
if (!$middleware instanceof ServerMiddlewareInterface) {
throw new \TypeError(
'All members of middleware must implement ServerMiddlewareInterface'
);
}
}
return $middleware->process($request, $this);
}
return $this->response;
}
}
|
Add legacy support for i18n and backbone | //Generator http://patorjk.com/software/taag/#p=display&h=1&f=Banner4&t=Focus-COMPONENTS
import './style';
import translation from 'focus-core/translation';
import history from 'focus-core/history';
const infos = require(`${__PACKAGE_JSON_PATH__}/package.json`);
import components from './components';
import behaviours from './behaviours';
/** LEGACY DIRTY HACKISH RUBBISH TRICK */
window.i18n = {
t: translation.translate,
init: translation.init
};
window.Backbone = {
history
};
/**
* Display information data for Focus-COMPONENTS
*/
const infosFn = function infos() {
console.log(
`
FOCUS COMPONENTS
version: ${infos.version}
focus-components: ${infos.homepage}
documentation: ${infos.documentation}
issues: ${infos.bugs.url}
`
);
};
module.exports = {
VERSION: infos.version,
AUTHORS: infos.author,
NAME: infos.name,
/**
* Display documentation data
*/
DOCUMENTATION: function() {
console.log('documentation: http://kleegroup.github.io/focus-components');
console.log('components available');
console.table(infos.components);
console.log(`repository: ${infos.repository.url}`);
console.log(`issues: ${infos.bugs.url}`);
},
common: require('./common'),
list: require('./list'),
search: require('./search'),
page: require('./page'),
message: require('./message'),
application: require('./application'),
infos: infosFn,
components,
behaviours
};
| //Generator http://patorjk.com/software/taag/#p=display&h=1&f=Banner4&t=Focus-COMPONENTS
import './style';
const infos = require(`${__PACKAGE_JSON_PATH__}/package.json`);
import components from './components';
import behaviours from './behaviours';
/**
* Display information data for Focus-COMPONENTS
*/
const infosFn = function infos() {
console.log(
`
FOCUS COMPONENTS
version: ${infos.version}
focus-components: ${infos.homepage}
documentation: ${infos.documentation}
issues: ${infos.bugs.url}
`
);
};
module.exports = {
VERSION: infos.version,
AUTHORS: infos.author,
NAME: infos.name,
/**
* Display documentation data
*/
DOCUMENTATION: function() {
console.log('documentation: http://kleegroup.github.io/focus-components');
console.log('components available');
console.table(infos.components);
console.log(`repository: ${infos.repository.url}`);
console.log(`issues: ${infos.bugs.url}`);
},
common: require('./common'),
list: require('./list'),
search: require('./search'),
page: require('./page'),
message: require('./message'),
application: require('./application'),
infos: infosFn,
components,
behaviours
};
|
Fix regex when no date is specified in the url, thx @kashike | $(function() {
var moving = false;
var availableDays = JSON.parse($('#available-log-days').text());
var $dateInput = $('#log-date');
$dateInput.datepicker({
format: "yyyy/mm/dd",
endDate: "today",
todayBtn: "linked",
language: "en-GB",
orientation: "top right",
forceParse: false,
beforeShowDay: function (date) {
for(var i = 0; i < availableDays.length; ++i) {
if(date.getDate() === availableDays[i].day
&& date.getMonth() + 1 === availableDays[i].month
&& date.getYear() + 1900 === availableDays[i].year) {
return 'has-data';
}
}
return true;
}
});
$('label[for=log-date]').click(function() {
$dateInput.datepicker('show');
});
$dateInput.change(function() {
if(moving) {
return;
}
moving = true;
window.location = window.location.href.replace(/logs\/?.*/, 'logs/' + $dateInput.val());
})
});
| $(function() {
var moving = false;
var availableDays = JSON.parse($('#available-log-days').text());
var $dateInput = $('#log-date');
$dateInput.datepicker({
format: "yyyy/mm/dd",
endDate: "today",
todayBtn: "linked",
language: "en-GB",
orientation: "top right",
forceParse: false,
beforeShowDay: function (date) {
for(var i = 0; i < availableDays.length; ++i) {
if(date.getDate() === availableDays[i].day
&& date.getMonth() + 1 === availableDays[i].month
&& date.getYear() + 1900 === availableDays[i].year) {
return 'has-data';
}
}
return true;
}
});
$('label[for=log-date]').click(function() {
$dateInput.datepicker('show');
});
$dateInput.change(function() {
if(moving) {
return;
}
moving = true;
window.location = window.location.href.replace(/logs\/.*/, 'logs/' + $dateInput.val());
})
});
|
Use filter macro for request validation
StringifiedTrytesArray(Type) filter macro was
introduced in #243. Becasue of this, no request
filter test case is needed, hence the macro is
covered already in other test cases. | # coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from typing import Iterable, List, Optional
import filters as f
from iota import Transaction, TransactionHash
from iota.commands.core import GetTrytesCommand
from iota.commands import FilterCommand, RequestFilter
from iota.filters import StringifiedTrytesArray
__all__ = [
'GetTransactionObjectsCommand',
]
class GetTransactionObjectsCommand(FilterCommand):
"""
Executes `GetTransactionObjectsCommand` command.
See :py:meth:`iota.api.Iota.get_transaction_objects`.
"""
command = 'getTransactionObjects'
def get_request_filter(self):
return GetTransactionObjectsRequestFilter()
def get_response_filter(self):
pass
def _execute(self, request):
hashes = request\
.get('hashes') # type: Iterable[TransactionHash]
transactions = []
if hashes:
gt_response = GetTrytesCommand(adapter=self.adapter)(hashes=hashes)
transactions = list(map(
Transaction.from_tryte_string,
gt_response.get('trytes') or [],
)) # type: List[Transaction]
return {
'transactions': transactions,
}
class GetTransactionObjectsRequestFilter(RequestFilter):
def __init__(self):
super(GetTransactionObjectsRequestFilter, self).__init__({
'hashes':
StringifiedTrytesArray(TransactionHash) | f.Required
}) | # coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from typing import Iterable, List, Optional
import filters as f
from iota import Transaction, TransactionHash
from iota.commands.core import GetTrytesCommand
from iota.commands import FilterCommand, RequestFilter
from iota.filters import Trytes
__all__ = [
'GetTransactionObjectsCommand',
]
class GetTransactionObjectsCommand(FilterCommand):
"""
Executes `GetTransactionObjectsCommand` command.
See :py:meth:`iota.api.StrictIota.get_transaction_objects`.
"""
command = 'getTransactionObjects'
def get_request_filter(self):
return GetTransactionObjectsRequestFilter()
def get_response_filter(self):
pass
def _execute(self, request):
hashes = request\
.get('hashes') # type: Optional[Iterable[TransactionHash]]
transactions = []
if hashes:
gt_response = GetTrytesCommand(adapter=self.adapter)(hashes=hashes)
transactions = list(map(
Transaction.from_tryte_string,
gt_response.get('trytes') or [],
)) # type: List[Transaction]
return {
'transactions': transactions,
}
class GetTransactionObjectsRequestFilter(RequestFilter):
def __init__(self):
super(GetTransactionObjectsRequestFilter, self).__init__({
'hashes':
f.Required | f.Array | f.FilterRepeater(
f.Required |
Trytes(TransactionHash) |
f.Unicode(encoding='ascii', normalize=False),
),
}) |
Prepare the analyzer base config values before opening the config dialog (setting default values) | 'use strict';
import _ from 'lodash/core';
import ConfigurationEditController from './config.edit.controller';
import configurationEditTpl from './config.edit.modal.html';
export default class OrganizationConfigsController {
constructor($log, $uibModal, AnalyzerService, NotificationService) {
'ngInject';
this.$log = $log;
this.$uibModal = $uibModal;
this.AnalyzerService = AnalyzerService;
this.NotificationService = NotificationService;
this.state = {
filter: ''
};
}
edit(config) {
let modal = this.$uibModal.open({
controller: ConfigurationEditController,
templateUrl: configurationEditTpl,
controllerAs: '$modal',
size: 'lg',
resolve: {
configuration: () => {
let conf = angular.copy(config);
_.forEach(conf.configurationItems, item => {
conf.config[item.name] =
item.defaultValue || (item.multi ? [null] : undefined);
});
return conf;
}
}
});
modal.result
.then(configuration =>
this.AnalyzerService.saveConfiguration(config.name, {
config: configuration
})
)
.then(() => this.AnalyzerService.configurations())
.then(configs => (this.configurations = configs))
.then(() =>
this.NotificationService.success(
`Configuration ${config.name} updated successfully`
)
)
.catch(err => {
if (!_.isString(err)) {
this.NotificationService.error(
`Failed to update configuration ${config.name}`
);
}
});
}
}
| 'use strict';
import _ from 'lodash/core';
import ConfigurationEditController from './config.edit.controller';
import configurationEditTpl from './config.edit.modal.html';
export default class OrganizationConfigsController {
constructor($log, $uibModal, AnalyzerService, NotificationService) {
'ngInject';
this.$log = $log;
this.$uibModal = $uibModal;
this.AnalyzerService = AnalyzerService;
this.NotificationService = NotificationService;
this.state = {
filter: ''
};
}
edit(config) {
let modal = this.$uibModal.open({
controller: ConfigurationEditController,
templateUrl: configurationEditTpl,
controllerAs: '$modal',
size: 'lg',
resolve: {
configuration: () => angular.copy(config)
}
});
modal.result
.then(configuration =>
this.AnalyzerService.saveConfiguration(config.name, {
config: configuration
})
)
.then(() => this.AnalyzerService.configurations())
.then(configs => (this.configurations = configs))
.then(() =>
this.NotificationService.success(
`Configuration ${config.name} updated successfully`
)
)
.catch(err => {
if (!_.isString(err)) {
this.NotificationService.error(
`Failed to update configuration ${config.name}`
);
}
});
}
}
|
Update grunt watch to include sass | module.exports = function(grunt) {
grunt.initConfig({
coffee: {
compile: {
options: {
bare: false,
join: true
},
files: {
'blitz.js': ['lib/blitz.coffee'],
'test/blitz_test.js': ['test/blitz_test.coffee']
}
}
},
uglify: {
options: {
report: 'min'
},
dist: {
src: 'blitz.js',
dest: 'blitz.min.js'
}
},
mocha: {
src: ['test/test.html'],
options: {
bail: true,
log: true,
run: true,
mocha: {
ignoreLeaks: true
}
}
},
sass: {
dist: {
options: {
outputStyle: 'nested'
},
files: {
'blitz.css': 'blitz.scss'
}
}
},
watch: {
scripts: {
files: ['lib/*.coffee', 'test/*.coffee'],
tasks: ['coffee:compile']
},
sass: {
files: ['*.scss'],
tasks: ['sass']
}
}
});
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('default', ['coffee:compile', 'sass', 'mocha']);
grunt.registerTask('release', ['default', 'uglify']);
};
| module.exports = function(grunt) {
grunt.initConfig({
coffee: {
compile: {
options: {
bare: false,
join: true
},
files: {
'blitz.js': ['lib/blitz.coffee'],
'test/blitz_test.js': ['test/blitz_test.coffee']
}
}
},
uglify: {
options: {
report: 'min'
},
dist: {
src: 'blitz.js',
dest: 'blitz.min.js'
}
},
mocha: {
src: ['test/test.html'],
options: {
bail: true,
log: true,
run: true,
mocha: {
ignoreLeaks: true
}
}
},
sass: {
dist: {
options: {
outputStyle: 'nested'
},
files: {
'blitz.css': 'blitz.scss'
}
}
},
watch: {
files: ['lib/*.coffee', 'test/*.coffee'],
tasks: ['coffee:compile']
}
});
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('default', ['coffee:compile', 'sass', 'mocha']);
grunt.registerTask('release', ['default', 'uglify']);
};
|
Add api and model to packages | from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
raise SystemExit(errno)
with open('README.rst') as file:
long_description = file.read()
setup(
name='webpay',
packages=['webpay', 'webpay.api', 'webpay.model'],
version='0.1.0',
author='webpay',
author_email='[email protected]',
url='https://github.com/webpay/webpay-python',
description='WebPay Python bindings',
cmdclass={'test': PyTest},
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
requires=[
'requests (== 2.0.1)'
]
)
| from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
raise SystemExit(errno)
with open('README.rst') as file:
long_description = file.read()
setup(
name='webpay',
packages=['webpay'],
version='0.1.0',
author='webpay',
author_email='[email protected]',
url='https://github.com/webpay/webpay-python',
description='WebPay Python bindings',
cmdclass={'test': PyTest},
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
requires=[
'requests (== 2.0.1)'
]
)
|
Fix bug that can happen when configuration file doesn't exist | var Promise = require('../utils/promise');
var validateConfig = require('./validateConfig');
var CONFIG_FILES = require('../constants/configFiles');
/**
Parse configuration from "book.json" or "book.js"
@param {Book} book
@return {Promise<Book>}
*/
function parseConfig(book) {
var fs = book.getFS();
var config = book.getConfig();
return Promise.some(CONFIG_FILES, function(filename) {
// Is this file ignored?
if (book.isFileIgnored(filename)) {
return;
}
// Try loading it
return fs.loadAsObject(filename)
.then(function(cfg) {
return fs.statFile(filename)
.then(function(file) {
return {
file: file,
values: cfg
};
});
})
.fail(function(err) {
if (err.code != 'MODULE_NOT_FOUND') throw(err);
else return Promise(false);
});
})
.then(function(result) {
var values = result? result.values : {};
values = validateConfig(values);
// Set the file
if (result.file) {
config = config.setFile(result.file);
}
// Merge with old values
config = config.mergeValues(values);
return book.setConfig(config);
});
}
module.exports = parseConfig;
| var Promise = require('../utils/promise');
var validateConfig = require('./validateConfig');
var CONFIG_FILES = require('../constants/configFiles');
/**
Parse configuration from "book.json" or "book.js"
@param {Book} book
@return {Promise<Book>}
*/
function parseConfig(book) {
var fs = book.getFS();
var config = book.getConfig();
return Promise.some(CONFIG_FILES, function(filename) {
// Is this file ignored?
if (book.isFileIgnored(filename)) {
return;
}
// Try loading it
return Promise.all([
fs.loadAsObject(filename),
fs.statFile(filename)
])
.spread(function(cfg, file) {
return {
file: file,
values: cfg
};
})
.fail(function(err) {
if (err.code != 'MODULE_NOT_FOUND') throw(err);
else return Promise(false);
});
})
.then(function(result) {
var values = result? result.values : {};
values = validateConfig(values);
// Set the file
if (result.file) {
config = config.setFile(result.file);
}
// Merge with old values
config = config.mergeValues(values);
return book.setConfig(config);
});
}
module.exports = parseConfig;
|
Fix the manager methods for deferred/non_deferred | from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)
def normal_priority(self):
"""
Return a QuerySet of normal priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_NORMAL)
def low_priority(self):
"""
Return a QuerySet of low priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_LOW)
def non_deferred(self):
"""
Return a QuerySet containing all non-deferred queued messages.
"""
return self.filter(deferred=None)
def deferred(self):
"""
Return a QuerySet of all deferred messages in the queue.
"""
return self.exclude(deferred=None)
def retry_deferred(self, new_priority=None):
"""
Reset the deferred flag for all deferred messages so they will be
retried.
"""
count = self.deferred().count()
update_kwargs = dict(deferred=False, retries=models.F('retries')+1)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs)
return count
| from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)
def normal_priority(self):
"""
Return a QuerySet of normal priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_NORMAL)
def low_priority(self):
"""
Return a QuerySet of low priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_LOW)
def non_deferred(self):
"""
Return a QuerySet containing all non-deferred queued messages.
"""
return self.filter(deferred=False)
def deferred(self):
"""
Return a QuerySet of all deferred messages in the queue.
"""
return self.filter(deferred=True)
def retry_deferred(self, new_priority=None):
"""
Reset the deferred flag for all deferred messages so they will be
retried.
"""
count = self.deferred().count()
update_kwargs = dict(deferred=False, retries=models.F('retries')+1)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs)
return count
|
feat: Remove label and just show checkbox | import React from 'react';
import PropTypes from 'prop-types';
import { RadioGroup, Radio, Checkbox } from '@blueprintjs/core';
import { NotificationTypes } from 'enums';
const NotificationsPanel = ({
notificationType,
onSettingsChange,
setNotificationType,
continuousMode,
setContinuousMode
}) => (
<div className="mt-1">
<Checkbox
label="Ask for confirmation before moving onto the next phase"
checked={continuousMode}
onChange={e => {
onSettingsChange(
'system.continuousMode',
e.target.checked,
setContinuousMode
);
}}
/>
<RadioGroup
label="Notify me of..."
onChange={e =>
onSettingsChange(
'system.notificationType',
e.target.value,
setNotificationType
)}
selectedValue={notificationType}
>
<Radio
label="Phase changes when window is not active"
value={NotificationTypes.PHASE_CHANGES_NO_WINDOW}
/>
<Radio
label="Phase changes all the time"
value={NotificationTypes.PHASE_CHANGES_ALL}
/>
</RadioGroup>
</div>
);
NotificationsPanel.propTypes = {
notificationType: PropTypes.string.isRequired,
onSettingsChange: PropTypes.func.isRequired,
setNotificationType: PropTypes.func.isRequired,
continuousMode: PropTypes.bool.isRequired,
setContinuousMode: PropTypes.func.isRequired
};
export default NotificationsPanel;
| import React from 'react';
import PropTypes from 'prop-types';
import { RadioGroup, Radio, Checkbox } from '@blueprintjs/core';
import { NotificationTypes } from 'enums';
const NotificationsPanel = ({
notificationType,
onSettingsChange,
setNotificationType,
continuousMode,
setContinuousMode
}) => (
<div className="mt-1">
<label className="pt-label">Continuous Mode</label>
<Checkbox
label="Ask for confirmation before moving onto the next phase"
checked={continuousMode}
onChange={e => {
onSettingsChange(
'system.continuousMode',
e.target.checked,
setContinuousMode
);
}}
/>
<RadioGroup
label="Notify me of..."
onChange={e =>
onSettingsChange(
'system.notificationType',
e.target.value,
setNotificationType
)}
selectedValue={notificationType}
>
<Radio
label="Phase changes when window is not active"
value={NotificationTypes.PHASE_CHANGES_NO_WINDOW}
/>
<Radio
label="Phase changes all the time"
value={NotificationTypes.PHASE_CHANGES_ALL}
/>
</RadioGroup>
</div>
);
NotificationsPanel.propTypes = {
notificationType: PropTypes.string.isRequired,
onSettingsChange: PropTypes.func.isRequired,
setNotificationType: PropTypes.func.isRequired,
continuousMode: PropTypes.bool.isRequired,
setContinuousMode: PropTypes.func.isRequired
};
export default NotificationsPanel;
|
Fix incorrect issue ref in test | package com.fasterxml.jackson.dataformat.xml.misc;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.XmlTestBase;
// test(s) for [dataformat-xml#169]
public class EmptyPolymorphicTest extends XmlTestBase
{
static class Data {
public String name;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({ @JsonSubTypes.Type(EmptyProxy.class) })
public Proxy proxy;
public Data() { }
public Data(String n) {
name = n;
proxy = new EmptyProxy();
}
}
static interface Proxy { }
@JsonTypeName("empty")
static class EmptyProxy implements Proxy { }
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
protected XmlMapper MAPPER = new XmlMapper();
public void testEmpty() throws Exception
{
String xml = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(new Data("Foobar"));
//System.out.println("XML:\n"+xml);
final Data data = MAPPER.readValue(xml, Data.class);
// "<data><name>Foobar</name><proxy><empty></empty></proxy></data>"
assertNotNull(data);
}
}
| package com.fasterxml.jackson.dataformat.xml.misc;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.XmlTestBase;
// test(s) for [dataformat-xml#111]
public class EmptyPolymorphicTest extends XmlTestBase
{
static class Data {
public String name;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({ @JsonSubTypes.Type(EmptyProxy.class) })
public Proxy proxy;
public Data() { }
public Data(String n) {
name = n;
proxy = new EmptyProxy();
}
}
static interface Proxy { }
@JsonTypeName("empty")
static class EmptyProxy implements Proxy { }
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
protected XmlMapper MAPPER = new XmlMapper();
public void testEmpty() throws Exception
{
String xml = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(new Data("Foobar"));
//System.out.println("XML:\n"+xml);
final Data data = MAPPER.readValue(xml, Data.class);
// "<data><name>Foobar</name><proxy><empty></empty></proxy></data>"
assertNotNull(data);
}
}
|
Refactor view widget Twig extension. | <?php declare(strict_types=1);
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\AdminBundle\Twig\Extension;
use Darvin\AdminBundle\View\Widget\WidgetPool;
use Darvin\Utils\Service\ServiceProviderInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* View widget Twig extension
*/
class ViewWidgetExtension extends AbstractExtension
{
/**
* @var \Darvin\Utils\Service\ServiceProviderInterface
*/
private $widgetPoolProvider;
/**
* @param \Darvin\Utils\Service\ServiceProviderInterface $widgetPoolProvider View widget pool provider
*/
public function __construct(ServiceProviderInterface $widgetPoolProvider)
{
$this->widgetPoolProvider = $widgetPoolProvider;
}
/**
* {@inheritdoc}
*/
public function getFunctions(): iterable
{
foreach ($this->getWidgetPool()->getWidgets() as $alias => $widget) {
yield new TwigFunction(sprintf('admin_widget_%s', $alias), [$widget, 'getContent'], [
'is_safe' => ['html'],
]);
}
}
/**
* @return \Darvin\AdminBundle\View\Widget\WidgetPool
*/
private function getWidgetPool(): WidgetPool
{
return $this->widgetPoolProvider->getService();
}
}
| <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\AdminBundle\Twig\Extension;
use Darvin\Utils\Service\ServiceProviderInterface;
/**
* View widget Twig extension
*/
class ViewWidgetExtension extends \Twig_Extension
{
/**
* @var \Darvin\Utils\Service\ServiceProviderInterface
*/
private $widgetPoolProvider;
/**
* @param \Darvin\Utils\Service\ServiceProviderInterface $widgetPoolProvider View widget pool provider
*/
public function __construct(ServiceProviderInterface $widgetPoolProvider)
{
$this->widgetPoolProvider = $widgetPoolProvider;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
$functions = [];
foreach ($this->getWidgetPool()->getWidgets() as $alias => $widget) {
$functions[] = new \Twig_SimpleFunction('admin_widget_'.$alias, [$widget, 'getContent'], [
'is_safe' => ['html'],
]);
}
return $functions;
}
/**
* @return \Darvin\AdminBundle\View\Widget\WidgetPool
*/
private function getWidgetPool()
{
return $this->widgetPoolProvider->getService();
}
}
|
Add hyperlink to spendings in search view | @extends('layout')
@section('body')
<h1>Search</h1>
<form method="GET" class="tight">
<div class="row spacing-top-large">
<div class="column">
<input type="text" name="query" />
</div>
<div class="column tight">
<input type="submit" value="Search" />
</div>
</div>
</form>
@if (!empty($query))
@if (sizeof($earnings))
<h2 class="spacing-top-large spacing-bottom-medium">Earnings</h2>
<table class="box">
<thead>
<tr>
<th>Description</th>
</tr>
</thread>
<tbody>
@foreach ($earnings as $earning)
<tr>
<td>{{ $earning->description }}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
@if (sizeof($spendings))
<h2 class="spacing-top-large spacing-bottom-medium">Spendings</h2>
<table class="box">
<thead>
<tr>
<th>Description</th>
</tr>
</thread>
<tbody>
@foreach ($spendings as $spending)
<tr>
<td>
<a href="/spendings/{{ $spending->id }}">{{ $spending->description }}</a>
</td>
</tr>
@endforeach
</tbody>
</table>
@endif
@endif
@endsection
| @extends('layout')
@section('body')
<h1>Search</h1>
<form method="GET" class="tight">
<div class="row spacing-top-large">
<div class="column">
<input type="text" name="query" />
</div>
<div class="column tight">
<input type="submit" value="Search" />
</div>
</div>
</form>
@if (!empty($query))
@if (sizeof($earnings))
<h2 class="spacing-top-large spacing-bottom-medium">Earnings</h2>
<table class="box">
<thead>
<tr>
<th>Description</th>
</tr>
</thread>
<tbody>
@foreach ($earnings as $earning)
<tr>
<td>{{ $earning->description }}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
@if (sizeof($spendings))
<h2 class="spacing-top-large spacing-bottom-medium">Spendings</h2>
<table class="box">
<thead>
<tr>
<th>Description</th>
</tr>
</thread>
<tbody>
@foreach ($spendings as $spending)
<tr>
<td>{{ $spending->description }}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
@endif
@endsection
|
Store timestamp also in articles | var MongoClient = require("mongodb").MongoClient;
var config = require("./config.json");
var dbConnection = null;
function getDB() {
return new Promise(function(resolve, reject) {
if (!dbConnection) {
var mongoServerUri = 'mongodb://' +
config.mongodb.user + ':' + config.mongodb.password + '@' +
config.mongodb.host + '/' + config.mongodb.database +
'?authSource=' + config.mongodb.authSource;
MongoClient
.connect(mongoServerUri)
.then(function(db) {
console.log("Connected to mongodb");
dbConnection = db;
dbConnection.on("close", function(err) {
console.log("Mongodb connection closed. Reason:", err);
}).on("error", function(err) {
console.log("Mongodb error:", err);
});
resolve(dbConnection);
}, function(err) {
reject(err);
});
} else {
resolve(dbConnection);
}
});
}
module.exports.saveRawArticles = function(rawArticles) {
getDB().then(function (db) {
console.log("Received " + rawArticles.length + " articles");
rawArticles.forEach(function (article) {
article._id = article.id;
article.timestamp = new Date();
db.collection('raw-articles').insertOne(article).then(function(res) {
console.log(res.insertedCount + " raw article stored in db: " + article.id);
}, function(err) {
console.log("Mongodb error: ", err.errmsg);
});
});
});
};
| var MongoClient = require("mongodb").MongoClient;
var config = require("./config.json");
var dbConnection = null;
function getDB() {
return new Promise(function(resolve, reject) {
if (!dbConnection) {
var mongoServerUri = 'mongodb://' +
config.mongodb.user + ':' + config.mongodb.password + '@' +
config.mongodb.host + '/' + config.mongodb.database +
'?authSource=' + config.mongodb.authSource;
MongoClient
.connect(mongoServerUri)
.then(function(db) {
console.log("Connected to mongodb");
dbConnection = db;
dbConnection.on("close", function(err) {
console.log("Mongodb connection closed. Reason:", err);
}).on("error", function(err) {
console.log("Mongodb error:", err);
});
resolve(dbConnection);
}, function(err) {
reject(err);
});
} else {
resolve(dbConnection);
}
});
}
module.exports.saveRawArticles = function(rawArticles) {
getDB().then(function (db) {
console.log("Received " + rawArticles.length + " articles");
rawArticles.forEach(function (article) {
article._id = article.id;
db.collection('raw-articles').insertOne(article).then(function(res) {
console.log(res.insertedCount + " raw article stored in db: " + article.id);
}, function(err) {
console.log("Mongodb error: ", err.errmsg);
});
});
});
};
|
Remove the topic and time from the pandas index so they are included in the json output again. | """Serializers for the use with rest-pandas"""
from rest_framework import serializers
from .models import MQTTMessage
import re
import copy
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = MQTTMessage
fields = ['id', 'time_recorded', 'topic', 'payload']
pandas_index = ['id']
def generate_parsing_serializer_class(regex):
"""Generate a serializer class from a regular expression."""
regex = re.compile(regex)
groups = regex.groupindex.keys()
# Copy vanilla MessageSerializer class
class_name = 'DynamicParsingMessageSerializer'
parent_classes = (MessageSerializer,)
class_dict = {}
meta_dict = copy.deepcopy(MessageSerializer.Meta.__dict__)
class_dict['Meta'] = type('Meta', (object,), meta_dict)
# Add additional parsed fields
for group in groups:
name, typ = MQTTMessage._parse_group_name(group)
# Add custom field to the serializer
class_dict['parsed_'+name] = serializers.SerializerMethodField()
class_dict['Meta'].fields.append('parsed_'+name)
# Add a method to actually get the value
def _f(self, obj):
parsed = obj.parse_payload(regex)
if parsed is None or name not in parsed:
return None
else:
return parsed[name]
class_dict['get_parsed_'+name] = _f
return type(class_name, parent_classes, class_dict)
| """Serializers for the use with rest-pandas"""
from rest_framework import serializers
from .models import MQTTMessage
import re
import copy
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = MQTTMessage
fields = ['id', 'time_recorded', 'topic', 'payload']
pandas_index = ['time_recorded', 'topic', 'id']
def generate_parsing_serializer_class(regex):
"""Generate a serializer class from a regular expression."""
regex = re.compile(regex)
groups = regex.groupindex.keys()
# Copy vanilla MessageSerializer class
class_name = 'DynamicParsingMessageSerializer'
parent_classes = (MessageSerializer,)
class_dict = {}
meta_dict = copy.deepcopy(MessageSerializer.Meta.__dict__)
class_dict['Meta'] = type('Meta', (object,), meta_dict)
# Add additional parsed fields
for group in groups:
name, typ = MQTTMessage._parse_group_name(group)
# Add custom field to the serializer
class_dict['parsed_'+name] = serializers.SerializerMethodField()
class_dict['Meta'].fields.append('parsed_'+name)
# Add a method to actually get the value
def _f(self, obj):
parsed = obj.parse_payload(regex)
if parsed is None or name not in parsed:
return None
else:
return parsed[name]
class_dict['get_parsed_'+name] = _f
return type(class_name, parent_classes, class_dict)
|
FIX password reset method that was not resetting the password | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, models
from odoo.addons.auth_signup.models.res_partner import now
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
def action_reset_password(self):
create_mode = bool(self.env.context.get('create_user'))
# Only override the rest behavior, not normal signup
if create_mode:
super(ResUsers, self).action_reset_password()
else:
expiration = now(days=+1)
self.mapped('partner_id').signup_prepare(
signup_type="reset", expiration=expiration)
config = self.env.ref(
'partner_communication_switzerland.reset_password_email')
for user in self:
self.env['partner.communication.job'].create({
'partner_id': user.partner_id.id,
'config_id': config.id
})
@api.multi
def _compute_signature_letter(self):
""" Translate country in Signature (for Compassion Switzerland) """
for user in self:
employee = user.employee_ids
signature = ''
if len(employee) == 1:
signature += employee.name + '<br/>'
if employee.department_id:
signature += employee.department_id.name + '<br/>'
signature += user.company_id.name.split(' ')[0] + ' '
signature += user.company_id.country_id.name
user.signature_letter = signature
| # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, models
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
def action_reset_password(self):
create_mode = bool(self.env.context.get('create_user'))
# Only override the rest behavior, not normal signup
if create_mode:
super(ResUsers, self).action_reset_password()
else:
config = self.env.ref(
'partner_communication_switzerland.reset_password_email')
for user in self:
self.env['partner.communication.job'].create({
'partner_id': user.partner_id.id,
'config_id': config.id
})
@api.multi
def _compute_signature_letter(self):
""" Translate country in Signature (for Compassion Switzerland) """
for user in self:
employee = user.employee_ids
signature = ''
if len(employee) == 1:
signature += employee.name + '<br/>'
if employee.department_id:
signature += employee.department_id.name + '<br/>'
signature += user.company_id.name.split(' ')[0] + ' '
signature += user.company_id.country_id.name
user.signature_letter = signature
|
FIX Ensure file is written after FileSize is set | <?php
/**
* Post upgrade, update filesizes for assets uploaded prior to FileSize capture
*
* @author marcus
*/
class UpdateFileSizeTask extends BuildTask
{
public function run($request)
{
$number = $request->getVar('number');
if (!$number) {
$number = 50;
}
if (!$request->getVar('run')) {
exit("Please supply the run= parameter, and a 'number' parameter (defaults to 50 if not set)");
}
$files = File::get()->filter(['FileSize' => 0, 'ClassName:not' => 'Folder', 'CDNFile:PartialMatch' => ':||'])->limit($number);
echo "Processing " . $number . " files<br/>\n"; flush();
foreach ($files as $file) {
echo "Downloading $file->ClassName #{$file->ID} " . $file->Title . " ... "; flush();
$file->ensureLocalFile();
if ($file->localFileExists()) {
$file->FileSize = filesize($file->getFullPath());
echo "filesize {$file->FileSize} ... "; flush();
if ($file instanceof CdnImage) {
$dim = $file->getDimensions();
echo "dimensions $dim ... "; flush();
}
$file->write();
unlink($file->getFullPath());
} else {
echo " cannot download $file->Title - $file->CDNFile <br/>\n";
}
echo "<br/>\n";
}
}
}
| <?php
/**
* Post upgrade, update filesizes for assets uploaded prior to FileSize capture
*
* @author marcus
*/
class UpdateFileSizeTask extends BuildTask
{
public function run($request)
{
$number = $request->getVar('number');
if (!$number) {
$number = 50;
}
if (!$request->getVar('run')) {
exit("Please supply the run= parameter, and a 'number' parameter (defaults to 50 if not set)");
}
$files = File::get()->filter(['FileSize' => 0, 'ClassName:not' => 'Folder', 'CDNFile:PartialMatch' => ':||'])->limit($number);
echo "Processing " . $number . " files<br/>\n"; flush();
foreach ($files as $file) {
echo "Downloading $file->ClassName #{$file->ID} " . $file->Title . " ... "; flush();
$file->ensureLocalFile();
if ($file->localFileExists()) {
$file->FileSize = filesize($file->getFullPath());
echo "filesize {$file->FileSize} ... "; flush();
if ($file instanceof CdnImage) {
$dim = $file->getDimensions();
echo "dimensions $dim ... "; flush();
}
unlink($file->getFullPath());
} else {
echo " cannot download $file->Title - $file->CDNFile <br/>\n";
}
echo "<br/>\n";
}
}
}
|
Return xls as type for application/vnd.ms-excel. | (function(module) {
module.directive("displayFileContents", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: "E",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,
scope: {
file: '=file'
},
templateUrl: 'application/core/projects/project/files/display-file-contents.html'
};
}
module.controller("DisplayFileContentsDirectiveController", DisplayFileContentsDirectiveController);
DisplayFileContentsDirectiveController.$inject = ["mcfile"];
/* @ngInject */
function DisplayFileContentsDirectiveController(mcfile) {
var ctrl = this;
ctrl.fileType = determineFileType(ctrl.file.mediatype);
ctrl.fileSrc = mcfile.src(ctrl.file.id);
//////////////
function determineFileType(mediatype) {
if (isImage(mediatype.mime)) {
return "image";
} else {
switch(mediatype.mime) {
case "application/pdf":
return "pdf";
case "application/vnd.ms-excel":
return "xls";
default:
return mediatype.mime;
}
}
}
}
}(angular.module('materialscommons')));
| (function(module) {
module.directive("displayFileContents", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: "E",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,
scope: {
file: '=file'
},
templateUrl: 'application/core/projects/project/files/display-file-contents.html'
};
}
module.controller("DisplayFileContentsDirectiveController", DisplayFileContentsDirectiveController);
DisplayFileContentsDirectiveController.$inject = ["mcfile"];
/* @ngInject */
function DisplayFileContentsDirectiveController(mcfile) {
var ctrl = this;
ctrl.fileType = determineFileType(ctrl.file.mediatype);
ctrl.fileSrc = mcfile.src(ctrl.file.id);
//////////////
function determineFileType(mediatype) {
if (isImage(mediatype.mime)) {
return "image";
} else {
switch(mediatype.mime) {
case "application/pdf":
return "pdf";
case "application/vnd.ms-excel":
return "excel";
default:
return mediatype.mime;
}
}
}
}
}(angular.module('materialscommons')));
|
Remove unnecessary parsing of body -- it's already an object. | var http = require('http');
var r = require('request');
var config = require('./config.json');
var doneUrl;
var userUrl;
http.createServer(function(request, response) {
if (!isEvent(request)) return;
r.post({
url: doneUrl
}, function(error, response, body) {
if (error !== null) {
throw error;
}
r.post({
url: doneUrl,
form: {
authUrl: userUrl
}
}, function(error, response, body) {
if (error !== null) {
throw error;
}
});
});
}).listen(config.port);
var isEvent = function(request) {
return request.url === config.eventsUrl && request.method === 'POST';
};
var helperUrl = config.helper.host + config.helper.endpoint;
r.post({
url: helperUrl,
body: {
media: {
type: "url",
content: config.sampleImageUrl
},
eventsURL: config.eventsUrl
},
json: true
}, function(error, response, body) {
if (error !== null) {
throw error;
}
doneUrl = body.doneUrl;
userUrl = body.userUrl;
});
| var http = require('http');
var r = require('request');
var config = require('./config.json');
var doneUrl;
var userUrl;
http.createServer(function(request, response) {
if (!isEvent(request)) return;
r.post({
url: doneUrl
}, function(error, response, body) {
if (error !== null) {
throw error;
}
r.post({
url: doneUrl,
form: {
authUrl: userUrl
}
}, function(error, response, body) {
if (error !== null) {
throw error;
}
});
});
}).listen(config.port);
var isEvent = function(request) {
return request.url === config.eventsUrl && request.method === 'POST';
};
var helperUrl = config.helper.host + config.helper.endpoint;
r.post({
url: helperUrl,
body: {
media: {
type: "url",
content: config.sampleImageUrl
},
eventsURL: config.eventsUrl
},
json: true
}, function(error, response, body) {
if (error !== null) {
throw error;
}
var bodyInJson = JSON.parse(body);
doneUrl = bodyInJson.doneUrl;
userUrl = bodyInJson.userUrl;
});
|
III-2522: Fix language factory method test | <?php
namespace CultuurNet\UDB3;
use CultuurNet\UDB3\Model\ValueObject\Translation\Language as Udb3ModelLanguage;
use InvalidArgumentException;
use PHPUnit_Framework_TestCase;
class LanguageTest extends PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_requires_an_iso_639_1_code()
{
$language = new Language('en');
$this->assertEquals('en', $language->getCode());
}
/**
* Data provider with invalid codes.
*
* @return array
*/
public function invalidCodes()
{
return [
['eng'],
['dut'],
[false],
[true],
[null],
['09'],
['whatever'],
];
}
/**
* @test
* @dataProvider invalidCodes
* @param mixed $invalid_code
*/
public function it_refuses_something_that_does_not_look_like_a_iso_639_1_code(
$invalid_code
) {
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid language code: ' . $invalid_code);
new Language($invalid_code);
}
/**
* @test
*/
public function it_should_be_creatable_from_an_udb3_model_language()
{
$udb3ModelLanguage = new Udb3ModelLanguage('nl');
$expected = new Language('nl');
$actual = Language::fromUdb3ModelLanguage($udb3ModelLanguage);
$this->assertEquals($expected, $actual);
}
}
| <?php
namespace CultuurNet\UDB3;
use InvalidArgumentException;
use PHPUnit_Framework_TestCase;
class LanguageTest extends PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_requires_an_iso_639_1_code()
{
$language = new Language('en');
$this->assertEquals('en', $language->getCode());
}
/**
* Data provider with invalid codes.
*
* @return array
*/
public function invalidCodes()
{
return [
['eng'],
['dut'],
[false],
[true],
[null],
['09'],
['whatever'],
];
}
/**
* @test
* @dataProvider invalidCodes
* @param mixed $invalid_code
*/
public function it_refuses_something_that_does_not_look_like_a_iso_639_1_code(
$invalid_code
) {
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid language code: ' . $invalid_code);
new Language($invalid_code);
}
public function it_should_be_creatable_from_an_udb3_model_language()
{
$udb3ModelLanguage = new \CultuurNet\UDB3\Model\ValueObject\Translation\Language('nl');
$expected = new Language('nl');
$actual = Language::fromUdb3ModelLanguage($udb3ModelLanguage);
$this->assertEquals($expected, $actual);
}
}
|
Extend AbstractArezTest otherwise invariant checking state is not controlled and thus some tests may fail | package org.realityforge.arez;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class DisposableTest
extends AbstractArezTest
{
static class TestDisposable
implements Disposable
{
private boolean _disposed;
@Override
public void dispose()
{
_disposed = true;
}
@Override
public boolean isDisposed()
{
return _disposed;
}
}
@Test
public void randomObject()
throws Exception
{
//No exception but no action
final Object object = new Object();
assertEquals( Disposable.isDisposed( object ), false );
Disposable.dispose( object );
assertEquals( Disposable.isDisposed( object ), false );
}
@Test
public void disposable()
throws Exception
{
final TestDisposable object = new TestDisposable();
assertEquals( object.isDisposed(), false );
assertEquals( Disposable.isDisposed( object ), false );
Disposable.dispose( object );
assertEquals( object.isDisposed(), true );
assertEquals( Disposable.isDisposed( object ), true );
}
@Test
public void asDisposable()
throws Exception
{
final TestDisposable object = new TestDisposable();
assertEquals( Disposable.asDisposable( object ), object );
final Object element = new Object();
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> Disposable.asDisposable( element ) );
assertEquals( exception.getMessage(),
"Object passed to asDisposable does not implement Disposable. Object: " + element );
}
}
| package org.realityforge.arez;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class DisposableTest
{
static class TestDisposable
implements Disposable
{
private boolean _disposed;
@Override
public void dispose()
{
_disposed = true;
}
@Override
public boolean isDisposed()
{
return _disposed;
}
}
@Test
public void randomObject()
throws Exception
{
//No exception but no action
final Object object = new Object();
assertEquals( Disposable.isDisposed( object ), false );
Disposable.dispose( object );
assertEquals( Disposable.isDisposed( object ), false );
}
@Test
public void disposable()
throws Exception
{
final TestDisposable object = new TestDisposable();
assertEquals( object.isDisposed(), false );
assertEquals( Disposable.isDisposed( object ), false );
Disposable.dispose( object );
assertEquals( object.isDisposed(), true );
assertEquals( Disposable.isDisposed( object ), true );
}
@Test
public void asDisposable()
throws Exception
{
final TestDisposable object = new TestDisposable();
assertEquals( Disposable.asDisposable( object ), object );
final Object element = new Object();
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> Disposable.asDisposable( element ) );
assertEquals( exception.getMessage(),
"Object passed to asDisposable does not implement Disposable. Object: " + element );
}
}
|
Correct THE stupid mistake. Now we have a string! | package framework.util;
import framework.util.RingBuffer;
import framework.generators.Generator;
/**
* Models a guitar string using the Karplus-Strong algorithm.
*/
public class GuitarString {
/**
* Create a GuitarString of the given frequency.
* @param f the frequency
*/
public GuitarString(Double f) {
N = (int) (Generator.SAMPLE_RATE / f);
buffer = new RingBuffer(N);
// Guitar string at rest
for(int i = 0; i < N; i++)
buffer.enqueue(0.);
}
/**
* Models the plucking of the string.
*/
public void pluck() {
for(int i = 0; i < N; i++) {
// Enqueue random value between -0.5 and 0.5 (noise)
buffer.enqueue(Math.random() - 0.5);
}
}
/**
* Apply the Karplus-Strong update.
*/
public void tic() {
buffer.enqueue((buffer.dequeue() + buffer.peek()) / 2 * ENERGY_DECAY_FACTOR);
}
/**
* Get the value at the front of the buffer.
* @return the value at the front of the buffer
*/
public Double sample() {
return buffer.peek();
}
RingBuffer buffer;
int N;
final Double ENERGY_DECAY_FACTOR = 0.996;
} | package framework.util;
import framework.util.RingBuffer;
import framework.generators.Generator;
/**
* Models a guitar string using the Karplus-Strong algorithm.
*/
public class GuitarString {
/**
* Create a GuitarString of the given frequency.
* @param f the frequency
*/
public GuitarString(Double f) {
N = (int) (Generator.SAMPLE_RATE / f);
buffer = new RingBuffer(N);
// Guitar string at rest
for(int i = 0; i < N; i++)
buffer.enqueue(0.);
}
/**
* Models the plucking of the string.
*/
public void pluck() {
for(int i = 0; i < N; i++) {
// Enqueue random value between -0.5 and 0.5 (noise)
buffer.enqueue(Math.random() - 0.5);
}
}
/**
* Apply the Karplus-Strong update.
*/
public void tic() {
Double first = buffer.dequeue();
buffer.enqueue((first * buffer.peek()) * 0.5 * ENERGY_DECAY_FACTOR);
}
/**
* Get the value at the front of the buffer.
* @return the value at the front of the buffer
*/
public Double sample() {
return buffer.peek();
}
RingBuffer buffer;
int N;
final Double ENERGY_DECAY_FACTOR = 0.996;
} |
Change querying param to variable | import React, { useEffect, useState } from "react";
import classes from "./SelectCompetition.module.css";
import CompetitionCard from "../../components/CompetitionCard/CompetitionCard";
import LinkButton from "../../components/UI/LinkButton/LinkButton";
const SelectCompetition = (props) => {
const userId = 123;
const [comps, setComps] = useState(null);
const renderCompCards = (compsList) => {
setComps(
compsList.map((comp) => {
return (
<CompetitionCard
key={comp.id}
id={comp.id}
name={comp.competitionName}
organiser={comp.organiserName}
organiserLdap={comp.organiserUsername}
startDate={comp.startDate}
endDate={comp.endDate}
></CompetitionCard>
);
})
);
};
useEffect(() => {
fetch("./competitionInfo?userId=" + userId)
.then((response) => response.json())
.then((data) => {
console.log(data);
renderCompCards(data);
});
}, [userId]);
return (
<div className={classes.SelectCompetitionContainer}>
<p>Select a competition...</p>
<div className={classes.CardsContainer}>
<ul>{comps}</ul>
</div>
<p>Or...</p>
<LinkButton>Create a competition</LinkButton>
</div>
);
};
export default SelectCompetition;
| import React, { useEffect, useState } from "react";
import classes from "./SelectCompetition.module.css";
import CompetitionCard from "../../components/CompetitionCard/CompetitionCard";
import LinkButton from "../../components/UI/LinkButton/LinkButton";
const SelectCompetition = (props) => {
const userId = 123;
const [comps, setComps] = useState(null);
const renderCompCards = (compsList) => {
setComps(
compsList.map((comp) => {
return (
<CompetitionCard
key={comp.id}
id={comp.id}
name={comp.competitionName}
organiser={comp.organiserName}
organiserLdap={comp.organiserUsername}
startDate={comp.startDate}
endDate={comp.endDate}
></CompetitionCard>
);
})
);
};
useEffect(() => {
fetch("./competitionInfo?userId=" + "123")
.then((response) => response.json())
.then((data) => {
console.log(data);
renderCompCards(data);
});
}, [userId]);
return (
<div className={classes.SelectCompetitionContainer}>
<p>Select a competition...</p>
<div className={classes.CardsContainer}>
<ul>{comps}</ul>
</div>
<p>Or...</p>
<LinkButton>Create a competition</LinkButton>
</div>
);
};
export default SelectCompetition;
|
Add test for fellow model | from django.test import TestCase
from .models import Fellow, Event
class FellowTestCase(TestCase):
def setUp(self):
fellows = (
{
"forenames": "A",
"surname": "C",
"affiliation": "King's College",
"research_area": "L391",
"email": "[email protected]",
"phone": "+441111111111",
"gender": "M",
"work_description": "Sociology of science & technology",
"year": "2013",
},
)
for fellow in fellows:
Fellow.objects.create(**fellow)
class EventTestCase(TestCase):
def setUp(self):
events = (
{
"fellow": 1,
"category": "O",
"name": "CW16",
"url": "http://www.software.ac.uk/cw16",
"location": "Edinburgh",
"start_date": "2016-03-18",
"end_date": "2016-03-20",
"budget_request_travel": 100.00,
"budget_request_attendance_fees": 50.00,
"budget_request_subsistence_cost": 50.00,
"budget_request_venue_hire": 0.00,
"budget_request_catering": 0.00,
"budget_request_others": 0.00,
"justification": "Collaborate.",
},
)
for event in events:
Event.objects.create(**event)
| from django.test import TestCase
from .models import Event
class EventTestCase(TestCase):
def setUp(self):
events = (
{
"fellow": 1,
"category": "O",
"name": "CW16",
"url": "http://www.software.ac.uk/cw16",
"location": "Edinburgh",
"start_date": "2016-03-18",
"end_date": "2016-03-20",
"budget_request_travel": 100.00,
"budget_request_attendance_fees": 50.00,
"budget_request_subsistence_cost": 50.00,
"budget_request_venue_hire": 0.00,
"budget_request_catering": 0.00,
"budget_request_others": 0.00,
"justification": "Collaborate.",
},
)
for event in events:
Event.objects.create(**event)
|
Set web middleware to get token | <?php
namespace Asvae\ApiTester\Providers;
use Illuminate\Routing\Router;
class RouteServiceProvider extends \Illuminate\Foundation\Support\Providers\RouteServiceProvider
{
/**
* Define the routes for the application.
*
* Module
* ├ Http
* │ └ routes.php
* │
* └ Providers
* └ [static]
*
* @param Router $router
*
* @return void
*/
public function map(Router $router)
{
$router->group([
'namespace' => $this->getNamespace(),
'middleware' => ['web'],
], function () {
$this->requireRoutes();
});
}
public function boot(Router $router)
{
parent::boot($router);
$this->loadViewsFrom(__DIR__.'/../resources/assets/views', 'api-tester');
$this->publishes([
__DIR__.'/../resources/assets/build' => public_path('vendor/api-tester'),
], 'public');
}
/**
* Get module namespace
*
* @return string
*/
protected function getNamespace()
{
return 'Asvae\ApiTester\Http\Controllers';
}
/**
* @return string
*/
protected function requireRoutes()
{
require __DIR__.'/../Http/routes.php';
}
} | <?php
namespace Asvae\ApiTester\Providers;
use Illuminate\Routing\Router;
class RouteServiceProvider extends \Illuminate\Foundation\Support\Providers\RouteServiceProvider
{
/**
* Define the routes for the application.
*
* Module
* ├ Http
* │ └ routes.php
* │
* └ Providers
* └ [static]
*
* @param Router $router
*
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->getNamespace()], function () {
$this->requireRoutes();
});
}
public function boot(Router $router)
{
parent::boot($router);
$this->loadViewsFrom(__DIR__.'/../resources/assets/views', 'api-tester');
$this->publishes([
__DIR__.'/../resources/assets/build' => public_path('vendor/api-tester'),
], 'public');
}
/**
* Get module namespace
*
* @return string
*/
protected function getNamespace()
{
return 'Asvae\ApiTester\Http\Controllers';
}
/**
* @return string
*/
protected function requireRoutes()
{
require __DIR__.'/../Http/routes.php';
}
} |
Fix mistake in geocoder reverse method | <?php
namespace Ivory\GoogleMapBundle\Model\Services\Geocoding;
use Geocoder\Geocoder as BaseGeocoder;
/**
* Geocoder which describes a google map geocoder
*
* @see http://code.google.com/apis/maps/documentation/javascript/reference.html#Geocoder
* @author GeLo <[email protected]>
*/
class Geocoder extends BaseGeocoder
{
/**
* {@inheritDoc}
*/
public function geocode($request)
{
if($this->getProvider() instanceof Provider)
{
$result = $this->retrieve($request);
if(is_null($result))
{
$result = $this->getProvider()->getGeocodedData($request);
$this->store($request, $result);
}
return $result;
}
else
return parent::geocode($request);
}
/**
* {@inheritDoc}
*/
public function reverse($latitude, $longitude)
{
if($this->getProvider() instanceof Provider)
{
$request = new GeocoderRequest();
$request->setCoordinate($latitude, $longitude);
return $this->geocode($request)
}
else
return parent::geocode($request);
}
}
| <?php
namespace Ivory\GoogleMapBundle\Model\Services\Geocoding;
use Geocoder\Geocoder as BaseGeocoder;
/**
* Geocoder which describes a google map geocoder
*
* @see http://code.google.com/apis/maps/documentation/javascript/reference.html#Geocoder
* @author GeLo <[email protected]>
*/
class Geocoder extends BaseGeocoder
{
/**
* {@inheritDoc}
*/
public function geocode($request)
{
if($this->getProvider() instanceof Provider)
{
$result = $this->retrieve($request);
if(is_null($result))
{
$result = $this->getProvider()->getGeocodedData($request);
$this->store($request, $result);
}
return $result;
}
else
return parent::geocode($request);
}
/**
* {@inheritDoc}
*/
public function reverse($latitude, $longitude)
{
if($this->getProvider() instanceof Provider)
{
$value = sprintf('%s-%s', $latitude, $longitude);
$result = $this->retrieve($value);
if(is_null($result))
{
$result = $this->getProvider()->getGeocodedData($geocoderRequest);
$this->store($value, $result);
}
return $result;
}
else
return parent::geocode($request);
}
}
|
Remove line break in tweets | 'use strict';
if (process.env.NODE_ENV === 'production') {
var Twit = Npm.require('twit');
var twitter = new Twit({
consumer_key: process.env.TWIT_KEY,
consumer_secret: process.env.TWIT_SECRET,
access_token: process.env.TWIT_TOKEN,
access_token_secret: process.env.TWIT_TOKEN_SECRET
});
var tweetHot = () => {
var hot = Posts.find({}, {
limit: 50,
sort: {
heat: -1
},
fields: {
oldChildren: false
}
}).fetch();
var finished = false;
_(hot).forEach((item) => {
// it hasn't been tweeted yet
if (finished === false && (typeof item.tweeted === 'undefined')) {
twitter.post('statuses/update',
{
status: item.title + 'http://beta.fraction.io/comments/' + item._id
}, (err /*, response */) => {
if (err) {
throw err;
}
});
Posts.update({
_id: item._id
}, {
$set: {
tweeted: true
}
});
console.log('Tweeting "' + item.title + '"');
finished = true;
}
});
};
//post a new link every 20 minutes
Meteor.setInterval(tweetHot, 20 * 60 * 1000);
}
| 'use strict';
if (process.env.NODE_ENV === 'production') {
var Twit = Npm.require('twit');
var twitter = new Twit({
consumer_key: process.env.TWIT_KEY,
consumer_secret: process.env.TWIT_SECRET,
access_token: process.env.TWIT_TOKEN,
access_token_secret: process.env.TWIT_TOKEN_SECRET
});
var tweetHot = () => {
var hot = Posts.find({}, {
limit: 50,
sort: {
heat: -1
},
fields: {
oldChildren: false
}
}).fetch();
var finished = false;
_(hot).forEach((item) => {
// it hasn't been tweeted yet
if (finished === false && (typeof item.tweeted === 'undefined')) {
twitter.post('statuses/update',
{
status: item.title + "\n" +
'http://beta.fraction.io/comments/' + item._id
}, (err /*, response */) => {
if (err) {
throw err;
}
});
Posts.update({
_id: item._id
}, {
$set: {
tweeted: true
}
});
console.log('Tweeting "' + item.title + '"');
finished = true;
}
});
};
//post a new link every 20 minutes
Meteor.setInterval(tweetHot, 20 * 60 * 1000);
}
|
Add vibration when time runs out. | (function () {
'use strict';
function WordCtrl(Term, Session, $location, $route, $scope) {
var time,
soundEffect = new Audio('/mp3/bike.mp3');
$scope.word = 'tralala';
$scope.started = false;
$scope.term = Term.get({
discipline: $route.current.params.discipline,
language: $route.current.params.language
});
$scope.start = function() {
$scope.started = true;
time = new Date().getTime();
};
$('.progress-bar').on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
soundEffect.play();
window.navigator.vibrate([200, 100, 200, 100, 200]);
$(this).unbind('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend');
});
$scope.redirect = function() {
// post results back here
time = new Date().getTime() - time;
Session.save({
time: time,
termId: $scope.term.id,
discipline: $route.current.params.discipline,
language: $route.current.params.language
},
function(response){
$location.path('/' + $route.current.params.language + '/summary');
});
};
}
angular.module('controllers') // [] instantiates controller module
.controller('WordCtrl', ['Term', 'Session', '$location', '$route', '$scope', WordCtrl]);
})(); | (function () {
'use strict';
function WordCtrl(Term, Session, $location, $route, $scope) {
var time;
$scope.word = 'tralala';
$scope.started = false;
$scope.term = Term.get({
discipline: $route.current.params.discipline,
language: $route.current.params.language
});
$scope.start = function() {
$scope.started = true;
time = new Date().getTime();
};
$('.progress-bar').on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
new Audio('/mp3/bike.mp3').play();
$(this).unbind('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend');
});
$scope.redirect = function() {
// post results back here
time = new Date().getTime() - time;
Session.save({
time: time,
termId: $scope.term.id,
discipline: $route.current.params.discipline,
language: $route.current.params.language
},
function(response){
$location.path('/' + $route.current.params.language + '/summary');
});
};
}
angular.module('controllers') // [] instantiates controller module
.controller('WordCtrl', ['Term', 'Session', '$location', '$route', '$scope', WordCtrl]);
})(); |
Fix bug of session data being stored with an extra `values` key | 'use strict';
export default {
setup,
};
/**
* Module dependencies.
*/
import SequelizeStore from 'koa-generic-session-sequelize';
// import convert from 'koa-convert';
import session from 'koa-generic-session';
/**
* Prepares session middleware and methods without attaching to the stack
*
* @param {Object} settings
* @param {Object} database
* @param {Object} [store] Store for `koa-generic-sessions`. Uses the database if a store is not provided
* @return {Object}
*/
function setup(settings, database, store) {
return {
// session middleware
session: session({
key: 'identityDesk.sid',
store: store || new SequelizeStore(database),
}),
sessionMethods: function(ctx, next) {
// set the secret keys for Keygrip
ctx.app.keys = settings.session.keys;
// attach session methods
ctx.identityDesk = {
get(key) {
if (ctx.session && ctx.session.identityDesk && ctx.session.identityDesk[key] !== undefined) {
return ctx.session.identityDesk[key];
} else {
return undefined;
}
},
set(values) {
ctx.session = ctx.session || { identityDesk: values };
ctx.session.identityDesk = ctx.session.identityDesk || values;
Object.assign(ctx.session.identityDesk, values);
},
};
return next();
},
};
} | 'use strict';
export default {
setup,
};
/**
* Module dependencies.
*/
import SequelizeStore from 'koa-generic-session-sequelize';
// import convert from 'koa-convert';
import session from 'koa-generic-session';
/**
* Prepares session middleware and methods without attaching to the stack
*
* @param {Object} settings
* @param {Object} database
* @param {Object} [store] Store for `koa-generic-sessions`. Uses the database if a store is not provided
* @return {Object}
*/
function setup(settings, database, store) {
return {
// session middleware
session: session({
key: 'identityDesk.sid',
store: store || new SequelizeStore(database),
}),
sessionMethods: function(ctx, next) {
// set the secret keys for Keygrip
ctx.app.keys = settings.session.keys;
// attach session methods
ctx.identityDesk = {
get(key) {
if (ctx.session && ctx.session.identityDesk && ctx.session.identityDesk[key] !== undefined) {
return ctx.session.identityDesk[key];
} else {
return undefined;
}
},
set(values) {
ctx.session = ctx.session || { identityDesk: { values } };
ctx.session.identityDesk = ctx.session.identityDesk || { values };
Object.assign(ctx.session.identityDesk, values);
},
};
return next();
},
};
} |
Fix endpoint for clone operation | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/upgrade/clone".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
| from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/changes".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
|
Fix logging, add a sleep to molify Google's rate limit. | """Geocode Contact objects."""
import sys
import time
from geopy import geocoders
from django.core.management.base import BaseCommand, CommandError
from portal import models
class Command(BaseCommand):
"""Set lat/long fields on contacts with a street address,
currently just using Google's geocoder."""
def handle(self, *args, **kwargs):
"""Run geocode."""
self.geocoder = geocoders.Google()
for contact in models.Contact.objects.all():
self.geocode_contact(contact)
def geocode_contact(self, contact):
"""Set lat/long fields on contact objects."""
if contact.street_address and not contact.lat:
sys.stderr.write("Geocoding: %s: %s\n" % (contact.repository.name, contact.format()))
try:
formaddr, latlon = self.geocoder.geocode(contact.format().encode("utf8"))
except ValueError:
sys.stderr.write(" - More than one value found!\n")
except geocoders.google.GTooManyQueriesError:
raise CommandError("Too many queries for Google Geocode.")
except geocoders.google.GQueryError:
sys.stderr.write(" - Unable to get latlong for address\n")
else:
contact.lat = latlon[0]
contact.lon = latlon[1]
contact.save()
sys.stderr.write("Set lat/lon: %s, %s\n\n" % latlon)
# delay to keep Google rate limit happy (hopefully)
time.sleep(0.25)
| """Geocode Contact objects."""
import sys
from geopy import geocoders
from django.core.management.base import BaseCommand, CommandError
from portal import models
class Command(BaseCommand):
"""Set lat/long fields on contacts with a street address,
currently just using Google's geocoder."""
def handle(self, *args, **kwargs):
"""Run geocode."""
self.geocoder = geocoders.GeoNames()
for contact in models.Contact.objects.all():
self.geocode_contact(contact)
def geocode_contact(self, contact):
"""Set lat/long fields on contact objects."""
if contact.street_address:
sys.stderr.write("Geocoding: %s: %s\n" % (contact.repository.name, contact.format()))
try:
formaddr, latlon = self.geocoder.geocode(contact.format().encode("utf8"))
except ValueError:
sys.stderr.write(" - More than one value found!\n")
except geocoders.google.GTooManyQueriesError:
raise CommandError("Too many queries for Google Geocode.")
except geocoders.google.GQueryError:
sys.stderr.write(" - Unable to get latlong for address\n")
else:
contact.lat = latlon[0]
contact.lon = latlon[1]
contact.save()
sys.stderr("Set lat/lon: %s, %s\n\n" % latlon)
|
Add type safety to the url parameters | <?php
namespace Backend\Modules\ContentBlocks\Api;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlock;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlockRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
final class ApiController
{
/** @var ContentBlockRepository */
private $blockRepository;
/** @var SerializerInterface */
private $serializer;
public function __construct(ContentBlockRepository $blockRepository, SerializerInterface $serializer)
{
$this->blockRepository = $blockRepository;
$this->serializer = $serializer;
}
/**
* @Rest\Get("/content-blocks")
*/
public function getContentblocksAction(): JsonResponse
{
return JsonResponse::create(
json_decode(
$this->serializer->serialize($this->blockRepository->findAll(), 'json'),
true
)
);
}
/**
* @Rest\Get("/content-blocks/{language}/{id}")
*/
public function getContentblockAction(string $language, int $id): JsonResponse
{
$contentBlock = $this->blockRepository->findOneBy(['locale' => $language, 'id' => $id]);
if (!$contentBlock instanceof ContentBlock) {
throw new NotFoundHttpException();
}
return JsonResponse::create(
json_decode(
$this->serializer->serialize($contentBlock, 'json'),
true
)
);
}
}
| <?php
namespace Backend\Modules\ContentBlocks\Api;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlock;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlockRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
final class ApiController
{
/** @var ContentBlockRepository */
private $blockRepository;
/** @var SerializerInterface */
private $serializer;
public function __construct(ContentBlockRepository $blockRepository, SerializerInterface $serializer)
{
$this->blockRepository = $blockRepository;
$this->serializer = $serializer;
}
/**
* @Rest\Get("/content-blocks")
*/
public function getContentblocksAction(): JsonResponse
{
return JsonResponse::create(
json_decode(
$this->serializer->serialize($this->blockRepository->findAll(), 'json'),
true
)
);
}
/**
* @Rest\Get("/content-blocks/{language}/{id}")
*
* @param string $language
* @param int $id
* @return JsonResponse
*/
public function getContentblockAction($language, $id): JsonResponse
{
$contentBlock = $this->blockRepository->findOneBy(['locale' => $language, 'id' => $id]);
if (!$contentBlock instanceof ContentBlock) {
throw new NotFoundHttpException();
}
return JsonResponse::create(
json_decode(
$this->serializer->serialize($contentBlock, 'json'),
true
)
);
}
}
|
Add identifier relation popout to grants and projects | <div class="related-grants-and-projects">
<h4>Related Grants and Projects</h4>
<ul class="list-unstyled">
@foreach($related['grants_projects']['docs'] as $col)
<li>
<i class="fa fa-flask icon-portal"></i>
<small>{{ $col['display_relationship'] }}</small>
<a href="{{ base_url() }}{{$col['to_slug']}}/{{$col['to_id']}}"
title="{{ $col['to_title'] }}"
class="ro_preview"
tip="{{ $col['display_description'] }}"
@if(isset($col['to_id']) && $col['to_id']!='false')
ro_id="{{ $col['to_id'] }}"
@elseif(isset($col["relation_identifier_id"]))
identifier_relation_id="{{ $col['relation_identifier_id'] }}"
@endif
>
{{$col['to_title']}}</a>
{{ isset($col['to_funder']) ? "(funded by ". $col['to_funder'] .")" : '' }}
</li>
@endforeach
@if($related['grants_projects']['count'] > 5)
<li><a href="{{ $related['grants_projects']['searchUrl'] }}">View all {{ $related['grants_projects']['count'] }} related grants and projects</a></li>
@endif
</ul>
</div> | <div class="related-grants-and-projects">
<h4>Related Grants and Projects</h4>
<ul class="list-unstyled">
@foreach($related['grants_projects']['docs'] as $col)
<li>
<i class="fa fa-flask icon-portal"></i>
<small>{{ $col['display_relationship'] }}</small>
<a href="{{ base_url() }}{{$col['to_slug']}}/{{$col['to_id']}}"
title="{{ $col['to_title'] }}"
class="ro_preview"
tip="{{ $col['display_description'] }}"
ro_id="{{ $col['to_id'] }}">
{{$col['to_title']}}</a>
{{ isset($col['to_funder']) ? "(funded by ". $col['to_funder'] .")" : '' }}
</li>
@endforeach
@if($related['grants_projects']['count'] > 5)
<li><a href="{{ $related['grants_projects']['searchUrl'] }}">View all {{ $related['grants_projects']['count'] }} related grants and projects</a></li>
@endif
</ul>
</div> |
Correct scroll on menu click | function generateMenu(nodes) {
let output = [];
nodes.forEach((node) => {
output.push(generateMenuFromNode(node));
});
return output.join('');
}
function generateMenuFromNode(node) {
if (node.children !== undefined && node.children.length > 0) {
let output = [
`<ul class='menu-block'>
${generateMenuItem({
tagClass: 'menu-block-header',
menuAnchor: node.children[0].metadata.menuAnchor,
label: node.children[0].metadata.label
})}
<ul class='menu-sub-block'>`];
for (let i = 1; i < node.children.length; i++) {
output.push(generateMenuFromNode(node.children[i]));
}
output.push(`
</ul>
</ul>`);
return output.join('');
}
return generateMenuItem({
tagClass: 'menu-sub-block-item',
menuAnchor: node.metadata.menuAnchor,
label: node.metadata.label
});
}
function generateMenuItem(menuItemCfg) {
return `
<li>
<a
class='${menuItemCfg.tagClass}'
onclick='(function (id) {
var e = document.getElementById(id);
if (e === undefined || e === null) {
console.warn("Cannot find element with id:", id);
return;
}
var offsetTop = e.offsetTop - 60;
console.log(offsetTop);
window.scrollTo(0, offsetTop);
})("${menuItemCfg.menuAnchor}")'>
${menuItemCfg.label}
</a>
</li>
`;
}
module.exports.generateMenu = generateMenu; | function generateMenu(nodes) {
let output = [];
nodes.forEach((node) => {
output.push(generateMenuFromNode(node));
});
return output.join('');
}
function generateMenuFromNode(node) {
if (node.children !== undefined && node.children.length > 0) {
let output = [
`<ul class='menu-block'>
${generateMenuItem({
tagClass: 'menu-block-header',
menuAnchor: node.children[0].metadata.menuAnchor,
label: node.children[0].metadata.label
})}
<ul class='menu-sub-block'>`];
for (let i = 1; i < node.children.length; i++) {
output.push(generateMenuFromNode(node.children[i]));
}
output.push(`
</ul>
</ul>`);
return output.join('');
}
return generateMenuItem({
tagClass: 'menu-sub-block-item',
menuAnchor: node.metadata.menuAnchor,
label: node.metadata.label
});
}
function generateMenuItem(menuItemCfg) {
return `
<li>
<a
class='${menuItemCfg.tagClass}'
href='#${menuItemCfg.menuAnchor}'>
${menuItemCfg.label}
</a>
</li>
`;
}
module.exports.generateMenu = generateMenu; |
Call parent constructor on response object
Signed-off-by: Roeland Jago Douma <[email protected]> | <?php
/**
* Audio Player
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the LICENSE.md file.
*
* @author Marcel Scherello <[email protected]>
* @author Olivier Paroz <[email protected]>
* @copyright 2016-2019 Marcel Scherello
*/
namespace OCA\audioplayer\Http;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http;
/**
* A renderer for cover arts
*/
class ImageResponse extends Response
{
private $preview;
/**
* @param array $image image meta data
* @param int $statusCode the Http status code, defaults to 200
*/
public function __construct(array $image, $statusCode = Http::STATUS_OK)
{
parent::__construct();
$this->preview = $image['content'];
$this->setStatus($statusCode);
$this->addHeader('Content-type', $image['mimetype'] . '; charset=utf-8');
$this->cacheFor(365 * 24 * 60 * 60);
$etag = md5($image['content']);
$this->setETag($etag);
}
/**
* Returns the rendered image
*
* @return string the file
*/
public function render()
{
if ($this->preview instanceof \OC_Image) {
return $this->preview->data();
} else {
return $this->preview;
}
}
}
| <?php
/**
* Audio Player
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the LICENSE.md file.
*
* @author Marcel Scherello <[email protected]>
* @author Olivier Paroz <[email protected]>
* @copyright 2016-2019 Marcel Scherello
*/
namespace OCA\audioplayer\Http;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http;
/**
* A renderer for cover arts
*/
class ImageResponse extends Response
{
private $preview;
/**
* @param array $image image meta data
* @param int $statusCode the Http status code, defaults to 200
*/
public function __construct(array $image, $statusCode = Http::STATUS_OK)
{
$this->preview = $image['content'];
$this->setStatus($statusCode);
$this->addHeader('Content-type', $image['mimetype'] . '; charset=utf-8');
$this->cacheFor(365 * 24 * 60 * 60);
$etag = md5($image['content']);
$this->setETag($etag);
}
/**
* Returns the rendered image
*
* @return string the file
*/
public function render()
{
if ($this->preview instanceof \OC_Image) {
return $this->preview->data();
} else {
return $this->preview;
}
}
}
|
Add compact and delete stubs | import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localhost', port=2379):
self.channel = grpc.insecure_channel('{host}:{port}'.format(
host=host, port=port)
)
self.kvstub = etcdrpc.KVStub(self.channel)
def get(self, key):
'''
Get the value of a key from etcd.
'''
range_request = etcdrpc.RangeRequest()
range_request.key = key.encode('utf-8')
range_response = self.kvstub.Range(range_request)
if range_response.count < 1:
raise exceptions.KeyNotFoundError(
'the key "{}" was not found'.format(key))
else:
# smells funny - there must be a cleaner way to get the value?
return range_response.kvs.pop().value
def put(self, key, value):
'''
Save a value to etcd.
'''
put_request = etcdrpc.PutRequest()
put_request.key = key.encode('utf-8')
put_request.value = value.encode('utf-8')
self.kvstub.Put(put_request)
def delete(self, key):
pass
def compact(self):
pass
def client():
'''Return an instance of an Etcd3Client'''
return Etcd3Client(host='localhost', port=2379)
| import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localhost', port=2379):
self.channel = grpc.insecure_channel('{host}:{port}'.format(
host=host, port=port)
)
self.kvstub = etcdrpc.KVStub(self.channel)
def get(self, key):
'''
Get the value of a key from etcd.
'''
range_request = etcdrpc.RangeRequest()
range_request.key = key.encode('utf-8')
range_response = self.kvstub.Range(range_request)
if range_response.count < 1:
raise exceptions.KeyNotFoundError(
'the key "{}" was not found'.format(key))
else:
# smells funny - there must be a cleaner way to get the value?
return range_response.kvs.pop().value
def put(self, key, value):
'''
Save a value to etcd.
'''
put_request = etcdrpc.PutRequest()
put_request.key = key.encode('utf-8')
put_request.value = value.encode('utf-8')
self.kvstub.Put(put_request)
def client():
'''Return an instance of an Etcd3Client'''
return Etcd3Client(host='localhost', port=2379)
|
Throw RuntimeException if getResourceName() fails | package com.xtremelabs.robolectric.res;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
public class ResourceExtractor {
private Map<String, Integer> resourceStringToId = new HashMap<String, Integer>();
private Map<Integer, String> resourceIdToString = new HashMap<Integer, String>();
public void addRClass(Class rClass) throws Exception {
for (Class innerClass : rClass.getClasses()) {
for (Field field : innerClass.getDeclaredFields()) {
if (field.getType().equals(Integer.TYPE) && Modifier.isStatic(field.getModifiers())) {
String name = innerClass.getSimpleName() + "/" + field.getName();
int value = field.getInt(null);
resourceStringToId.put(name, value);
resourceIdToString.put(value, name);
}
}
}
}
public int resourceIdOrZero(String resourceName) {
Integer resId = getResourceId(resourceName);
return (resId == null) ? 0 : resId;
}
public Integer getResourceId(String resourceName) {
if (resourceName == null) {
return null;
}
if (resourceName.startsWith("@+id")) {
resourceName = resourceName.substring(2);
} else if (resourceName.startsWith("@")) {
resourceName = resourceName.substring(1);
}
return resourceStringToId.get(resourceName);
}
public String getResourceName(int resourceId) {
String ret = resourceIdToString.get(resourceId);
if (ret == null)
throw new RuntimeException("Can't find resource "+resourceId);
return ret;
}
}
| package com.xtremelabs.robolectric.res;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
public class ResourceExtractor {
private Map<String, Integer> resourceStringToId = new HashMap<String, Integer>();
private Map<Integer, String> resourceIdToString = new HashMap<Integer, String>();
public void addRClass(Class rClass) throws Exception {
for (Class innerClass : rClass.getClasses()) {
for (Field field : innerClass.getDeclaredFields()) {
if (field.getType().equals(Integer.TYPE) && Modifier.isStatic(field.getModifiers())) {
String name = innerClass.getSimpleName() + "/" + field.getName();
int value = field.getInt(null);
resourceStringToId.put(name, value);
resourceIdToString.put(value, name);
}
}
}
}
public int resourceIdOrZero(String resourceName) {
Integer resId = getResourceId(resourceName);
return (resId == null) ? 0 : resId;
}
public Integer getResourceId(String resourceName) {
if (resourceName == null) {
return null;
}
if (resourceName.startsWith("@+id")) {
resourceName = resourceName.substring(2);
} else if (resourceName.startsWith("@")) {
resourceName = resourceName.substring(1);
}
return resourceStringToId.get(resourceName);
}
public String getResourceName(int resourceId) {
return resourceIdToString.get(resourceId);
}
} |
Add methods to work with retrieving bytes from ByteBuffer. | package com.sibilantsolutions.iptools.util;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public abstract class Convert
{
private Convert() {} //Prevent instantiation.
static public int byteToNum( byte b )
{
return b & 0xFF;
}
static public int getByte( ByteBuffer bb )
{
return byteToNum( bb.get() );
}
static public long toNum( ByteBuffer bb, int numBytes )
{
byte[] bytes = new byte[numBytes];
bb.get( bytes );
return toNum( bytes, 0, numBytes, bb.order() );
}
static public long toNum( byte[] bytes, int offset, int length )
{
return toNum( bytes, offset, length, ByteOrder.BIG_ENDIAN );
}
static public long toNum( byte[] bytes, int offset, int length, ByteOrder byteOrder )
{
long num = 0;
final int endIndex = offset + length;
if ( byteOrder == ByteOrder.BIG_ENDIAN )
{
while ( offset < endIndex )
{
char b = (char)( bytes[offset++] & 0xFF );
num <<= 8;
num += b;
}
}
else if ( byteOrder == ByteOrder.LITTLE_ENDIAN )
{
for ( int i = endIndex - 1; i >= offset; i-- )
{
char b = (char)( bytes[i] & 0xFF );
num <<= 8;
num += b;
}
}
else
{
throw new IllegalArgumentException( "Unexpected byte order=" + byteOrder );
}
return num;
}
}
| package com.sibilantsolutions.iptools.util;
import java.nio.ByteOrder;
public abstract class Convert
{
private Convert() {} //Prevent instantiation.
static public long toNum( byte[] bytes, int offset, int length )
{
return toNum( bytes, offset, length, ByteOrder.BIG_ENDIAN );
}
static public long toNum( byte[] bytes, int offset, int length, ByteOrder byteOrder )
{
long num = 0;
final int endIndex = offset + length;
if ( byteOrder == ByteOrder.BIG_ENDIAN )
{
while ( offset < endIndex )
{
char b = (char)( bytes[offset++] & 0xFF );
num <<= 8;
num += b;
}
}
else if ( byteOrder == ByteOrder.LITTLE_ENDIAN )
{
for ( int i = endIndex - 1; i >= offset; i-- )
{
char b = (char)( bytes[i] & 0xFF );
num <<= 8;
num += b;
}
}
else
{
throw new IllegalArgumentException( "Unexpected byte order=" + byteOrder );
}
return num;
}
}
|
ENH: Add very basic tests for codata and constants. |
import warnings
import codata
import constants
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = find('qwertyuiop', disp=False)
assert_equal(keys, [])
keys = find('natural unit', disp=False)
assert_equal(keys, sorted(['natural unit of velocity',
'natural unit of action',
'natural unit of action in eV s',
'natural unit of mass',
'natural unit of energy',
'natural unit of energy in MeV',
'natural unit of momentum',
'natural unit of momentum in MeV/c',
'natural unit of length',
'natural unit of time']))
def test_basic_table_parse():
c = 'speed of light in vacuum'
assert_equal(codata.value(c), constants.c)
assert_equal(codata.value(c), constants.speed_of_light)
def test_basic_lookup():
assert_equal('%d %s' % (codata.c, codata.unit('speed of light in vacuum')),
'299792458 m s^-1')
if __name__ == "__main__":
run_module_suite()
|
import warnings
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = find('qwertyuiop', disp=False)
assert_equal(keys, [])
keys = find('natural unit', disp=False)
assert_equal(keys, sorted(['natural unit of velocity',
'natural unit of action',
'natural unit of action in eV s',
'natural unit of mass',
'natural unit of energy',
'natural unit of energy in MeV',
'natural unit of momentum',
'natural unit of momentum in MeV/c',
'natural unit of length',
'natural unit of time']))
if __name__ == "__main__":
run_module_suite()
|
Update webpack settings for v2 | var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: path.join(__dirname, 'webapp', 'src'),
entry: {
main: './index.js'
},
output: {
path: path.join(__dirname, 'app', 'assets'),
filename: '[name].[hash].js',
publicPath: '/'
},
resolve: {
modules: [
path.join(__dirname, 'webapp', 'src'),
'node_modules'
]
},
devtool: "#source-map",
devServer: {
contentBase: path.join(__dirname, 'app', 'assets'),
port: 8090,
proxy: [{
context: ['/api/', '/invitation/', '/signin/', '/integrate/', '/auth/'],
target: 'http://localhost:8080/',
secure: false
}]
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
query:{
presets: ['es2015']
}
},
{
test: /\.hbs$/,
loader: 'handlebars-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'Custom template',
template: 'index.hbs',
})
],
externals: {
firebase: 'firebase',
jquery: 'jQuery'
}
}
| var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: path.join(__dirname, 'webapp', 'src'),
entry: {
main: './index.js'
},
output: {
path: path.join(__dirname, 'app', 'assets'),
filename: '[name].[hash].js',
publicPath: '/'
},
resolve: {
root: path.join(__dirname, 'webapp', 'src')
},
devtool: "#source-map",
devServer: {
contentBase: path.join(__dirname, 'app', 'assets'),
port: 8090,
proxy: [{
context: ['/api/', '/invitation/', '/signin/', '/integrate/', '/auth/'],
target: 'http://localhost:8080/',
secure: false
}]
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
query:{
presets: ['es2015']
}
},
{
test: /\.hbs$/,
loader: 'handlebars-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'Custom template',
template: 'index.hbs',
})
],
externals: {
firebase: 'firebase',
jquery: 'jQuery'
}
}
|
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command. | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
try:
# A settings module may be defined, but Django didn't attempt to
# load it yet. As an alternative to calling the private _setup(),
# we could also check whether DJANGO_SETTINGS_MODULE is set.
settings._setup()
except ImportError:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
else:
Loader = DjangoLoader
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
| import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
|
Stop auto fetching if view no more visible | /*global window: true */
define(
[
'text!templates/repoList.html',
'underscore',
'jquery',
'backbone'
],
function (template, _, $, Backbone) {
"use strict";
return Backbone.View.extend({
tagName: 'ul',
className: 'repos unstyled',
template: _.template(template),
initialize: function (options) {
this.repoCollection = options.repoCollection;
},
render: function () {
$('body').addClass('loading');
this.$el.html(this.template({
collection: this.repoCollection.presenter()
}));
},
autoFetch: function () {
var that = this;
if (false === $(this.el).is(':visible')) {
$('body').removeClass('loading');
return;
}
this.repoCollection.fetch().done(function () {
$('body').removeClass('loading');
that.render();
window.setTimeout(function () {
that.autoFetch();
}, 5000);
});
}
});
}
);
| /*global window: true */
define(
[
'text!templates/repoList.html',
'underscore',
'jquery',
'backbone'
],
function (template, _, $, Backbone) {
"use strict";
return Backbone.View.extend({
tagName: 'ul',
className: 'repos unstyled',
template: _.template(template),
initialize: function (options) {
this.repoCollection = options.repoCollection;
},
render: function () {
$('body').addClass('loading');
this.$el.html(this.template({
collection: this.repoCollection.presenter()
}));
},
autoFetch: function () {
var that = this;
this.repoCollection.fetch().done(function () {
$('body').removeClass('loading');
that.render();
window.setTimeout(function () {
that.autoFetch();
}, 5000);
});
}
});
}
);
|
Remove ‘using notify’ from nav (it’s a redirect now) | def features_nav():
return [
{
"name": "Features",
"link": "main.features",
"sub_navigation_items": [
{
"name": "Emails",
"link": "main.features_email",
},
{
"name": "Text messages",
"link": "main.features_sms",
},
{
"name": "Letters",
"link": "main.features_letters",
},
]
},
{
"name": "Roadmap",
"link": "main.roadmap",
},
{
"name": "Trial mode",
"link": "main.trial_mode_new",
},
{
"name": "Message status",
"link": "main.message_status",
},
{
"name": "Security",
"link": "main.security",
},
{
"name": "Terms of use",
"link": "main.terms",
},
]
| def features_nav():
return [
{
"name": "Features",
"link": "main.features",
"sub_navigation_items": [
{
"name": "Emails",
"link": "main.features_email",
},
{
"name": "Text messages",
"link": "main.features_sms",
},
{
"name": "Letters",
"link": "main.features_letters",
},
]
},
{
"name": "Roadmap",
"link": "main.roadmap",
},
{
"name": "Trial mode",
"link": "main.trial_mode_new",
},
{
"name": "Message status",
"link": "main.message_status",
},
{
"name": "Security",
"link": "main.security",
},
{
"name": "Terms of use",
"link": "main.terms",
},
{
"name": "Using Notify",
"link": "main.using_notify",
},
]
|
Adjust starting frequency to be more fun. | /** Global variables for processing.js access **/
var waveSpeed = 3;
var timestep = 0.3
var w = 0.25;
var w2 = 0.45;
var playing = false;
/** Page setup **/
$(document).ready(function() {
$("#speed-slider").slider({min: -5, max: 5, step: 0.1, slide: setAnimSpeed,
value: timestep});
$("#wave1-w-slider").slider({min: 0, max: 1, step: 0.03, slide: setW1,
value: w});
$("#wave2-w-slider").slider({min: 0, max: 1, step: 0.03, slide: setW2,
value: w2});
$("#play").click(function() {
var processing = Processing.getInstanceById("wave-sum-sim");
if (playing) {
processing.noLoop();
$("#play").html("Play");
} else {
processing.loop();
processing.draw();
$("#play").html("Pause");
}
playing = !playing;
});
});
function setAnimSpeed(event, ui) {
timestep = ui.value;
}
function setW1(event, ui) {
w = ui.value;
}
function setW2(event, ui) {
w2 = ui.value;
} | /** Global variables for processing.js access **/
var waveSpeed = 3;
var timestep = 0.3
var w = 0.3;
var w2 = 0.45;
var playing = false;
/** Page setup **/
$(document).ready(function() {
$("#speed-slider").slider({min: -5, max: 5, step: 0.1, slide: setAnimSpeed,
value: timestep});
$("#wave1-w-slider").slider({min: 0, max: 1, step: 0.03, slide: setW1,
value: w});
$("#wave2-w-slider").slider({min: 0, max: 1, step: 0.03, slide: setW2,
value: w2});
$("#play").click(function() {
var processing = Processing.getInstanceById("wave-sum-sim");
if (playing) {
processing.noLoop();
$("#play").html("Play");
} else {
processing.loop();
processing.draw();
$("#play").html("Pause");
}
playing = !playing;
});
});
function setAnimSpeed(event, ui) {
timestep = ui.value;
}
function setW1(event, ui) {
w = ui.value;
}
function setW2(event, ui) {
w2 = ui.value;
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.