text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix loading for Symfony 3 projects
In Symfony 3 the autoload file should always be loaded, and then the
cache file
This still works for Symfony 2 projects as the bootstrap uses
require_once for autoload | <?php
namespace Boris\Loader\Provider;
class Symfony2 extends AbstractProvider
{
public $name = 'symfony';
private $env;
private $debug;
public function __construct($environment = 'dev', $debug = true)
{
$this->env = $environment;
$this->debug = $debug;
}
public function assertDir($dir)
{
return (
is_file("$dir/app/bootstrap.php.cache") ||
is_file("$dir/app/autoload.php")
)
&& is_file("$dir/app/AppKernel.php");
}
public function initialize(\Boris\Boris $boris, $dir)
{
parent::initialize($boris, $dir);
if(is_file("$dir/app/autoload.php")) {
require "$dir/app/autoload.php";
}
if(is_file("$dir/app/bootstrap.php.cache")) {
require "$dir/app/bootstrap.php.cache";
}
require_once "$dir/app/AppKernel.php";
$kernel = new \AppKernel($this->env, $this->debug);
$kernel->loadClassCache();
$kernel->boot();
$boris->onStart(function ($worker, $vars) use ($kernel) {
$worker->setLocal('kernel', $kernel);
$worker->setLocal('container', $kernel->getContainer());
});
}
}
| <?php
namespace Boris\Loader\Provider;
class Symfony2 extends AbstractProvider
{
public $name = 'symfony';
private $env;
private $debug;
public function __construct($environment = 'dev', $debug = true)
{
$this->env = $environment;
$this->debug = $debug;
}
public function assertDir($dir)
{
return (
is_file("$dir/app/bootstrap.php.cache") ||
is_file("$dir/app/autoload.php")
)
&& is_file("$dir/app/AppKernel.php");
}
public function initialize(\Boris\Boris $boris, $dir)
{
parent::initialize($boris, $dir);
if(is_file("$dir/app/bootstrap.php.cache")) {
require "$dir/app/bootstrap.php.cache";
} else {
require "$dir/app/autoload.php";
}
require_once "$dir/app/AppKernel.php";
$kernel = new \AppKernel($this->env, $this->debug);
$kernel->loadClassCache();
$kernel->boot();
$boris->onStart(function ($worker, $vars) use ($kernel) {
$worker->setLocal('kernel', $kernel);
$worker->setLocal('container', $kernel->getContainer());
});
}
}
|
Add result property to AsyncResult
(it blocks if the result has not been previously retrieved, or return the
result otherwise) | """cell.result"""
from __future__ import absolute_import
from __future__ import with_statement
from kombu.pools import producers
from .exceptions import CellError, NoReplyError
__all__ = ['AsyncResult']
class AsyncResult(object):
Error = CellError
NoReplyError = NoReplyError
def __init__(self, ticket, actor):
self.ticket = ticket
self.actor = actor
self._result = None
def _first(self, replies):
if replies is not None:
replies = list(replies)
if replies:
return replies[0]
raise self.NoReplyError('No reply received within time constraint')
@property
def result(self):
if not self._result:
self._result = self.get()
return self.result
def get(self, **kwargs):
return self._first(self.gather(**dict(kwargs, limit=1)))
def gather(self, propagate=True, **kwargs):
connection = self.actor.connection
gather = self._gather
with producers[connection].acquire(block=True) as producer:
for r in gather(producer.connection, producer.channel, self.ticket,
propagate=propagate, **kwargs):
yield r
def _gather(self, *args, **kwargs):
propagate = kwargs.pop('propagate', True)
return (self.to_python(reply, propagate=propagate)
for reply in self.actor._collect_replies(*args, **kwargs))
def to_python(self, reply, propagate=True):
try:
return reply['ok']
except KeyError:
error = self.Error(*reply.get('nok') or ())
if propagate:
raise error
return error
| """cell.result"""
from __future__ import absolute_import
from __future__ import with_statement
from kombu.pools import producers
from .exceptions import CellError, NoReplyError
__all__ = ['AsyncResult']
class AsyncResult(object):
Error = CellError
NoReplyError = NoReplyError
def __init__(self, ticket, actor):
self.ticket = ticket
self.actor = actor
def _first(self, replies):
if replies is not None:
replies = list(replies)
if replies:
return replies[0]
raise self.NoReplyError('No reply received within time constraint')
def get(self, **kwargs):
return self._first(self.gather(**dict(kwargs, limit=1)))
def gather(self, propagate=True, **kwargs):
connection = self.actor.connection
gather = self._gather
with producers[connection].acquire(block=True) as producer:
for r in gather(producer.connection, producer.channel, self.ticket,
propagate=propagate, **kwargs):
yield r
def _gather(self, *args, **kwargs):
propagate = kwargs.pop('propagate', True)
return (self.to_python(reply, propagate=propagate)
for reply in self.actor._collect_replies(*args, **kwargs))
def to_python(self, reply, propagate=True):
try:
return reply['ok']
except KeyError:
error = self.Error(*reply.get('nok') or ())
if propagate:
raise error
return error
|
Fix PHP 5.6 compatibility for null driver
See https://github.com/laravel/scout/pull/224 | <?php
namespace Laravel\Scout;
use Illuminate\Support\Manager;
use AlgoliaSearch\Client as Algolia;
use Laravel\Scout\Engines\NullEngine;
use Laravel\Scout\Engines\AlgoliaEngine;
use AlgoliaSearch\Version as AlgoliaUserAgent;
class EngineManager extends Manager
{
/**
* Get a driver instance.
*
* @param string|null $name
* @return mixed
*/
public function engine($name = null)
{
return $this->driver($name);
}
/**
* Create an Algolia engine instance.
*
* @return \Laravel\Scout\Engines\AlgoliaEngine
*/
public function createAlgoliaDriver()
{
AlgoliaUserAgent::addSuffixUserAgentSegment('Laravel Scout', '3.0.7');
return new AlgoliaEngine(new Algolia(
config('scout.algolia.id'), config('scout.algolia.secret')
));
}
/**
* Create a Null engine instance.
*
* @return \Laravel\Scout\Engines\NullEngine
*/
public function createNullDriver()
{
return new NullEngine;
}
/**
* Get the default session driver name.
*
* @return string
*/
public function getDefaultDriver()
{
if (is_null($this->app['config']['scout.driver'])) {
return 'null';
}
return $this->app['config']['scout.driver'];
}
}
| <?php
namespace Laravel\Scout;
use Illuminate\Support\Manager;
use AlgoliaSearch\Client as Algolia;
use Laravel\Scout\Engines\NullEngine;
use Laravel\Scout\Engines\AlgoliaEngine;
use AlgoliaSearch\Version as AlgoliaUserAgent;
class EngineManager extends Manager
{
/**
* Get a driver instance.
*
* @param string|null $name
* @return mixed
*/
public function engine($name = null)
{
return $this->driver($name);
}
/**
* Create an Algolia engine instance.
*
* @return \Laravel\Scout\Engines\AlgoliaEngine
*/
public function createAlgoliaDriver()
{
AlgoliaUserAgent::addSuffixUserAgentSegment('Laravel Scout', '3.0.7');
return new AlgoliaEngine(new Algolia(
config('scout.algolia.id'), config('scout.algolia.secret')
));
}
/**
* Create a Null engine instance.
*
* @return \Laravel\Scout\Engines\NullEngine
*/
public function createNullDriver()
{
return new NullEngine;
}
/**
* Get the default session driver name.
*
* @return string
*/
public function getDefaultDriver()
{
return $this->app['config']['scout.driver'] ?? 'null';
}
}
|
Use forever instead of forever-mac. | var forever = require('forever');
var config = require('./config');
function start () {
forever.list('array', function (err, processes) {
// stop all forever
if (config === 'stop') {
if (!processes) {
return console.log('no process to stop');
}
forever.stopAll();
console.log('process stoped');
return;
}
// stop on config errors
if (typeof config === 'string') {
return console.log(config);
}
if (processes) {
return console.log('server already running');
}
// start the server directly
if (config.dev) {
return require(config.paths.PROXY_SERVER);
}
// start proxy as a deamon
forever.startDaemon(config.paths.PROXY_SERVER, {
"max" : config.attempts,
"minUptime" : config.minUptime,
"spinSleepTime" : config.spinSleepTime,
"silent" : config.silent,
"verbose" : config.verbose,
"logFile" : config.log
});
console.log('server is running in the background');
});
}
exports.start = start;
| var forever = require('forever-mac');
var config = require('./config');
function start () {
forever.list('array', function (err, processes) {
// stop all forever
if (config === 'stop') {
if (!processes) {
return console.log('no process to stop');
}
forever.stopAll();
console.log('process stoped');
return;
}
// stop on config errors
if (typeof config === 'string') {
return console.log(config);
}
if (processes) {
return console.log('server already running');
}
// start the server directly
if (config.dev) {
return require(config.paths.PROXY_SERVER);
}
// start proxy as a deamon
forever.startDaemon(config.paths.PROXY_SERVER, {
"max" : config.attempts,
"minUptime" : config.minUptime,
"spinSleepTime" : config.spinSleepTime,
"silent" : config.silent,
"verbose" : config.verbose,
"logFile" : config.log
});
console.log('server is running in the background');
});
}
exports.start = start;
|
Fix foreign key name for oauth_client_metadata rollback | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateOauthClientMetadataTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('oauth_client_metadata', function (Blueprint $table) {
$table->increments('id');
$table->string('client_id', 40);
$table->string('key', 40);
$table->string('value');
$table->timestamps();
$table->foreign('client_id')
->references('id')->on('oauth_clients')
->onDelete('cascade');
$table->unique(array('client_id', 'key'), 'oauth_client_metadata_cid_key_unique');
$table->index('client_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('oauth_client_metadata', function ($table) {
$table->dropForeign('oauth_client_metadata_client_id_foreign');
});
Schema::drop('oauth_client_metadata');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateOauthClientMetadataTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('oauth_client_metadata', function (Blueprint $table) {
$table->increments('id');
$table->string('client_id', 40);
$table->string('key', 40);
$table->string('value');
$table->timestamps();
$table->foreign('client_id')
->references('id')->on('oauth_clients')
->onDelete('cascade');
$table->unique(array('client_id', 'key'), 'oauth_client_metadata_cid_key_unique');
$table->index('client_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('oauth_client_metadata', function ($table) {
$table->dropForeign('oauth_grant_scopes_client_id_foreign');
});
Schema::drop('oauth_client_metadata');
}
}
|
Remove build status from rst for PyPI | from setuptools import setup
setup(
name='django-cacheops',
version='1.3.1',
author='Alexander Schepanovski',
author_email='[email protected]',
description='A slick ORM cache with automatic granular event-driven invalidation for Django.',
long_description=open('README.rst').read().replace('|Build Status|', '', 1),
url='http://github.com/Suor/django-cacheops',
license='BSD',
packages=[
'cacheops',
'cacheops.management',
'cacheops.management.commands',
'cacheops.templatetags'
],
install_requires=[
'django>=1.3',
'redis>=2.9.1',
'simplejson>=2.2.0',
'six>=1.4.0',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD 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',
'Programming Language :: Python :: 3.4',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
include_package_data=True,
)
| from setuptools import setup
setup(
name='django-cacheops',
version='1.3.1',
author='Alexander Schepanovski',
author_email='[email protected]',
description='A slick ORM cache with automatic granular event-driven invalidation for Django.',
long_description=open('README.rst').read(),
url='http://github.com/Suor/django-cacheops',
license='BSD',
packages=[
'cacheops',
'cacheops.management',
'cacheops.management.commands',
'cacheops.templatetags'
],
install_requires=[
'django>=1.3',
'redis>=2.9.1',
'simplejson>=2.2.0',
'six>=1.4.0',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD 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',
'Programming Language :: Python :: 3.4',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
include_package_data=True,
)
|
Update websocket url to use dynamic host rather than fixed
Former-commit-id: f04b7d503048424669a9d139ce67b11c277435ad
Former-commit-id: 3e4a3612aa6a7173b17b02119663a1833b285469
Former-commit-id: 558d23de277ed4c459fc917f6574e97f528e0a7c | import { browserHistory } from 'react-router';
const instanceID = Math.floor(Math.random() * 10000) + 1;
export const eventTypes = {
shownNotification: "SHOWN_NOTIFICATION",
shownWarning: "SHOWN_WARNING",
changedRoute: "CHANGED_ROUTE",
appInitialised: "APP_INITIALISED",
requestSent: "REQUEST_SENT",
requestReceived: "REQUEST_RECEIVED"
}
browserHistory.listen(location => {
log.add(eventTypes.changedRoute, {...location})
});
const socket = new WebSocket(`ws://${window.location.host}/florence/websocket`);
socket.onopen = () => {
log.add(eventTypes.appInitialised);
}
export default class log {
static add(eventType, payload) {
const event = {
type: eventType,
location: location.href,
instanceID,
clientTimestamp: new Date().toISOString(),
payload: payload || null
}
// console.log(event);
// Socket isn't open yet but something has been loged, wait until it is open to send it
if (socket.readyState === 0) {
socket.onopen = () => {
socket.send(`event:${JSON.stringify(event)}`);
}
return;
}
socket.send(`event:${JSON.stringify(event)}`);
// Send across with a top level type because other data, not just events, will be sent too e.g.
/*
{
type: "LOG_EVENT",
payload: {
event
}
}
*/
}
} | import { browserHistory } from 'react-router';
const instanceID = Math.floor(Math.random() * 10000) + 1;
export const eventTypes = {
shownNotification: "SHOWN_NOTIFICATION",
shownWarning: "SHOWN_WARNING",
changedRoute: "CHANGED_ROUTE",
appInitialised: "APP_INITIALISED",
requestSent: "REQUEST_SENT",
requestReceived: "REQUEST_RECEIVED"
}
browserHistory.listen(location => {
log.add(eventTypes.changedRoute, {...location})
});
const socket = new WebSocket('ws://localhost:8081/florence/websocket');
socket.onopen = () => {
log.add(eventTypes.appInitialised);
}
export default class log {
static add(eventType, payload) {
const event = {
type: eventType,
location: location.href,
instanceID,
clientTimestamp: new Date().toISOString(),
payload: payload || null
}
// console.log(event);
// Socket isn't open yet but something has been loged, wait until it is open to send it
if (socket.readyState === 0) {
socket.onopen = () => {
socket.send(`event:${JSON.stringify(event)}`);
}
return;
}
socket.send(`event:${JSON.stringify(event)}`);
// Send across with a top level type because other data, not just events, will be sent too e.g.
/*
{
type: "LOG_EVENT",
payload: {
event
}
}
*/
}
} |
Remove console logs, fix bug | const Octokat = require('octokat')
const open = require('open')
const Promise = require('bluebird')
var octo, organization, repository
module.exports = function openNotifications (input, opts, token) {
octo = new Octokat({
token: token || process.env.GITHUB_OGN_TOKEN
})
var amount = opts.amount || 30
if (input[0].split('/').length === 2) {
organization = input[0].split('/')[0]
repository = input[0].split('/')[1]
if (Number.isInteger(input[1])) {
amount = input[1]
}
} else {
organization = input[0]
repository = input[1]
amount = input[2] || amount
}
return Promise.resolve().then(() => {
if (!organization && !repository) {
return octo.notifications.fetch({
participating: opts.participating || false
})
} else {
return octo.repos(organization, repository, 'notifications').fetch()
}
}).then((result) => {
if (result) {
return Promise.some(result, amount).map((repo) => {
var res = repo.subject.url
.replace(/(https\:\/\/)api\./, '$1')
.replace(/\/repos\//, '/')
.replace(/\/pulls\//, '/pull/')
open(res)
return `Opened notifications.`
})
} else {
return `No notifications.`
}
}).catch((err) => {
console.log(err)
})
}
| const Octokat = require('octokat')
const open = require('open')
const Promise = require('bluebird')
var octo, organization, repository
module.exports = function openNotifications (input, opts, token) {
octo = new Octokat({
token: token || process.env.GITHUB_OGN_TOKEN
})
var amount = opts.amount || 30
if (input[0].split('/').length === 2) {
organization = input[0].split('/')[0]
repository = input[0].split('/')[1]
if (Number.isInteger(input[1])) {
amount = input[1]
}
} else {
organization = input[0]
repository = input[1]
amount = input[2] || amount
}
console.log('Organization:', organization)
console.log('Repository:', repository)
console.log('Amount:', amount)
return Promise.resolve().then(() => {
if (!organization && !repository) {
return octo.notifications.fetch({
participating: opts.participating || false
})
} else {
return octo.repos(organization, repository, 'notifications').fetch()
}
}).then((result) => {
if (result) {
return result.some(amount).map((repo) => {
var res = repo.subject.url
.replace(/(https\:\/\/)api\./, '$1')
.replace(/\/repos\//, '/')
.replace(/\/pulls\//, '/pull/')
open(res)
return `Opened notifications.`
})
} else {
return `No notifications.`
}
}).catch((err) => {
console.log(err)
})
}
|
Remove file from SharedFileTable seed | <?php
use Illuminate\Database\Seeder;
use REBELinBLUE\Deployer\SharedFile;
class SharedFileTableSeeder extends Seeder
{
public function run()
{
DB::table('shared_files')->delete();
SharedFile::create([
'name' => 'Storage',
'file' => 'storage/',
'target_type' => 'project',
'target_id' => 1,
]);
SharedFile::create([
'name' => 'README',
'file' => 'README.md',
'target_type' => 'project',
'target_id' => 1,
]);
SharedFile::create([
'name' => 'LICENSE',
'file' => '/LICENSE.md',
'target_type' => 'project',
'target_id' => 1,
]);
// SharedFile::create([
// 'name' => 'CSS',
// 'file' => 'resources/assets/css/console.css',
// 'target_type' => 'project',
// 'target_id' => 1,
// ]);
}
}
| <?php
use Illuminate\Database\Seeder;
use REBELinBLUE\Deployer\SharedFile;
class SharedFileTableSeeder extends Seeder
{
public function run()
{
DB::table('shared_files')->delete();
SharedFile::create([
'name' => 'Storage',
'file' => 'storage/',
'target_type' => 'project',
'target_id' => 1,
]);
SharedFile::create([
'name' => 'README',
'file' => 'README.md',
'target_type' => 'project',
'target_id' => 1,
]);
SharedFile::create([
'name' => 'LICENSE',
'file' => '/LICENSE.md',
'target_type' => 'project',
'target_id' => 1,
]);
SharedFile::create([
'name' => 'CSS',
'file' => 'resources/assets/css/console.css',
'target_type' => 'project',
'target_id' => 1,
]);
}
}
|
Fix error if relation empty | var _ = require('lodash');
var inflection = require('inflection');
module.exports = function Deserializer (data, serverRelations) {
var clientRelations = data.data.relationships;
var result = data.data.attributes || {};
if (_.isPlainObject(clientRelations)) {
_.each(clientRelations, function (clientRelation, clientRelationName) {
var serverRelation = serverRelations[clientRelationName];
if (_.isPlainObject(serverRelation)) {
var relationType = null;
var relationValue = null;
var fkSuffix = null;
var fk = null;
if (_.isArray(clientRelation.data)) {
if (_.isEmpty(clientRelation.data)) {
return;
}
relationType = _.result(_.find(clientRelation.data, 'type'), 'type');
relationValue = _.map(clientRelation.data, function (val) {
return val.id;
});
fkSuffix = 'Ids';
} else {
if (clientRelation.data === null) {
return;
}
relationType = clientRelation.data.type;
relationValue = clientRelation.data.id;
fkSuffix = 'Id';
}
relationType = inflection.singularize(relationType);
if (relationType === serverRelation.model) {
if (serverRelation.foreignKey) {
fk = serverRelation.foreignKey;
} else {
relationType = inflection.camelize(relationType, true);
fk = relationType + fkSuffix;
}
result[fk] = relationValue;
}
}
});
}
return result;
};
| var _ = require('lodash');
var inflection = require('inflection');
module.exports = function Deserializer (data, serverRelations) {
var clientRelations = data.data.relationships;
var result = data.data.attributes || {};
if (_.isPlainObject(clientRelations)) {
_.each(clientRelations, function (clientRelation, clientRelationName) {
var serverRelation = serverRelations[clientRelationName];
if (_.isPlainObject(serverRelation)) {
var relationType = null;
var relationValue = null;
var fkSuffix = null;
var fk = null;
if (_.isArray(clientRelation.data)) {
relationType = _.result(_.find(clientRelation.data, 'type'), 'type');
relationValue = _.map(clientRelation.data, function (val) {
return val.id;
});
fkSuffix = 'Ids';
} else {
relationType = clientRelation.data.type;
relationValue = clientRelation.data.id;
fkSuffix = 'Id';
}
relationType = inflection.singularize(relationType);
if (relationType === serverRelation.model) {
if (serverRelation.foreignKey) {
fk = serverRelation.foreignKey;
} else {
relationType = inflection.camelize(relationType, true);
fk = relationType + fkSuffix;
}
result[fk] = relationValue;
}
}
});
}
return result;
};
|
Print the time of checking status at github. | import argparse
import datetime
import json
import os
import time
import requests
from tardis import __githash__ as tardis_githash
parser = argparse.ArgumentParser(description="Run slow integration tests")
parser.add_argument("--yaml", dest="yaml_filepath",
help="Path to YAML config file for integration tests.")
parser.add_argument("--atomic-dataset", dest="atomic_dataset",
help="Path to atomic dataset.")
test_command = (
"python setup.py test --test-path=tardis/tests/tests_slow/test_integration.py "
"--args=\"-rs --integration-tests={0} --atomic-dataset={1} --remote-data\""
)
if __name__ == "__main__":
args = parser.parse_args()
while True:
gh_request = requests.get(
"https://api.github.com/repos/tardis-sn/tardis/branches/master"
)
gh_master_head_data = json.loads(gh_request.content)
gh_tardis_githash = gh_master_head_data['commit']['sha']
if gh_tardis_githash != tardis_githash:
os.system("git pull origin master")
os.system(test_command.format(args.yaml_filepath,
args.atomic_dataset))
else:
checked = datetime.datetime.now()
print "Up-to-date. Checked on {0} {1}".format(
checked.strftime("%d-%b-%Y"), checked.strftime("%H:%M:%S")
)
time.sleep(600)
| import argparse
import json
import os
import time
import requests
from tardis import __githash__ as tardis_githash
parser = argparse.ArgumentParser(description="Run slow integration tests")
parser.add_argument("--yaml", dest="yaml_filepath",
help="Path to YAML config file for integration tests.")
parser.add_argument("--atomic-dataset", dest="atomic_dataset",
help="Path to atomic dataset.")
test_command = (
"python setup.py test --test-path=tardis/tests/tests_slow/test_integration.py "
"--args=\"-rs --integration-tests={0} --atomic-dataset={1} --remote-data\""
)
if __name__ == "__main__":
args = parser.parse_args()
while True:
gh_request = requests.get(
"https://api.github.com/repos/tardis-sn/tardis/branches/master"
)
gh_master_head_data = json.loads(gh_request.content)
gh_tardis_githash = gh_master_head_data['commit']['sha']
if gh_tardis_githash != tardis_githash:
os.system("git pull origin master")
os.system(test_command.format(args.yaml_filepath,
args.atomic_dataset))
else:
time.sleep(600)
|
Allow castTo to automatically widen the generic bound. | package name.falgout.jeffrey.throwing;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
@FunctionalInterface
public interface RethrowChain<X extends Throwable, Y extends Throwable>
extends Function<X, Optional<Y>> {
public static <Y extends Throwable> RethrowChain<Throwable, Y> castTo(Class<? extends Y> clazz) {
return e -> Optional.ofNullable(clazz.isInstance(e) ? clazz.cast(e) : null);
}
default public RethrowChain<X, Y> connect(RethrowChain<X, Y> link) {
Objects.requireNonNull(link);
return x -> {
Optional<Y> y = apply(x);
if (y.isPresent()) {
return y;
}
return link.apply(x);
};
}
default public <Z extends Throwable> RethrowChain<X, Z> rethrow(
Function<? super Y, ? extends Z> mapper) {
Objects.requireNonNull(mapper);
return x -> apply(x).map(mapper);
}
default public Function<X, Y> finish() {
return finish(x -> {
throw new AssertionError(x);
});
}
default public Function<X, Y> finish(Function<? super X, ? extends Y> unhandledException) {
Objects.requireNonNull(unhandledException);
return x -> {
return apply(x).orElseGet(() -> {
if (x instanceof RuntimeException) {
throw (RuntimeException) x;
} else if (x instanceof Error) {
throw (Error) x;
}
return unhandledException.apply(x);
});
};
}
}
| package name.falgout.jeffrey.throwing;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
@FunctionalInterface
public interface RethrowChain<X extends Throwable, Y extends Throwable>
extends Function<X, Optional<Y>> {
public static <Y extends Throwable> RethrowChain<Throwable, Y> castTo(Class<Y> clazz) {
return e -> Optional.ofNullable(clazz.isInstance(e) ? clazz.cast(e) : null);
}
default public RethrowChain<X, Y> connect(RethrowChain<X, Y> link) {
Objects.requireNonNull(link);
return x -> {
Optional<Y> y = apply(x);
if (y.isPresent()) {
return y;
}
return link.apply(x);
};
}
default public <Z extends Throwable> RethrowChain<X, Z> rethrow(
Function<? super Y, ? extends Z> mapper) {
Objects.requireNonNull(mapper);
return x -> apply(x).map(mapper);
}
default public Function<X, Y> finish() {
return finish(x -> {
throw new AssertionError(x);
});
}
default public Function<X, Y> finish(Function<? super X, ? extends Y> unhandledException) {
Objects.requireNonNull(unhandledException);
return x -> {
return apply(x).orElseGet(() -> {
if (x instanceof RuntimeException) {
throw (RuntimeException) x;
} else if (x instanceof Error) {
throw (Error) x;
}
return unhandledException.apply(x);
});
};
}
}
|
Update required version of wptrunner. | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
PACKAGE_VERSION = '0.1'
deps = ['fxos-appgen>=0.2.7',
'marionette_client>=0.7.1.1',
'marionette_extension >= 0.1',
'mozdevice >= 0.33',
'mozlog >= 1.6',
'moznetwork >= 0.24',
'mozprocess >= 0.18',
'wptserve >= 1.0.1',
'wptrunner >= 0.2.6']
setup(name='fxos-certsuite',
version=PACKAGE_VERSION,
description='Certification suite for FirefoxOS',
classifiers=[],
keywords='mozilla',
author='Mozilla Automation and Testing Team',
author_email='[email protected]',
url='https://github.com/mozilla-b2g/fxos-certsuite',
license='MPL',
packages=['certsuite'],
include_package_data=True,
zip_safe=False,
install_requires=deps,
entry_points="""
# -*- Entry points: -*-
[console_scripts]
runcertsuite = certsuite:harness_main
cert = certsuite:certcli
""")
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
PACKAGE_VERSION = '0.1'
deps = ['fxos-appgen>=0.2.7',
'marionette_client>=0.7.1.1',
'marionette_extension >= 0.1',
'mozdevice >= 0.33',
'mozlog >= 1.6',
'moznetwork >= 0.24',
'mozprocess >= 0.18',
'wptserve >= 1.0.1',
'wptrunner >= 0.2.4']
setup(name='fxos-certsuite',
version=PACKAGE_VERSION,
description='Certification suite for FirefoxOS',
classifiers=[],
keywords='mozilla',
author='Mozilla Automation and Testing Team',
author_email='[email protected]',
url='https://github.com/mozilla-b2g/fxos-certsuite',
license='MPL',
packages=['certsuite'],
include_package_data=True,
zip_safe=False,
install_requires=deps,
entry_points="""
# -*- Entry points: -*-
[console_scripts]
runcertsuite = certsuite:harness_main
cert = certsuite:certcli
""")
|
Fix gulp live reload for less | var dest = './public/dist';
var src = './client';
var bowerComponents = './bower_components';
module.exports = {
adminAssets: {
src: src + '/admin/**',
dest: dest + '/admin/assets'
},
bower: {
dest: dest + '/',
filename: 'libs.min.js',
libs: [
bowerComponents + '/modernizr/modernizr.js',
bowerComponents + '/threejs/build/three.js',
bowerComponents + '/dat-gui/build/dat.gui.js',
bowerComponents + '/nprogress/nprogress.js',
bowerComponents + '/vivus/dist/vivus.js'
]
},
browserSync: {
server: {
baseDir: 'public/dist',
middleware: function(req, res, next) {
require('../server')(req, res, next);
}
}
},
fonts: {
src: src + '/fonts/**',
dest: dest + '/fonts'
},
less: {
entry: src + '/less/style.less',
src: src + '/less/**',
dest: dest + '/'
},
images: {
src: src + '/img/**',
dest: dest + '/img'
},
browserify: {
// A separate bundle will be generated for each
// bundle config in the list below
bundleConfigs: [{
entries: src + '/js/main.js',
dest: dest,
outputName: 'main.js'
}]
},
production: {
cssSrc: dest + '/*.css',
jsSrc: dest + '/*.js',
dest: dest
}
};
| var dest = './public/dist';
var src = './client';
var bowerComponents = './bower_components';
module.exports = {
adminAssets: {
src: src + '/admin/**',
dest: dest + '/admin/assets'
},
bower: {
dest: dest + '/',
filename: 'libs.min.js',
libs: [
bowerComponents + '/modernizr/modernizr.js',
bowerComponents + '/threejs/build/three.js',
bowerComponents + '/dat-gui/build/dat.gui.js',
bowerComponents + '/nprogress/nprogress.js',
bowerComponents + '/vivus/dist/vivus.js'
]
},
browserSync: {
server: {
baseDir: 'public/dist',
middleware: function(req, res, next) {
require('../server')(req, res, next);
}
}
},
fonts: {
src: src + '/fonts/**',
dest: dest + '/fonts'
},
less: {
entry: src + '/less/style.less',
src: src + '/styles/*.css',
dest: dest + '/'
},
images: {
src: src + '/img/**',
dest: dest + '/img'
},
browserify: {
// A separate bundle will be generated for each
// bundle config in the list below
bundleConfigs: [{
entries: src + '/js/main.js',
dest: dest,
outputName: 'main.js'
}]
},
production: {
cssSrc: dest + '/*.css',
jsSrc: dest + '/*.js',
dest: dest
}
};
|
Set global path and +1 month expiration date in angular cookies | (function() {
'use strict';
angular
.module('app', ['ngMaterial', 'ngMessages', 'ngCookies', 'ngSanitize'])
.config(['$mdThemingProvider', '$mdIconProvider', '$httpProvider', '$cookiesProvider', function(
$mdThemingProvider, $mdIconProvider, $httpProvider, $cookiesProvider
) {
$mdThemingProvider.theme('default')
.primaryPalette('green')
.accentPalette('grey')
.warnPalette('red', {'default': '700'});
$httpProvider.defaults.transformRequest = function(data) {
if (data === undefined) {
return data;
}
return $.param(data);
};
$httpProvider.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded; charset=UTF-8';
$httpProvider.defaults.headers.common['X-Requested-With'] =
'XMLHttpRequest';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token';
$httpProvider.defaults.xsrfCookieName = 'csrfToken';
var date = new Date();
$cookiesProvider.defaults.path = '/';
$cookiesProvider.defaults.expires = new Date(date.setMonth(date.getMonth() + 1));
}])
.filter('urlEncode', function() {
return function(input) {
if (input) {
return window.encodeURIComponent(input);
}
return "";
};
});
})();
| (function() {
'use strict';
angular
.module('app', ['ngMaterial', 'ngMessages', 'ngCookies', 'ngSanitize'])
.config(['$mdThemingProvider', '$mdIconProvider', '$httpProvider', function($mdThemingProvider, $mdIconProvider, $httpProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('green')
.accentPalette('grey')
.warnPalette('red', {'default': '700'});
$httpProvider.defaults.transformRequest = function(data) {
if (data === undefined) {
return data;
}
return $.param(data);
};
$httpProvider.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded; charset=UTF-8';
$httpProvider.defaults.headers.common['X-Requested-With'] =
'XMLHttpRequest';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token';
$httpProvider.defaults.xsrfCookieName = 'csrfToken';
}])
.filter('urlEncode', function() {
return function(input) {
if (input) {
return window.encodeURIComponent(input);
}
return "";
};
});
})();
|
Fix Scheduling\Event tests on Windows | <?php
use Illuminate\Console\Scheduling\Event;
class EventTest extends PHPUnit_Framework_TestCase
{
public function testBuildCommand()
{
$quote = (DIRECTORY_SEPARATOR == '\\') ? '"' : "'";
$event = new Event('php -i');
$defaultOutput = (DIRECTORY_SEPARATOR == '\\') ? 'NUL' : '/dev/null';
$this->assertSame("php -i > {$quote}{$defaultOutput}{$quote} 2>&1 &", $event->buildCommand());
}
public function testBuildCommandSendOutputTo()
{
$quote = (DIRECTORY_SEPARATOR == '\\') ? '"' : "'";
$event = new Event('php -i');
$event->sendOutputTo('/dev/null');
$this->assertSame("php -i > {$quote}/dev/null{$quote} 2>&1 &", $event->buildCommand());
$event = new Event('php -i');
$event->sendOutputTo('/my folder/foo.log');
$this->assertSame("php -i > {$quote}/my folder/foo.log{$quote} 2>&1 &", $event->buildCommand());
}
public function testBuildCommandAppendOutput()
{
$quote = (DIRECTORY_SEPARATOR == '\\') ? '"' : "'";
$event = new Event('php -i');
$event->appendOutputTo('/dev/null');
$this->assertSame("php -i >> {$quote}/dev/null{$quote} 2>&1 &", $event->buildCommand());
}
/**
* @expectedException LogicException
*/
public function testEmailOutputToThrowsExceptionIfOutputFileWasNotSpecified()
{
$event = new Event('php -i');
$event->emailOutputTo('[email protected]');
$event->buildCommand();
}
}
| <?php
use Illuminate\Console\Scheduling\Event;
class EventTest extends PHPUnit_Framework_TestCase
{
public function testBuildCommand()
{
$event = new Event('php -i');
$defaultOutput = (DIRECTORY_SEPARATOR == '\\') ? 'NUL' : '/dev/null';
$this->assertSame("php -i > '{$defaultOutput}' 2>&1 &", $event->buildCommand());
}
public function testBuildCommandSendOutputTo()
{
$event = new Event('php -i');
$event->sendOutputTo('/dev/null');
$this->assertSame("php -i > '/dev/null' 2>&1 &", $event->buildCommand());
$event = new Event('php -i');
$event->sendOutputTo('/my folder/foo.log');
$this->assertSame("php -i > '/my folder/foo.log' 2>&1 &", $event->buildCommand());
}
public function testBuildCommandAppendOutput()
{
$event = new Event('php -i');
$event->appendOutputTo('/dev/null');
$this->assertSame("php -i >> '/dev/null' 2>&1 &", $event->buildCommand());
}
/**
* @expectedException LogicException
*/
public function testEmailOutputToThrowsExceptionIfOutputFileWasNotSpecified()
{
$event = new Event('php -i');
$event->emailOutputTo('[email protected]');
$event->buildCommand();
}
}
|
Update to have it Uppercase (changed) | // ==UserScript==
// @name Anchor tags in Central
// @namespace http://central.tri.be/
// @version 0.1
// @description Adds anchor tags to some links in central
// @author You
// @include /^https:\/\/central.tri.be(\/.*)?/
// @grant none
// ==/UserScript==
var central_links = {};
( function( $, my ) {
my.init = function() {
my.$headings = $( 'table.attributes' ).find( 'th:contains(Pull Request:), th:contains(Forum Threads:), th:contains(User Story:), th:contains(UserVoice Threads:)' );
my.$headings.each( function() {
var $this = $( this ),
$link_cell = $this.next( 'td' ),
link = $link_cell.html();
if ( ! link ) {
return;
}
var links;
if ( link.indexOf( '<br>' ) ) {
links = link.split( '<br>' );
} else {
links = link.split( ' ' );
}
for ( var i in links ) {
links[i] = String( links[i] ).replace( /(http[^\n <]+)/, '<a href="$1" target="_blank">$1</a>' );
}
$link_cell.html( links.join( '<br>' ) );
} );
};
$( function() {
my.init();
});
} )( jQuery, central_links );
| // ==UserScript==
// @name Anchor tags in Central
// @namespace http://central.tri.be/
// @version 0.1
// @description Adds anchor tags to some links in central
// @author You
// @include /^https:\/\/central.tri.be(\/.*)?/
// @grant none
// ==/UserScript==
var central_links = {};
( function( $, my ) {
my.init = function() {
my.$headings = $( 'table.attributes' ).find( 'th:contains(Pull Request:), th:contains(Forum threads:), th:contains(User Story:), th:contains(UserVoice Threads:)' );
my.$headings.each( function() {
var $this = $( this ),
$link_cell = $this.next( 'td' ),
link = $link_cell.html();
if ( ! link ) {
return;
}
var links;
if ( link.indexOf( '<br>' ) ) {
links = link.split( '<br>' );
} else {
links = link.split( ' ' );
}
for ( var i in links ) {
links[i] = String( links[i] ).replace( /(http[^\n <]+)/, '<a href="$1" target="_blank">$1</a>' );
}
$link_cell.html( links.join( '<br>' ) );
} );
};
$( function() {
my.init();
});
} )( jQuery, central_links );
|
Disable i++ error in loops | // https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: "babel-eslint",
sourceType: "module"
},
env: {
browser: true
},
// required to lint *.vue files
plugins: ["vue"],
extends: ["plugin:vue/recommended", "airbnb-base"],
// check if imports actually resolve
settings: {
"import/resolver": {
webpack: {
config: "build/webpack.base.conf.js"
}
}
},
// add your custom rules here
rules: {
// don't require .vue extension when importing
"import/extensions": [
"error",
"always",
{
js: "never",
vue: "never"
}
],
// disallow reassignment of function parameters
// disallow parameter object manipulation except for specific exclusions
"no-param-reassign": [
"error",
{
props: true,
ignorePropertyModificationsFor: [
"state", // for vuex state
"acc", // for reduce accumulators
"e" // for e.returnvalue
]
}
],
"no-plusplus": [
"error",
{
"allowForLoopAfterthoughts": true
}
],
// allow optionalDependencies
"import/no-extraneous-dependencies": [
"error",
{
optionalDependencies: ["test/unit/index.js"]
}
],
// allow debugger during development
"no-debugger": process.env.NODE_ENV === "production" ? "error" : "off",
"linebreak-style": ["error", "windows"]
}
};
| // https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: "babel-eslint",
sourceType: "module"
},
env: {
browser: true
},
// required to lint *.vue files
plugins: ["vue"],
extends: ["plugin:vue/recommended", "airbnb-base"],
// check if imports actually resolve
settings: {
"import/resolver": {
webpack: {
config: "build/webpack.base.conf.js"
}
}
},
// add your custom rules here
rules: {
// don't require .vue extension when importing
"import/extensions": [
"error",
"always",
{
js: "never",
vue: "never"
}
],
// disallow reassignment of function parameters
// disallow parameter object manipulation except for specific exclusions
"no-param-reassign": [
"error",
{
props: true,
ignorePropertyModificationsFor: [
"state", // for vuex state
"acc", // for reduce accumulators
"e" // for e.returnvalue
]
}
],
// allow optionalDependencies
"import/no-extraneous-dependencies": [
"error",
{
optionalDependencies: ["test/unit/index.js"]
}
],
// allow debugger during development
"no-debugger": process.env.NODE_ENV === "production" ? "error" : "off",
"linebreak-style": ["error", "windows"]
}
};
|
Add additional test case for stripping existing hypens, too | QUnit.test(
"Slug.transform() defaults",
function (assert)
{
const Slug = mojave.url.Slug;
// test defaults
const instance = new Slug();
[
["abc def", "abc-def"],
["ä-ö-ü-ß", "ae-oe-ue-ss"],
["ääää", "aeaeaeae"],
[" ", ""],
["a?&b", "a-b"],
["abc(test)", "abc(test)"],
["a&-&b", "a-b"],
["a---b", "a-b"],
]
.forEach(
([raw, expected]) => assert.equal(instance.transform(raw), expected)
);
}
);
QUnit.test(
"Slug.transform() custom transforms",
function (assert)
{
const Slug = mojave.url.Slug;
// test defaults
const instance = new Slug([
[/z/, "a"],
]);
[
["abc def", "abc-def"],
["abczdef", "abcadef"],
]
.forEach(
([raw, expected]) => assert.equal(instance.transform(raw), expected)
);
}
);
QUnit.test(
"Slug.transform() custom sanitizer",
function (assert)
{
const Slug = mojave.url.Slug;
// test defaults
const instance = new Slug([], /z/);
[
["abc def", "abc def"],
["abczdef", "abc-def"],
]
.forEach(
([raw, expected]) => assert.equal(instance.transform(raw), expected)
);
}
);
| QUnit.test(
"Slug.transform() defaults",
function (assert)
{
const Slug = mojave.url.Slug;
// test defaults
const instance = new Slug();
[
["abc def", "abc-def"],
["ä-ö-ü-ß", "ae-oe-ue-ss"],
["ääää", "aeaeaeae"],
[" ", ""],
["a?&b", "a-b"],
["abc(test)", "abc(test)"],
]
.forEach(
([raw, expected]) => assert.equal(instance.transform(raw), expected)
);
}
);
QUnit.test(
"Slug.transform() custom transforms",
function (assert)
{
const Slug = mojave.url.Slug;
// test defaults
const instance = new Slug([
[/z/, "a"],
]);
[
["abc def", "abc-def"],
["abczdef", "abcadef"],
]
.forEach(
([raw, expected]) => assert.equal(instance.transform(raw), expected)
);
}
);
QUnit.test(
"Slug.transform() custom sanitizer",
function (assert)
{
const Slug = mojave.url.Slug;
// test defaults
const instance = new Slug([], /z/);
[
["abc def", "abc def"],
["abczdef", "abc-def"],
]
.forEach(
([raw, expected]) => assert.equal(instance.transform(raw), expected)
);
}
);
|
Change default users roles to 'manager' | <?php
class UserTableSeeder extends Seeder {
public function run()
{
// to use non Eloquent-functions we need to unguard
Eloquent::unguard();
// All existing users are deleted !!!
DB::table('users')->delete();
// add user using Eloquent
$user = new User;
$user->name = 'admin_name';
$user->lastname = 'admin_lastname';
$user->username = 'admin';
$user->password = Hash::make('password');
$user->email = '[email protected]';
$user->save();
$user->roles()->attach(1);
$user = new User;
$user->name = 'Nathakit';
$user->lastname = 'Praisuwanna';
$user->username = 'nathakit';
$user->password = Hash::make('password');
$user->email = '[email protected]';
$user->save();
$user->roles()->attach(3);
$user = new User;
$user->name = 'Nattanon';
$user->lastname = 'Rungparsert';
$user->username = 'nattanon';
$user->password = Hash::make('password');
$user->email = '[email protected]';
$user->save();
$user->roles()->attach(3);
// alternativ to eloquent we can also use direct database-methods
/*
User::create(array(
'username' => 'admin',
'password' => Hash::make('password'),
'email' => 'admin@localhost'
));
*/
}
} | <?php
class UserTableSeeder extends Seeder {
public function run()
{
// to use non Eloquent-functions we need to unguard
Eloquent::unguard();
// All existing users are deleted !!!
DB::table('users')->delete();
// add user using Eloquent
$user = new User;
$user->name = 'admin_name';
$user->lastname = 'admin_lastname';
$user->username = 'admin';
$user->password = Hash::make('password');
$user->email = '[email protected]';
$user->save();
$user->roles()->attach(1);
$user = new User;
$user->name = 'Nathakit';
$user->lastname = 'Praisuwanna';
$user->username = 'nathakit';
$user->password = Hash::make('password');
$user->email = '[email protected]';
$user->save();
$user->roles()->attach(2);
$user = new User;
$user->name = 'Nattanon';
$user->lastname = 'Rungparsert';
$user->username = 'nattanon';
$user->password = Hash::make('password');
$user->email = '[email protected]';
$user->save();
$user->roles()->attach(2);
// alternativ to eloquent we can also use direct database-methods
/*
User::create(array(
'username' => 'admin',
'password' => Hash::make('password'),
'email' => 'admin@localhost'
));
*/
}
} |
Fix getting wallet service when receiving stealth. | define(['./module', 'darkwallet'], function (controllers, DarkWallet) {
'use strict';
controllers.controller('ReceiveStealthCtrl', ['$scope', 'notify', function($scope, notify) {
// function to receive stealth information
$scope.receiveStealth = function() {
notify.note("stealth", "initializing");
notify.progress.start();
var client = DarkWallet.getClient();
var stealth_fetched = function(error, results) {
if (error) {
console.log("error on stealth");
notify.error("stealth", error);
//write_to_screen('<span style="color: red;">ERROR:</span> ' + error);
return;
}
console.log("fetching stealth", results);
var addresses;
try {
addresses = $scope.identity.wallet.processStealth(results);
} catch (e) {
notify.error("stealth", e.message);
return;
}
if (addresses && addresses.length) {
var walletService = DarkWallet.service.wallet;
addresses.forEach(function(walletAddress) {
walletService.initAddress(walletAddress);
})
notify.success("stealth ok");
} else {
notify.success("stealth ok", "payments detected");
}
}
client.fetch_stealth([0,0], stealth_fetched, 0);
};
}]);
});
| define(['./module', 'darkwallet'], function (controllers, DarkWallet) {
'use strict';
controllers.controller('ReceiveStealthCtrl', ['$scope', 'notify', function($scope, notify) {
// function to receive stealth information
$scope.receiveStealth = function() {
notify.note("stealth", "initializing");
notify.progress.start();
var client = DarkWallet.getClient();
var stealth_fetched = function(error, results) {
if (error) {
console.log("error on stealth");
notify.error("stealth", error);
//write_to_screen('<span style="color: red;">ERROR:</span> ' + error);
return;
}
console.log("fetching stealth", results);
var addresses;
try {
addresses = $scope.identity.wallet.processStealth(results);
} catch (e) {
notify.error("stealth", e.message);
return;
}
if (addresses && addresses.length) {
var walletService = DarkWallet.getService('wallet');
addresses.forEach(function(walletAddress) {
walletService.initAddress(walletAddress);
})
notify.success("stealth ok");
} else {
notify.success("stealth ok", "payments detected");
}
}
client.fetch_stealth([0,0], stealth_fetched, 0);
};
}]);
});
|
Remove URL from Spotify response | from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
"""Retrieve information about a Spotify URI."""
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location, '"{0}" by {1}'
.format(blob["name"], blob["artists"][0]["name"]))
else:
m.bot.private_message(m.location, blob["name"])
def _parse_spotify_uri(s):
"""Parse the type and ID from a Spotify URI."""
[type, id] = s.split(':')
return type, id
| from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
"""Retrieve information about a Spotify URI."""
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location, '"{0}" by {1} - {2}'
.format(blob["name"], blob["artists"][0]["name"],
blob["external_urls"]["spotify"]))
else:
m.bot.private_message(m.location, "{0} - {1}"
.format(blob["name"], blob["external_urls"]["spotify"]))
def _parse_spotify_uri(s):
"""Parse the type and ID from a Spotify URI."""
[type, id] = s.split(':')
return type, id
|
[DBAL-407] Implement method in Driver mock class | <?php
namespace Doctrine\Tests\Mocks;
class DriverMock implements \Doctrine\DBAL\Driver
{
private $_platformMock;
private $_schemaManagerMock;
public function connect(array $params, $username = null, $password = null, array $driverOptions = array())
{
return new DriverConnectionMock();
}
/**
* Constructs the Sqlite PDO DSN.
*
* @return string The DSN.
* @override
*/
protected function _constructPdoDsn(array $params)
{
return "";
}
/**
* @override
*/
public function getDatabasePlatform()
{
if ( ! $this->_platformMock) {
$this->_platformMock = new DatabasePlatformMock;
}
return $this->_platformMock;
}
/**
* @override
*/
public function getSchemaManager(\Doctrine\DBAL\Connection $conn)
{
if($this->_schemaManagerMock == null) {
return new SchemaManagerMock($conn);
} else {
return $this->_schemaManagerMock;
}
}
/* MOCK API */
public function setDatabasePlatform(\Doctrine\DBAL\Platforms\AbstractPlatform $platform)
{
$this->_platformMock = $platform;
}
public function setSchemaManager(\Doctrine\DBAL\Schema\AbstractSchemaManager $sm)
{
$this->_schemaManagerMock = $sm;
}
public function getName()
{
return 'mock';
}
public function getDatabase(\Doctrine\DBAL\Connection $conn)
{
return;
}
public function convertExceptionCode(\Exception $exception)
{
return 0;
}
} | <?php
namespace Doctrine\Tests\Mocks;
class DriverMock implements \Doctrine\DBAL\Driver
{
private $_platformMock;
private $_schemaManagerMock;
public function connect(array $params, $username = null, $password = null, array $driverOptions = array())
{
return new DriverConnectionMock();
}
/**
* Constructs the Sqlite PDO DSN.
*
* @return string The DSN.
* @override
*/
protected function _constructPdoDsn(array $params)
{
return "";
}
/**
* @override
*/
public function getDatabasePlatform()
{
if ( ! $this->_platformMock) {
$this->_platformMock = new DatabasePlatformMock;
}
return $this->_platformMock;
}
/**
* @override
*/
public function getSchemaManager(\Doctrine\DBAL\Connection $conn)
{
if($this->_schemaManagerMock == null) {
return new SchemaManagerMock($conn);
} else {
return $this->_schemaManagerMock;
}
}
/* MOCK API */
public function setDatabasePlatform(\Doctrine\DBAL\Platforms\AbstractPlatform $platform)
{
$this->_platformMock = $platform;
}
public function setSchemaManager(\Doctrine\DBAL\Schema\AbstractSchemaManager $sm)
{
$this->_schemaManagerMock = $sm;
}
public function getName()
{
return 'mock';
}
public function getDatabase(\Doctrine\DBAL\Connection $conn)
{
return;
}
} |
Write tab but don't warn | import ply.yacc
from slimit.parser import Parser
from js2xml.lexer import CustomLexer as Lexer
from js2xml.log import logger
lextab, yacctab = 'lextab', 'yacctab'
class CustomParser(Parser):
def __init__(self, lex_optimize=True, lextab=lextab,
yacc_optimize=True, yacctab=yacctab, yacc_debug=False,
logger=logger):
self.lex_optimize = lex_optimize
self.lextab = lextab
self.yacc_optimize = yacc_optimize
self.yacctab = yacctab
self.yacc_debug = yacc_debug
self.lexer = Lexer()
self.lexer.build(optimize=lex_optimize, lextab=lextab, errorlog=logger)
self.tokens = self.lexer.tokens
self.parser = ply.yacc.yacc(
module=self,
optimize=yacc_optimize,
debug=yacc_debug,
tabmodule=yacctab,
start='program',
errorlog=logger)
self._error_tokens = {}
def parse(self, text, debug=False):
result = super(CustomParser, self).parse(text, debug=debug)
self._error_tokens = {}
return result
| import ply.yacc
from slimit.parser import Parser
from js2xml.lexer import CustomLexer as Lexer
from js2xml.log import logger
lextab, yacctab = 'lextab', 'yacctab'
class CustomParser(Parser):
def __init__(self, lex_optimize=False, lextab=lextab,
yacc_optimize=True, yacctab=yacctab, yacc_debug=False,
logger=logger):
self.lex_optimize = lex_optimize
self.lextab = lextab
self.yacc_optimize = yacc_optimize
self.yacctab = yacctab
self.yacc_debug = yacc_debug
self.lexer = Lexer()
self.lexer.build(optimize=lex_optimize, lextab=lextab)
self.tokens = self.lexer.tokens
self.parser = ply.yacc.yacc(
module=self,
write_tables=False,
optimize=yacc_optimize,
debug=yacc_debug,
tabmodule=yacctab,
start='program',
errorlog=logger)
self._error_tokens = {}
def parse(self, text, debug=False):
result = super(CustomParser, self).parse(text, debug=debug)
self._error_tokens = {}
return result
|
Fix The bug in createCategory, Now can save subcategories with no problem | /**
* Created by meysamabl on 11/1/14.
*/
$(document).ready(function () {
// $('#picture').change(function () {
// $("#catForm").ajaxForm({ target: "#image_view" }).submit();
// return false;
// });
$("#level2Parent").hide();
$("#level1").change(function (e) {
e.preventDefault();
var id = $("#level1").val();
if (id != "") {
$("#level2Parent").show();
jsRoutes.controllers.Administration.getSubCategories(id).ajax({
dataType: 'json',
success: function (data) {
$('#level2').empty();
$('#level2').append($('<option>').text(Messages('chooseCategory')).attr('value', ""));
$.each(data, function(i, value) {
$('#level2').append($('<option>').text(value).attr('value', i));
});
},
error: function () {
alert("Error!")
}
})
} else {
$("#level2Parent").hide();
$("#level2").val("");
}
})
$("#level2").change(function() {
var id = $("#level2").val();
if(id != "") {
$("#level1").removeAttr("name");
} else {
$("#level1").attr('name', 'parentCategory');
}
})
});
| /**
* Created by meysamabl on 11/1/14.
*/
$(document).ready(function () {
// $('#picture').change(function () {
// $("#catForm").ajaxForm({ target: "#image_view" }).submit();
// return false;
// });
$("#level2Parent").hide();
$("#level1").change(function (e) {
e.preventDefault();
var form = $(this).closest('form');
var url = form.attr("action");
var id = $("#level1").val();
if ($("#level1").val() != "") {
$("#level2Parent").show();
jsRoutes.controllers.Administration.getSubCategories(id).ajax({
dataType: 'json',
success: function (data) {
$('#level2').empty();
$('#level2').append($('<option>').text(Messages('chooseCategory')).attr('value', null));
console.info(data);
$.each(data, function(i, value) {
$('#level2').append($('<option>').text(value).attr('value', value));
});
},
error: function () {
alert("Error!")
}
})
} else {
$("#level2Parent").hide();
$("#level2").val("");
}
})
});
|
Manage list task priority & urgency bug fix | <?php
namespace AppBundle\Form;
use AppBundle\Entity\TaskLists;
use AppBundle\Entity\Tasks;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class TasksMassEditType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('priority', ChoiceType::class, array(
'choices' => [
'Low' => -1,
'Normal' => 0,
'Important' => 1,
],
'expanded' => true,
'label_attr' => array('class' => 'radio-inline')
))
->add('urgency', ChoiceType::class, array(
'choices' => array(
'Not Urgent' => 0,
'Urgent' => 1,
),
'expanded' => true,
'label_attr' => array('class' => 'radio-inline')
))
->add('taskList', EntityType::class, array('class' => TaskLists::class, 'choice_label' => 'name'));
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Tasks::class
));
}
}
| <?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class TasksMassEditType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('priority', ChoiceType::class, array(
'choices' => array(
-1 => 'Low',
0 => 'Normal',
1 => 'Important',
),
'expanded' => true,
'label_attr' => array('class' => 'radio-inline')
))
->add('urgency', ChoiceType::class, array(
'choices' => array(
0 => 'Not Urgent',
1 => 'Urgent',
),
'expanded' => true,
'label_attr' => array('class' => 'radio-inline')
))
->add('taskList', EntityType::class, array('class' => \AppBundle\Entity\TaskLists::class, 'choice_label' => 'name'));
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => \AppBundle\Entity\Tasks::class
));
}
}
|
Fix bug with $errors->has(), presumably introduced with Laravel framework package upgrade | @if (App::environment() !== 'production')
<div class="row">
<div class="col-lg-12">
<div class="alert alert-warning">
<p><strong>Note:</strong> This installation of OpenDominion is running on
<b>{{ App::environment() }}</b> environment and is not meant for production purposes. Any data you
register and actions you take on this instance might be wiped without notice.</p>
</div>
</div>
</div>
@endif
@if (!$errors->isEmpty())
<div class="row">
<div class="col-lg-12">
<div class="alert alert-danger">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>One or more errors occurred:</p>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
</div>
</div>
@endif
@foreach (['danger', 'warning', 'success', 'info'] as $alert_type)
@if (Session::has('alert-' . $alert_type))
<div class="row">
<div class="col-lg-12">
<div class="alert alert-{{ $alert_type }}">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>{{ Session::get('alert-' . $alert_type) }}</p>
</div>
</div>
</div>
@endif
@endforeach
| @if (App::environment() !== 'production')
<div class="row">
<div class="col-lg-12">
<div class="alert alert-warning">
<p><strong>Note:</strong> This installation of OpenDominion is running on
<b>{{ App::environment() }}</b> environment and is not meant for production purposes. Any data you
register and actions you take on this instance might be wiped without notice.</p>
</div>
</div>
</div>
@endif
@if ($errors->has())
<div class="row">
<div class="col-lg-12">
<div class="alert alert-danger">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>One or more errors occurred:</p>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
</div>
</div>
@endif
@foreach (['danger', 'warning', 'success', 'info'] as $alert_type)
@if (Session::has('alert-' . $alert_type))
<div class="row">
<div class="col-lg-12">
<div class="alert alert-{{ $alert_type }}">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>{{ Session::get('alert-' . $alert_type) }}</p>
</div>
</div>
</div>
@endif
@endforeach
|
Set up the factory for the default route | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
# Include the transaction manager
config.include('pyramid_tm')
config.include('.session')
config.include('.security')
config.add_static_view('css', 'alexandria:static/css', cache_max_age=3600)
config.add_static_view('js', 'alexandria:static/js', cache_max_age=3600)
config.add_static_view('static', 'alexandria:static', cache_max_age=3600)
config.add_route('main',
'/*traverse',
factory='.traversal.Root',
use_global_views=True
)
# Scan the views sub-module
config.scan('.views')
return config.make_wsgi_app()
| import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
# Include the transaction manager
config.include('pyramid_tm')
config.include('.session')
config.include('.security')
config.add_static_view('css', 'alexandria:static/css', cache_max_age=3600)
config.add_static_view('js', 'alexandria:static/js', cache_max_age=3600)
config.add_static_view('static', 'alexandria:static', cache_max_age=3600)
config.add_route('main',
'/*traverse',
use_global_views=True
)
# Scan the views sub-module
config.scan('.views')
return config.make_wsgi_app()
|
Use dev version of Firefox (supports vertical writing-mode) in tests on Sauce Labs | module.exports = function(config) {
var commonConfig = (require("./karma-common.conf"))(config);
var customLaunchers = {
sl_chrome: {
base: "SauceLabs",
browserName: "chrome",
platform: "Windows 8.1"
},
sl_firefox: {
base: "SauceLabs",
browserName: "firefox",
platform: "Windows 8.1",
version: "dev"
},
sl_safari: {
base: "SauceLabs",
browserName: "safari",
platform: "OS X 10.10"
},
sl_ie_11: {
base: "SauceLabs",
browserName: "internet explorer",
platform: "Windows 8.1"
}
};
var options = {
reporters: ["verbose", "saucelabs"],
sauceLabs: {
testName: "Vivliostyle.js",
recordScreenshots: false,
startConnect: false, // Sauce Connect is started by Travis CI
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
},
captureTimeout: 120000,
customLaunchers: customLaunchers,
browsers: Object.keys(customLaunchers),
singleRun: true
};
for (var key in commonConfig) {
if (commonConfig.hasOwnProperty(key)) {
options[key] = commonConfig[key];
}
}
config.set(options);
};
| module.exports = function(config) {
var commonConfig = (require("./karma-common.conf"))(config);
var customLaunchers = {
sl_chrome: {
base: "SauceLabs",
browserName: "chrome",
platform: "Windows 8.1"
},
sl_firefox: {
base: "SauceLabs",
browserName: "firefox",
platform: "Windows 8.1",
version: "beta"
},
sl_safari: {
base: "SauceLabs",
browserName: "safari",
platform: "OS X 10.10"
},
sl_ie_11: {
base: "SauceLabs",
browserName: "internet explorer",
platform: "Windows 8.1"
}
};
var options = {
reporters: ["verbose", "saucelabs"],
sauceLabs: {
testName: "Vivliostyle.js",
recordScreenshots: false,
startConnect: false, // Sauce Connect is started by Travis CI
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
},
captureTimeout: 120000,
customLaunchers: customLaunchers,
browsers: Object.keys(customLaunchers),
singleRun: true
};
for (var key in commonConfig) {
if (commonConfig.hasOwnProperty(key)) {
options[key] = commonConfig[key];
}
}
config.set(options);
};
|
Stop passing redundant data around | #!/usr/bin/env python
import sys
import re
bugre = re.compile("bug\\s+(\\d+)", re.I);
def searchFile(f):
path = f.name
first = True
section = ''
for l in f.readlines():
# Skip trailing/leading whitespace
s = l.strip()
# We don't care about top-level comments
if len(s) < 2 or s[0] in ('#', ';'):
continue
if s[0] == '[' and s[-1] == ']':
section = s[1:-1]
continue
if not s.startswith("skip-if"):
continue
reasons = s.split('=', 1)[1].strip()
split = reasons.split('#', 1)
comment = ""
expr = split[0]
if len(split) > 1:
comment = split[1]
if expr.find("e10s") == -1:
continue
bugno = bugre.search(comment)
if section == "DEFAULT":
if not bugno:
print "=== %s - MISSING BUGNUM" % path
else:
print "=== %s - %s" % (path, bugno.group(1))
break
if first:
first = False
print "=== %s" % path
if not bugno:
print "%s - MISSING BUGNUM" % section
else:
print "%s - %s" % (section, bugno.group(1))
for path in sys.argv[1:]:
with open(path) as f:
searchFile(f)
| #!/usr/bin/env python
import sys
import re
bugre = re.compile("bug\\s+(\\d+)", re.I);
def searchFile(f, path):
first = True
section = ''
for l in f.readlines():
# Skip trailing/leading whitespace
s = l.strip()
# We don't care about top-level comments
if len(s) < 2 or s[0] in ('#', ';'):
continue
if s[0] == '[' and s[-1] == ']':
section = s[1:-1]
continue
if not s.startswith("skip-if"):
continue
reasons = s.split('=', 1)[1].strip()
split = reasons.split('#', 1)
comment = ""
expr = split[0]
if len(split) > 1:
comment = split[1]
if expr.find("e10s") == -1:
continue
bugno = bugre.search(comment)
if section == "DEFAULT":
if not bugno:
print "=== %s - MISSING BUGNUM" % path
else:
print "=== %s - %s" % (path, bugno.group(1))
break
if first:
first = False
print "=== %s" % path
if not bugno:
print "%s - MISSING BUGNUM" % section
else:
print "%s - %s" % (section, bugno.group(1))
for path in sys.argv[1:]:
with open(path) as f:
searchFile(f, path)
|
Fix upgrade: Check for empty items first | /** @namespace H5PUpgrades */
var H5PUpgrades = H5PUpgrades || {};
H5PUpgrades['H5P.Agamotto'] = (function ($) {
return {
1: {
3: function (parameters, finished) {
// Update image items
if (parameters.items) {
parameters.items = parameters.items.map( function (item) {
// Create new image structure
var newImage = {
library: 'H5P.Image 1.0',
// We avoid using H5P.createUUID since this is an upgrade script and H5P function may change
subContentId: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(char) {
var random = Math.random()*16|0, newChar = char === 'x' ? random : (random&0x3|0x8);
return newChar.toString(16);
}),
params: {
alt: item.labelText || '',
contentName: 'Image',
title: item.labelText || '',
file: item.image
}
};
// Compose new item
item = {
description: item.description,
image: newImage,
labelText: item.labelText
};
return item;
});
}
finished(null, parameters);
}
}
};
})(H5P.jQuery);
| /** @namespace H5PUpgrades */
var H5PUpgrades = H5PUpgrades || {};
H5PUpgrades['H5P.Agamotto'] = (function ($) {
return {
1: {
3: function (parameters, finished) {
// Update image items
parameters.items = parameters.items.map( function (item) {
// Create new image structure
var newImage = {
library: 'H5P.Image 1.0',
// We avoid using H5P.createUUID since this is an upgrade script and H5P function may change
subContentId: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(char) {
var random = Math.random()*16|0, newChar = char === 'x' ? random : (random&0x3|0x8);
return newChar.toString(16);
}),
params: {
alt: item.labelText || '',
contentName: 'Image',
title: item.labelText || '',
file: item.image
}
};
// Compose new item
item = {
description: item.description,
image: newImage,
labelText: item.labelText
};
return item;
});
finished(null, parameters);
}
}
};
})(H5P.jQuery);
|
Set check to a lower value in image async component | 'use strict';
angular.module('app.components')
.directive('imgAsync', ['$timeout', function($timeout) {
return {
restrict: 'E',
replace: true,
scope: {
ngSrc: '@'
},
templateUrl: 'app/components/imgasync/view.html',
link: function(scope, element, attrs) {
var el = angular.element(element),
image = el.find('img')[0],
angularImage = angular.element(image),
index = 0;
// Listen for when the image is loaded
image.onload = function() {
scope.$apply(function() {
scope.loading = false;
});
};
scope.$watch('ngSrc', function(source) {
scope.loading = true;
image.src = source;
});
angularImage.on('error', function() {
check();
});
function check() {
$timeout(function() {
image.src = scope.ngSrc;
}, (index++)*200);
}
}
};
}]); | 'use strict';
angular.module('app.components')
.directive('imgAsync', ['$timeout', function($timeout) {
return {
restrict: 'E',
replace: true,
scope: {
ngSrc: '@'
},
templateUrl: 'app/components/imgasync/view.html',
link: function(scope, element, attrs) {
var el = angular.element(element),
image = el.find('img')[0],
angularImage = angular.element(image),
index = 0;
// Listen for when the image is loaded
image.onload = function() {
scope.$apply(function() {
scope.loading = false;
});
};
scope.$watch('ngSrc', function(source) {
scope.loading = true;
image.src = source;
});
angularImage.on('error', function() {
check();
});
function check() {
$timeout(function() {
image.src = scope.ngSrc;
}, (index++)*1000);
}
}
};
}]); |
Add Project.first_event to API serializer | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import OrganizationMemberType, Project, Team
@register(Project)
class ProjectSerializer(Serializer):
def get_attrs(self, item_list, user):
organization = item_list[0].team.organization
team_map = dict(
(t.id, t) for t in Team.objects.get_for_user(
organization=organization,
user=user,
)
)
result = {}
for project in item_list:
try:
team = team_map[project.team_id]
except KeyError:
access_type = None
else:
access_type = team.access_type
result[project] = {
'access_type': access_type,
}
return result
def serialize(self, obj, attrs, user):
from sentry import features
feature_list = []
if features.has('projects:quotas', obj, actor=user):
feature_list.append('quotas')
if features.has('projects:user-reports', obj, actor=user):
feature_list.append('user-reports')
return {
'id': str(obj.id),
'slug': obj.slug,
'name': obj.name,
'isPublic': obj.public,
'dateCreated': obj.date_added,
'firstEvent': obj.first_event,
'features': feature_list,
'permission': {
'owner': attrs['access_type'] <= OrganizationMemberType.OWNER,
'admin': attrs['access_type'] <= OrganizationMemberType.ADMIN,
},
}
| from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import OrganizationMemberType, Project, Team
@register(Project)
class ProjectSerializer(Serializer):
def get_attrs(self, item_list, user):
organization = item_list[0].team.organization
team_map = dict(
(t.id, t) for t in Team.objects.get_for_user(
organization=organization,
user=user,
)
)
result = {}
for project in item_list:
try:
team = team_map[project.team_id]
except KeyError:
access_type = None
else:
access_type = team.access_type
result[project] = {
'access_type': access_type,
}
return result
def serialize(self, obj, attrs, user):
from sentry import features
feature_list = []
if features.has('projects:quotas', obj, actor=user):
feature_list.append('quotas')
if features.has('projects:user-reports', obj, actor=user):
feature_list.append('user-reports')
return {
'id': str(obj.id),
'slug': obj.slug,
'name': obj.name,
'isPublic': obj.public,
'dateCreated': obj.date_added,
'features': feature_list,
'permission': {
'owner': attrs['access_type'] <= OrganizationMemberType.OWNER,
'admin': attrs['access_type'] <= OrganizationMemberType.ADMIN,
},
}
|
Use correct section index for EventContextDataProvider
We need to pass the index of the rendered section, not the current
section. Passing the current section index causes the wrong section to
be reported in media events when a video is played that is not in the
current section but still visible in the viewport.
It also causes extra context updates and rendering.
REDMINE-17754 | import React from 'react';
import Section from './Section';
import {EventContextDataProvider} from './useEventContextData';
export default function Chapter(props) {
return (
<div id={`chapter-${props.permaId}`}>
{renderSections(props.sections,
props.currentSectionIndex,
props.setCurrentSectionIndex,
props.scrollTargetSectionIndex,
props.setScrollTargetSectionIndex)}
</div>
);
}
function renderSections(sections,
currentSectionIndex,
setCurrentSectionIndex,
scrollTargetSectionIndex,
setScrollTargetSectionIndex) {
function onActivate(sectionIndex) {
setCurrentSectionIndex(sectionIndex);
setScrollTargetSectionIndex(null);
}
return sections.map((section) => {
return (
<EventContextDataProvider key={section.permaId} sectionIndex={section.sectionIndex}>
<Section state={section.sectionIndex > currentSectionIndex ? 'below' : section.sectionIndex < currentSectionIndex ? 'above' : 'active'}
isScrollTarget={section.sectionIndex === scrollTargetSectionIndex}
onActivate={() => onActivate(section.sectionIndex)}
{...section} />
</EventContextDataProvider>
)
});
}
| import React from 'react';
import Section from './Section';
import {EventContextDataProvider} from './useEventContextData';
export default function Chapter(props) {
return (
<div id={`chapter-${props.permaId}`}>
{renderSections(props.sections,
props.currentSectionIndex,
props.setCurrentSectionIndex,
props.scrollTargetSectionIndex,
props.setScrollTargetSectionIndex)}
</div>
);
}
function renderSections(sections,
currentSectionIndex,
setCurrentSectionIndex,
scrollTargetSectionIndex,
setScrollTargetSectionIndex) {
function onActivate(sectionIndex) {
setCurrentSectionIndex(sectionIndex);
setScrollTargetSectionIndex(null);
}
return sections.map((section) => {
return (
<EventContextDataProvider key={section.permaId} sectionIndex={currentSectionIndex}>
<Section state={section.sectionIndex > currentSectionIndex ? 'below' : section.sectionIndex < currentSectionIndex ? 'above' : 'active'}
isScrollTarget={section.sectionIndex === scrollTargetSectionIndex}
onActivate={() => onActivate(section.sectionIndex)}
{...section} />
</EventContextDataProvider>
)
});
}
|
Use `array_rand()` instead of `mt_rand()`/`count()` to reduce code, optimization, cleaner code | <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Milestone Celebration / Inc / Class
*/
namespace PH7;
use PH7\Framework\Core\Kernel;
final class MessageGenerator
{
/**
* @return string A random patron paragraph.
*/
public static function getPatreonParagraph()
{
$aParagraphs = self::getParagraphs();
return $aParagraphs[array_rand($aParagraphs)];
}
/**
* @return array
*/
private static function getParagraphs()
{
$aParagraphs = [
t('Do you think it is the right time to <a href="%0%">Become a Patron</a> and support the development of the software?', Kernel::PATREON_URL),
t('Are you generous enough to thank the development of the software? <a href="%0%">Become a patron</a> today.', Kernel::PATREON_URL),
t('Subscribe to <a href="%0%">pH7CMS Patreon</a>.', Kernel::PATREON_URL),
t('<a href="%0%">Subscribe to be a patron</a>.', Kernel::PATREON_URL)
];
return $aParagraphs;
}
}
| <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Milestone Celebration / Inc / Class
*/
namespace PH7;
use PH7\Framework\Core\Kernel;
final class MessageGenerator
{
/**
* @return string A random patron paragraph.
*/
public static function getPatreonParagraph()
{
$aParagraphs = self::getParagraphs();
return $aParagraphs[mt_rand(0, count($aParagraphs) - 1)];
}
/**
* @return array
*/
private static function getParagraphs()
{
$aParagraphs = [
t('Do you think it is the right time to <a href="%0%">Become a Patron</a> and support the development of the software?', Kernel::PATREON_URL),
t('Are you generous enough to thank the development of the software? <a href="%0%">Become a patron</a> today.', Kernel::PATREON_URL),
t('Subscribe to <a href="%0%">pH7CMS Patreon</a>.', Kernel::PATREON_URL),
t('<a href="%0%">Subscribe to be a patron</a>.', Kernel::PATREON_URL)
];
return $aParagraphs;
}
}
|
Fix nierozpoznawania bledu pierwszego ruchu v.2 | from game import Game
from input_con import InputCon
from output_con import OutputCon
class Harness():
def __init__(self, output, inputs):
self._game = Game()
self._output = output
self._inputs = inputs
def Start(self):
self._output.show_welcome()
while True:
self._output.show_board(self._game.get_board())
player_id = self._game.get_turn_no()
player = self._game.get_turn()
self._output.show_player_turn(player)
while True:
move = self._inputs[player_id].get_move()
if move is False:
self._output.show_move_error(player)
continue
if self._game.make_move(move) is False:
self._output.show_move_error(player)
continue
break
if not self._game.get_end():
continue
# End of game.
self._output.show_board(self._game.get_board())
w = self._game.get_winner()
if w is None:
# Draw.
self._output.show_draw()
else:
self._output.show_winner(w)
break
def main():
inputcon1 = InputCon()
inputcon2 = InputCon()
outputcon = OutputCon()
player_inputs = [ inputcon1, inputcon2 ]
player_output = outputcon
h = Harness(player_output, player_inputs)
h.Start()
if __name__ == "__main__":
main()
| from game import Game
from input_con import InputCon
from output_con import OutputCon
class Harness():
def __init__(self, output, inputs):
self._game = Game()
self._output = output
self._inputs = inputs
def Start(self):
self._output.show_welcome()
while True:
self._output.show_board(self._game.get_board())
player_id = self._game.get_turn_no()
player = self._game.get_turn()
self._output.show_player_turn(player)
while True:
move = self._inputs[player_id].get_move()
if move is False:
self._output.show_move_error(player)
continue
if self._game.make_move(move) is False:
self._output.show_move_error(player)
break
break
if not self._game.get_end():
continue
# End of game.
self._output.show_board(self._game.get_board())
w = self._game.get_winner()
if w is None:
# Draw.
self._output.show_draw()
else:
self._output.show_winner(w)
break
def main():
inputcon1 = InputCon()
inputcon2 = InputCon()
outputcon = OutputCon()
player_inputs = [ inputcon1, inputcon2 ]
player_output = outputcon
h = Harness(player_output, player_inputs)
h.Start()
if __name__ == "__main__":
main()
|
Fix SQL column naming conventions | package com.gitrekt.resort.model.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "mailing_addresses")
public class MailingAddress {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column (name = "address_line_1")
private String addressLine1;
@Column (name = "address_line_2")
private String addressLine2;
@Column (name = "postal_code")
private String postalCode;
@Column (name = "state")
@Enumerated(EnumType.STRING)
private USState state;
@Column (name = "country")
private String country;
public MailingAddress(String addressLine1, String addressLine2,
String postalCode,USState state, String country) {
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.postalCode = postalCode;
this.state = state;
this.country = country;
}
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getPostalCode() {
return postalCode;
}
public String getCountry() {
return country;
}
public USState getState() {
return state;
}
}
| package com.gitrekt.resort.model.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "mailing_addresses")
public class MailingAddress {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column (name = "address_line1")
private String addressLine1;
@Column (name = "address_line2")
private String addressLine2;
@Column (name = "postal_code")
private String postalCode;
@Column (name = "state")
@Enumerated(EnumType.STRING)
private USState state;
@Column (name = "country")
private String country;
public MailingAddress(String addressLine1, String addressLine2,
String postalCode,USState state, String country) {
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.postalCode = postalCode;
this.state = state;
this.country = country;
}
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getPostalCode() {
return postalCode;
}
public String getCountry() {
return country;
}
public USState getState() {
return state;
}
}
|
bii: Make _bii_deps_in_place actually behave like a context manager | # /ciscripts/coverage/bii/coverage.py
#
# Submit coverage totals for a bii project to coveralls
#
# See /LICENCE.md for Copyright information
"""Submit coverage totals for a bii project to coveralls."""
import errno
import os
from contextlib import contextmanager
def _move_ignore_enoent(src, dst):
"""Move src to dst, ignoring ENOENT."""
try:
os.rename(src, dst)
except OSError as error:
if error.errno != errno.ENOENT:
raise error
@contextmanager
def _bii_deps_in_place(cont):
"""Move bii project dependencies into layout.
The coverage step may require these dependencies to be present.
"""
bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii")
_move_ignore_enoent(bii_dir, os.path.join(os.getcwd(), "bii"))
try:
yield
finally:
_move_ignore_enoent(os.path.join(os.getcwd(), "bii"), bii_dir)
def run(cont, util, shell, argv=None):
"""Submit coverage total to coveralls, with bii specific preparation."""
with _bii_deps_in_place(cont):
util.fetch_and_import("coverage/cmake/coverage.py").run(cont,
util,
shell,
argv)
| # /ciscripts/coverage/bii/coverage.py
#
# Submit coverage totals for a bii project to coveralls
#
# See /LICENCE.md for Copyright information
"""Submit coverage totals for a bii project to coveralls."""
import errno
import os
from contextlib import contextmanager
@contextmanager
def _bii_deps_in_place(cont):
"""Move bii project dependencies into layout.
The coverage step may require these dependencies to be present.
"""
bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii")
try:
os.rename(bii_dir, os.path.join(os.getcwd(), "bii"))
except OSError as error:
if error.errno != errno.ENOENT:
raise error
def run(cont, util, shell, argv=None):
"""Submit coverage total to coveralls, with bii specific preparation."""
with _bii_deps_in_place(cont):
util.fetch_and_import("coverage/cmake/coverage.py").run(cont,
util,
shell,
argv)
|
Remove weird bug where clicking certain parts of pages wouldn't cause them to flip | $(function() {
var $pages = $('.page'),
currPage = 0;
function setZIndex(currPage) {
$pages.each(function(index) {
if (currPage === index) {
$(this).css('z-index', 2);
} else if (Math.abs(currPage - index) === 1) {
$(this).css('z-index', 1);
} else {
$(this).css('z-index', 0);
}
});
}
function centerCard(currPage) {
if (!currPage) {
$pages.css('left', '25%');
} else if (currPage === $pages.length) {
$pages.css('left', '75%');
} else {
$pages.css('left', '50%');
}
}
function prevPage() {
if (currPage) {
currPage--;
setZIndex(currPage);
$pages.eq(currPage).removeClass('flipped');
centerCard(currPage);
}
}
function nextPage() {
if (currPage < $pages.length) {
setZIndex(currPage);
$pages.eq(currPage).addClass('flipped');
currPage++;
centerCard(currPage);
}
}
setZIndex(currPage);
$('#prev').click(prevPage);
$('#next').click(nextPage);
$('.page').click(function() {
if($(this).hasClass('flipped')) {
console.log('next');
prevPage();
} else {
console.log('prev');
nextPage();
}
});
}); | $(function() {
var $pages = $('.page'),
currPage = 0;
function setZIndex(currPage) {
$pages.each(function(index) {
if (currPage === index) {
$(this).css('z-index', 2);
} else if (Math.abs(currPage - index) === 1) {
$(this).css('z-index', 1);
} else {
$(this).css('z-index', 0);
}
});
}
function centerCard(currPage) {
if (!currPage) {
$pages.css('left', '25%');
} else if (currPage === $pages.length) {
$pages.css('left', '75%');
} else {
$pages.css('left', '50%');
}
}
function prevPage() {
if (currPage) {
currPage--;
setZIndex(currPage);
$pages.eq(currPage).removeClass('flipped');
centerCard(currPage);
}
}
function nextPage() {
if (currPage < $pages.length) {
setZIndex(currPage);
$pages.eq(currPage).addClass('flipped');
currPage++;
centerCard(currPage);
}
}
setZIndex(currPage);
$('#prev').click(prevPage);
$('#next').click(nextPage);
$('.front').click(nextPage);
$('.back').click(prevPage);
}); |
Move initializing of Resume sub-objects back to parse so we get
that behavior on sync. | define([
'underscore',
'backbone',
'models/profile',
'models/address',
'collections/item'
], function (_, Backbone, Profile, Address, ItemCollection) {
'use strict';
var ResumeModel = Backbone.Model.extend({
defaults: {
name: ''
},
hasOne: ['profile', 'address'],
hasMany: ['items'],
parse: function(response) {
if (response.resume) {
var resp = response.resume;
} else {
var resp = response;
}
var options = { resumeId: this.id };
resp.address = new Address(resp.address, options);
resp.profile = new Profile(resp.profile, options);
resp.items = new ItemCollection(resp.items, options);
return resp;
},
toJSON: function() {
var json = JSON.parse(JSON.stringify(this.attributes));
// has one associations
_.each(this.hasOne, function(assoc) {
json[assoc + '_id'] = this.get(assoc).id;
delete json[assoc];
}, this);
// has many associations
_.each(this.hasMany, function(assoc) {
var singular = assoc.substring(0, assoc.length - 1);
json[singular + '_ids'] = this.get(assoc).map(function(item) {
return item.id;
});
delete json[assoc];
}, this);
return {
resume: json
};
}
});
return ResumeModel;
});
| define([
'underscore',
'backbone',
'models/profile',
'models/address',
'collections/item'
], function (_, Backbone, Profile, Address, ItemCollection) {
'use strict';
var ResumeModel = Backbone.Model.extend({
defaults: {
name: ''
},
hasOne: ['profile', 'address'],
hasMany: ['items'],
initialize: function(attributes, options) {
var options = { resumeId: this.id };
this.set('address', new Address(attributes.address, options));
this.set('profile', new Profile(attributes.profile, options));
this.set('items', new ItemCollection(attributes.items, options));
},
parse: function(response) {
if (response.resume) {
return response.resume;
} else {
return response;
}
},
toJSON: function() {
var json = JSON.parse(JSON.stringify(this.attributes));
// has one associations
_.each(this.hasOne, function(assoc) {
json[assoc + '_id'] = this.get(assoc).id;
delete json[assoc];
}, this);
// has many associations
_.each(this.hasMany, function(assoc) {
var singular = assoc.substring(0, assoc.length - 1);
json[singular + '_ids'] = this.get(assoc).map(function(item) {
return item.id;
});
delete json[assoc];
}, this);
return {
resume: json
};
}
});
return ResumeModel;
});
|
Add worflow validation to prevent user replacement assumptions | (function( $ ) {
$.fn.searchify = function() {
return this.each(function() {
$(this).autocomplete({
source: $(this).data("search-url"),
select: function (event, ui) {
if (select_url = $(this).data("select-url")) {
for (element in ui.item)
select_url = select_url.replace('\(' + element + '\)', ui.item[element]);
window.location.href = select_url;
} else {
$(this).prev().val(ui.item.id);
$(this).data('value', ui.item.id)
$(this).blur();
$(this).focus();
}
}
});
$(this).change( function (event, ui) {
if ( $(this).data('value') != $(this).prev().val() ) {
$(this).val('');
$(this).prev().val('');
}
});
$(this).focus( function (event, ui) {
$(this).data('value', '');
});
});
};
})( jQuery );
| (function( $ ) {
$.fn.searchify = function() {
return this.each(function() {
$(this).autocomplete({
source: $(this).data("search-url"),
change: function (event, ui) {
if ( $(this).data('value') != $(this).prev().val() ) {
$(this).val('');
$(this).prev().val('');
}
},
select: function (event, ui) {
if (select_url = $(this).data("select-url")) {
for (element in ui.item)
select_url = select_url.replace('\(' + element + '\)', ui.item[element]);
window.location.href = select_url;
} else {
$(this).prev().val(ui.item.id);
$(this).data('value', ui.item.id)
}
}
});
});
};
})( jQuery );
|
Reimplement test method 'testInTerminal' to use serial port event listener | /* *\
** SICU Stress Measurement System **
** Project P04 | C380 Team A **
** EBME 380: Biomedical Engineering Design Experience **
** Case Western Reserve University **
** 2016 Fall Semester **
\* */
package edu.cwru.sicu_sms.util;
import org.junit.jupiter.api.*;
import java.util.Arrays;
/**
* Test class for {@link EKGSerialPort}.
*
* @since December 14, 2016
* @author Ted Frohlich <[email protected]>
* @author Abby Walker <[email protected]>
*/
class EKGSerialPortTest {
private static long READ_DURATION = (long) 3e9; // 3 seconds, expressed in nanoseconds
private EKGSerialPort serialPort;
@BeforeEach
void setUp() {
serialPort = new EKGSerialPort();
serialPort.openPort();
}
@AfterEach
void tearDown() {
serialPort.closePort();
}
@Test
void testInTerminal() {
long startTime = System.nanoTime();
serialPort.setEventListener(serialPortEvent -> {
int[] data = serialPort.readIntArray();
System.out.println(Arrays.toString(data));
});
while (System.nanoTime() - startTime < READ_DURATION);
}
@Test
void testInFXChart() {
}
} | /* *\
** SICU Stress Measurement System **
** Project P04 | C380 Team A **
** EBME 380: Biomedical Engineering Design Experience **
** Case Western Reserve University **
** 2016 Fall Semester **
\* */
package edu.cwru.sicu_sms.util;
import jssc.SerialPortEvent;
import org.junit.jupiter.api.*;
import java.util.Arrays;
/**
* Test class for {@link EKGSerialPort}.
*
* @since December 14, 2016
* @author Ted Frohlich <[email protected]>
* @author Abby Walker <[email protected]>
*/
class EKGSerialPortTest {
private static long READ_DURATION = (long) 3e9; // 3 seconds, expressed in nanoseconds
private EKGSerialPort serialPort;
@BeforeEach
void setUp() {
serialPort = new EKGSerialPort() {
@Override
public void serialEvent(SerialPortEvent serialPortEvent) {
}
};
serialPort.openPort();
}
@AfterEach
void tearDown() {
serialPort.closePort();
}
@Test
void testInTerminal() {
int[] data;
long startTime = System.nanoTime();
do {
data = serialPort.readIntArray();
if (data != null && data.length > 0) {
System.out.println(Arrays.toString(data));
}
} while (System.nanoTime() - startTime < READ_DURATION);
}
} |
Fix buglet introduced by longcode clean-up. | from django.conf import settings
from vumi.tests.utils import FakeRedis
from go.base.tests.utils import VumiGoDjangoTestCase, declare_longcode_tags
from go.vumitools.tests.utils import CeleryTestMixIn
from go.vumitools.api import VumiApi
class DjangoGoApplicationTestCase(VumiGoDjangoTestCase, CeleryTestMixIn):
def setUp(self):
super(DjangoGoApplicationTestCase, self).setUp()
self.setup_api()
self.declare_longcode_tags()
self.setup_celery_for_tests()
def tearDown(self):
self.teardown_api()
super(DjangoGoApplicationTestCase, self).tearDown()
def setup_api(self):
self._fake_redis = FakeRedis()
vumi_config = settings.VUMI_API_CONFIG.copy()
vumi_config['redis_cls'] = lambda **kws: self._fake_redis
self.patch_settings(VUMI_API_CONFIG=vumi_config)
self.api = VumiApi(settings.VUMI_API_CONFIG)
def teardown_api(self):
self._fake_redis.teardown()
def declare_longcode_tags(self):
declare_longcode_tags(self.api)
def acquire_all_longcode_tags(self):
for _i in range(4):
self.api.acquire_tag("longcode")
def get_api_commands_sent(self):
consumer = self.get_cmd_consumer()
return self.fetch_cmds(consumer)
| from django.conf import settings
from vumi.tests.utils import FakeRedis
from go.base.tests.utils import VumiGoDjangoTestCase, declare_longcode_tags
from go.vumitools.tests.utils import CeleryTestMixIn
from go.vumitools.api import VumiApi
class DjangoGoApplicationTestCase(VumiGoDjangoTestCase, CeleryTestMixIn):
def setUp(self):
super(DjangoGoApplicationTestCase, self).setUp()
self.setup_api()
self.declare_longcode_tags(self.api)
self.setup_celery_for_tests()
def tearDown(self):
self.teardown_api()
super(DjangoGoApplicationTestCase, self).tearDown()
def setup_api(self):
self._fake_redis = FakeRedis()
vumi_config = settings.VUMI_API_CONFIG.copy()
vumi_config['redis_cls'] = lambda **kws: self._fake_redis
self.patch_settings(VUMI_API_CONFIG=vumi_config)
self.api = VumiApi(settings.VUMI_API_CONFIG)
def teardown_api(self):
self._fake_redis.teardown()
def declare_longcode_tags(self):
declare_longcode_tags(self.api)
def acquire_all_longcode_tags(self):
for _i in range(4):
self.api.acquire_tag("longcode")
def get_api_commands_sent(self):
consumer = self.get_cmd_consumer()
return self.fetch_cmds(consumer)
|
Update grunt tasks for heroku | "use strict";
module.exports = function (grunt) {
grunt.initConfig({
bump: {
options: {
files: ["package.json"],
commit: true,
commitMessage: "Release %VERSION%",
commitFiles: ["-a"],
createTag: true,
tagName: "%VERSION%",
tagMessage: "Version %VERSION%",
push: false,
}
},
shell: {
options: {
stdout: true,
stderr: true,
failOnError: true
},
push: {
command: "git push -u -f --tags origin master"
},
publish: {
command: "npm publish"
},
update: {
command: "npm-check-updates -u"
},
modules: {
command: "rm -rf node_modules && npm install"
},
jitsu : {
command: "jitsu login && jitsu deploy && jitsu logs tail"
},
heroku : {
command: "git push -u -f --tags heroku master"
}
}
});
grunt.registerTask("update", ["shell:update", "shell:modules"]);
grunt.registerTask("release", ["bump", "shell:push", "shell:publish", "shell:heroku", "shell:jitsu"]);
grunt.registerTask("minor", ["bump:minor", "shell:push", "shell:publish"]);
grunt.registerTask("major", ["bump:major", "shell:push", "shell:publish"]);
grunt.registerTask("deploy", ["shell:heroku", "shell:jitsu"]);
grunt.loadNpmTasks("grunt-bump");
grunt.loadNpmTasks("grunt-shell");
};
| "use strict";
module.exports = function (grunt) {
grunt.initConfig({
bump: {
options: {
files: ["package.json"],
commit: true,
commitMessage: "Release %VERSION%",
commitFiles: ["-a"],
createTag: true,
tagName: "%VERSION%",
tagMessage: "Version %VERSION%",
push: false,
}
},
shell: {
options: {
stdout: true,
stderr: true,
failOnError: true
},
push: {
command: "git push -u -f --tags origin master"
},
publish: {
command: "npm publish"
},
update: {
command: "npm-check-updates -u"
},
modules: {
command: "rm -rf node_modules && npm install"
},
deploy : {
command: "jitsu login && jitsu deploy && jitsu logs tail"
}
}
});
grunt.registerTask("update", ["shell:update", "shell:modules"]);
grunt.registerTask("release", ["bump", "shell:push", "shell:publish", "shell:deploy"]);
grunt.registerTask("minor", ["bump:minor", "shell:push", "shell:publish"]);
grunt.registerTask("major", ["bump:major", "shell:push", "shell:publish"]);
grunt.registerTask("deploy", ["shell:deploy"]);
grunt.loadNpmTasks("grunt-bump");
grunt.loadNpmTasks("grunt-shell");
};
|
Change getName() => getDisplayName() for Bolt ^3.6 compatibility.
Since Bolt 3.6.0-beta, getName() has not been overrideable. | <?php
namespace Bolt\Extension\royallthefourth\CodeHighlightBolt;
use Bolt\Asset\File\JavaScript;
use Bolt\Asset\Snippet\Snippet;
use Bolt\Asset\File\Stylesheet;
use Bolt\Asset\Target;
use Bolt\Extension\SimpleExtension;
/**
* CodeHighlightBolt extension class.
*
* @author Royall Spence <[email protected]>
*/
class CodeHighlightBoltExtension extends SimpleExtension
{
public function getDisplayName()
{
return "Code Highlight";
}
/**
* {@inheritdoc}
*/
protected function registerAssets()
{
$config = $this->getConfig();
$theme = $config['theme'];
$jsInit = new Snippet();
$jsInit->setCallback([$this, 'jsInitSnippet'])
->setLocation(Target::AFTER_JS)
->setPriority(99)
;
return [
new JavaScript('assets/highlightjs/highlight.pack.min.js'),
new Stylesheet("assets/highlightjs/styles/{$theme}.css"),
$jsInit,
];
}
public function jsInitSnippet()
{
return '<script>hljs.initHighlightingOnLoad();</script>';
}
/**
* {@inheritdoc}
*/
protected function getDefaultConfig()
{
return [
'theme' => 'monokai'
];
}
}
| <?php
namespace Bolt\Extension\royallthefourth\CodeHighlightBolt;
use Bolt\Asset\File\JavaScript;
use Bolt\Asset\Snippet\Snippet;
use Bolt\Asset\File\Stylesheet;
use Bolt\Asset\Target;
use Bolt\Extension\SimpleExtension;
/**
* CodeHighlightBolt extension class.
*
* @author Royall Spence <[email protected]>
*/
class CodeHighlightBoltExtension extends SimpleExtension
{
public function getName()
{
return "Code Highlight";
}
/**
* {@inheritdoc}
*/
protected function registerAssets()
{
$config = $this->getConfig();
$theme = $config['theme'];
$jsInit = new Snippet();
$jsInit->setCallback([$this, 'jsInitSnippet'])
->setLocation(Target::AFTER_JS)
->setPriority(99)
;
return [
new JavaScript('assets/highlightjs/highlight.pack.min.js'),
new Stylesheet("assets/highlightjs/styles/{$theme}.css"),
$jsInit,
];
}
public function jsInitSnippet()
{
return '<script>hljs.initHighlightingOnLoad();</script>';
}
/**
* {@inheritdoc}
*/
protected function getDefaultConfig()
{
return [
'theme' => 'monokai'
];
}
}
|
Fix for absolute paths when using params | package com.crowdin.cli.commands.functionality;
import com.crowdin.cli.properties.CliProperties;
import com.crowdin.cli.properties.Params;
import com.crowdin.cli.properties.PropertiesBean;
import com.crowdin.cli.utils.file.FileReader;
import java.io.File;
import java.nio.file.Files;
public class PropertiesBuilder {
private File configFile;
private File identityFile;
private Params params;
public PropertiesBuilder(File configFile, File identityFile, Params params) {
this.configFile = configFile;
this.identityFile = identityFile;
this.params = params;
}
public PropertiesBean build() {
PropertiesBean pb = (!(Files.notExists(configFile.toPath()) && params != null))
? CliProperties.buildFromMap(new FileReader().readCliConfig(configFile))
: new PropertiesBean();
if (identityFile != null) {
CliProperties.populateWithCredentials(pb, new FileReader().readCliConfig(configFile));
}
if (params != null) {
CliProperties.populateWithParams(pb, params);
}
String basePathIfEmpty = (Files.exists(configFile.toPath()) && !(params != null && params.getBasePathParam() != null))
? new File(configFile.getAbsolutePath()).getParent()
: "";
return CliProperties.processProperties(pb, basePathIfEmpty);
}
}
| package com.crowdin.cli.commands.functionality;
import com.crowdin.cli.properties.CliProperties;
import com.crowdin.cli.properties.Params;
import com.crowdin.cli.properties.PropertiesBean;
import com.crowdin.cli.utils.file.FileReader;
import java.io.File;
import java.nio.file.Files;
public class PropertiesBuilder {
private File configFile;
private File identityFile;
private Params params;
public PropertiesBuilder(File configFile, File identityFile, Params params) {
this.configFile = configFile;
this.identityFile = identityFile;
this.params = params;
}
public PropertiesBean build() {
PropertiesBean pb = (!(Files.notExists(configFile.toPath()) && params != null))
? CliProperties.buildFromMap(new FileReader().readCliConfig(configFile))
: new PropertiesBean();
if (identityFile != null) {
CliProperties.populateWithCredentials(pb, new FileReader().readCliConfig(configFile));
}
if (params != null) {
CliProperties.populateWithParams(pb, params);
}
String basePathIfEmpty = (Files.exists(configFile.toPath()) && !(params != null && params.getBasePathParam() != null))
? new File(configFile.getAbsolutePath()).getParent()
: System.getProperty("user.dir");
return CliProperties.processProperties(pb, basePathIfEmpty);
}
}
|
Fix two left over renames | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"pinax.forums",
"pinax.forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="pinax.forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
| #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"forums",
"forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
|
Use method in storybook example that wasn't being used that logs actions | import React, { Component } from 'react';
import { action } from '@kadira/storybook';
import { DraftJSEditor, Renderer, defaultBlocks } from '../../src';
const draftRenderer = new Renderer(defaultBlocks);
class SetStateExample extends Component {
state = {
content: {
entityMap: {},
blocks: [
{
text: '',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
},
],
},
};
onChange = content => {
action('onChange')(content); // Log to storybook's "action-logger"
this.setState({ content });
};
render() {
return (
<div>
<h1>@synapsestudios/draftjs-editor</h1>
<p className="p text-center">
A customized WYSIWYG editor utilizing Facebook's Draft.js library
</p>
<p className="p text-center">
View this project on
{' '}
<a href="https://github.com/synapsestudios/draftjs-editor" target="_blank">Github</a>
</p>
<DraftJSEditor
content={this.state.content || null}
onChange={this.onChange}
placeholder="Tell a story..."
customBlocks={defaultBlocks}
customBlockControls={Object.keys(defaultBlocks)}
/>
{this.state.content
? <div
dangerouslySetInnerHTML={{
__html: draftRenderer.convertRawToHTML(this.state.content),
}}
/>
: null}
</div>
);
}
}
export default SetStateExample;
| import React, { Component } from 'react';
import { action } from '@kadira/storybook';
import { DraftJSEditor, Renderer, defaultBlocks } from '../../src';
const draftRenderer = new Renderer(defaultBlocks);
class SetStateExample extends Component {
state = {
content: {
entityMap: {},
blocks: [
{
text: '',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
},
],
},
};
onChange = content => {
action('onChange')(content); // Log to storybook's "action-logger"
this.setState(content);
};
render() {
return (
<div>
<h1>@synapsestudios/draftjs-editor</h1>
<p className="p text-center">
A customized WYSIWYG editor utilizing Facebook's Draft.js library
</p>
<p className="p text-center">
View this project on
{' '}
<a href="https://github.com/synapsestudios/draftjs-editor" target="_blank">Github</a>
</p>
<DraftJSEditor
content={this.state.content || null}
onChange={content => this.setState({ content })}
placeholder="Tell a story..."
customBlocks={defaultBlocks}
customBlockControls={Object.keys(defaultBlocks)}
/>
{this.state.content
? <div
dangerouslySetInnerHTML={{
__html: draftRenderer.convertRawToHTML(this.state.content),
}}
/>
: null}
</div>
);
}
}
export default SetStateExample;
|
Indent two spaces instead of tabs | /**
* Functionality for the node info side display panel
*
* @author Taylor Welter - tdwelter
*/
(function()
'use strict';
angular
.module('nodeproperties', ['ngVis'])
.controller('NodeInfoController', NodeInfoController);
function NodeInfoController()
{
var nodeInfo = [];
// However this vis selectNode function is invoked
node = network.on('selectNode', onSelectNode);
network.on('deselectNode', onDeselectNode);
for(var key in node)
{
if(node.hasOwnProperty(key))
{
nodeInfo.push(key);
nodeInfo.push(node[key]);
}
}
}
function onSelectNode(nodeInfo)
{
// Push the HTML to list the information, RE: nodeInfo array
}
function onDeselectNode()
{
// Remove the HTML to list the information, get ready for them to click another node
// Possibly resize the window pane
}
})();
/***********************************TemporaryPsuedocode************************************
* Function: displayNodeInformation
*
* // probably using select node
* while a node is selected:
* display the information from the nodes on info panel
*
* for each attribute of the node:
* // Display everything for now, cull information later
* display the associated information
*
* // Q: Where do I receive this information?
* // A: Seems like the return of the selectNode
* otherwise: // on deselectNode
* the panel should probably not be visible
* // or display helpful generic information or something
****************************************************************************************** | /**
* Functionality for the node info side display panel
*
* @author Taylor Welter - tdwelter
*/
(function()
'use strict';
angular
.module('nodeproperties', ['ngVis'])
.controller('NodeInfoController', NodeInfoController);
function NodeInfoController()
{
var nodeInfo = [];
// However this vis selectNode function is invoked
node = network.on('selectNode', onSelectNode);
network.on('deselectNode', onDeselectNode);
for(var key in node)
{
if(node.hasOwnProperty(key))
{
nodeInfo.push(key);
nodeInfo.push(node[key]);
}
}
}
function onSelectNode(nodeInfo)
{
// Push the HTML to list the information, RE: nodeInfo array
}
function onDeselectNode()
{
// Remove the HTML to list the information, get ready for them to click another node
// Possibly resize the window pane
}
})();
/***********************************TemporaryPsuedocode************************************
* Function: displayNodeInformation
*
* // probably using select node
* while a node is selected:
* display the information from the nodes on info panel
*
* for each attribute of the node:
* // Display everything for now, cull information later
* display the associated information
*
* // Q: Where do I receive this information?
* // A: Seems like the return of the selectNode
* otherwise: // on deselectNode
* the panel should probably not be visible
* // or display helpful generic information or something
****************************************************************************************** |
Return env instead of the $_server | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->environment;
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
protected function getEnvParameters()
{
return $_ENV;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config.yml');
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$loader->load(function (ContainerBuilder $container) use ($loader) {
$container->loadFromExtension('framework', array(
'test' => true
));
});
}
}
}
| <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->environment;
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
protected function getEnvParameters()
{
return $_SERVER;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config.yml');
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$loader->load(function (ContainerBuilder $container) use ($loader) {
$container->loadFromExtension('framework', array(
'test' => true
));
});
}
}
}
|
Rewrite to avoid capitalization issues | import binascii
import os
import pytest
from cryptography.bindings import _ALL_APIS
from cryptography.primitives.block import BlockCipher
def generate_encrypt_test(param_loader, path, file_names, cipher_factory,
mode_factory, only_if=lambda api: True,
skip_message=None):
def test_encryption(self):
for api in _ALL_APIS:
for file_name in file_names:
for params in param_loader(os.path.join(path, file_name)):
yield (
encrypt_test,
api,
cipher_factory,
mode_factory,
params,
only_if,
skip_message
)
return test_encryption
def encrypt_test(api, cipher_factory, mode_factory, params, only_if,
skip_message):
if not only_if(api):
pytest.skip(skip_message)
plaintext = params.pop("plaintext")
ciphertext = params.pop("ciphertext")
cipher = BlockCipher(
cipher_factory(**params),
mode_factory(**params),
api
)
actual_ciphertext = cipher.encrypt(binascii.unhexlify(plaintext))
actual_ciphertext += cipher.finalize()
assert actual_ciphertext == binascii.unhexlify(ciphertext)
| import binascii
import os
import pytest
from cryptography.bindings import _ALL_APIS
from cryptography.primitives.block import BlockCipher
def generate_encrypt_test(param_loader, path, file_names, cipher_factory,
mode_factory, only_if=lambda api: True,
skip_message=None):
def test_encryption(self):
for api in _ALL_APIS:
for file_name in file_names:
for params in param_loader(os.path.join(path, file_name)):
yield (
encrypt_test,
api,
cipher_factory,
mode_factory,
params,
only_if,
skip_message
)
return test_encryption
def encrypt_test(api, cipher_factory, mode_factory, params, only_if,
skip_message):
if not only_if(api):
pytest.skip(skip_message)
plaintext = params.pop("plaintext")
ciphertext = params.pop("ciphertext")
cipher = BlockCipher(
cipher_factory(**params),
mode_factory(**params),
api
)
actual_ciphertext = cipher.encrypt(binascii.unhexlify(plaintext))
actual_ciphertext += cipher.finalize()
assert binascii.hexlify(actual_ciphertext) == ciphertext
|
Add a feature to detected use of the Dingo API package and assign its router for ease-of-use | <?php
namespace SebastiaanLuca\Router\Routers;
use Illuminate\Contracts\Routing\Registrar as RegistrarContract;
/**
* Class BaseRouter
*
* The base class every router should extend.
*
* @package SebastiaanLuca\Router\Routers
*/
abstract class BaseRouter implements RouterInterface
{
/**
* The routing instance.
*
* @var \SebastiaanLuca\Router\ExtendedRouter|\Illuminate\Routing\Router
*/
protected $router;
/**
* The Dingo API router.
*
* @var \Dingo\Api\Routing\Router
*/
protected $api;
/**
* The default controller namespace.
*
* @var string
*/
protected $namespace = '';
/**
* BaseRouter constructor.
*
* @param \Illuminate\Contracts\Routing\Registrar $router
*/
public function __construct(RegistrarContract $router)
{
$this->router = $router;
$this->setUpApiRouter();
$this->map();
}
/**
* Assign the API router if the Dingo API package is installed.
*/
protected function setUpApiRouter()
{
if (class_exists('\Dingo\Api\Routing\Router')) {
$this->api = app('\Dingo\Api\Routing\Router');
}
}
/**
* Get the default namespace with the suffix attached.
*
* @param string|null $suffix
*
* @return string
*/
public function getNamespace($suffix = null)
{
if (! $suffix) {
return $this->namespace;
}
return $this->namespace . '\\' . $suffix;
}
/**
* Map the routes.
*/
public abstract function map();
}
| <?php
namespace SebastiaanLuca\Router\Routers;
use Illuminate\Contracts\Routing\Registrar as RegistrarContract;
/**
* Class BaseRouter
*
* The base class every router should extend.
*
* @package SebastiaanLuca\Router\Routers
*/
abstract class BaseRouter implements RouterInterface
{
/**
* The routing instance.
*
* @var \SebastiaanLuca\Router\ExtendedRouter|\Illuminate\Routing\Router
*/
protected $router;
/**
* The default controller namespace.
*
* @var string
*/
protected $namespace = '';
/**
* BaseRouter constructor.
*
* @param \Illuminate\Contracts\Routing\Registrar $router
*/
public function __construct(RegistrarContract $router)
{
$this->router = $router;
$this->map();
}
/**
* Get the default namespace with the suffix attached.
*
* @param string|null $suffix
*
* @return string
*/
public function getNamespace($suffix = null)
{
if (! $suffix) {
return $this->namespace;
}
return $this->namespace . '\\' . $suffix;
}
/**
* Map the routes.
*/
public abstract function map();
}
|
Fix script for release file already present case
This avoids a:
"AttributeError: 'HTTPError' object has no attribute 'message'"
Signed-off-by: Ulysses Souza <[email protected]> | from __future__ import absolute_import
from __future__ import unicode_literals
from configparser import Error
from requests.exceptions import HTTPError
from twine.commands.upload import main as twine_upload
from twine.utils import get_config
from .utils import ScriptError
def pypi_upload(args):
print('Uploading to PyPi')
try:
rel = args.release.replace('-rc', 'rc')
twine_upload([
'dist/docker_compose-{}*.whl'.format(rel),
'dist/docker-compose-{}*.tar.gz'.format(rel)
])
except HTTPError as e:
if e.response.status_code == 400 and 'File already exists' in str(e):
if not args.finalize_resume:
raise ScriptError(
'Package already uploaded on PyPi.'
)
print('Skipping PyPi upload - package already uploaded')
else:
raise ScriptError('Unexpected HTTP error uploading package to PyPi: {}'.format(e))
def check_pypirc():
try:
config = get_config()
except Error as e:
raise ScriptError('Failed to parse .pypirc file: {}'.format(e))
if config is None:
raise ScriptError('Failed to parse .pypirc file')
if 'pypi' not in config:
raise ScriptError('Missing [pypi] section in .pypirc file')
if not (config['pypi'].get('username') and config['pypi'].get('password')):
raise ScriptError('Missing login/password pair for pypi repo')
| from __future__ import absolute_import
from __future__ import unicode_literals
from configparser import Error
from requests.exceptions import HTTPError
from twine.commands.upload import main as twine_upload
from twine.utils import get_config
from .utils import ScriptError
def pypi_upload(args):
print('Uploading to PyPi')
try:
rel = args.release.replace('-rc', 'rc')
twine_upload([
'dist/docker_compose-{}*.whl'.format(rel),
'dist/docker-compose-{}*.tar.gz'.format(rel)
])
except HTTPError as e:
if e.response.status_code == 400 and 'File already exists' in e.message:
if not args.finalize_resume:
raise ScriptError(
'Package already uploaded on PyPi.'
)
print('Skipping PyPi upload - package already uploaded')
else:
raise ScriptError('Unexpected HTTP error uploading package to PyPi: {}'.format(e))
def check_pypirc():
try:
config = get_config()
except Error as e:
raise ScriptError('Failed to parse .pypirc file: {}'.format(e))
if config is None:
raise ScriptError('Failed to parse .pypirc file')
if 'pypi' not in config:
raise ScriptError('Missing [pypi] section in .pypirc file')
if not (config['pypi'].get('username') and config['pypi'].get('password')):
raise ScriptError('Missing login/password pair for pypi repo')
|
Fix machine enable monitoring in js | define('app/views/machine_manual_monitoring', ['app/views/templated', 'ember'],
/**
* Machine Manual Monitoring View
*
* @returns Class
*/
function (TemplatedView) {
return TemplatedView.extend({
/**
*
* Actions
*
*/
actions: {
selectCommandText: function () {
Mist.selectElementContents('manual-monitoring-command');
},
cancelClicked: function () {
Mist.machineManualMonitoringController.close();
},
doneClicked: function () {
Mist.monitoringController.enableMonitoring(
Mist.machineManualMonitoringController.machine, null, true
);
Mist.machineManualMonitoringController.close();
}
}
});
}
);
| define('app/views/machine_manual_monitoring', ['app/views/templated', 'ember'],
/**
* Machine Manual Monitoring View
*
* @returns Class
*/
function (TemplatedView) {
return TemplatedView.extend({
/**
*
* Actions
*
*/
actions: {
selectCommandText: function () {
Mist.selectElementContents('manual-monitoring-command');
},
cancelClicked: function () {
Mist.machineManualMonitoringController.close();
},
doneClicked: function () {
Mist.machineManualMonitoringController.close();
Mist.monitoringController.enableMonitoring(
Mist.machineManualMonitoringController.machine, null, true
);
}
}
});
}
);
|
Install pycommand.3 manpage with pip | from setuptools import setup
import pycommand
setup(
name='pycommand',
version=pycommand.__version__,
description=pycommand.__doc__,
author=pycommand.__author__,
author_email='[email protected]',
url='https://github.com/babab/pycommand',
download_url='http://pypi.python.org/pypi/pycommand/',
py_modules=['pycommand'],
license='ISC',
long_description='{}\n{}'.format(open('README.rst').read(),
open('CHANGELOG.rst').read()),
platforms='any',
scripts=['scripts/pycommand'],
data_files=[
('share/pycommand/examples', ['examples/basic-example',
'examples/full-example']),
('share/pycommand', ['LICENSE', 'README.rst']),
('share/man/man3', ['pycommand.3']),
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Shells',
'Topic :: System :: Software Distribution',
'Topic :: Terminals',
'Topic :: Utilities',
'BLOCK FOR UPLOAD',
],
)
| from setuptools import setup
import pycommand
setup(
name='pycommand',
version=pycommand.__version__,
description=pycommand.__doc__,
author=pycommand.__author__,
author_email='[email protected]',
url='https://github.com/babab/pycommand',
download_url='http://pypi.python.org/pypi/pycommand/',
py_modules=['pycommand'],
license='ISC',
long_description='{}\n{}'.format(open('README.rst').read(),
open('CHANGELOG.rst').read()),
platforms='any',
scripts=['scripts/pycommand'],
data_files=[
('share/pycommand/examples', ['examples/basic-example',
'examples/full-example']),
('share/pycommand', ['LICENSE', 'README.rst'])
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Shells',
'Topic :: System :: Software Distribution',
'Topic :: Terminals',
'Topic :: Utilities',
'BLOCK FOR UPLOAD',
],
)
|
Remove row class and show only 2 columns | <div class="row">
<?php
$html = '<div id="shopProducts">';
if(count($items) > 0) {
foreach ($items as $item){
$html.= '<div id="'.$item['product'].'-'.$item['id'].'" class="col-md-6">
<div class="thumbnail">
<a href="'.Option::get('siteurl').DS.miniShop::$shop.DS.'item?id='.$item['id'].'" title="'.$item['title'].'" >
<img src="'.Option::get('siteurl').DS.'public/shop/large/'.$item['image1'].'">
</a>
<div class="caption clearfix">
<h4>'.$item['title'].'</h4>
<div class="btn btn-default btn-sm pull-left" disabled="disabled"><b>Precio: </b><span> '.$item['price'].'</span></div>
<a class="btn btn-default btn-sm pull-right" href="'.Option::get('siteurl').DS.miniShop::$shop.DS.'item?id='.$item['id'].'" >
'.__("View details", "minishop").'
</a>
</div>
</div>
</div>';
}
$html.= '</div>
<div class="clearfix"></div>';
echo $html;
echo $result;
miniShop::getActions();
}else{
echo '<div class="well">'
.__('Still not have products','minishop').
'</div>';
}
?>
</div>
| <div class="row">
<?php
$html = '<div id="shopProducts" class="row">';
if(count($items) > 0) {
foreach ($items as $item){
$html.= '<div id="'.$item['product'].'-'.$item['id'].'" class="col-md-4">
<div class="thumbnail">
<a href="'.Option::get('siteurl').DS.miniShop::$shop.DS.'item?id='.$item['id'].'" title="'.$item['title'].'" >
<img src="'.Option::get('siteurl').DS.'public/shop/large/'.$item['image1'].'">
</a>
<div class="caption clearfix">
<h4>'.$item['title'].'</h4>
<div class="btn btn-default btn-sm pull-left" disabled="disabled"><b>Precio: </b><span> '.$item['price'].'</span></div>
<a class="btn btn-default btn-sm pull-right" href="'.Option::get('siteurl').DS.miniShop::$shop.DS.'item?id='.$item['id'].'" >
'.__("View details", "minishop").'
</a>
</div>
</div>
</div>';
}
$html.= '</div>
<div class="clearfix"></div>';
echo $html;
echo $result;
miniShop::getActions();
}else{
echo '<div class="media">'
.__('Still not have products','minishop').
'</div>';
}
?>
</div> |
Use foam.LIB and be a bit lazier. | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.core',
name: 'AxiomCloner',
documentation: 'An axiom that clones an axiom from another model.',
properties: [
{
class: 'Class',
name: 'from'
},
{
class: 'String',
name: 'axiom'
},
{
class: 'String',
name: 'name',
transient: true,
expression: function(axiom) {
return axiom + '_cloner';
}
},
{
class: 'Map',
name: 'config'
}
],
methods: [
function installInClass(cls) {
var axiom = this.from.getAxiomByName(this.axiom);
if ( ! axiom ) {
throw `Cannot find ${this.axiom} on ${this.from.id}`;
}
axiom = axiom.clone().copyFrom(this.config);
cls.installAxiom(axiom);
}
]
});
foam.LIB({
name: 'foam',
methods: [
function axiomCloner(from, axiom, config) {
return {
class: 'foam.core.AxiomCloner',
from: from,
axiom: axiom,
config: config
};
}
]
}); | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.core',
name: 'AxiomCloner',
documentation: 'An axiom that clones an axiom from another model.',
properties: [
{
class: 'Class',
name: 'from'
},
{
class: 'String',
name: 'axiom'
},
{
class: 'String',
name: 'name',
transient: true,
expression: function(axiom) {
return axiom + '_cloner';
}
},
{
class: 'Map',
name: 'config'
}
],
methods: [
function installInClass(cls) {
var axiom = this.from.getAxiomByName(this.axiom);
if ( ! axiom ) {
throw `Cannot find ${this.axiom} on ${this.from.id}`;
}
axiom = axiom.clone().copyFrom(this.config);
cls.installAxiom(axiom);
}
]
});
foam.SCRIPT({
package: 'foam.core',
name: 'AxiomClonerConvenienceMethod',
code: function() {
foam.axiomCloner = function(from, axiom, config) {
return foam.core.AxiomCloner.create({
from: from,
axiom: axiom,
config: config
});
};
}
});
|
Add error output to exec error messages
e.g. for an error like "env: ‘node’: No such file or directory"
the sublime console was only reporting "exited with code 127"
which wasn't very helpful in determining the cause. | import os
import json
import threading
import subprocess
import sublime
class ExecFlowCommand(threading.Thread):
"""Threaded class used for running flow commands in a different thread.
The subprocess must be threaded so we don't lockup the UI.
"""
def __init__(self, cmd, content):
"""Initialize with the command and the file content to send."""
self.cmd = cmd
self.content = content
self.stdout = None
self.returncode = 0
self.stderr = None
threading.Thread.__init__(self)
def run(self):
"""Execute the command in a subprocess."""
read, write = os.pipe()
os.write(write, str.encode(self.content))
os.close(write)
try:
output = subprocess.check_output(
self.cmd,
shell=sublime.platform() == 'windows',
stdin=read,
stderr=subprocess.STDOUT
)
if type(output) is bytes:
output = output.decode('utf-8')
try:
self.stdout = json.loads(output)
except ValueError:
self.stdout = output
os.close(read)
except subprocess.CalledProcessError as err:
if type(err.output) is bytes:
output = err.output.decode('utf-8')
else:
output = err.output
self.stderr = str(err) + ': ' + str(output)
self.returncode = 1
| import os
import json
import threading
import subprocess
import sublime
class ExecFlowCommand(threading.Thread):
"""Threaded class used for running flow commands in a different thread.
The subprocess must be threaded so we don't lockup the UI.
"""
def __init__(self, cmd, content):
"""Initialize with the command and the file content to send."""
self.cmd = cmd
self.content = content
self.stdout = None
self.returncode = 0
self.stderr = None
threading.Thread.__init__(self)
def run(self):
"""Execute the command in a subprocess."""
read, write = os.pipe()
os.write(write, str.encode(self.content))
os.close(write)
try:
output = subprocess.check_output(
self.cmd,
shell=sublime.platform() == 'windows',
stdin=read,
stderr=subprocess.STDOUT
)
if type(output) is bytes:
output = output.decode('utf-8')
try:
self.stdout = json.loads(output)
except ValueError:
self.stdout = output
os.close(read)
except subprocess.CalledProcessError as err:
self.stderr = str(err)
self.returncode = 1
|
Swap back to Fuzzer, no monkey patching | from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer, Interactive
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controller
command_line = ('''./pox.py --verbose openflow.debug ''' #sts.syncproto.pox_syncer '''
'''forwarding.l2_multi '''
#'''sts.util.socket_mux.pox_monkeypatcher '''
'''openflow.of_01 --address=__address__ --port=__port__''')
controllers = [ControllerConfig(command_line, cwd="betta")]
topology_class = MeshTopology
topology_params = "num_switches=2"
dataplane_trace = "dataplane_traces/ping_pong_same_subnet.trace"
simulation_config = SimulationConfig(controller_configs=controllers,
topology_class=topology_class,
topology_params=topology_params,
dataplane_trace=dataplane_trace,
multiplex_sockets=False)
control_flow = Fuzzer(simulation_config, check_interval=80,
halt_on_violation=False,
input_logger=InputLogger(),
invariant_check=InvariantChecker.check_connectivity)
#control_flow = Interactive(simulation_config, input_logger=InputLogger())
| from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controller
command_line = ('''./pox.py --verbose --no-cli sts.syncproto.pox_syncer '''
'''samples.topo forwarding.l2_multi '''
'''sts.util.socket_mux.pox_monkeypatcher '''
'''openflow.of_01 --address=../sts_socket_pipe''')
controllers = [ControllerConfig(command_line, address="sts_socket_pipe", cwd="pox", sync="tcp:localhost:18899")]
topology_class = MeshTopology
topology_params = "num_switches=4"
dataplane_trace = "dataplane_traces/ping_pong_same_subnet_4_switches.trace"
simulation_config = SimulationConfig(controller_configs=controllers,
topology_class=topology_class,
topology_params=topology_params,
dataplane_trace=dataplane_trace,
multiplex_sockets=True)
control_flow = Fuzzer(simulation_config, check_interval=1, halt_on_violation=True,
input_logger=InputLogger(),
invariant_check=InvariantChecker.check_liveness)
|
TASK: Fix return typehint for getBuiltinType | <?php
namespace Neos\Flow\Reflection;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
/**
* Extended version of the ReflectionParameter
*
* @Flow\Proxy(false)
*/
class ParameterReflection extends \ReflectionParameter
{
/**
* @var string
*/
protected $parameterClassName;
/**
* Returns the declaring class
*
* @return ClassReflection The declaring class
*/
public function getDeclaringClass()
{
return new ClassReflection(parent::getDeclaringClass()->getName());
}
/**
* Returns the parameter class
*
* @return ClassReflection The parameter class
*/
public function getClass()
{
try {
$class = parent::getClass();
} catch (\Exception $exception) {
return null;
}
return is_object($class) ? new ClassReflection($class->getName()) : null;
}
/**
* @return string|null The name of a builtin type (e.g. string, int) if it was declared for the parameter (scalar type declaration), null otherwise
*/
public function getBuiltinType()
{
$type = $this->getType();
if (!$type instanceof \ReflectionNamedType) {
return null;
}
return $type->isBuiltin() ? $type->getName() : null;
}
}
| <?php
namespace Neos\Flow\Reflection;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
/**
* Extended version of the ReflectionParameter
*
* @Flow\Proxy(false)
*/
class ParameterReflection extends \ReflectionParameter
{
/**
* @var string
*/
protected $parameterClassName;
/**
* Returns the declaring class
*
* @return ClassReflection The declaring class
*/
public function getDeclaringClass()
{
return new ClassReflection(parent::getDeclaringClass()->getName());
}
/**
* Returns the parameter class
*
* @return ClassReflection The parameter class
*/
public function getClass()
{
try {
$class = parent::getClass();
} catch (\Exception $exception) {
return null;
}
return is_object($class) ? new ClassReflection($class->getName()) : null;
}
/**
* @return string The name of a builtin type (e.g. string, int) if it was declared for the parameter (scalar type declaration), null otherwise
*/
public function getBuiltinType()
{
$type = $this->getType();
if (!$type instanceof \ReflectionNamedType) {
return null;
}
return $type->isBuiltin() ? $type->getName() : null;
}
}
|
Use config to cache from composer.json
Signed-off-by: Mior Muhammad Zaki <[email protected]> | <?php
namespace Orchestra\Config\Console;
use Symfony\Component\Finder\Finder;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Console\ConfigCacheCommand as BaseCommand;
class ConfigCacheCommand extends BaseCommand
{
/**
* Boot a fresh copy of the application configuration.
*
* @return array
*/
protected function getFreshConfiguration()
{
$app = require $this->laravel->bootstrapPath('app.php');
$app->make(Kernel::class)->bootstrap();
$config = $app->make('config');
$files = \array_merge(
$this->configToCache(), $this->getConfigurationFiles()
);
foreach ($files as $file) {
$config[$file];
}
return $config->all();
}
/**
* Get all of the configuration files for the application.
*
* @return array
*/
protected function getConfigurationFiles()
{
$files = [];
$path = $this->laravel->configPath();
$found = Finder::create()->files()->name('*.php')->depth('== 0')->in($path);
foreach ($found as $file) {
$files[] = \basename($file->getRealPath(), '.php');
}
return $files;
}
/**
* Get all of the package names that should be ignored.
*
* @return array
*/
protected function configToCache()
{
if (! file_exists($this->laravel->basePath('composer.json')) {
return [];
}
return json_decode(file_get_contents(
$this->laravel->basePath('composer.json')
), true)['extra']['config-cache'] ?? [];
}
}
| <?php
namespace Orchestra\Config\Console;
use Symfony\Component\Finder\Finder;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Console\ConfigCacheCommand as BaseCommand;
class ConfigCacheCommand extends BaseCommand
{
/**
* Boot a fresh copy of the application configuration.
*
* @return array
*/
protected function getFreshConfiguration()
{
$app = require $this->laravel->basePath().'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$config = $app->make('config');
$files = \array_merge(
$config->get('compile.config', []), $this->getConfigurationFiles()
);
foreach ($files as $file) {
$config[$file];
}
return $config->all();
}
/**
* Get all of the configuration files for the application.
*
* @return array
*/
protected function getConfigurationFiles()
{
$files = [];
$path = $this->laravel->configPath();
$found = Finder::create()->files()->name('*.php')->depth('== 0')->in($path);
foreach ($found as $file) {
$files[] = \basename($file->getRealPath(), '.php');
}
return $files;
}
}
|
Rename oAuthSecret -> secretKey in bearer auth object | <?php
namespace Konsulting\JustGivingApiSdk\Support\Auth;
class BearerAuth implements AuthValue
{
/**
* The application ID (also known as API key).
*
* @see https://developer.justgiving.com/apidocs/documentation#AppId
* @var string
*/
protected $appId;
/**
* The bearer token obtained via oAuth.
*
* @see https://justgivingdeveloper.zendesk.com/hc/en-us/articles/207071499-Getting-a-bearer-token
* @var string
*/
protected $token;
/**
* The secret key provided by JustGiving (this currently has to be requested manually).
*
* @see https://justgivingdeveloper.zendesk.com/hc/en-us/articles/115002238925-How-do-I-get-a-secret-key-
* @var string
*/
protected $secretKey;
public function __construct($appId, $secretKey, $token)
{
$this->appId = $appId;
$this->token = $token;
$this->secretKey = $secretKey;
}
/**
* Get the authentication headers.
*
* @return array
*/
public function getHeaders()
{
return [
'Authorization' => 'Bearer ' . $this->token,
'x-api-key' => $this->appId,
'x-application-key' => $this->secretKey,
];
}
}
| <?php
namespace Konsulting\JustGivingApiSdk\Support\Auth;
class BearerAuth implements AuthValue
{
/**
* The application ID (also known as API key).
*
* @see https://developer.justgiving.com/apidocs/documentation#AppId
* @var string
*/
protected $appId;
/**
* The bearer token obtained via oAuth.
*
* @see https://justgivingdeveloper.zendesk.com/hc/en-us/articles/207071499-Getting-a-bearer-token
* @var string
*/
protected $token;
/**
* The oAuth secret provided by JustGiving (this currently has to be requested manually).
*
* @see https://justgivingdeveloper.zendesk.com/hc/en-us/articles/115002238925-How-do-I-get-a-secret-key-
* @var string
*/
protected $oAuthSecret;
public function __construct($appId, $oAuthSecret, $token)
{
$this->appId = $appId;
$this->token = $token;
$this->oAuthSecret = $oAuthSecret;
}
/**
* Get the authentication headers.
*
* @return array
*/
public function getHeaders()
{
return [
'Authorization' => 'Bearer ' . $this->token,
'x-api-key' => $this->appId,
'x-application-key' => $this->oAuthSecret,
];
}
}
|
Use PHP 5.3-compatible traditional array syntax | <?php
namespace Liip\RMT\Tests\Functional;
use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;
class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$informationCollector = $this->getMock('Liip\RMT\Information\InformationCollector');
$informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false);
$output = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
$output->method('write');
$context = Context::getInstance();
$context->setService('information-collector', $informationCollector);
$context->setService('output', $output);
}
/** @test */
public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s()
{
$check = new TestsCheck(array('command' => 'echo OK'));
$check->execute();
}
/** @test */
public function succeeds_when_command_finished_within_configured_timeout()
{
$check = new TestsCheck(array('command' => 'echo OK', 'timeout' => 0.100));
$check->execute();
}
/** @test */
public function fails_when_the_command_exceeds_the_timeout()
{
$this->setExpectedException('Exception', 'exceeded the timeout');
$check = new TestsCheck(array('command' => 'sleep 1', 'timeout' => 0.100));
$check->execute();
}
}
| <?php
namespace Liip\RMT\Tests\Functional;
use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;
class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$informationCollector = $this->getMock('Liip\RMT\Information\InformationCollector');
$informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false);
$output = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
$output->method('write');
$context = Context::getInstance();
$context->setService('information-collector', $informationCollector);
$context->setService('output', $output);
}
/** @test */
public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s()
{
$check = new TestsCheck(['command' => 'echo OK']);
$check->execute();
}
/** @test */
public function succeeds_when_command_finished_within_configured_timeout()
{
$check = new TestsCheck(['command' => 'echo OK', 'timeout' => 0.100]);
$check->execute();
}
/** @test */
public function fails_when_the_command_exceeds_the_timeout()
{
$this->setExpectedException('Exception', 'exceeded the timeout');
$check = new TestsCheck(['command' => 'sleep 1', 'timeout' => 0.100]);
$check->execute();
}
}
|
Change alert color in login page | @extends('theme/main')
@section('title')
Login - Researchew
@endsection
@section('content')
<div class="am-container">
<div class="am-u-sm-8 am-u-sm-centered">
@if(Session::has('message'))
<div class="am-alert am-alert-success" data-am-alert>{{ Session::get('message') }}</div>
@endif
<div class="am-panel am-panel-default">
<div class="am-panel-hd">Login</div>
<div class="am-panel-bd">
{{ Form::open(array('url'=>'user/auth', 'class'=>'am-form')) }}
<div class="am-form-group">
<label for="email">Email</label>
{{ Form::text('email', null, array('class'=>'', 'placeholder'=>'Please type in your account email')) }}
</div>
<div class="am-form-group">
<label for="password">Password</label>
{{ Form::password('password', array('class'=>'', 'placeholder'=>'Please type in your password')) }}
</div>
<p><button type="submit" class="am-btn am-btn-primary am-btn-block">Submit</button></p>
{{ Form::close() }}
</div>
</div>
</div>
</div>
@endsection
@section('script')
@endsection
| @extends('theme/main')
@section('title')
Login - Researchew
@endsection
@section('content')
<div class="am-container">
<div class="am-u-sm-8 am-u-sm-centered">
@if(Session::has('message'))
<div class="am-alert am-alert-danger" data-am-alert>{{ Session::get('message') }}</div>
@endif
<div class="am-panel am-panel-default">
<div class="am-panel-hd">Login</div>
<div class="am-panel-bd">
{{ Form::open(array('url'=>'user/auth', 'class'=>'am-form')) }}
<div class="am-form-group">
<label for="email">Email</label>
{{ Form::text('email', null, array('class'=>'', 'placeholder'=>'Please type in your account email')) }}
</div>
<div class="am-form-group">
<label for="password">Password</label>
{{ Form::password('password', array('class'=>'', 'placeholder'=>'Please type in your password')) }}
</div>
<p><button type="submit" class="am-btn am-btn-primary am-btn-block">Submit</button></p>
{{ Form::close() }}
</div>
</div>
</div>
</div>
@endsection
@section('script')
@endsection
|
Clarify error condition when failing to sync docs | """
sentry.runner.commands.repair
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
import os
import click
from sentry.runner.decorators import configuration
@click.command()
@configuration
def repair():
"Attempt to repair any invalid data."
click.echo('Forcing documentation sync')
from sentry.utils.integrationdocs import sync_docs, DOC_FOLDER
if os.access(DOC_FOLDER, os.W_OK):
sync_docs()
elif os.path.isdir(DOC_FOLDER):
click.echo(' - skipping, path cannot be written to: %r' % DOC_FOLDER)
else:
click.echo(' - skipping, path does not exist: %r' % DOC_FOLDER)
from sentry.models import Activity, Project, ProjectKey
click.echo('Creating missing project keys')
queryset = Project.objects.filter(key_set__isnull=True)
for project in queryset:
try:
ProjectKey.objects.get_or_create(
project=project,
)
except ProjectKey.MultipleObjectsReturned:
pass
from django.db import connection
click.echo("Correcting Group.num_comments counter")
cursor = connection.cursor()
cursor.execute("""
UPDATE sentry_groupedmessage SET num_comments = (
SELECT COUNT(*) from sentry_activity
WHERE type = %s and group_id = sentry_groupedmessage.id
)
""", [Activity.NOTE])
| """
sentry.runner.commands.repair
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
import os
import click
from sentry.runner.decorators import configuration
@click.command()
@configuration
def repair():
"Attempt to repair any invalid data."
click.echo('Forcing documentation sync')
from sentry.utils.integrationdocs import sync_docs, DOC_FOLDER
if os.access(DOC_FOLDER, os.W_OK):
sync_docs()
else:
click.echo(' - skipping (path cannot be written to)')
from sentry.models import Activity, Project, ProjectKey
click.echo('Creating missing project keys')
queryset = Project.objects.filter(key_set__isnull=True)
for project in queryset:
try:
ProjectKey.objects.get_or_create(
project=project,
)
except ProjectKey.MultipleObjectsReturned:
pass
from django.db import connection
click.echo("Correcting Group.num_comments counter")
cursor = connection.cursor()
cursor.execute("""
UPDATE sentry_groupedmessage SET num_comments = (
SELECT COUNT(*) from sentry_activity
WHERE type = %s and group_id = sentry_groupedmessage.id
)
""", [Activity.NOTE])
|
Enable doctrine migrations bundle in kernel | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new JMS\AopBundle\JMSAopBundle(),
new JMS\DiExtraBundle\JMSDiExtraBundle($this),
new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
new SimplyTestable\WorkerBundle\SimplyTestableWorkerBundle(),
new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new JMS\AopBundle\JMSAopBundle(),
new JMS\DiExtraBundle\JMSDiExtraBundle($this),
new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
new SimplyTestable\WorkerBundle\SimplyTestableWorkerBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
|
Fix missed resolve check on converted resolver. | /**
* @class SchemaResolver
* Class exposing a method to resolve schema references to schema objects in a
* schema.
*/
define([
], function (
) {
return function(resolvers) {
/**
* Given the passed subobject walk its properties looking for $refs and
* replace them with the loaded schema.
* @param subobj - object to walk
* @param parent - parent of object if the $ref needs to be replaced.
* @param parentKey - key to replace $ref, if found.
*/
this.resolveRefs = function (subobj, parent, parentKey) {
if (!(subobj.tag && subobj.tag.resolved)) {
Object.keys(subobj).forEach(function (key, idx, obj) {
var val = subobj[key], value;
if (key === "$ref") {
resolvers.some(function (res) {
value = res(val);
return value;
});
if (value && value.tag && !value.tag.resolved) {
value.resolved = true;
this.resolveRefs(value, subobj, key);
}
parent[parentKey] = value;
} else if (typeof val === "object" && !val.resolved) {
this.resolveRefs(val, subobj, key);
}
}, this);
}
}
};
});
| /**
* @class SchemaResolver
* Class exposing a method to resolve schema references to schema objects in a
* schema.
*/
define([
], function (
) {
return function(resolvers) {
/**
* Given the passed subobject walk its properties looking for $refs and
* replace them with the loaded schema.
* @param subobj - object to walk
* @param parent - parent of object if the $ref needs to be replaced.
* @param parentKey - key to replace $ref, if found.
*/
this.resolveRefs = function (subobj, parent, parentKey) {
if (!(subobj.tag && subobj.tag.resolved)) {
Object.keys(subobj).forEach(function (key, idx, obj) {
var val = subobj[key], value;
if (key === "$ref") {
resolvers.some(function (res) {
value = res(val);
return value;
});
if (value && value.tag && !value.tag.resolved) {
value.resolved = true;
this.resolveRefs(value, subobj, key);
}
parent[parentKey] = value;
} else if (typeof val === "object") {
this.resolveRefs(val, subobj, key);
}
}, this);
}
}
};
});
|
Allow setting invisible for styled features | (function () {
"use strict";
$(document).ready(function () {
OpenLayers.Feature.prototype.equals = function (feature) {
return this.fid === feature.fid;
};
OpenLayers.Feature.prototype.isNew = false;
OpenLayers.Feature.prototype.isChanged = false;
OpenLayers.Feature.prototype.isCopy = false;
OpenLayers.Feature.prototype.disabled = false;
OpenLayers.Feature.prototype.visible = true;
OpenLayers.Feature.prototype.cluster = false;
OpenLayers.Feature.prototype.getClusterSize = function () {
return this.cluster ? this.cluster.length : null;
};
OpenLayers.Feature.prototype.setRenderIntent = function () {
var feature = this;
feature.renderIntent = "default";
if (feature.isChanged || feature.isNew) {
feature.renderIntent = 'unsaved';
}
if (feature.isCopy) {
feature.renderIntent = 'copy';
}
if (!feature.visible) {
feature.renderIntent = 'invisible';
feature.deactivatedStyle = feature.style;
feature.style = null;
} else {
feature.style = feature.deactivatedStyle;
}
}
});
})(); | (function () {
"use strict";
$(document).ready(function () {
OpenLayers.Feature.prototype.equals = function (feature) {
return this.fid === feature.fid;
};
OpenLayers.Feature.prototype.isNew = false;
OpenLayers.Feature.prototype.isChanged = false;
OpenLayers.Feature.prototype.isCopy = false;
OpenLayers.Feature.prototype.disabled = false;
OpenLayers.Feature.prototype.visible = true;
OpenLayers.Feature.prototype.cluster = false;
OpenLayers.Feature.prototype.getClusterSize = function () {
return this.cluster ? this.cluster.length : null;
};
OpenLayers.Feature.prototype.setRenderIntent = function () {
var feature = this;
feature.renderIntent = "default";
if (feature.isChanged || feature.isNew) {
feature.renderIntent = 'unsaved';
}
if (feature.isCopy) {
feature.renderIntent = 'copy';
}
if (!feature.visible) {
feature.renderIntent = 'invisible';
}
}
});
})(); |
Fix reference to md5 helper in test
Fixes reference to md5 helper and removes reference to js client
as the md5 function is now provided by utils. | 'use strict'
var net = require('net')
var helper = require(__dirname + '/../test-helper')
var Connection = require(__dirname + '/../../../lib/connection')
var utils = require(__dirname + '/../../../lib/utils')
var connect = function (callback) {
var username = helper.args.user
var database = helper.args.database
var con = new Connection({stream: new net.Stream()})
con.on('error', function (error) {
console.log(error)
throw new Error('Connection error')
})
con.connect(helper.args.port || '5432', helper.args.host || 'localhost')
con.once('connect', function () {
con.startup({
user: username,
database: database
})
con.once('authenticationCleartextPassword', function () {
con.password(helper.args.password)
})
con.once('authenticationMD5Password', function (msg) {
var inner = utils.md5(helper.args.password + helper.args.user)
var outer = utils.md5(Buffer.concat([Buffer.from(inner), msg.salt]))
con.password('md5' + outer)
})
con.once('readyForQuery', function () {
con.query('create temp table ids(id integer)')
con.once('readyForQuery', function () {
con.query('insert into ids(id) values(1); insert into ids(id) values(2);')
con.once('readyForQuery', function () {
callback(con)
})
})
})
})
}
module.exports = {
connect: connect
}
| 'use strict'
var net = require('net')
var helper = require(__dirname + '/../test-helper')
var Connection = require(__dirname + '/../../../lib/connection')
var connect = function (callback) {
var username = helper.args.user
var database = helper.args.database
var con = new Connection({stream: new net.Stream()})
con.on('error', function (error) {
console.log(error)
throw new Error('Connection error')
})
con.connect(helper.args.port || '5432', helper.args.host || 'localhost')
con.once('connect', function () {
con.startup({
user: username,
database: database
})
con.once('authenticationCleartextPassword', function () {
con.password(helper.args.password)
})
con.once('authenticationMD5Password', function (msg) {
// need js client even if native client is included
var client = require(__dirname + '/../../../lib/client')
var inner = client.md5(helper.args.password + helper.args.user)
var outer = client.md5(inner + msg.salt.toString('binary'))
con.password('md5' + outer)
})
con.once('readyForQuery', function () {
con.query('create temp table ids(id integer)')
con.once('readyForQuery', function () {
con.query('insert into ids(id) values(1); insert into ids(id) values(2);')
con.once('readyForQuery', function () {
callback(con)
})
})
})
})
}
module.exports = {
connect: connect
}
|
Allow base=PeriodicTask argument to task decorator | from celery.task.base import Task
from inspect import getargspec
def task(**options):
"""Make a task out of any callable.
Examples:
>>> @task()
... def refresh_feed(url):
... return Feed.objects.get(url=url).refresh()
>>> refresh_feed("http://example.com/rss") # Regular
<Feed: http://example.com/rss>
>>> refresh_feed.delay("http://example.com/rss") # Async
<AsyncResult: 8998d0f4-da0b-4669-ba03-d5ab5ac6ad5d>
# With setting extra options and using retry.
>>> @task(exchange="feeds")
... def refresh_feed(url, **kwargs):
... try:
... return Feed.objects.get(url=url).refresh()
... except socket.error, exc:
... refresh_feed.retry(args=[url], kwargs=kwargs,
... exc=exc)
"""
def _create_task_cls(fun):
base = options.pop("base", Task)
cls_name = fun.__name__
def run(self, *args, **kwargs):
return fun(*args, **kwargs)
run.__name__ = fun.__name__
run.argspec = getargspec(fun)
cls_dict = dict(options)
cls_dict["run"] = run
cls_dict["__module__"] = fun.__module__
task = type(cls_name, (base, ), cls_dict)()
return task
return _create_task_cls
| from celery.task.base import Task
from celery.registry import tasks
from inspect import getargspec
def task(**options):
"""Make a task out of any callable.
Examples:
>>> @task()
... def refresh_feed(url):
... return Feed.objects.get(url=url).refresh()
>>> refresh_feed("http://example.com/rss") # Regular
<Feed: http://example.com/rss>
>>> refresh_feed.delay("http://example.com/rss") # Async
<AsyncResult: 8998d0f4-da0b-4669-ba03-d5ab5ac6ad5d>
# With setting extra options and using retry.
>>> @task(exchange="feeds")
... def refresh_feed(url, **kwargs):
... try:
... return Feed.objects.get(url=url).refresh()
... except socket.error, exc:
... refresh_feed.retry(args=[url], kwargs=kwargs,
... exc=exc)
"""
def _create_task_cls(fun):
name = options.pop("name", None)
cls_name = fun.__name__
def run(self, *args, **kwargs):
return fun(*args, **kwargs)
run.__name__ = fun.__name__
run.argspec = getargspec(fun)
cls_dict = dict(options)
cls_dict["run"] = run
cls_dict["__module__"] = fun.__module__
task = type(cls_name, (Task, ), cls_dict)()
return task
return _create_task_cls
|
Allow multiple configuration files for both rules and attributes | <?php
namespace PhpAbac\Manager;
use PhpAbac\Loader\YamlAbacLoader;
use Symfony\Component\Config\FileLocatorInterface;
class ConfigurationManager {
/** @var FileLocatorInterface **/
protected $locator;
/** @var string **/
protected $format;
/** @var array **/
protected $loaders;
/** @var array **/
protected $rules;
/** @var array **/
protected $attributes;
/**
* @param FileLocatorInterface $locator
* @param string $format
*/
public function __construct(FileLocatorInterface $locator, $format = 'yaml') {
$this->locator = $locator;
$this->format = $format;
$this->attributes = [];
$this->rules = [];
$this->loaders['yaml'] = new YamlAbacLoader($locator);
}
/**
* @param array $configurationFiles
*/
public function parseConfigurationFile($configurationFiles) {
foreach($configurationFiles as $configurationFile) {
$config = $this->loaders[$this->format]->load($configurationFile);
if(isset($config['attributes'])) {
$this->attributes = array_merge($this->attributes, $config['attributes']);
}
if(isset($config['rules'])) {
$this->rules = array_merge($this->rules, $config['rules']);
}
}
}
/**
* @return array
*/
public function getAttributes() {
return $this->attributes;
}
/**
* @return array
*/
public function getRules() {
return $this->rules;
}
} | <?php
namespace PhpAbac\Manager;
use PhpAbac\Loader\YamlAbacLoader;
use Symfony\Component\Config\FileLocatorInterface;
class ConfigurationManager {
/** @var FileLocatorInterface **/
protected $locator;
/** @var string **/
protected $format;
/** @var array **/
protected $loaders;
/** @var array **/
protected $rules;
/** @var array **/
protected $attributes;
/**
* @param FileLocatorInterface $locator
* @param string $format
*/
public function __construct(FileLocatorInterface $locator, $format = 'yaml') {
$this->locator = $locator;
$this->format = $format;
$this->attributes = [];
$this->rules = [];
$this->loaders['yaml'] = new YamlAbacLoader($locator);
}
/**
* @param array $configurationFiles
*/
public function parseConfigurationFile($configurationFiles) {
foreach($configurationFiles as $configurationFile) {
$config = $this->loaders[$this->format]->load($configurationFile);
$this->attributes = array_merge($this->attributes, $config['attributes']);
$this->rules = array_merge($this->rules, $config['rules']);
}
}
/**
* @return array
*/
public function getAttributes() {
return $this->attributes;
}
/**
* @return array
*/
public function getRules() {
return $this->rules;
}
} |
Disable width/height resize on image browse selection and use inlnie url for responsive images.
Add Download URL to images automatically | (function() {
CKEDITOR.plugins.add('concrete5filemanager', {
init: function () {
CKEDITOR.on('dialogDefinition', function(event) {
var editor = event.editor,
dialogDefinition = event.data.definition,
tabContent = dialogDefinition.contents.length;
for (var i = 0; i < tabContent; i++) {
var browseButton = dialogDefinition.contents[i].get('browse');
if (browseButton !== null) {
browseButton.hidden = false;
browseButton.onClick = function() {
editor._.filebrowserSe = this;
ConcreteFileManager.launchDialog(function(data) {
jQuery.fn.dialog.showLoader();
ConcreteFileManager.getFileDetails(data.fID, function(r) {
jQuery.fn.dialog.hideLoader();
var file = r.files[0];
CKEDITOR.tools.callFunction(editor._.filebrowserFn, file.urlInline, function() {
var dialog = this.getDialog();
if ( dialog.getName() == 'image' || dialog.getName() == 'image2') {
dialog.dontResetSize = true;
dialog.getContentElement( 'info', 'txtAlt').setValue(file.title);
dialog.getContentElement( 'info', 'txtWidth').setValue('');
dialog.getContentElement( 'info', 'txtHeight').setValue('');
dialog.getContentElement( 'Link', 'txtUrl').setValue(file.urlDownload);
}
});
});
});
}
}
}
});
}
});
})(); | (function() {
CKEDITOR.plugins.add('concrete5filemanager', {
init: function () {
CKEDITOR.on('dialogDefinition', function(event) {
var editor = event.editor,
dialogDefinition = event.data.definition,
tabContent = dialogDefinition.contents.length;
for (var i = 0; i < tabContent; i++) {
var browseButton = dialogDefinition.contents[i].get('browse');
if (browseButton !== null) {
browseButton.hidden = false;
browseButton.onClick = function() {
editor._.filebrowserSe = this;
ConcreteFileManager.launchDialog(function(data) {
jQuery.fn.dialog.showLoader();
ConcreteFileManager.getFileDetails(data.fID, function(r) {
jQuery.fn.dialog.hideLoader();
var file = r.files[0];
CKEDITOR.tools.callFunction(editor._.filebrowserFn, file.urlDownload);
});
});
}
}
}
});
}
});
})(); |
Fix the missing `return null;` in `getUserByIdentifier` | <?php
namespace Auth0\Login\Repository;
use Auth0\Login\Auth0User;
use Auth0\Login\Auth0JWTUser;
use Auth0\Login\Contract\Auth0UserRepository as Auth0UserRepositoryContract;
use Illuminate\Contracts\Auth\Authenticatable;
class Auth0UserRepository implements Auth0UserRepositoryContract
{
/**
* @param array $decodedJwt
*
* @return Auth0JWTUser
*/
public function getUserByDecodedJWT(array $decodedJwt) : Authenticatable
{
return new Auth0JWTUser($decodedJwt);
}
/**
* @param array $userInfo
*
* @return Auth0User
*/
public function getUserByUserInfo(array $userInfo) : Authenticatable
{
return new Auth0User($userInfo['profile'], $userInfo['accessToken']);
}
/**
* @param string|int|null $identifier
*
* @return Authenticatable|null
*/
public function getUserByIdentifier($identifier) : ?Authenticatable
{
// Get the user info of the user logged in (probably in session)
$user = \App::make('auth0')->getUser();
if ($user === null) {
return null;
}
// Build the user
$auth0User = $this->getUserByUserInfo($user);
// It is not the same user as logged in, it is not valid
if ($auth0User && $auth0User->getAuthIdentifier() == $identifier) {
return $auth0User;
}
return null;
}
}
| <?php
namespace Auth0\Login\Repository;
use Auth0\Login\Auth0User;
use Auth0\Login\Auth0JWTUser;
use Auth0\Login\Contract\Auth0UserRepository as Auth0UserRepositoryContract;
use Illuminate\Contracts\Auth\Authenticatable;
class Auth0UserRepository implements Auth0UserRepositoryContract
{
/**
* @param array $decodedJwt
*
* @return Auth0JWTUser
*/
public function getUserByDecodedJWT(array $decodedJwt) : Authenticatable
{
return new Auth0JWTUser($decodedJwt);
}
/**
* @param array $userInfo
*
* @return Auth0User
*/
public function getUserByUserInfo(array $userInfo) : Authenticatable
{
return new Auth0User($userInfo['profile'], $userInfo['accessToken']);
}
/**
* @param string|int|null $identifier
*
* @return Authenticatable|null
*/
public function getUserByIdentifier($identifier) : ?Authenticatable
{
// Get the user info of the user logged in (probably in session)
$user = \App::make('auth0')->getUser();
if ($user === null) {
return null;
}
// Build the user
$auth0User = $this->getUserByUserInfo($user);
// It is not the same user as logged in, it is not valid
if ($auth0User && $auth0User->getAuthIdentifier() == $identifier) {
return $auth0User;
}
}
}
|
Change dateTime validation regex - it is now optional | package seedu.emeraldo.model.task;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
/**
* Represents a Person's address in the address book.
* Guarantees: immutable; is valid as declared in {@link #isValidAddress(String)}
*/
public class DateTime {
public static final String MESSAGE_ADDRESS_CONSTRAINTS = "Person addresses can be in any format";
public static final String ADDRESS_VALIDATION_REGEX = "(.+)?";
public final String value;
/**
* Validates given address.
*
* @throws IllegalValueException if given address string is invalid.
*/
public DateTime(String address) throws IllegalValueException {
assert address != null;
if (!isValidAddress(address)) {
throw new IllegalValueException(MESSAGE_ADDRESS_CONSTRAINTS);
}
this.value = address;
}
private static boolean isValidAddress(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 Person's address in the address book.
* Guarantees: immutable; is valid as declared in {@link #isValidAddress(String)}
*/
public class DateTime {
public static final String MESSAGE_ADDRESS_CONSTRAINTS = "Person addresses can be in any format";
public static final String ADDRESS_VALIDATION_REGEX = ".+";
public final String value;
/**
* Validates given address.
*
* @throws IllegalValueException if given address string is invalid.
*/
public DateTime(String address) throws IllegalValueException {
assert address != null;
if (!isValidAddress(address)) {
throw new IllegalValueException(MESSAGE_ADDRESS_CONSTRAINTS);
}
this.value = address;
}
private static boolean isValidAddress(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();
}
} |
Remove resolve in top level | import commonjs from '@rollup/plugin-commonjs';
import glslify from 'rollup-plugin-glslify';
import resolve from '@rollup/plugin-node-resolve';
import copy from "rollup-plugin-copy";
export default {
input: ['source/gltf-sample-viewer.js'],
output: [
{
file: 'dist/gltf-viewer.js',
format: 'cjs',
sourcemap: true
},
{
file: 'dist/gltf-viewer.module.js',
format: 'esm',
sourcemap: true,
}
],
plugins: [
glslify(),
copy({
targets: [
{
src: [
"assets/images/lut_charlie.png",
"assets/images/lut_ggx.png",
"assets/images/lut_sheen_E.png",
], dest: "dist/assets"
},
{ src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" }
]
}),
commonjs(),
]
};
| import commonjs from '@rollup/plugin-commonjs';
import glslify from 'rollup-plugin-glslify';
import resolve from '@rollup/plugin-node-resolve';
import copy from "rollup-plugin-copy";
export default {
input: ['source/gltf-sample-viewer.js'],
output: [
{
file: 'dist/gltf-viewer.js',
format: 'cjs',
sourcemap: true
},
{
file: 'dist/gltf-viewer.module.js',
format: 'esm',
sourcemap: true,
}
],
plugins: [
glslify(),
resolve({
browser: true,
preferBuiltins: false,
dedupe: ['gl-matrix', 'axios', 'jpeg-js', 'fast-png']
}),
copy({
targets: [
{
src: [
"assets/images/lut_charlie.png",
"assets/images/lut_ggx.png",
"assets/images/lut_sheen_E.png",
], dest: "dist/assets"
},
{ src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" }
]
}),
commonjs(),
]
};
|
Update P2_combinePDF.py
added module reference in docstring | #! python3
"""Combine PDFs
Combines all the PDFs in the current working directory into a single PDF.
Note:
* Example PDFs can be downloaded from http://nostarch.com/automatestuff/
* Book uses :py:mod:`PyPDF2`; I'm an overachiever that uses PyPDF4
"""
def main():
import PyPDF4, os
# Get all the PDF filenames.
if os.path.exists("allminutes.pdf"):
os.remove("allminutes.pdf")
pdfFiles = []
for filename in os.listdir('.'):
if filename.endswith(".pdf"):
pdfFiles.append(filename)
pdfFiles.sort(key=str.lower)
pdfWriter = PyPDF4.PdfFileWriter()
# Loop through all the PDF files.
for filename in pdfFiles:
pdfFileObj = open(filename, "rb")
pdfReader = PyPDF4.PdfFileReader(pdfFileObj)
if pdfReader.isEncrypted and filename == "encrypted.pdf":
pdfReader.decrypt("rosebud")
if pdfReader.isEncrypted and filename == "encryptedminutes.pdf":
pdfReader.decrypt("swordfish")
# Loop through all the pages (except the first) and add them.
for pageNum in range(1, pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
# Save the resulting PDF to a file.
pdfOutput = open("allminutes.pdf", "wb")
pdfWriter.write(pdfOutput)
pdfOutput.close()
if __name__ == '__main__':
main()
| #! python3
"""Combine PDFs
Combines all the PDFs in the current working directory into a single PDF.
Note:
* Example PDFs can be downloaded from http://nostarch.com/automatestuff/
* Book uses PyPDF2; I'm an overachiever that uses PyPDF4
"""
def main():
import PyPDF4, os
# Get all the PDF filenames.
if os.path.exists("allminutes.pdf"):
os.remove("allminutes.pdf")
pdfFiles = []
for filename in os.listdir('.'):
if filename.endswith(".pdf"):
pdfFiles.append(filename)
pdfFiles.sort(key=str.lower)
pdfWriter = PyPDF4.PdfFileWriter()
# Loop through all the PDF files.
for filename in pdfFiles:
pdfFileObj = open(filename, "rb")
pdfReader = PyPDF4.PdfFileReader(pdfFileObj)
if pdfReader.isEncrypted and filename == "encrypted.pdf":
pdfReader.decrypt("rosebud")
if pdfReader.isEncrypted and filename == "encryptedminutes.pdf":
pdfReader.decrypt("swordfish")
# Loop through all the pages (except the first) and add them.
for pageNum in range(1, pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
# Save the resulting PDF to a file.
pdfOutput = open("allminutes.pdf", "wb")
pdfWriter.write(pdfOutput)
pdfOutput.close()
if __name__ == '__main__':
main()
|
Remove unsupported pythons from classifiers | """setup.py"""
from codecs import open as codecs_open
from setuptools import setup
with codecs_open("README.md", "r", "utf-8") as f:
README = f.read()
setup(
author="Beau Barker",
author_email="[email protected]",
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
description="Send JSON-RPC requests",
entry_points={"console_scripts": ["jsonrpc = jsonrpcclient.__main__:main"]},
extras_require={
"aiohttp": ["aiohttp"],
"requests": ["requests"],
"requests_security": ["requests[security]"],
"tornado": ["tornado"],
"unittest": [
"requests",
"pyzmq",
"tornado",
"responses",
"testfixtures",
"mock",
],
"websockets": ["websockets"],
"zmq": ["pyzmq"],
},
include_package_data=True,
install_requires=["jsonschema>2,<3", "click>6,<7"],
license="MIT",
long_description=README,
long_description_content_type="text/markdown",
name="jsonrpcclient",
package_data={"jsonrpcclient": ["response-schema.json"]},
packages=["jsonrpcclient"],
url="https://github.com/bcb/jsonrpcclient",
version="3.0.0rc1",
)
| """setup.py"""
from codecs import open as codecs_open
from setuptools import setup
with codecs_open("README.md", "r", "utf-8") as f:
README = f.read()
setup(
author="Beau Barker",
author_email="[email protected]",
classifiers=[
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
description="Send JSON-RPC requests",
entry_points={"console_scripts": ["jsonrpc = jsonrpcclient.__main__:main"]},
extras_require={
"aiohttp": ["aiohttp"],
"requests": ["requests"],
"requests_security": ["requests[security]"],
"tornado": ["tornado"],
"unittest": [
"requests",
"pyzmq",
"tornado",
"responses",
"testfixtures",
"mock",
],
"websockets": ["websockets"],
"zmq": ["pyzmq"],
},
include_package_data=True,
install_requires=["future<1", "jsonschema>2,<3", "click>6,<7"],
license="MIT",
long_description=README,
long_description_content_type="text/markdown",
name="jsonrpcclient",
package_data={"jsonrpcclient": ["response-schema.json"]},
packages=["jsonrpcclient"],
url="https://github.com/bcb/jsonrpcclient",
version="3.0.0rc1",
)
|
Use SlugRelatedField for foreign keys for better readability | import uuid
import jsonschema
from rest_framework import serializers
from .models import (
Api,
Consumer,
ConsumerKey,
Plugin,
)
from .schemas import plugins
class ConsumerSerializer(serializers.ModelSerializer):
class Meta:
model = Consumer
fields = '__all__'
class ConsumerKeySerializer(serializers.ModelSerializer):
consumer = serializers.SlugRelatedField(
many=False,
read_only=False,
slug_field='username',
queryset=Consumer.objects.all()
)
class Meta:
model = ConsumerKey
fields = '__all__'
extra_kwargs = {
'key': {
'required': False,
'allow_null': True,
'allow_blank': True,
},
}
def validate_key(self, value):
"""Verify if no key is given and generate one"""
if not value:
value = str(uuid.uuid4()).replace('-', '')
return value
class PluginSerializer(serializers.ModelSerializer):
api = serializers.SlugRelatedField(
many=False,
read_only=True,
slug_field='name'
)
class Meta:
model = Plugin
fields = '__all__'
extra_kwargs = {
'config': {
'default': {},
}
}
def validate(self, data):
name = data.get('name')
if not name or name not in plugins:
raise serializers.ValidationError('Invalid plugin name')
plugin_schema = plugins[name]
try:
jsonschema.validate(data['config'], plugin_schema)
except jsonschema.ValidationError as e:
raise serializers.ValidationError({'config': e})
return data
class ApiSerializer(serializers.ModelSerializer):
plugins = PluginSerializer(
many=True,
read_only=False,
)
class Meta:
model = Api
fields = '__all__'
| import uuid
import jsonschema
from rest_framework import serializers
from .models import (
Api,
Consumer,
ConsumerKey,
Plugin,
)
from .schemas import plugins
class ApiSerializer(serializers.ModelSerializer):
class Meta:
model = Api
fields = '__all__'
class ConsumerSerializer(serializers.ModelSerializer):
class Meta:
model = Consumer
fields = '__all__'
class ConsumerKeySerializer(serializers.ModelSerializer):
class Meta:
model = ConsumerKey
fields = '__all__'
extra_kwargs = {
'key': {
'required': False,
'allow_null': True,
'allow_blank': True,
},
}
def validate_key(self, value):
"""Verify if no key is given and generate one"""
if not value:
value = str(uuid.uuid4()).replace('-', '')
return value
class PluginSerializer(serializers.ModelSerializer):
class Meta:
model = Plugin
fields = '__all__'
extra_kwargs = {
'config': {
'default': {},
}
}
def validate(self, data):
name = data.get('name')
if not name or name not in plugins:
raise serializers.ValidationError('Invalid plugin name')
plugin_schema = plugins[name]
try:
jsonschema.validate(data['config'], plugin_schema)
except jsonschema.ValidationError as e:
raise serializers.ValidationError({'config': e})
return data
|
Add a criterion kind for extends/implements. It's not used anywhere yet. An option would be to have separate constants for extends and implements, but that's probably not needed. | package annotator.find;
import com.sun.source.util.TreePath;
import com.sun.source.tree.Tree;
/**
* A criterion for locating a program element in an AST. A Criterion does
* not actually give a location. Given a location, the isSatisfiedBy
* method indicates whether that location is a desired one.
*/
public interface Criterion {
/**
* Types of criterion.
*/
public static enum Kind {
IN_METHOD,
IN_CLASS,
ENCLOSED_BY,
HAS_KIND,
NOT_IN_METHOD,
TYPE_PARAM,
GENERIC_ARRAY_LOCATION,
RECEIVER,
RETURN_TYPE,
SIG_METHOD,
PARAM,
CAST,
LOCAL_VARIABLE,
FIELD,
NEW,
INSTANCE_OF,
BOUND_LOCATION,
EXTIMPLS_LOCATION,
METHOD_BOUND,
CLASS_BOUND,
IN_PACKAGE,
CLASS,
PACKAGE;
}
/**
* Determines if the given tree path is satisfied by this criterion.
*
* @param path the tree path to check against
* @return true if this criterion is satisfied by the given path,
* false otherwise
*/
public boolean isSatisfiedBy(TreePath path, Tree tree);
/**
* Determines if the given tree path is satisfied by this criterion.
*
* @param path the tree path to check against
* @return true if this criterion is satisfied by the given path,
* false otherwise
*/
public boolean isSatisfiedBy(TreePath path);
/**
* Gets the type of this criterion.
*
* @return this criterion's kind
*/
public Kind getKind();
}
| package annotator.find;
import com.sun.source.util.TreePath;
import com.sun.source.tree.Tree;
/**
* A criterion for locating a program element in an AST. A Criterion does
* not actually give a location. Given a location, the isSatisfiedBy
* method indicates whether that location is a desired one.
*/
public interface Criterion {
/**
* Types of criterion.
*/
public static enum Kind {
IN_METHOD,
IN_CLASS,
ENCLOSED_BY,
HAS_KIND,
NOT_IN_METHOD,
TYPE_PARAM,
GENERIC_ARRAY_LOCATION,
RECEIVER,
RETURN_TYPE,
SIG_METHOD,
PARAM,
CAST,
LOCAL_VARIABLE,
FIELD,
NEW,
INSTANCE_OF,
BOUND_LOCATION,
METHOD_BOUND,
CLASS_BOUND,
IN_PACKAGE,
CLASS,
PACKAGE;
}
/**
* Determines if the given tree path is satisfied by this criterion.
*
* @param path the tree path to check against
* @return true if this criterion is satisfied by the given path,
* false otherwise
*/
public boolean isSatisfiedBy(TreePath path, Tree tree);
/**
* Determines if the given tree path is satisfied by this criterion.
*
* @param path the tree path to check against
* @return true if this criterion is satisfied by the given path,
* false otherwise
*/
public boolean isSatisfiedBy(TreePath path);
/**
* Gets the type of this criterion.
*
* @return this criterion's kind
*/
public Kind getKind();
}
|
Support table custom table prefix
Laravel automatically adds a table prefix to any table names, so we
need to wrap our aliased table in DB::raw. | <?php namespace Flarum\Core\Notifications;
use Flarum\Core\Users\User;
class NotificationRepository
{
/**
* Find a user's notifications.
*
* @param User $user
* @param int|null $limit
* @param int $offset
* @return \Illuminate\Database\Eloquent\Collection
*/
public function findByUser(User $user, $limit = null, $offset = 0)
{
$primaries = Notification::select(
app('flarum.db')->raw('MAX(id) AS id'),
app('flarum.db')->raw('SUM(is_read = 0) AS unread_count')
)
->where('user_id', $user->id)
->whereIn('type', $user->getAlertableNotificationTypes())
->where('is_deleted', false)
->groupBy('type', 'subject_id')
->orderByRaw('MAX(time) DESC')
->skip($offset)
->take($limit);
return Notification::select('notifications.*', app('flarum.db')->raw('p.unread_count'))
->mergeBindings($primaries->getQuery())
->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', app('flarum.db')->raw('p.id'))
->latest('time')
->get();
}
}
| <?php namespace Flarum\Core\Notifications;
use Flarum\Core\Users\User;
class NotificationRepository
{
/**
* Find a user's notifications.
*
* @param User $user
* @param int|null $limit
* @param int $offset
* @return \Illuminate\Database\Eloquent\Collection
*/
public function findByUser(User $user, $limit = null, $offset = 0)
{
$primaries = Notification::select(
app('flarum.db')->raw('MAX(id) AS id'),
app('flarum.db')->raw('SUM(is_read = 0) AS unread_count')
)
->where('user_id', $user->id)
->whereIn('type', $user->getAlertableNotificationTypes())
->where('is_deleted', false)
->groupBy('type', 'subject_id')
->orderByRaw('MAX(time) DESC')
->skip($offset)
->take($limit);
return Notification::select('notifications.*', 'p.unread_count')
->mergeBindings($primaries->getQuery())
->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', 'p.id')
->latest('time')
->get();
}
}
|
REMOVE unneeded babel/preset in override | module.exports = {
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage' }],
'@babel/preset-react',
'@babel/preset-flow',
],
plugins: [
'babel-plugin-emotion',
'babel-plugin-macros',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-export-default-from',
],
env: {
test: {
plugins: ['babel-plugin-require-context-hook', 'babel-plugin-dynamic-import-node'],
},
},
overrides: [
{
test: './examples/vue-kitchen-sink',
presets: [
'babel-preset-vue',
],
},
{
test: [
'./lib/core/src/server',
'./lib/node-logger',
'./lib/codemod',
'./addons/storyshots',
'./addons/storysource/src/loader',
'./app/**/src/server/**',
],
presets: [
[
'@babel/preset-env',
{
targets: {
node: '8.11',
},
},
],
],
},
],
};
| module.exports = {
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage' }],
'@babel/preset-react',
'@babel/preset-flow',
],
plugins: [
'babel-plugin-emotion',
'babel-plugin-macros',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-export-default-from',
],
env: {
test: {
plugins: ['babel-plugin-require-context-hook', 'babel-plugin-dynamic-import-node'],
},
},
overrides: [
{
test: './examples/vue-kitchen-sink',
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage' }],
'babel-preset-vue',
],
},
{
test: [
'./lib/core/src/server',
'./lib/node-logger',
'./lib/codemod',
'./addons/storyshots',
'./addons/storysource/src/loader',
'./app/**/src/server/**',
],
presets: [
[
'@babel/preset-env',
{
targets: {
node: '8.11',
},
},
],
],
},
],
};
|
Support more general documentation path names. | # encoding: utf-8
"""
URL conf for django-sphinxdoc.
"""
from django.conf.urls.defaults import patterns, url
from django.views.generic import list_detail
from sphinxdoc import models
from sphinxdoc.views import ProjectSearchView
project_info = {
'queryset': models.Project.objects.all().order_by('name'),
'template_object_name': 'project',
}
urlpatterns = patterns('sphinxdoc.views',
url(
r'^$',
list_detail.object_list,
project_info,
),
url(
r'^(?P<slug>[\w-]+)/search/$',
ProjectSearchView(),
name='doc-search',
),
url(
r'^(?P<slug>[\w-]+)/_images/(?P<path>.*)$',
'images',
),
url(
r'^(?P<slug>[\w-]+)/_source/(?P<path>.*)$',
'source',
),
url(
r'^(?P<slug>[\w-]+)/_objects/$',
'objects_inventory',
name='objects-inv',
),
url(
r'^(?P<slug>[\w-]+)/$',
'documentation',
{'path': ''},
name='doc-index',
),
url(
r'^(?P<slug>[\w-]+)/(?P<path>.+)/$',
'documentation',
name='doc-detail',
),
)
| # encoding: utf-8
"""
URL conf for django-sphinxdoc.
"""
from django.conf.urls.defaults import patterns, url
from django.views.generic import list_detail
from sphinxdoc import models
from sphinxdoc.views import ProjectSearchView
project_info = {
'queryset': models.Project.objects.all().order_by('name'),
'template_object_name': 'project',
}
urlpatterns = patterns('sphinxdoc.views',
url(
r'^$',
list_detail.object_list,
project_info,
),
url(
r'^(?P<slug>[\w-]+)/search/$',
ProjectSearchView(),
name='doc-search',
),
url(
r'^(?P<slug>[\w-]+)/_images/(?P<path>.*)$',
'images',
),
url(
r'^(?P<slug>[\w-]+)/_source/(?P<path>.*)$',
'source',
),
url(
r'^(?P<slug>[\w-]+)/_objects/$',
'objects_inventory',
name='objects-inv',
),
url(
r'^(?P<slug>[\w-]+)/$',
'documentation',
{'path': ''},
name='doc-index',
),
url(
r'^(?P<slug>[\w-]+)/(?P<path>(([\w-]+)/)+)$',
'documentation',
name='doc-detail',
),
)
|
Fix bug to display the default snapshot item | // @flow
import type {Snapshot, SnapshotItem} from 'redux-ship';
export type State = {
logs: {action: mixed, snapshot: Snapshot<mixed, mixed>}[],
selectedLog: ?number,
selectedSnapshotItem: ?SnapshotItem<mixed, mixed>,
};
export const initialState: State = {
logs: [],
selectedLog: null,
selectedSnapshotItem: null,
};
export type Commit = {
type: 'AddLog',
action: mixed,
snapshot: Snapshot<mixed, mixed>,
} | {
type: 'SelectLog',
logIndex: number,
} | {
type: 'SelectSnapshotItem',
snapshotItem: SnapshotItem<mixed, mixed>,
};
export function reduce(state: State, commit: Commit): State {
switch (commit.type) {
case 'AddLog':
return {
...state,
logs: [
...state.logs,
{
action: commit.action,
snapshot: commit.snapshot,
}
],
selectedLog: typeof state.selectedLog !== 'number' ?
state.logs.length :
state.selectedLog,
selectedSnapshotItem: typeof state.selectedLog !== 'number' ?
commit.snapshot[0] || null :
state.selectedSnapshotItem,
};
case 'SelectLog':
return commit.logIndex === state.selectedLog ? state : {
...state,
selectedLog: commit.logIndex,
selectedSnapshotItem: state.logs[commit.logIndex].snapshot[0] || null,
};
case 'SelectSnapshotItem':
return {
...state,
selectedSnapshotItem: commit.snapshotItem,
};
default:
return state;
}
}
| // @flow
import type {Snapshot, SnapshotItem} from 'redux-ship';
export type State = {
logs: {action: mixed, snapshot: Snapshot<mixed, mixed>}[],
selectedLog: ?number,
selectedSnapshotItem: ?SnapshotItem<mixed, mixed>,
};
export const initialState: State = {
logs: [],
selectedLog: null,
selectedSnapshotItem: null,
};
export type Commit = {
type: 'AddLog',
action: mixed,
snapshot: Snapshot<mixed, mixed>,
} | {
type: 'SelectLog',
logIndex: number,
} | {
type: 'SelectSnapshotItem',
snapshotItem: SnapshotItem<mixed, mixed>,
};
export function reduce(state: State, commit: Commit): State {
switch (commit.type) {
case 'AddLog':
return {
...state,
logs: [
...state.logs,
{
action: commit.action,
snapshot: commit.snapshot,
}
],
selectedLog: typeof state.selectedLog !== 'number' ?
state.logs.length :
state.selectedLog,
selectedSnapshotItem: commit.snapshot[0] || null,
};
case 'SelectLog':
return commit.logIndex === state.selectedLog ? state : {
...state,
selectedLog: commit.logIndex,
selectedSnapshotItem: state.logs[commit.logIndex].snapshot[0] || null,
};
case 'SelectSnapshotItem':
return {
...state,
selectedSnapshotItem: commit.snapshotItem,
};
default:
return state;
}
}
|
Rename variable from placeName to cityName | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class HomeController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('googleAPIProxy');
}
public function index()
{
$data = [
'search' => false
];
$this->load->view('templates/header');
$this->load->view('index', $data);
$this->load->view('templates/footer');
}
public function search()
{
$this->load->driver('cache');
$cityName = str_replace(' ', '+', $this->input->post('city_name'));
$cityNameAPIKey = sprintf('GoogleAPI-%s', $cityName);
$result = $this->cache->file->get($cityNameAPIKey);
if (!$result) {
$result = $this->googleAPIProxy->getSearchPlaceResult($cityName);
$this->cache->file->save($cityNameAPIKey, $result, CACHE_TIME);
}
$data = [
'search' => true,
'cityName' => $cityName,
'searchResult' => json_decode($result),
];
$this->load->view('templates/header');
$this->load->view('index', $data);
$this->load->view('templates/footer');
}
} | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class HomeController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('googleAPIProxy');
}
public function index()
{
$data = [
'search' => false
];
$this->load->view('templates/header');
$this->load->view('index', $data);
$this->load->view('templates/footer');
}
public function search()
{
$this->load->driver('cache');
$cityName = str_replace(' ', '+', $this->input->post('place_name'));
$cityNameAPIKey = sprintf('GoogleAPI-%s', $cityName);
$result = $this->cache->file->get($cityNameAPIKey);
if (!$result) {
$result = $this->googleAPIProxy->getSearchPlaceResult($cityName);
$this->cache->file->save($cityNameAPIKey, $result, CACHE_TIME);
}
$data = [
'search' => true,
'cityName' => $cityName,
'searchResult' => json_decode($result),
];
$this->load->view('templates/header');
$this->load->view('index', $data);
$this->load->view('templates/footer');
}
} |
Change bad function decorator implementation | import datetime
from openedoo.core.libs.tools import hashing_werkzeug
from openedoo_project import db
from .users import User
class Employee(User):
@classmethod
def is_exist(self, username):
employee = self.query.get(username=username).first()
return employee
@classmethod
def get_public_list(self):
employees = self.query.with_entities(self.username,
self.fullname,
self.nip)
return employees
@classmethod
def check_records(self):
employees = self.query.limit(1).all()
return employees
@classmethod
def add(self, form={}):
if not form:
raise ValueError('Form is supplied with wrong data.')
data = {
'username': form['username'],
'fullname': form['fullname'],
'password': hashing_werkzeug(form['password']),
'nip': form['nip'],
'created': datetime.datetime.now()
}
employeeData = self(data)
db.session.add(employeeData)
return db.session.commit()
| import datetime
from openedoo.core.libs.tools import hashing_werkzeug
from openedoo_project import db
from .users import User
class Employee(User):
@staticmethod
def is_exist(self, username):
employee = self.query.get(username=username).first()
return employee
@classmethod
def get_public_list(self):
employees = self.query.with_entities(self.username,
self.fullname,
self.nip)
return employees
@classmethod
def check_records(self):
employees = self.query.limit(1).all()
return employees
@classmethod
def add(self, form={}):
if not form:
raise ValueError('Form is supplied with wrong data.')
data = {
'username': form['username'],
'fullname': form['fullname'],
'password': hashing_werkzeug(form['password']),
'nip': form['nip'],
'created': datetime.datetime.now()
}
employeeData = self(data)
db.session.add(employeeData)
return db.session.commit()
|
Fix incorrect import of modules n commonjs env | (function (root, factory) {
'use strict';
/* global define, module, require */
if (typeof define === 'function' && define.amd) { // AMD
define(['./lib/Dice', './lib/inventory', './lib/modifiers', './lib/ProtoTree', './lib/random', './lib/requirements'], factory);
} else if (typeof exports === 'object') { // Node, browserify and alike
console.log('node')
module.exports = factory(
require('./lib/Dice'),
require('./lib/inventory'),
require('./lib/modifiers'),
require('./lib/ProtoTree'),
require('./lib/random'),
require('./lib/requirements')
);
} else { // Browser globals (root is window)
console.log('browser')
var modules = ['Dice', 'inventory', 'modifiers', 'ProtoTree', 'random', 'requirements'];
root.rpgTools = (root.rpgTools || {});
root.rpgTools = factory.apply(null, modules.map(function (module) { return root.rpgTools[module]; }));
}
}(this, function (Dice, inventory, modifiers, ProtoTree, random, requirements) {
'use strict';
var exports = {
Dice: Dice,
inventory: inventory,
modifiers: modifiers,
ProtoTree: ProtoTree,
random: random,
requirements: requirements
};
return exports;
})); | (function (root, factory) {
'use strict';
/* global define, module, require */
if (typeof define === 'function' && define.amd) { // AMD
define(['./lib/Dice', './lib/inventory', './lib/modifiers', './lib/ProtoTree', './lib/random', './lib/requirements'], factory);
} else if (typeof exports === 'object') { // Node, browserify and alike
module.exports = factory.apply(
require('./lib/Dice'),
require('./lib/inventory'),
require('./lib/modifiers'),
require('./lib/ProtoTree'),
require('./lib/random'),
require('./lib/requirements')
);
} else { // Browser globals (root is window)
var modules = ['Dice', 'inventory', 'modifiers', 'ProtoTree', 'random', 'requirements'];
root.rpgTools = (root.rpgTools || {});
root.rpgTools = factory.apply(null, modules.map(function (module) { return root.rpgTools[module]; }));
}
}(this, function (Dice, inventory, modifiers, ProtoTree, random, requirements) {
'use strict';
var exports = {
Dice: Dice,
inventory: inventory,
modifiers: modifiers,
ProtoTree: ProtoTree,
random: random,
requirements: requirements
};
return exports;
})); |
Make it easier to change the default Grunt task | // Configuration
module.exports = function(grunt) {
// Initialize config
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
});
// Load required tasks from submodules
grunt.loadTasks('grunt');
// Default task
grunt.registerTask('default', ['dev']);
// Development
grunt.registerTask('dev', [
'connect',
'localtunnel',
'watch'
]);
// Testing
grunt.registerTask('test', [
'htmlhint',
'jshint',
'scsslint'
]);
// Staging
grunt.registerTask('stage', [
'clean:deploy',
'fontello:build',
'assemble:stage',
'copy:stage',
'concat',
'sass:deploy',
'autoprefixer:deploy',
'uglify',
'imagemin:deploy',
'svgmin:deploy',
'modernizr',
'hashres:deploy'
]);
// Deployment
grunt.registerTask('deploy', [
'clean:deploy',
'fontello:build',
'assemble:deploy',
'copy:deploy',
'concat',
'sass:deploy',
'autoprefixer:deploy',
'uglify',
'imagemin:deploy',
'svgmin:deploy',
'modernizr',
'hashres:deploy'
]);
};
| // Configuration
module.exports = function(grunt) {
// Initialize config
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
});
// Load required tasks from submodules
grunt.loadTasks('grunt');
// Default
grunt.registerTask('default', [
'connect',
'localtunnel',
'watch'
]);
// Testing
grunt.registerTask('test', [
'htmlhint',
'jshint',
'scsslint'
]);
// Staging
grunt.registerTask('stage', [
'clean:deploy',
'fontello:build',
'assemble:stage',
'copy:stage',
'concat',
'sass:deploy',
'autoprefixer:deploy',
'uglify',
'imagemin:deploy',
'svgmin:deploy',
'modernizr',
'hashres:deploy'
]);
// Deployment
grunt.registerTask('deploy', [
'clean:deploy',
'fontello:build',
'assemble:deploy',
'copy:deploy',
'concat',
'sass:deploy',
'autoprefixer:deploy',
'uglify',
'imagemin:deploy',
'svgmin:deploy',
'modernizr',
'hashres:deploy'
]);
};
|
Add missing handle ipn url | from django.conf.urls import patterns, url
from oscar.core.application import Application
from systempay import views
class SystemPayApplication(Application):
name = 'systempay'
place_order_view = views.PlaceOrderView
cancel_response_view = views.CancelResponseView
secure_redirect_view = views.SecureRedirectView
handle_ipn_view = views.HandleIPN
def __init__(self, *args, **kwargs):
super(SystemPayApplication, self).__init__(*args, **kwargs)
def get_urls(self):
urlpatterns = super(SystemPayApplication, self).get_urls()
urlpatterns += patterns('',
url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'),
url(r'^preview/', self.place_order_view.as_view(preview=True),
name='preview'),
url(r'^cancel/', self.cancel_response_view.as_view(),
name='cancel-response'),
url(r'^place-order/', self.place_order_view.as_view(),
name='place-order'),
url(r'^handle-ipn/', self.handle_ipn_view.as_view(),
name='handle-ipn'),
)
return self.post_process_urls(urlpatterns)
application = SystemPayApplication()
| from django.conf.urls import patterns, url
from oscar.core.application import Application
from systempay import views
class SystemPayApplication(Application):
name = 'systempay'
place_order_view = views.PlaceOrderView
cancel_response_view = views.CancelResponseView
secure_redirect_view = views.SecureRedirectView
def __init__(self, *args, **kwargs):
super(SystemPayApplication, self).__init__(*args, **kwargs)
def get_urls(self):
urlpatterns = super(SystemPayApplication, self).get_urls()
urlpatterns += patterns('',
url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'),
url(r'^preview/', self.place_order_view.as_view(preview=True),
name='preview'),
url(r'^cancel/', self.cancel_response_view.as_view(),
name='cancel-response'),
url(r'^place-order/', self.place_order_view.as_view(),
name='place-order'),
# View for using PayPal as a payment method
# url(r'^handle-ipn/', self.redirect_view.as_view(as_payment_method=True),
# name='systempay-direct-payment'),
)
return self.post_process_urls(urlpatterns)
application = SystemPayApplication()
|
Use ValidationError rather than ValueError | """ MongoHN.forms - WTForms used by MongoHN """
from MongoHN.models import User
from flask.ext.wtf import Form
from wtforms import SubmitField, TextField, BooleanField, PasswordField
from wtforms.validators import Required, DataRequired, ValidationError
class LoginForm(Form):
username = TextField('Username', validators = [ Required() ])
password = PasswordField('Password', validators = [ Required() ])
remember_me = BooleanField('remember_me', default = False)
submit = SubmitField('Login')
def validate(self):
rv = Form.validate(self)
if not rv:
return False
user = User.objects(username=self.username.data).first()
if user is None:
self.username.errors.append('Unknown username')
return False
if not user.check_password(self.password.data):
self.password.errors.append('Invalid password')
return False
self.user = user
return True
class RegistrationForm(Form):
username = TextField('Username', validators=[ DataRequired() ])
password = PasswordField('Password', validators=[ DataRequired() ])
email = TextField('Email', validators=[ DataRequired() ])
submit = SubmitField('Register', validators=[ Required() ])
def validate_username(form, field):
if User.objects(username=field.data).first():
raise ValidationError("Username already exists.")
def create_user(self):
user = User()
user.username = self.username.data
user.password = self.password.data
user.email = self.email.data
user.save()
self.user = user
#
| """ MongoHN.forms - WTForms used by MongoHN """
from MongoHN.models import User
from flask.ext.wtf import Form
from wtforms import SubmitField, TextField, BooleanField, PasswordField
from wtforms.validators import Required, DataRequired
class LoginForm(Form):
username = TextField('Username', validators = [ Required() ])
password = PasswordField('Password', validators = [ Required() ])
remember_me = BooleanField('remember_me', default = False)
submit = SubmitField('Login')
def validate(self):
rv = Form.validate(self)
if not rv:
return False
user = User.objects(username=self.username.data).first()
if user is None:
self.username.errors.append('Unknown username')
return False
if not user.check_password(self.password.data):
self.password.errors.append('Invalid password')
return False
self.user = user
return True
class RegistrationForm(Form):
username = TextField('Username', validators=[ DataRequired() ])
password = PasswordField('Password', validators=[ DataRequired() ])
email = TextField('Email', validators=[ DataRequired() ])
submit = SubmitField('Register', validators=[ Required() ])
def validate_username(form, field):
if User.objects(username=field.data).first():
raise ValueError("Username already exists.")
def create_user(self):
user = User()
user.username = self.username.data
user.password = self.password.data
user.email = self.email.data
user.save()
self.user = user
#
|
Fix loading of modules by only their name | var findup = require('findup'),
path = require('path');
var local = require('./local');
function find(dir, file, callback) {
var name = file.split('/')[0],
modulePath = './node_modules/' + name + '/package.json';
findup(dir, modulePath, function (err, moduleDir) {
if (err) { return callback(err); }
var root = path.dirname(path.resolve(moduleDir, modulePath));
var location;
// if import is just a module name
if (file.split('/').length === 1) {
var json = require(path.resolve(moduleDir, modulePath));
// look for "style" declaration in package.json
if (json.style) {
location = json.style;
// otherwise assume ./styles.scss
} else {
location = './styles';
}
// if a full path is provided
} else {
location = path.join('../', file);
}
callback(null, path.resolve(root, location));
});
}
function importer(url, file, done) {
local(url, file, function (err, isLocal) {
if (err || isLocal) {
done({
file: url
});
} else {
find(path.dirname(file), url, function (err, location) {
if (err) {
done({
file: url
});
} else {
done({
file: location
});
};
});
}
})
}
module.exports = importer;
| var findup = require('findup'),
path = require('path');
var local = require('./local');
function find(dir, file, callback) {
var name = file.split('/')[0],
modulePath = './node_modules/' + name + '/package.json';
findup(dir, modulePath, function (err, moduleDir) {
if (err) { return callback(err); }
var root = path.dirname(path.resolve(moduleDir, modulePath));
var location;
// if import is just a module name
if (file.split('/').length === 0) {
var json = require(path.resolve(moduleDir, modulePath));
// look for "style" declaration in package.json
if (json.style) {
location = json.style;
// otherwise assume ./styles.scss
} else {
location = './styles';
}
// if a full path is provided
} else {
location = path.join('../', file);
}
callback(null, path.resolve(root, location));
});
}
function importer(url, file, done) {
local(url, file, function (err, isLocal) {
if (err || isLocal) {
done({
file: url
});
} else {
find(path.dirname(file), url, function (err, location) {
if (err) {
done({
file: url
});
} else {
done({
file: location
});
};
});
}
})
}
module.exports = importer;
|
Revert "Test that typo in sources break the CI build"
This reverts commit 78e3eda95cfe36ed811aa35ba90424a6f7503f4f. | (function() {
'use strict';
angular
.module('afterHeap')
.config(routerConfig);
/** @ngInject */
function routerConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state('city', {
abstract: true,
url: '/:cityId',
template: '<ui-view/>'
})
.state('city.highlights', {
url: '/',
templateUrl: 'app/highlights/highlights.html',
controller: 'HighlightsController',
controllerAs: 'highlightsController',
resolve: {
highlights: function(api, processResponse, $stateParams){
return api.getCityFeed($stateParams.cityId).then(function(res) {
return processResponse.createTopSuggestions(res);
})
}
}
})
.state('city.feed', {
url: '/feed',
templateUrl: 'app/activityfeed/activityfeed.html',
controller: 'ActivityFeedController',
controllerAs: 'activityFeed',
resolve: {
checkins: function(api, processResponse, $stateParams){
return api.getCityFeed($stateParams.cityId).then(function(res){
return processResponse.removeBlackListed(res);
});
}
}
});
$urlRouterProvider.otherwise('/Tampere/');
}
})();
| (function() {
'use strict';
angular
.module('afterHeap')
.config(routerConfig);
/** @ngInject */
function routerConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state('city', {
abstract: true,
url: '/:cityId',
template: '<ui-view/>'
})
.state('city.highlights', {
url: '/',
templateUrl: 'app/highlights/highlights.html',
controller: 'HighlightsController',
controllerAs: 'highlightsController',
resolve: {
highlights: function(api, processResponse, $stateParams){
return api.getCityFeed($stateParams.cityId).then(function(res) {
return processResponse.createTopSuggestions(res);
})
}
}this_should_break_the_build
})
.state('city.feed', {
url: '/feed',
templateUrl: 'app/activityfeed/activityfeed.html',
controller: 'ActivityFeedController',
controllerAs: 'activityFeed',
resolve: {
checkins: function(api, processResponse, $stateParams){
return api.getCityFeed($stateParams.cityId).then(function(res){
return processResponse.removeBlackListed(res);
});
}
}
});
$urlRouterProvider.otherwise('/Tampere/');
}
})();
|
Return catcher value, give catcher the callback. | var slice = [].slice
var eject = require('eject')
// todo: create strings parser.
function Interrupt () {
this._types = {}
}
Interrupt.prototype._populate = function (error, type, vargs) {
this._types[type] || (this._types[type] = {})
error.message = error.type = type
error.typeIdentifier = this._types[type]
var context = error.context = {}
vargs.forEach(function (values) {
for (var key in values) {
context[key] = values[key]
}
})
error.context = context
return error
}
Interrupt.prototype.error = function (error, type) {
return this._populate(error, type, slice.call(arguments, 2))
}
Interrupt.prototype.panic = function (error, type) {
throw this._populate(error, type, slice.call(arguments, 2))
}
Interrupt.prototype.type = function (error) {
if (error.type
&& this._types[error.type]
&& this._types[error.type] === error.typeIdentifier
) {
return error.type
}
return null
}
Interrupt.prototype.rescue = function (catcher, callback) {
callback || (callback = eject)
return function (error) {
if (error) {
if (this.type(error) != null) {
return catcher(error, callback)
} else {
callback(error)
}
}
}.bind(this)
}
module.exports = function (messages) {
return new Interrupt
}
| var slice = [].slice
var eject = require('eject')
// todo: create strings parser.
function Interrupt () {
this._types = {}
}
Interrupt.prototype._populate = function (error, type, vargs) {
this._types[type] || (this._types[type] = {})
error.message = error.type = type
error.typeIdentifier = this._types[type]
var context = error.context = {}
vargs.forEach(function (values) {
for (var key in values) {
context[key] = values[key]
}
})
error.context = context
return error
}
Interrupt.prototype.error = function (error, type) {
return this._populate(error, type, slice.call(arguments, 2))
}
Interrupt.prototype.panic = function (error, type) {
throw this._populate(error, type, slice.call(arguments, 2))
}
Interrupt.prototype.type = function (error) {
if (error.type
&& this._types[error.type]
&& this._types[error.type] === error.typeIdentifier
) {
return error.type
}
return null
}
Interrupt.prototype.rescue = function (catcher, callback) {
callback || (callback = eject)
return function (error) {
if (error) {
if (this.type(error) != null) {
catcher(error)
} else {
callback(error)
}
}
}.bind(this)
}
module.exports = function (messages) {
return new Interrupt
}
|
Include .jpeg in extensions that should trigger a save dialog. | // Stopgap atom.js file for handling normal browser things that atom
// does not yet have stable from the browser-side API.
// - Opening external links in default web browser
// - Saving files/downloads to disk
$(document).ready(function() {
if (typeof process === 'undefined') return;
if (typeof process.versions['atom-shell'] === undefined) return;
var remote = require('remote');
var shell = require('shell');
var http = require('http');
var url = require('url');
var fs = require('fs');
$('body').on('click', 'a', function(ev) {
var uri = url.parse(ev.currentTarget.href);
// Opening external URLs.
if (uri.hostname && uri.hostname !== 'localhost') {
shell.openExternal(ev.currentTarget.href);
return false;
}
// File saving.
var extensions = /(\.tm2z|\.mbtiles|\.png|\.jpg|\.jpeg)$/;
var ext = extensions.exec(uri.pathname);
if (ext) {
var filepath = remote.require('dialog').showSaveDialog({
title: 'Save file',
defaultPath: ext[0]
});
if (filepath) {
uri.method = 'GET';
var writestream = fs.createWriteStream(filepath);
var req = http.request(uri, function(res) {
if (res.statusCode !== 200) return;
res.pipe(writestream);
});
req.end();
}
return false;
}
// Passthrough evthing else.
});
});
| // Stopgap atom.js file for handling normal browser things that atom
// does not yet have stable from the browser-side API.
// - Opening external links in default web browser
// - Saving files/downloads to disk
$(document).ready(function() {
if (typeof process === 'undefined') return;
if (typeof process.versions['atom-shell'] === undefined) return;
var remote = require('remote');
var shell = require('shell');
var http = require('http');
var url = require('url');
var fs = require('fs');
$('body').on('click', 'a', function(ev) {
var uri = url.parse(ev.currentTarget.href);
// Opening external URLs.
if (uri.hostname && uri.hostname !== 'localhost') {
shell.openExternal(ev.currentTarget.href);
return false;
}
// File saving.
var extensions = /(\.tm2z|\.mbtiles|\.png|\.jpg)$/;
var ext = extensions.exec(uri.pathname);
if (ext) {
var filepath = remote.require('dialog').showSaveDialog({
title: 'Save file',
defaultPath: ext[0]
});
if (filepath) {
uri.method = 'GET';
var writestream = fs.createWriteStream(filepath);
var req = http.request(uri, function(res) {
if (res.statusCode !== 200) return;
res.pipe(writestream);
});
req.end();
}
return false;
}
// Passthrough evthing else.
});
});
|
Allow to set invoker through filesystem decorator | <?php
namespace React\Filesystem;
use React\EventLoop\LoopInterface;
use React\Filesystem\Node;
class Filesystem
{
protected $filesystem;
/**
* @param LoopInterface $loop
* @param AdapterInterface $adapter
* @return static
* @throws NoAdapterException
*/
public static function create(LoopInterface $loop, AdapterInterface $adapter = null)
{
if ($adapter instanceof AdapterInterface) {
return new static($adapter);
}
if (extension_loaded('eio')) {
return new static(new EioAdapter($loop));
}
throw new NoAdapterException();
}
/**
* @param AdapterInterface $filesystem
*/
private function __construct(AdapterInterface $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* @param string $filename
* @return Node\File
*/
public function file($filename)
{
return new Node\File($filename, $this->filesystem);
}
/**
* @param string $path
* @return Node\Directory
*/
public function dir($path)
{
return new Node\Directory($path, $this->filesystem);
}
/**
* @param string $filename
* @return \React\Promise\PromiseInterface
*/
public function getContents($filename)
{
return $this->file($filename)->getContents();
}
/**
* @param CallInvokerInterface $invoker
*/
public function setInvoker(CallInvokerInterface $invoker)
{
$this->filesystem->setInvoker($invoker);
}
}
| <?php
namespace React\Filesystem;
use React\EventLoop\LoopInterface;
use React\Filesystem\Node;
class Filesystem
{
protected $filesystem;
/**
* @param LoopInterface $loop
* @param AdapterInterface $adapter
* @return static
* @throws NoAdapterException
*/
public static function create(LoopInterface $loop, AdapterInterface $adapter = null)
{
if ($adapter instanceof AdapterInterface) {
return new static($adapter);
}
if (extension_loaded('eio')) {
return new static(new EioAdapter($loop));
}
throw new NoAdapterException();
}
/**
* @param AdapterInterface $filesystem
*/
private function __construct(AdapterInterface $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* @param string $filename
* @return Node\File
*/
public function file($filename)
{
return new Node\File($filename, $this->filesystem);
}
/**
* @param string $path
* @return Node\Directory
*/
public function dir($path)
{
return new Node\Directory($path, $this->filesystem);
}
/**
* @param string $filename
* @return \React\Promise\PromiseInterface
*/
public function getContents($filename)
{
return $this->file($filename)->getContents();
}
}
|
Add new builder to compiler passes | <?php
namespace Knp\Rad\AutoRegistration\Bundle;
use Knp\Rad\AutoRegistration\DependencyInjection\AutoRegistrationExtension;
use Knp\Rad\AutoRegistration\DependencyInjection\Compiler\DefinitionBuilderActivationPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\FormPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\KernelInterface;
class AutoRegistrationBundle extends Bundle
{
/**
* @var KernelInterface
*/
private $kernel;
/**
* @param KernelInterface $kernel
*/
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
/**
* {@inheritDoc}
*/
public function build(ContainerBuilder $container)
{
$container->set('knp_rad_auto_registration.kernel', $this->kernel);
$container->addCompilerPass(new DefinitionBuilderActivationPass([
'doctrine', 'doctrine_mongodb', 'doctrine_couchdb',
]), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new DefinitionBuilderActivationPass([
'form_type', 'form_type_extension', 'security_voter', 'twig_extension',
]), PassConfig::TYPE_BEFORE_OPTIMIZATION);
$container->addCompilerPass(new FormPass());
}
/**
* {@inheritDoc}
*/
public function getContainerExtension()
{
if (null === $this->extension) {
$this->extension = new AutoRegistrationExtension();
}
return $this->extension;
}
}
| <?php
namespace Knp\Rad\AutoRegistration\Bundle;
use Knp\Rad\AutoRegistration\DependencyInjection\AutoRegistrationExtension;
use Knp\Rad\AutoRegistration\DependencyInjection\Compiler\DefinitionBuilderActivationPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\FormPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\KernelInterface;
class AutoRegistrationBundle extends Bundle
{
/**
* @var KernelInterface
*/
private $kernel;
/**
* @param KernelInterface $kernel
*/
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
/**
* {@inheritDoc}
*/
public function build(ContainerBuilder $container)
{
$container->set('knp_rad_auto_registration.kernel', $this->kernel);
$container->addCompilerPass(new DefinitionBuilderActivationPass([
'doctrine', 'doctrine_mongodb', 'doctrine_couchdb',
]), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new DefinitionBuilderActivationPass([
'form_type', 'form_type_extension',
]), PassConfig::TYPE_BEFORE_OPTIMIZATION);
$container->addCompilerPass(new FormPass());
}
/**
* {@inheritDoc}
*/
public function getContainerExtension()
{
if (null === $this->extension) {
$this->extension = new AutoRegistrationExtension();
}
return $this->extension;
}
}
|
Call long_desc instead of the function | import multiprocessing # noqa # stop tests breaking tox
from setuptools import find_packages, setup
import tvrenamr
def long_desc():
with open('README.rst') as f:
readme = f.read()
with open('CHANGELOG.rst') as f:
changelog = f.read()
return readme + '\n\n' + changelog
setup(
name=tvrenamr.__title__,
version=tvrenamr.__version__,
description='Rename tv show files using online databases',
long_description=long_desc(),
author=tvrenamr.__author__,
author_email='[email protected]',
url='http://tvrenamr.info',
license='MIT',
packages=find_packages(exclude=['docs', 'tests']),
entry_points={'console_scripts': ['tvr=tvrenamr.frontend:run']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Utilities',
],
)
| import multiprocessing # noqa # stop tests breaking tox
from setuptools import find_packages, setup
import tvrenamr
def long_desc():
with open('README.rst') as f:
readme = f.read()
with open('CHANGELOG.rst') as f:
changelog = f.read()
return readme + '\n\n' + changelog
setup(
name=tvrenamr.__title__,
version=tvrenamr.__version__,
description='Rename tv show files using online databases',
long_description=long_desc,
author=tvrenamr.__author__,
author_email='[email protected]',
url='http://tvrenamr.info',
license='MIT',
packages=find_packages(exclude=['docs', 'tests']),
entry_points={'console_scripts': ['tvr=tvrenamr.frontend:run']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Utilities',
],
)
|
Update the path and the url | <?php
/*
* This file is part of the AlphaLemonThemeEngineBundle and it is distributed
* under the MIT License. To use this bundle you must leave
* intact this copyright notice.
*
* Copyright (c) AlphaLemon <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* For extra documentation and help please visit http://alphalemon.com
*
* @license MIT License
*/
namespace AlphaLemon\ElFinderBundle\Core\Connector;
/**
* Configures the connector
*
* @author AlphaLemon
*/
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
protected function configure()
{
$request = $this->container->get('request');
$options = array(
'roots' => array(
array(
'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
'path' => 'bundles/alphalemonelfinder/vendor/ElFinder/files/', // path to files (REQUIRED)
'URL' => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/vendor/ElFinder/files/', // URL to files (REQUIRED)
'accessControl' => 'access' // disable and hide dot starting files (OPTIONAL)
)
)
);
return $options;
}
}
| <?php
/*
* This file is part of the AlphaLemonThemeEngineBundle and it is distributed
* under the MIT License. To use this bundle you must leave
* intact this copyright notice.
*
* Copyright (c) AlphaLemon <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* For extra documentation and help please visit http://alphalemon.com
*
* @license MIT License
*/
namespace AlphaLemon\ElFinderBundle\Core\Connector;
/**
* Configures the connector
*
* @author AlphaLemon
*/
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
protected function configure()
{
$request = $this->container->get('request');
$options = array(
'roots' => array(
array(
'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
'path' => 'bundles/alphalemonelfinder/files/', // path to files (REQUIRED)
'URL' => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/files/', // URL to files (REQUIRED)
'accessControl' => 'access' // disable and hide dot starting files (OPTIONAL)
)
)
);
return $options;
}
}
|
Make Django to find the pydoc-tool.py script tests | import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
# -- Allow Django test command to find the script tests
import os
import sys
test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'tests')
sys.path.append(test_dir)
from test_pydoc_tool import *
| import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
|
Add more logging to see what this strange user is | var moment = require('moment');
var userCache = {};
var cacheTimeInMilliseconds = 1000 * 60 * 15;
/**
* Every time a user posts a message, we update their slack profile so we can stay up to date on their profile
* @param {Object} bot
* @param {Object} message
* @param {Object} controller
*/
module.exports = function updateSlackProfile(bot, message, controller) {
// This can come in as undefined, so we will just ignore those requests
if (!message.user) {
return;
}
// Cache the user updates for 15 minutes so we don't do too much stuff
if (userCache[message.user]) {
var userCacheExpiration = moment(userCache[message.user]);
if (userCacheExpiration.diff(moment(), 'minutes') < 15) {
return;
}
}
controller.storage.users.get(message.user, function(err, user) {
if (err) {
return console.trace(err);
}
bot.api.users.info({user: message.user}, function(err, res) {
if (err) {
console.error('could not get info for user %s', message.user);
console.dir(message.user);
return console.trace(err);
}
if (!user) {
user = {
id: message.user,
};
}
user.slackUser = res.user;
controller.storage.users.save(user, function() {
userCache[user.id] = new Date();
});
});
});
};
| var moment = require('moment');
var userCache = {};
var cacheTimeInMilliseconds = 1000 * 60 * 15;
/**
* Every time a user posts a message, we update their slack profile so we can stay up to date on their profile
* @param {Object} bot
* @param {Object} message
* @param {Object} controller
*/
module.exports = function updateSlackProfile(bot, message, controller) {
// This can come in as undefined, so we will just ignore those requests
if (!message.user) {
return;
}
// Cache the user updates for 15 minutes so we don't do too much stuff
if (userCache[message.user]) {
var userCacheExpiration = moment(userCache[message.user]);
if (userCacheExpiration.diff(moment(), 'minutes') < 15) {
return;
}
}
controller.storage.users.get(message.user, function(err, user) {
if (err) {
return console.trace(err);
}
bot.api.users.info({user: message.user}, function(err, res) {
if (err) {
console.error('could not get info for user %s', message.user);
return console.trace(err);
}
if (!user) {
user = {
id: message.user,
};
}
user.slackUser = res.user;
controller.storage.users.save(user, function() {
userCache[user.id] = new Date();
});
});
});
};
|
Update StatMoments tests (passing); empty tests to be filled in when the testing data is updated | # Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
import pytest
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test_moments():
tester = StatMoments(dataset1["moment0"])
tester.run()
# TODO: Add more test comparisons. Save the total moments over the whole
# arrays, portions of the local arrays, and the histogram values.
def test_moments_units():
pass
def test_moments_nonperiodic():
pass
def test_moments_custombins():
pass
def test_moment_distance():
tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
tester_dist.distance_metric()
assert np.allclose(tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(tester_dist.skewness_distance,
computed_distances['skewness_distance'])
| # Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class TestMoments(TestCase):
def test_moments(self):
self.tester = StatMoments(dataset1["moment0"])
self.tester.run()
# This simply ensures the data set will run.
# There are subtle differences due to matching the bins
# between the sets. So all tests are completed below
def test_moment_distance(self):
self.tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
self.tester_dist.distance_metric()
assert np.allclose(self.tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(self.tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(self.tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(self.tester_dist.skewness_distance,
computed_distances['skewness_distance'])
|