text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
NXP-11577: Fix Sonar Major violations: Final Class | package org.nuxeo.drive.service.impl;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;
/**
* Helper to handle synchronization root definitions.
*
* @author Antoine Taillefer
*/
public final class RootDefinitionsHelper {
private RootDefinitionsHelper() {
// Utility class
}
/**
* Parses the given synchronization root definitions string.
*/
public static Map<String, Set<IdRef>> parseRootDefinitions(
String rootDefinitions) {
Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
if (rootDefinitions != null) {
String[] rootDefinitionComponents = StringUtils.split(
rootDefinitions, ",");
for (String rootDefinition : rootDefinitionComponents) {
String[] rootComponents = StringUtils.split(rootDefinition, ":");
String repoName = rootComponents[0].trim();
Set<IdRef> refs = lastActiveRootRefs.get(repoName);
if (refs == null) {
refs = new HashSet<IdRef>();
lastActiveRootRefs.put(repoName, refs);
}
refs.add(new IdRef(rootComponents[1].trim()));
}
}
return lastActiveRootRefs;
}
}
| package org.nuxeo.drive.service.impl;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;
/**
* Helper to handle synchronization root definitions.
*
* @author Antoine Taillefer
*/
public class RootDefinitionsHelper {
private RootDefinitionsHelper() {
// Utility class
}
/**
* Parses the given synchronization root definitions string.
*/
public static Map<String, Set<IdRef>> parseRootDefinitions(
String rootDefinitions) {
Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
if (rootDefinitions != null) {
String[] rootDefinitionComponents = StringUtils.split(
rootDefinitions, ",");
for (String rootDefinition : rootDefinitionComponents) {
String[] rootComponents = StringUtils.split(rootDefinition, ":");
String repoName = rootComponents[0].trim();
Set<IdRef> refs = lastActiveRootRefs.get(repoName);
if (refs == null) {
refs = new HashSet<IdRef>();
lastActiveRootRefs.put(repoName, refs);
}
refs.add(new IdRef(rootComponents[1].trim()));
}
}
return lastActiveRootRefs;
}
}
|
Check webUrl of groups for null to prevent NullPointerException | package com.commit451.gitlab.model.api;
import com.google.gson.annotations.SerializedName;
import org.parceler.Parcel;
import android.net.Uri;
@Parcel
public class Group {
@SerializedName("id")
long mId;
@SerializedName("name")
String mName;
@SerializedName("path")
String mPath;
@SerializedName("description")
String mDescription;
@SerializedName("avatar_url")
Uri mAvatarUrl;
@SerializedName("web_url")
Uri mWebUrl;
public Group() {}
public long getId() {
return mId;
}
public String getName() {
return mName;
}
public String getPath() {
return mPath;
}
public String getDescription() {
return mDescription;
}
public Uri getAvatarUrl() {
return mAvatarUrl;
}
public Uri getWebUrl() {
return mWebUrl;
}
public Uri getFeedUrl() {
if (mWebUrl == null) {
return null;
}
return Uri.parse(mWebUrl.toString() + ".atom");
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Group)) {
return false;
}
Group group = (Group) o;
return mId == group.mId;
}
@Override
public int hashCode() {
return (int) (mId ^ (mId >>> 32));
}
}
| package com.commit451.gitlab.model.api;
import com.google.gson.annotations.SerializedName;
import org.parceler.Parcel;
import android.net.Uri;
@Parcel
public class Group {
@SerializedName("id")
long mId;
@SerializedName("name")
String mName;
@SerializedName("path")
String mPath;
@SerializedName("description")
String mDescription;
@SerializedName("avatar_url")
Uri mAvatarUrl;
@SerializedName("web_url")
Uri mWebUrl;
public Group() {}
public long getId() {
return mId;
}
public String getName() {
return mName;
}
public String getPath() {
return mPath;
}
public String getDescription() {
return mDescription;
}
public Uri getAvatarUrl() {
return mAvatarUrl;
}
public Uri getWebUrl() {
return mWebUrl;
}
public Uri getFeedUrl() {
return Uri.parse(mWebUrl.toString() + ".atom");
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Group)) {
return false;
}
Group group = (Group) o;
return mId == group.mId;
}
@Override
public int hashCode() {
return (int) (mId ^ (mId >>> 32));
}
}
|
Remove test that fails because of qualified function call | <?php
namespace Ramsey\Uuid\Test\Generator;
use phpmock\phpunit\PHPMock;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Generator\SodiumRandomGenerator;
class SodiumRandomGeneratorTest extends TestCase
{
use PHPMock;
protected function skipIfLibsodiumExtensionNotLoaded()
{
if (!extension_loaded('libsodium')) {
$this->markTestSkipped(
'The libsodium extension is not available.'
);
}
}
public function testGenerateReturnsBytes()
{
$this->skipIfLibsodiumExtensionNotLoaded();
$generator = new SodiumRandomGenerator();
$bytes = $generator->generate(16);
$this->assertInternalType('string', $bytes);
$this->assertEquals(16, strlen($bytes));
}
public function testFactoryUsesSodiumRandomGenerator()
{
$this->skipIfLibsodiumExtensionNotLoaded();
$uuidFactory = new \Ramsey\Uuid\UuidFactory();
$uuidFactory->setRandomGenerator(new SodiumRandomGenerator());
\Ramsey\Uuid\Uuid::setFactory($uuidFactory);
$uuid = \Ramsey\Uuid\Uuid::uuid4();
$this->assertInstanceOf(
'Ramsey\Uuid\Generator\SodiumRandomGenerator',
$uuid->getFactory()->getRandomGenerator()
);
}
}
| <?php
namespace Ramsey\Uuid\Test\Generator;
use phpmock\phpunit\PHPMock;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Generator\SodiumRandomGenerator;
class SodiumRandomGeneratorTest extends TestCase
{
use PHPMock;
protected function skipIfLibsodiumExtensionNotLoaded()
{
if (!extension_loaded('libsodium')) {
$this->markTestSkipped(
'The libsodium extension is not available.'
);
}
}
public function testGenerateReturnsBytes()
{
$this->skipIfLibsodiumExtensionNotLoaded();
$generator = new SodiumRandomGenerator();
$bytes = $generator->generate(16);
$this->assertInternalType('string', $bytes);
$this->assertEquals(16, strlen($bytes));
}
public function testFactoryUsesSodiumRandomGenerator()
{
$this->skipIfLibsodiumExtensionNotLoaded();
$uuidFactory = new \Ramsey\Uuid\UuidFactory();
$uuidFactory->setRandomGenerator(new SodiumRandomGenerator());
\Ramsey\Uuid\Uuid::setFactory($uuidFactory);
$uuid = \Ramsey\Uuid\Uuid::uuid4();
$this->assertInstanceOf(
'Ramsey\Uuid\Generator\SodiumRandomGenerator',
$uuid->getFactory()->getRandomGenerator()
);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGenerateUsesSodiumLibrary()
{
$randomBytesFunc = $this->getFunctionMock('Sodium', 'randombytes_buf');
$randomBytesFunc->expects($this->once())
->with(10);
$generator = new SodiumRandomGenerator();
$generator->generate(10);
}
}
|
Revert "Added cookies deletion step to @BeforeMethod."
This reverts commit bc44573ae5011b2155badbc77c530189e0b356ce. | package tests;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.*;
import pages.HomePage;
import selenium.WebDriverFactory;
import utils.Log4Test;
import utils.PropertyLoader;
public class BaseTest {
public static WebDriver driver;
@BeforeSuite
public void intEnv() {
driver = WebDriverFactory.initDriver(PropertyLoader.loadProperty("browser.name"));
driver.manage().window().maximize();
}
@BeforeTest
public void beforeTest() {
Log4Test.info("*#*#*#*#*#* Start of the test suite. *#*#*#*#*#*");
}
@BeforeMethod
public void beforeMethod() {
Log4Test.info("-_-_-_-_- Start of the test. -_-_-_-_-");
HomePage homePage = new HomePage(driver);
homePage.open();
Assert.assertTrue(homePage.isOpened(), Log4Test.error("Home page is not open."));
}
@AfterMethod
public void afterMethod() {
Log4Test.info("-_-_-_-_- End of the test. -_-_-_-_-");
}
@AfterTest
public void afterTest() {
Log4Test.info("*#*#*#*#*#* End of the test suite. *#*#*#*#*#*");
}
@AfterSuite
public void shutEnv() {
if (driver != null) {
driver.quit();
}
}
} | package tests;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.*;
import pages.HomePage;
import selenium.WebDriverFactory;
import utils.Log4Test;
import utils.PropertyLoader;
public class BaseTest {
public static WebDriver driver;
@BeforeSuite
public void intEnv() {
driver = WebDriverFactory.initDriver(PropertyLoader.loadProperty("browser.name"));
driver.manage().window().maximize();
}
@BeforeTest
public void beforeTest() {
Log4Test.info("*#*#*#*#*#* Start of the test suite. *#*#*#*#*#*");
}
@BeforeMethod
public void beforeMethod() {
driver.manage().deleteAllCookies();
Log4Test.info("-_-_-_-_- Start of the test. -_-_-_-_-");
HomePage homePage = new HomePage(driver);
homePage.open();
Assert.assertTrue(homePage.isOpened(), Log4Test.error("Home page is not open."));
}
@AfterMethod
public void afterMethod() {
Log4Test.info("-_-_-_-_- End of the test. -_-_-_-_-");
}
@AfterTest
public void afterTest() {
Log4Test.info("*#*#*#*#*#* End of the test suite. *#*#*#*#*#*");
}
@AfterSuite
public void shutEnv() {
if (driver != null) {
driver.quit();
}
}
} |
Remove get user by id nonsense, now exponent.auth.name | from twisted.cred import checkers, portal
from twisted.protocols import amp
from zope import interface
class AuthenticationLocator(amp.CommandLocator):
"""
A base class for responder locators that allow users to authenticate.
"""
credentialInterfaces = []
def __init__(self, store):
"""
Initializes an authentication responder locator.
:param store: The root store.
"""
self.store = store
storeCheckers = store.powerupsFor(checkers.ICredentialsChecker)
self.portal = portal.Portal(Realm(store), storeCheckers)
def acquireStore(self, userIdentifier):
"""
Acquires a user store.
"""
@interface.implementer(portal.IRealm)
class Realm(object):
"""
A realm that produces box receivers for users.
"""
def __init__(self, getUserByUid):
self._getUser = getUserByUid
def requestAvatar(self, uid, mind, *interfaces):
"""
Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``.
"""
if amp.IBoxReceiver not in interfaces:
raise NotImplementedError()
return self._getUser(uid).addCallback(_gotUser)
def _gotUser(user):
"""
Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable
as the return value for ``requestAvatar``.
"""
return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None
| from exponent.auth import common
from twisted.cred import checkers, portal
from twisted.internet import defer
from twisted.protocols import amp
from zope import interface
def _getUserByIdentifier(rootStore, userIdentifier):
"""
Gets a user by uid.
"""
user = common.User.findUnique(rootStore, userIdentifier)
return defer.succeed(user)
class AuthenticationLocator(amp.CommandLocator):
"""
A base class for responder locators that allow users to authenticate.
"""
credentialInterfaces = []
def __init__(self, store):
"""
Initializes an authentication responder locator.
:param store: The root store.
"""
self.store = store
storeCheckers = store.powerupsFor(checkers.ICredentialsChecker)
self.portal = portal.Portal(Realm(store), storeCheckers)
def acquireStore(self, userIdentifier):
"""
Acquires a user store.
"""
@interface.implementer(portal.IRealm)
class Realm(object):
"""
A realm that produces box receivers for users.
"""
def __init__(self, getUserByUid):
self._getUser = getUserByUid
def requestAvatar(self, uid, mind, *interfaces):
"""
Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``.
"""
if amp.IBoxReceiver not in interfaces:
raise NotImplementedError()
return self._getUser(uid).addCallback(_gotUser)
def _gotUser(user):
"""
Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable
as the return value for ``requestAvatar``.
"""
return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None
|
Add support for -debug=true when testing clouds. --debug is still unsafe.
We need to redirect sdtout to a log. | #!/usr/bin/env python
from __future__ import print_function
__metaclass__ = type
from argparse import ArgumentParser
import os
import subprocess
import sys
from jujupy import (
CannotConnectEnv,
Environment,
)
def deploy_stack(environment, debug):
""""Deploy a test stack in the specified environment.
:param environment: The name of the desired environment.
"""
env = Environment.from_config(environment)
env.client.debug = debug
# Clean up any leftover junk
env.destroy_environment()
env.bootstrap()
try:
# wait for status info....
try:
try:
env.get_status()
except CannotConnectEnv:
print("Status got Unable to connect to env. Retrying...")
env.get_status()
env.wait_for_started()
except subprocess.CalledProcessError as e:
if getattr(e, 'stderr', None) is not None:
sys.stderr.write(e.stderr)
raise
finally:
env.destroy_environment()
def main():
parser = ArgumentParser('Test a cloud')
parser.add_argument('env', help='The juju environment to test')
args = parser.parse_args()
debug = bool(os.environ.get('DEBUG') == 'true')
try:
deploy_stack(args.env, debug)
except Exception as e:
print('%s: %s' % (type(e), e))
sys.exit(1)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
__metaclass__ = type
from argparse import ArgumentParser
import subprocess
import sys
from jujupy import (
CannotConnectEnv,
Environment,
until_timeout,
)
def deploy_stack(environment):
""""Deploy a test stack in the specified environment.
:param environment: The name of the desired environment.
"""
env = Environment.from_config(environment)
# Clean up any leftover junk
env.destroy_environment()
env.bootstrap()
try:
# wait for status info....
try:
try:
env.get_status()
except CannotConnectEnv:
print "Status got Unable to connect to env. Retrying..."
env.get_status()
env.wait_for_started()
except subprocess.CalledProcessError as e:
if getattr(e, 'stderr', None) is not None:
sys.stderr.write(e.stderr)
raise
finally:
env.destroy_environment()
def main():
parser = ArgumentParser('Test a cloud')
parser.add_argument('env', help='The juju environment to test')
args = parser.parse_args()
try:
deploy_stack(args.env)
except Exception as e:
print '%s: %s' % (type(e), e)
sys.exit(1)
if __name__ == '__main__':
main()
|
Remove force_load which was added in later versions. | from __future__ import unicode_literals
from django.core.management.base import NoArgsCommand, CommandError
from allaccess.models import Provider
class Command(NoArgsCommand):
"Convert existing providers from django-social-auth to django-all-access."
def handle_noargs(self, **options):
verbosity = int(options.get('verbosity'))
try:
from social_auth.backends import get_backends, BaseOAuth
except ImportError: # pragma: no cover
raise CommandError("django-social-auth is not installed.")
for name, backend in get_backends().items():
if issubclass(backend, BaseOAuth) and backend.enabled():
# Create providers if they don't already exist
key, secret = backend.get_key_and_secret()
defaults = {
'request_token_url': getattr(backend, 'REQUEST_TOKEN_URL', ''),
'authorization_url': getattr(backend, 'AUTHORIZATION_URL', ''),
'access_token_url': getattr(backend, 'ACCESS_TOKEN_URL', ''),
'profile_url': '',
'key': key or None,
'secret': secret or None,
}
provider, created = Provider.objects.get_or_create(name=name, defaults=defaults)
if created and verbosity > 0:
self.stdout.write('New provider created from "%s" backend.\n' % name)
| from __future__ import unicode_literals
from django.core.management.base import NoArgsCommand, CommandError
from allaccess.models import Provider
class Command(NoArgsCommand):
"Convert existing providers from django-social-auth to django-all-access."
def handle_noargs(self, **options):
verbosity = int(options.get('verbosity'))
try:
from social_auth.backends import get_backends, BaseOAuth
except ImportError: # pragma: no cover
raise CommandError("django-social-auth is not installed.")
for name, backend in get_backends(force_load=True).items():
if issubclass(backend, BaseOAuth) and backend.enabled():
# Create providers if they don't already exist
key, secret = backend.get_key_and_secret()
defaults = {
'request_token_url': getattr(backend, 'REQUEST_TOKEN_URL', ''),
'authorization_url': getattr(backend, 'AUTHORIZATION_URL', ''),
'access_token_url': getattr(backend, 'ACCESS_TOKEN_URL', ''),
'profile_url': '',
'key': key or None,
'secret': secret or None,
}
provider, created = Provider.objects.get_or_create(name=name, defaults=defaults)
if created and verbosity > 0:
self.stdout.write('New provider created from "%s" backend.\n' % name)
|
Fix a few issues with the POST tests. | var request = require('request'),
should = require('chai').should(),
muxamp = require('../lib/server').getApplication(),
testutils = require('../lib/testutils'),
playlist = require('../lib/playlist');
describe('POST', function() {
var baseUrl = 'http://localhost:' + 3000 + '/playlists/save';
function getParameters(body) {
var str = JSON.stringify(body);
return {
url: baseUrl,
body: str,
headers: {
'Content-Type': 'application/json',
'Content-Length': str.length
}
};
}
context = {};
before(testutils.hooks.server.before(context));
describe('playlist saving endpoint', function() {
describe('should be okay', function() {
it('when no tracks are passed in the request body', function(done) {
request.post(getParameters({}), function(err, response, body) {
response.statusCode.should.eql(205);
done();
});
});
});
describe('should return an error message', function() {
it('when something other than array is passed in the request body', function(done) {
var options = getParameters({problemo: true});
request.post(options, function(err, response, body) {
response.statusCode.should.eql(400);
done();
});
});
it('when the request body contains an array of something other than tracks', function(done) {
var options = getParameters([1, "a"]);
request.post(options, function(err, response, body) {
response.statusCode.should.eql(400);
done();
});
});
});
});
after(testutils.hooks.server.after(context));
}); | var request = require('request'),
should = require('chai').should(),
muxamp = require('../lib/server').getApplication(),
testutils = require('../lib/testutils'),
playlist = require('../lib/playlist');
describe('POST', function() {
var baseUrl = 'http://localhost:' + 3000 + '/playlists/save';
function getParameters(body) {
return {
url: baseUrl,
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
'Content-Length': body.length
}
};
}
context = {};
before(testutils.hooks.server.before(context));
describe('playlist saving endpoint', function() {
describe('should be okay', function() {
it('when no tracks are passed in the request body', function(done) {
request.post({url: baseUrl}, function(err, response, body) {
response.statusCode.should.eql(205);
done();
});
});
});
describe('should return an error message', function() {
it('when something other than array is passed in the request body', function(done) {
var options = getParameters({problemo: true});
request.post(options, function(err, response, body) {
response.statusCode.should.eql(400);
done();
});
});
});
});
after(testutils.hooks.server.after(context));
}); |
Connect before using the database | <?php
namespace Aureka\VBBundle;
use Aureka\VBBundle\Exception\VBUserException,
Aureka\VBBundle\Exception\VBSessionException;
class VBUsers
{
private $db;
public function __construct(VBDatabase $db)
{
$this->db = $db;
}
public function create(VBSession $session, $username, $password = null, $id = null)
{
$user = new VBUser($username, $password, $id);
$user->setSession($session);
return $user;
}
public function load(VBSession $session, $username)
{
$this->db->connect();
$data = $this->db->load('user', array('username' => $username));
if (!$data) {
throw new VBUserException(sprintf('Unable to load data for user with username %s', $username));
}
return $this->create($session, $username, $data['password'], $data['userid']);
}
public function persist(VBUser $user)
{
$this->db->connect();
$this->db->insert('user', $user->export());
return $this;
}
public function updateSession(VBSession $session)
{
if (is_null($session->getId())) {
throw new VBSessionException('Unable to update a session that is not initialized');
}
$this->db->connect();
$this->db->delete('session', array('idhash' => $session->getId()));
$this->db->insert('session', $session->export());
return $this;
}
}
| <?php
namespace Aureka\VBBundle;
use Aureka\VBBundle\Exception\VBUserException,
Aureka\VBBundle\Exception\VBSessionException;
class VBUsers
{
private $db;
public function __construct(VBDatabase $db)
{
$this->db = $db;
}
public function create(VBSession $session, $username, $password = null, $id = null)
{
$user = new VBUser($username, $password, $id);
$user->setSession($session);
return $user;
}
public function load(VBSession $session, $username)
{
$data = $this->db->load('user', array('username' => $username));
if (!$data) {
throw new VBUserException(sprintf('Unable to load data for user with username %s', $username));
}
return $this->create($session, $username, $data['password'], $data['userid']);
}
public function persist(VBUser $user)
{
$this->db->insert('user', $user->export());
return $this;
}
public function updateSession(VBSession $session)
{
if (is_null($session->getId())) {
throw new VBSessionException('Unable to update a session that is not initialized');
}
$this->db->delete('session', array('idhash' => $session->getId()));
$this->db->insert('session', $session->export());
return $this;
}
}
|
Add list:server command enable option | <?php
/**
* SiteCLI - Help you manage Nginx local development configuration
*
* @author [email protected]
* @link https://github.com/panlatent/site-cli
* @license https://opensource.org/licenses/MIT
*/
namespace Panlatent\SiteCli\Commands;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ListServerCommand extends Command
{
protected function configure()
{
$this->setName('list:server')
->setAliases(['servers'])
->setDescription('Lists all server')
->addOption(
'enable',
'e',
InputOption::VALUE_NONE,
'Show only enabled sites'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$servers = $this->manager->getServers();
if ($input->getOption('enable')) {
$servers = array_filter($servers, function($server) {
/** @var \Panlatent\SiteCli\SiteServer $server */
return $server->getSite()->isEnable();
});
}
sort($servers);
foreach ($servers as $server) {
$status = $server->getSite()->isEnable() ? '<info>√</info>' : '<comment>x</comment>';
$output->writeln(sprintf(" - %s server <info>%s</info> listen <info>%s</info> on <comment>%s/%s</comment>",
$status,
$server->getName(),
$server->getListen(),
$server->getSite()->getGroup()->getName(),
$server->getSite()->getName()));
}
}
} | <?php
/**
* SiteCLI - Help you manage Nginx local development configuration
*
* @author [email protected]
* @link https://github.com/panlatent/site-cli
* @license https://opensource.org/licenses/MIT
*/
namespace Panlatent\SiteCli\Commands;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ListServerCommand extends Command
{
protected function configure()
{
$this->setName('list:server')
->setAliases(['servers'])
->setDescription('Lists all server');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$servers = $this->manager->getServers();
sort($servers);
foreach ($servers as $server) {
$status = $server->getSite()->isEnable() ? '<info>√</info>' : '<comment>x</comment>';
$output->writeln(sprintf(" - %s server <info>%s</info> listen <info>%s</info> on <comment>%s/%s</comment>",
$status,
$server->getName(),
$server->getListen(),
$server->getSite()->getGroup()->getName(),
$server->getSite()->getName()));
}
}
} |
Add COUNTRY_APP to settings exposed to the templates | from django.conf import settings
import logging
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'STAGING': settings.STAGING,
'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER,
'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT,
'POLLDADDY_WIDGET_ID': settings.POLLDADDY_WIDGET_ID,
'DISQUS_SHORTNAME': settings.DISQUS_SHORTNAME,
'DISQUS_USE_IDENTIFIERS': settings.DISQUS_USE_IDENTIFIERS,
'TWITTER_USERNAME': settings.TWITTER_USERNAME,
'TWITTER_WIDGET_ID': settings.TWITTER_WIDGET_ID,
'BLOG_RSS_FEED': settings.BLOG_RSS_FEED,
'ENABLED_FEATURES': settings.ENABLED_FEATURES,
'COUNTRY_APP': settings.COUNTRY_APP,
'MAP_BOUNDING_BOX_NORTH': settings.MAP_BOUNDING_BOX_NORTH,
'MAP_BOUNDING_BOX_EAST': settings.MAP_BOUNDING_BOX_EAST,
'MAP_BOUNDING_BOX_SOUTH': settings.MAP_BOUNDING_BOX_SOUTH,
'MAP_BOUNDING_BOX_WEST': settings.MAP_BOUNDING_BOX_WEST,
}
}
| from django.conf import settings
import logging
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'STAGING': settings.STAGING,
'STATIC_GENERATION_NUMBER': settings.STATIC_GENERATION_NUMBER,
'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT,
'POLLDADDY_WIDGET_ID': settings.POLLDADDY_WIDGET_ID,
'DISQUS_SHORTNAME': settings.DISQUS_SHORTNAME,
'DISQUS_USE_IDENTIFIERS': settings.DISQUS_USE_IDENTIFIERS,
'TWITTER_USERNAME': settings.TWITTER_USERNAME,
'TWITTER_WIDGET_ID': settings.TWITTER_WIDGET_ID,
'BLOG_RSS_FEED': settings.BLOG_RSS_FEED,
'ENABLED_FEATURES': settings.ENABLED_FEATURES,
'MAP_BOUNDING_BOX_NORTH': settings.MAP_BOUNDING_BOX_NORTH,
'MAP_BOUNDING_BOX_EAST': settings.MAP_BOUNDING_BOX_EAST,
'MAP_BOUNDING_BOX_SOUTH': settings.MAP_BOUNDING_BOX_SOUTH,
'MAP_BOUNDING_BOX_WEST': settings.MAP_BOUNDING_BOX_WEST,
}
}
|
Make sure ALLOWED_HOSTS is correctly set |
DEFAULT_FILE_STORAGE = 'djangae.storage.BlobstoreStorage'
FILE_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024
FILE_UPLOAD_HANDLERS = (
'djangae.storage.BlobstoreFileUploadHandler',
'django.core.files.uploadhandler.MemoryFileUploadHandler',
)
DATABASES = {
'default': {
'ENGINE': 'djangae.db.backends.appengine'
}
}
GENERATE_SPECIAL_INDEXES_DURING_TESTING = False
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
}
}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
TEST_RUNNER = 'djangae.test_runner.DjangaeTestSuiteRunner'
EMAIL_BACKEND = 'djangae.mail.AsyncEmailBackend'
#Setting to *.appspot.com is OK, because GAE takes care of domain routing
#it needs to be like this because of the syntax of addressing non-default versions
# (e.g. -dot-)
ALLOWED_HOSTS = (".appspot.com", )
|
DEFAULT_FILE_STORAGE = 'djangae.storage.BlobstoreStorage'
FILE_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024
FILE_UPLOAD_HANDLERS = (
'djangae.storage.BlobstoreFileUploadHandler',
'django.core.files.uploadhandler.MemoryFileUploadHandler',
)
DATABASES = {
'default': {
'ENGINE': 'djangae.db.backends.appengine'
}
}
GENERATE_SPECIAL_INDEXES_DURING_TESTING = False
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
}
}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
TEST_RUNNER = 'djangae.test_runner.DjangaeTestSuiteRunner'
EMAIL_BACKEND = 'djangae.mail.AsyncEmailBackend'
|
Add classifier for Python 3.5 | import sys
from shutil import rmtree
from setuptools import setup, find_packages
if sys.argv[:2] == ['setup.py', 'bdist_wheel']:
# Remove previous build dir when creating a wheel build, since if files
# have been removed from the project, they'll still be cached in the build
# dir and end up as part of the build, which is unexpected
try:
rmtree('build')
except:
pass
setup(
name = "django-gnupg-mails",
version = __import__("gnupg_mails").__version__,
author = "Jan Dittberner",
author_email = "[email protected]",
description = (
"A Django reusable app providing the ability to send PGP/MIME signed "
"multipart emails."
),
long_description = open("README.rst").read(),
url = "https://github.com/jandd/django-gnupg-mails",
packages = find_packages(),
zip_safe = False,
include_package_data = True,
install_requires = ['python-gnupg', 'sphinx-me'],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Framework :: Django',
'Topic :: Communications :: Email',
'Topic :: Security :: Cryptography',
]
)
| import sys
from shutil import rmtree
from setuptools import setup, find_packages
if sys.argv[:2] == ['setup.py', 'bdist_wheel']:
# Remove previous build dir when creating a wheel build, since if files
# have been removed from the project, they'll still be cached in the build
# dir and end up as part of the build, which is unexpected
try:
rmtree('build')
except:
pass
setup(
name = "django-gnupg-mails",
version = __import__("gnupg_mails").__version__,
author = "Jan Dittberner",
author_email = "[email protected]",
description = (
"A Django reusable app providing the ability to send PGP/MIME signed "
"multipart emails."
),
long_description = open("README.rst").read(),
url = "https://github.com/jandd/django-gnupg-mails",
packages = find_packages(),
zip_safe = False,
include_package_data = True,
install_requires = ['python-gnupg', 'sphinx-me'],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Framework :: Django',
'Topic :: Communications :: Email',
'Topic :: Security :: Cryptography',
]
)
|
Comment out test that fails locally because issue not resolved yet because preventing mvn deploy
git-svn-id: 545e707062091c2f19509f4812c0e7d129870002@853 922cec90-98bc-ecba-b0a9-867c771b4a74 | package org.jaudiotagger.issues;
import org.jaudiotagger.AbstractTestCase;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.tag.FieldKey;
import java.io.File;
/**
*File corrupt after write
*/
public class Issue290Test extends AbstractTestCase
{
public void testSavingFile()
{
File orig = new File("testdata", "test59.mp4");
if (!orig.isFile())
{
System.err.println("Unable to test file - not available");
return;
}
/* Issue still needs fixing
File testFile = null;
Exception exceptionCaught = null;
try
{
testFile = AbstractTestCase.copyAudioToTmp("test59.mp4");
AudioFile af = AudioFileIO.read(testFile);
System.out.println("Tag is"+af.getTag().toString());
af.getTag().setField(af.getTag().createField(FieldKey.ARTIST,"fred"));
af.commit();
af = AudioFileIO.read(testFile);
assertEquals("fred",af.getTag().getFirst(FieldKey.ARTIST));
}
catch (Exception e)
{
e.printStackTrace();
exceptionCaught = e;
}
assertNull(exceptionCaught);
*/
}
}
| package org.jaudiotagger.issues;
import org.jaudiotagger.AbstractTestCase;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.tag.FieldKey;
import java.io.File;
/**
*File corrupt after write
*/
public class Issue290Test extends AbstractTestCase
{
public void testSavingFile()
{
File orig = new File("testdata", "test59.mp4");
if (!orig.isFile())
{
System.err.println("Unable to test file - not available");
return;
}
File testFile = null;
Exception exceptionCaught = null;
try
{
testFile = AbstractTestCase.copyAudioToTmp("test59.mp4");
AudioFile af = AudioFileIO.read(testFile);
System.out.println("Tag is"+af.getTag().toString());
af.getTag().setField(af.getTag().createField(FieldKey.ARTIST,"fred"));
af.commit();
af = AudioFileIO.read(testFile);
assertEquals("fred",af.getTag().getFirst(FieldKey.ARTIST));
}
catch (Exception e)
{
e.printStackTrace();
exceptionCaught = e;
}
assertNull(exceptionCaught);
}
}
|
Fix error when already renamed | #!/usr/bin/env python
import os
import sys
from string import Template
import argparse
import hashlib
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Rename files based on content.')
parser.add_argument('files', metavar='FILE', type=str, nargs='+',
help='Files to rename')
parser.add_argument('-m', '--mask', nargs='?',
help='File destination mask', default='${hash}.${ext}')
parser.add_argument('-p', '--pretend', action='store_true',
help='Do not rename, just print')
args = parser.parse_args()
print 'Renaming with mask: %s' % args.mask
mask = Template(args.mask)
for f in args.files:
if not os.path.exists(f):
print >>sys.stderr, 'File %s does not exists.' % f
else:
with open(f) as fp:
h = hashlib.sha1(fp.read()).hexdigest()
ext = os.path.splitext(f)[1][1:]
name = mask.substitute(hash=h, ext=ext)
dest = os.path.join(os.path.dirname(f), name)
if os.path.basename(f) == name:
print 'OK %s' % name
else:
print "`%s' -> `%s'" % (f, dest)
if os.path.exists(dest):
print >>sys.stderr, 'Destination %s already exists.' % dest
elif not args.pretend:
os.rename(f, dest)
| #!/usr/bin/env python
import os
import sys
from string import Template
import argparse
import hashlib
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Rename files based on content.')
parser.add_argument('files', metavar='FILE', type=str, nargs='+',
help='Files to rename')
parser.add_argument('-m', '--mask', nargs='?',
help='File destination mask', default='${hash}.${ext}')
parser.add_argument('-p', '--pretend', action='store_true',
help='Do not rename, just print')
args = parser.parse_args()
print 'Renaming with mask: %s' % args.mask
mask = Template(args.mask)
for f in args.files:
if not os.path.exists(f):
print >>sys.stderr, 'File %s does not exists.' % f
else:
with open(f) as fp:
h = hashlib.sha1(fp.read()).hexdigest()
ext = os.path.splitext(f)[1][1:]
name = mask.substitute(hash=h, ext=ext)
dest = os.path.join(os.path.dirname(f), name)
print "`%s' -> `%s'" % (f, dest)
if os.path.exists(dest):
print >>sys.stderr, 'Destination %s already exists.' % dest
elif not args.pretend:
os.rename(f, dest)
|
Rename package to use dashes. | from setuptools import setup
REQUIRES = [
'markdown',
'mdx_outline',
]
SOURCES = []
with open('README.rst', 'r') as f:
long_description = f.read()
setup(
name="mdx-attr-cols",
version="0.1.1",
url='http://github.com/CTPUG/mdx_attr_cols',
license='MIT',
description="A bootstrap 3 row and columns extension for Markdown",
long_description=long_description,
author='CTPUG',
author_email='[email protected]',
py_modules=[
'mdx_attr_cols',
],
install_requires=REQUIRES,
dependency_links=SOURCES,
setup_requires=[
# Add setuptools-git, so we get correct behaviour for
# include_package_data
'setuptools_git >= 1.0',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Framework :: Django',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
],
)
| from setuptools import setup
REQUIRES = [
'markdown',
'mdx_outline',
]
SOURCES = []
with open('README.rst', 'r') as f:
long_description = f.read()
setup(
name="mdx_attr_cols",
version="0.1.1",
url='http://github.com/CTPUG/mdx_attr_cols',
license='MIT',
description="A bootstrap 3 row and columns extension for Markdown",
long_description=long_description,
author='CTPUG',
author_email='[email protected]',
py_modules=[
'mdx_attr_cols',
],
install_requires=REQUIRES,
dependency_links=SOURCES,
setup_requires=[
# Add setuptools-git, so we get correct behaviour for
# include_package_data
'setuptools_git >= 1.0',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Framework :: Django',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Put reference handling correct way around | VIE.prototype.Collection = Backbone.Collection.extend({
model: VIE.prototype.Entity,
get: function(id) {
if (!this.models.length) {
return null;
}
if (!this.models[0].isReference(id)) {
id = this.models[0].toReference(id);
}
if (id == null) return null;
return this._byId[id.id != null ? id.id : id];
},
addOrUpdate: function(model) {
var collection = this;
if (_.isArray(model)) {
var entities = [];
_.each(model, function(item) {
entities.push(collection.addOrUpdate(item));
});
return entities;
}
if (!model.isEntity) {
model = new this.model(model);
}
if (!model.id) {
this.add(model);
return model;
}
if (this.get(model.id)) {
var existing = this.get(model.id);
if (model.attributes) {
return existing.set(model.attributes);
}
return existing.set(model);
}
this.add(model);
return model;
}
});
| VIE.prototype.Collection = Backbone.Collection.extend({
model: VIE.prototype.Entity,
get: function(id) {
if (!this.models.length) {
return null;
}
if (this.models[0].isReference(id)) {
id = this.models[0].fromReference(id);
}
if (id == null) return null;
return this._byId[id.id != null ? id.id : id];
},
addOrUpdate: function(model) {
var collection = this;
if (_.isArray(model)) {
var entities = [];
_.each(model, function(item) {
entities.push(collection.addOrUpdate(item));
});
return entities;
}
if (!model.isEntity) {
model = new this.model(model);
}
if (!model.id) {
this.add(model);
return model;
}
if (this.get(model.id)) {
var existing = this.get(model.id);
if (model.attributes) {
return existing.set(model.attributes);
}
return existing.set(model);
}
this.add(model);
return model;
}
});
|
Fix custom template tag to work with django 1.8 | from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcontext_names:
value = context.get(field, {})
if isinstance(value, dict):
new_context.update(context.get(field, {}))
else:
new_context[field] = value
new_context = context.new(new_context)
return self.nodelist.render(new_context)
@register.tag('begincontext')
def in_context(parser, token):
"""
Replaces the context (inside of this block) for easy (and safe) inclusion
of sub-content.
For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}}
1: {{ name }} {{ size }}
{% begincontext sub %}
2: {{ name }} {{ size }}
{% endcontext %}
3: {{ name }} {{ size }}
Will print
1: Kitty
2: 5
3: Kitty
Arguments which are not dictionaries will 'cascade' into the inner
context.
"""
nodelist = parser.parse(('endcontext',))
parser.delete_first_token()
return InContextNode(nodelist, token.split_contents()[1:])
| from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcontext_names:
value = context.get(field, {})
if isinstance(value, dict):
new_context.update(context.get(field, {}))
else:
new_context[field] = value
return self.nodelist.render(template.Context(new_context))
@register.tag('begincontext')
def in_context(parser, token):
"""
Replaces the context (inside of this block) for easy (and safe) inclusion
of sub-content.
For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}}
1: {{ name }} {{ size }}
{% begincontext sub %}
2: {{ name }} {{ size }}
{% endcontext %}
3: {{ name }} {{ size }}
Will print
1: Kitty
2: 5
3: Kitty
Arguments which are not dictionaries will 'cascade' into the inner
context.
"""
nodelist = parser.parse(('endcontext',))
parser.delete_first_token()
return InContextNode(nodelist, token.split_contents()[1:])
|
Send event author in webhook notification | <?php
namespace Kanboard\Notification;
use Kanboard\Core\Base;
use Kanboard\Core\Notification\NotificationInterface;
/**
* Webhook Notification
*
* @package Kanboard\Notification
* @author Frederic Guillot
*/
class WebhookNotification extends Base implements NotificationInterface
{
/**
* Send notification to a user
*
* @access public
* @param array $user
* @param string $event_name
* @param array $event_data
*/
public function notifyUser(array $user, $event_name, array $event_data)
{
}
/**
* Send notification to a project
*
* @access public
* @param array $project
* @param string $event_name
* @param array $event_data
*/
public function notifyProject(array $project, $event_name, array $event_data)
{
$url = $this->configModel->get('webhook_url');
$token = $this->configModel->get('webhook_token');
if (! empty($url)) {
if (strpos($url, '?') !== false) {
$url .= '&token='.$token;
} else {
$url .= '?token='.$token;
}
$payload = array(
'event_name' => $event_name,
'event_data' => $event_data,
'event_author' => ($this->userSession->isLogged() ? $this->userSession->getUsername() : NULL),
);
$this->httpClient->postJson($url, $payload);
}
}
}
| <?php
namespace Kanboard\Notification;
use Kanboard\Core\Base;
use Kanboard\Core\Notification\NotificationInterface;
/**
* Webhook Notification
*
* @package Kanboard\Notification
* @author Frederic Guillot
*/
class WebhookNotification extends Base implements NotificationInterface
{
/**
* Send notification to a user
*
* @access public
* @param array $user
* @param string $event_name
* @param array $event_data
*/
public function notifyUser(array $user, $event_name, array $event_data)
{
}
/**
* Send notification to a project
*
* @access public
* @param array $project
* @param string $event_name
* @param array $event_data
*/
public function notifyProject(array $project, $event_name, array $event_data)
{
$url = $this->configModel->get('webhook_url');
$token = $this->configModel->get('webhook_token');
if (! empty($url)) {
if (strpos($url, '?') !== false) {
$url .= '&token='.$token;
} else {
$url .= '?token='.$token;
}
$payload = array(
'event_name' => $event_name,
'event_data' => $event_data,
);
$this->httpClient->postJson($url, $payload);
}
}
}
|
Remove overlay JS function since we now use Magnific popup. | ;(function($){
$(function() {
var selections = $('#add-cart select');
var showImage = function(id) {
var image = $(id);
if (image.length == 1) {
$('#product-images-large li').hide();
image.show();
}
};
// on selection of an option, reduce the list of variations to the one
// matching all the selected options - if there is one, show it and hide
// the others
selections.change(function() {
var variation = $.grep(variations, function(v) {
var valid = true;
$.each(selections, function() {
valid = valid && v[this.name] == this[this.selectedIndex].value;
});
return valid;
});
if (variation.length == 1) {
$('#variations li').hide();
$('#variation-' + variation[0].sku).show();
showImage('#image-' + variation[0].image_id + '-large');
}
});
selections.change();
// show enlarged image on thumbnail click
$('#product-images-thumb a').click(function() {
showImage('#' + $(this).attr('id') + '-large');
return false;
});
});
})(jQuery);
| ;(function($){
$(function() {
var selections = $('#add-cart select');
var showImage = function(id) {
var image = $(id);
if (image.length == 1) {
$('#product-images-large li').hide();
image.show();
}
};
// on selection of an option, reduce the list of variations to the one
// matching all the selected options - if there is one, show it and hide
// the others
selections.change(function() {
var variation = $.grep(variations, function(v) {
var valid = true;
$.each(selections, function() {
valid = valid && v[this.name] == this[this.selectedIndex].value;
});
return valid;
});
if (variation.length == 1) {
$('#variations li').hide();
$('#variation-' + variation[0].sku).show();
showImage('#image-' + variation[0].image_id + '-large');
}
});
selections.change();
// show enlarged image on thumbnail click
$('#product-images-thumb a').click(function() {
showImage('#' + $(this).attr('id') + '-large');
return false;
});
// Add overlay to large image.
var expose = {color: '#333', loadSpeed: 200, opacity: 0.9};
var overlay = {expose: expose, close: '*', fixed:false};
$('.product-image-large').overlay(overlay);
});
})(jQuery);
|
Build regular and minified CSS. | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
compass: {
dist: {
options: {
sourcemap: true,
sassDir: 'sass',
cssDir: 'static/css',
outputStyle: 'expanded',
}
},
watch: {
options: {
sourcemap: true,
sassDir: 'sass',
cssDir: 'static/css',
outputStyle: 'expanded',
watch: true
}
}
},
cssmin: {
options: {
sourceMap: true
},
dist: {
files: {
'static/css/screen.min.css': 'static/css/screen.css'
}
}
},
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask('default', 'Build the theme.', ['compass:dist', 'cssmin']);
};
| module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
compass: {
dist: {
options: {
sourcemap: true,
sassDir: 'sass',
cssDir: 'static/css',
outputStyle: 'expanded',
}
},
watch: {
options: {
sourcemap: true,
sassDir: 'sass',
cssDir: 'static/css',
outputStyle: 'expanded',
watch: true
}
}
},
cssmin: {
options: {
sourceMap: true
},
target: {
files: {
'static/css/screen.css': 'static/css/screen.css'
}
}
},
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask('default', ['compass:dist', 'cssmin']);
};
|
Update the CVS unit tests to use build_client().
This updates the CVS unit tests to build a `CVSClient` in each test
where it's needed, rather than in `setUp()`. This is in prepration for
new tests that will need to handle client construction differently.
Testing Done:
CVS unit tests pass.
Reviewed at https://reviews.reviewboard.org/r/12504/ | """Unit tests for CVSClient."""
from __future__ import unicode_literals
import kgb
from rbtools.clients import RepositoryInfo
from rbtools.clients.cvs import CVSClient
from rbtools.clients.tests import SCMClientTestCase
class CVSClientTests(kgb.SpyAgency, SCMClientTestCase):
"""Unit tests for CVSClient."""
scmclient_cls = CVSClient
def test_get_repository_info_with_found(self):
"""Testing CVSClient.get_repository_info with repository found"""
client = self.build_client()
self.spy_on(client.get_local_path,
op=kgb.SpyOpReturn('/path/to/cvsdir'))
repository_info = client.get_repository_info()
self.assertIsInstance(repository_info, RepositoryInfo)
self.assertIsNone(repository_info.base_path)
self.assertEqual(repository_info.path, '/path/to/cvsdir')
self.assertEqual(repository_info.local_path, '/path/to/cvsdir')
def test_get_repository_info_with_not_found(self):
"""Testing CVSClient.get_repository_info with repository not found"""
client = self.build_client()
self.spy_on(client.get_local_path,
op=kgb.SpyOpReturn(None))
repository_info = client.get_repository_info()
self.assertIsNone(repository_info)
| """Unit tests for CVSClient."""
from __future__ import unicode_literals
import kgb
from rbtools.clients import RepositoryInfo
from rbtools.clients.cvs import CVSClient
from rbtools.clients.tests import SCMClientTestCase
class CVSClientTests(kgb.SpyAgency, SCMClientTestCase):
"""Unit tests for CVSClient."""
def setUp(self):
super(CVSClientTests, self).setUp()
self.client = CVSClient(options=self.options)
def test_get_repository_info_with_found(self):
"""Testing CVSClient.get_repository_info with repository found"""
self.spy_on(CVSClient.get_local_path,
op=kgb.SpyOpReturn('/path/to/cvsdir'))
repository_info = self.client.get_repository_info()
self.assertIsInstance(repository_info, RepositoryInfo)
self.assertIsNone(repository_info.base_path)
self.assertEqual(repository_info.path, '/path/to/cvsdir')
self.assertEqual(repository_info.local_path, '/path/to/cvsdir')
def test_get_repository_info_with_not_found(self):
"""Testing CVSClient.get_repository_info with repository not found"""
self.spy_on(CVSClient.get_local_path,
op=kgb.SpyOpReturn(None))
repository_info = self.client.get_repository_info()
self.assertIsNone(repository_info)
|
Set manual timeout for count test | var mongoose = require('mongoose'),
async = require('async'),
config = require('./config'),
Schema = mongoose.Schema,
mongoosastic = require('../lib/mongoosastic');
var CommentSchema = new Schema({
user: String,
post_date: {type:Date, es_type:'date'},
message: {type:String},
title: {type:String, es_boost:2.0}
});
CommentSchema.plugin(mongoosastic, {
bulk: {
size: 2,
delay: 100
}
});
var Comment = mongoose.model('Comment', CommentSchema);
describe.only('Count', function() {
before(function(done) {
mongoose.connect(config.mongoUrl, function() {
Comment.remove(function() {
config.deleteIndexIfExists(['comments'], function() {
var comments = [
new Comment({
user: 'terry',
title: 'Ilikecars'
}),
new Comment({
user: 'fred',
title: 'Ihatefish'
})
];
async.forEach(comments, function(item, cb) {
item.save(cb);
}, function() {
setTimeout(done, 2000);
});
});
});
});
});
after(function() {
mongoose.disconnect();
Comment.esClient.close();
});
it('should count a type', function(done) {
Comment.esCount({
term: {
user: 'terry'
}
}, function(err, results) {
results.count.should.eql(1);
done(err);
});
});
});
| var mongoose = require('mongoose'),
async = require('async'),
config = require('./config'),
Schema = mongoose.Schema,
mongoosastic = require('../lib/mongoosastic');
var CommentSchema = new Schema({
user: String,
post_date: {type:Date, es_type:'date'},
message: {type:String},
title: {type:String, es_boost:2.0}
});
CommentSchema.plugin(mongoosastic, {
bulk: {
size: 2,
delay: 100
}
});
var Comment = mongoose.model('Comment', CommentSchema);
describe.only('Count', function() {
before(function(done) {
mongoose.connect(config.mongoUrl, function() {
Comment.remove(function() {
config.deleteIndexIfExists(['comments'], function() {
var comments = [
new Comment({
user: 'terry',
title: 'Ilikecars'
}),
new Comment({
user: 'fred',
title: 'Ihatefish'
})
];
async.forEach(comments, function(item, cb) {
item.save(cb);
}, function() {
setTimeout(done, config.indexingTimeout);
});
});
});
});
});
after(function() {
mongoose.disconnect();
Comment.esClient.close();
});
it('should count a type', function(done) {
Comment.esCount({
term: {
user: 'terry'
}
}, function(err, results) {
results.count.should.eql(1);
done(err);
});
});
});
|
Support for finalize and unfinalize | (function(window)
{
var Gitana = window.Gitana;
Gitana.Release = Gitana.AbstractRepositoryObject.extend(
/** @lends Gitana.Release.prototype */
{
/**
* @constructs
* @augments Gitana.AbstractRepositoryObject
*
* @class Release
*
* @param {Gitana.Repository} repository
* @param [Object] object json object (if no callback required for populating)
*/
constructor: function(repository, object)
{
this.base(repository, object);
this.objectType = function() { return "Gitana.Release"; };
},
/**
* @OVERRIDE
*/
getType: function()
{
return Gitana.TypedIDConstants.TYPE_RELEASE;
},
/**
* @OVERRIDE
*/
getUri: function()
{
return "/repositories/" + this.getRepositoryId() + "/releases/" + this.getId();
},
/**
* @override
*/
clone: function()
{
return this.getFactory().release(this.getRepository(), this);
},
/**
* Finalizes the release.
*
* @param callback
* @returns {*}
*/
finalize: function(callback)
{
var self = this;
var uriFunction = function()
{
return self.getUri() + "/finalize";
};
return this.chainPostResponse(this, uriFunction).then(function(response) {
callback(response);
});
},
/**
* Unfinalizes the release.
*
* @param callback
* @returns {*}
*/
unfinalize: function(callback)
{
var self = this;
var uriFunction = function()
{
return self.getUri() + "/unfinalize";
};
return this.chainPostResponse(this, uriFunction).then(function(response) {
callback(response);
});
}
});
})(window);
| (function(window)
{
var Gitana = window.Gitana;
Gitana.Release = Gitana.AbstractRepositoryObject.extend(
/** @lends Gitana.Release.prototype */
{
/**
* @constructs
* @augments Gitana.AbstractRepositoryObject
*
* @class Release
*
* @param {Gitana.Repository} repository
* @param [Object] object json object (if no callback required for populating)
*/
constructor: function(repository, object)
{
this.base(repository, object);
this.objectType = function() { return "Gitana.Release"; };
},
/**
* @OVERRIDE
*/
getType: function()
{
return Gitana.TypedIDConstants.TYPE_RELEASE;
},
/**
* @OVERRIDE
*/
getUri: function()
{
return "/repositories/" + this.getRepositoryId() + "/releases/" + this.getId();
},
/**
* @override
*/
clone: function()
{
return this.getFactory().release(this.getRepository(), this);
}
});
})(window);
|
Use a variadic call instead of call_user_func_array(). | <?php
namespace Knp\Bundle\MenuBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* This compiler pass registers the voters in the Matcher.
*
* @author Christophe Coevoet <[email protected]>
*
* @internal
* @final
*/
final class AddVotersPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
if (!$container->hasDefinition('knp_menu.matcher')) {
return;
}
$definition = $container->getDefinition('knp_menu.matcher');
$voters = [];
foreach ($container->findTaggedServiceIds('knp_menu.voter') as $id => $tags) {
// Process only the first tag. Registering the same voter multiple time
// does not make any sense, and this allows user to overwrite the tag added
// by the autoconfiguration to change the priority (autoconfigured tags are
// always added at the end of the list).
$tag = $tags[0];
$priority = isset($tag['priority']) ? (int) $tag['priority'] : 0;
$voters[$priority][] = new Reference($id);
}
if (empty($voters)) {
return;
}
krsort($voters);
$sortedVoters = array_merge(...$voters);
$definition->replaceArgument(0, new IteratorArgument($sortedVoters));
}
}
| <?php
namespace Knp\Bundle\MenuBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
/**
* This compiler pass registers the voters in the Matcher.
*
* @author Christophe Coevoet <[email protected]>
*
* @internal
* @final
*/
final class AddVotersPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
if (!$container->hasDefinition('knp_menu.matcher')) {
return;
}
$definition = $container->getDefinition('knp_menu.matcher');
$voters = [];
foreach ($container->findTaggedServiceIds('knp_menu.voter') as $id => $tags) {
// Process only the first tag. Registering the same voter multiple time
// does not make any sense, and this allows user to overwrite the tag added
// by the autoconfiguration to change the priority (autoconfigured tags are
// always added at the end of the list).
$tag = $tags[0];
$priority = isset($tag['priority']) ? (int) $tag['priority'] : 0;
$voters[$priority][] = new Reference($id);
}
if (empty($voters)) {
return;
}
krsort($voters);
$sortedVoters = \call_user_func_array('array_merge', $voters);
$definition->replaceArgument(0, new IteratorArgument($sortedVoters));
}
}
|
[Customer][Core] Rename DashboardStatistic customers count() method to countCustomers() | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Core\Dashboard;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Repository\CustomerRepositoryInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
/**
* @author Paweł Jędrzejewski <[email protected]>
*/
class DashboardStatisticsProvider implements DashboardStatisticsProviderInterface
{
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @param OrderRepositoryInterface $orderRepository
* @param CustomerRepositoryInterface $customerRepository
*/
public function __construct(
OrderRepositoryInterface $orderRepository,
CustomerRepositoryInterface $customerRepository
) {
$this->orderRepository = $orderRepository;
$this->customerRepository = $customerRepository;
}
/**
* {@inheritdoc}
*/
public function getStatisticsForChannel(ChannelInterface $channel): DashboardStatistics
{
return new DashboardStatistics(
$this->orderRepository->getTotalSalesForChannel($channel),
$this->orderRepository->countFulfilledByChannel($channel),
$this->customerRepository->countCustomers()
);
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Core\Dashboard;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Repository\CustomerRepositoryInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
/**
* @author Paweł Jędrzejewski <[email protected]>
*/
class DashboardStatisticsProvider implements DashboardStatisticsProviderInterface
{
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @param OrderRepositoryInterface $orderRepository
* @param CustomerRepositoryInterface $customerRepository
*/
public function __construct(
OrderRepositoryInterface $orderRepository,
CustomerRepositoryInterface $customerRepository
) {
$this->orderRepository = $orderRepository;
$this->customerRepository = $customerRepository;
}
/**
* {@inheritdoc}
*/
public function getStatisticsForChannel(ChannelInterface $channel): DashboardStatistics
{
return new DashboardStatistics(
$this->orderRepository->getTotalSalesForChannel($channel),
$this->orderRepository->countFulfilledByChannel($channel),
$this->customerRepository->count()
);
}
}
|
Allow blank source_id in event, tweak formatting of the code | from django.contrib.gis.db import models
from django.contrib.gis import geos
from datetime import datetime
class Venue(models.Model):
name = models.CharField(max_length=255)
street_address = models.TextField()
country = models.CharField(max_length=255)
location = models.PointField(blank=True)
objects = models.GeoManager()
def __init__(self, *args, **kwargs):
super(Venue, self).__init__(*args, **kwargs)
if self.location is None:
self.location = geos.Point(0, 0)
@property
def latitude(self):
return self.location.x
@latitude.setter
def latitude(self, value):
self.location.x = value
@property
def longitude(self):
return self.location.y
@longitude.setter
def longitude(self, value):
self.location.y = value
class Event(models.Model):
name = models.CharField(max_length = 255)
event_url = models.CharField(max_length = 255, blank = True)
venue = models.ForeignKey(Venue)
start = models.DateTimeField(null = True, blank = True)
end = models.DateTimeField(null = True, blank = True)
source_id = models.CharField(max_length = 255, blank = True)
organiser_email = models.CharField(max_length = 255)
objects = models.GeoManager()
@classmethod
def upcoming(self):
return self.objects.filter(start__gte = datetime.now())
| from django.contrib.gis.db import models
from django.contrib.gis import geos
from datetime import datetime
class Venue(models.Model):
name = models.CharField(max_length=255)
street_address = models.TextField()
country = models.CharField(max_length=255)
location = models.PointField(blank=True)
objects = models.GeoManager()
def __init__(self, *args, **kwargs):
super(Venue, self).__init__(*args, **kwargs)
if self.location is None:
self.location = geos.Point(0, 0)
@property
def latitude(self):
return self.location.x
@latitude.setter
def latitude(self, value):
self.location.x = value
@property
def longitude(self):
return self.location.y
@longitude.setter
def longitude(self, value):
self.location.y = value
class Event(models.Model):
name = models.CharField(max_length=255)
event_url = models.CharField(max_length=255, blank = True)
venue = models.ForeignKey(Venue)
start = models.DateTimeField(null = True, blank = True)
end = models.DateTimeField(null = True, blank = True)
source_id = models.CharField(max_length=255)
organiser_email = models.CharField(max_length=255)
objects = models.GeoManager()
@classmethod
def upcoming(self):
return self.objects.filter(start__gte = datetime.now())
|
Allow Mongo connections to Mongo Replicaset Cluster | import pymongo
DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
DEFAULT_MONGODB_PORT,
DEFAULT_MONGODB_NAME)
class MongoDB(object):
"""Simple wrapper to get pymongo real objects from the settings uri"""
def __init__(self, db_uri=DEFAULT_MONGODB_URI,
connection_factory=pymongo.MongoClient):
self.db_uri = db_uri
self.connection = connection_factory(
host=self.db_uri,
tz_aware=True)
if self.db_uri.path:
self.database_name = self.db_uri.path[1:]
else:
self.database_name = DEFAULT_MONGODB_NAME
def get_connection(self):
return self.connection
def get_database(self):
database = self.connection[self.database_name]
if self.db_uri.username and self.db_uri.password:
database.authenticate(self.db_uri.username, self.db_uri.password)
return database
def get_db(request):
return request.registry.settings['mongodb'].get_database()
| import pymongo
from eduid_signup.compat import urlparse
DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
DEFAULT_MONGODB_PORT,
DEFAULT_MONGODB_NAME)
class MongoDB(object):
"""Simple wrapper to get pymongo real objects from the settings uri"""
def __init__(self, db_uri=DEFAULT_MONGODB_URI,
connection_factory=pymongo.Connection):
self.db_uri = urlparse.urlparse(db_uri)
self.connection = connection_factory(
host=self.db_uri.hostname or DEFAULT_MONGODB_HOST,
port=self.db_uri.port or DEFAULT_MONGODB_PORT,
tz_aware=True)
if self.db_uri.path:
self.database_name = self.db_uri.path[1:]
else:
self.database_name = DEFAULT_MONGODB_NAME
def get_connection(self):
return self.connection
def get_database(self):
database = self.connection[self.database_name]
if self.db_uri.username and self.db_uri.password:
database.authenticate(self.db_uri.username, self.db_uri.password)
return database
def get_db(request):
return request.registry.settings['mongodb'].get_database()
|
Reset device list on scan | (function(){
'use strict';
angular
.module('steamWorks')
.controller('btCtrl', btCtrl);
btCtrl.$inject = ['$scope', '$state', 'deviceSvc'];
function btCtrl($scope, $state, deviceSvc){
var vm = this;
vm.devices = []; // the devices listed in the page
vm.scan = scan;
vm.connect = connect;
vm.showSpinner = false;
function scan (){
deviceSvc.reset();
vm.devices = deviceSvc.getDevices();
vm.showSpinner = true;
deviceSvc.reset();
ble.startScan(
[],
function(device){
if(device.name){
deviceSvc.addDevice({ 'id': device.id, 'name': device.name });
}
},
function(err){
alert('Scanning failed. Please try again.');
}
);
setTimeout(
ble.stopScan,
1500,
function(){
$scope.$apply(function(){
vm.showSpinner = false;
vm.devices = deviceSvc.getDevices();
});
},
function(){
// Stopping scan failed
}
);
}
function connect (device_id){
$state.go('app.welcome');
}
}
})();
| (function(){
'use strict';
angular
.module('steamWorks')
.controller('btCtrl', btCtrl);
btCtrl.$inject = ['$scope', '$state', 'deviceSvc'];
function btCtrl($scope, $state, deviceSvc){
var vm = this;
vm.devices = []; // the devices listed in the page
vm.scan = scan;
vm.connect = connect;
vm.showSpinner = false;
function scan (){
vm.showSpinner = true;
deviceSvc.reset();
ble.startScan(
[],
function(device){
if(device.name){
deviceSvc.addDevice({ 'id': device.id, 'name': device.name });
}
},
function(err){
alert('Scanning failed. Please try again.');
}
);
setTimeout(
ble.stopScan,
1500,
function(){
$scope.$apply(function(){
vm.showSpinner = false;
vm.devices = deviceSvc.getDevices();
});
},
function(){
// Stopping scan failed
}
);
}
function connect (device_id){
$state.go('app.welcome');
}
}
})();
|
Update to new webapp and skin rendering (I like it better than before!)
git-svn-id: fac99be8204c57f0935f741ea919b5bf0077cdf6@9248 688a9155-6ab5-4160-a077-9df41f55a9e9 | var webapp = loadModule('helma.webapp');
var handleRequest = loadModule('helma.webapp.handler').handleRequest;
// db model
var model = loadModule('model');
// the main action is invoked for http://localhost:8080/
// this also shows simple skin rendering
function main_action(req, res) {
if (req.data.save) {
createBook(req, res);
}
if (req.data.remove) {
removeBook(req, res);
}
var books = model.Book.all();
res.render('skins/index.html', {
title: 'Storage Demo',
books: function(/*tag, skin, context*/) {
var buffer = [];
for (var i in books) {
var book = books[i]
buffer.push(book.getFullTitle(), getDeleteLink(book), "<br>\r\n");
}
return buffer.join(' ');
}
});
}
function createBook(req, res) {
var author = new model.Author({name: req.data.author});
var book = new model.Book({author: author, title: req.data.title});
// author is saved transitively
book.save();
res.redirect('/');
}
function removeBook(req, res) {
var book = model.Book.get(req.data.remove);
// author is removed through cascading delete
book.remove();
res.redirect('/');
}
function getDeleteLink(book) {
return '<a href="/?remove=' + book._id + '">delete</a>';
}
if (__name__ == "__main__") {
webapp.start();
}
| var handleRequest = loadModule('helma.simpleweb').handleRequest;
var render = loadModule('helma.skin').render;
var webapp = loadModule('helma.webapp');
// db model
var model = loadModule('model');
// the main action is invoked for http://localhost:8080/
// this also shows simple skin rendering
function main_action() {
if (req.data.save) {
createBook();
}
if (req.data.remove) {
removeBook();
}
var books = model.Book.all();
res.write(render('skins/index.html', {
title: 'Storage Demo',
books: function(/*tag, skin, context*/) {
for (var i in books) {
var book = books[i]
res.writeln(book.getFullTitle(), getDeleteLink(book), "<br>");
}
}
}));
}
function createBook() {
var author = new model.Author({name: req.data.author});
var book = new model.Book({author: author, title: req.data.title});
// author is saved transitively
book.save();
res.redirect('/');
}
function removeBook() {
var book = model.Book.get(req.data.remove);
// author is removed through cascading delete
book.remove();
res.redirect('/');
}
function getDeleteLink(book) {
return '<a href="/?remove=' + book._id + '">delete</a>';
}
if (__name__ == "__main__") {
webapp.start();
}
|
Add interface method as abstract to trait
Code quality: while trait is supposed to go together with the interface,
it makes sense to add interface method used by trait as an abstract method. This
way implementors will not be caught by surprise if method definition is
ever changed or removed altogether | <?php
declare(strict_types=1);
namespace Xerkus\Neovim\Plugin\RpcHandler;
/**
* Rpc handler that announces itself to neovim.
*
*/
trait RpcSpecTrait
{
private $name;
private $sync;
private $pluginPath;
/**
* @inheritDoc
*/
abstract public function getType() : string;
/**
* @inheritDoc
*/
public function getName() : string
{
return $this->name;
}
/**
* @inheritDoc
*/
public function getIsSync() : bool
{
return $this->sync;
}
/**
* @inheritDoc
*/
public function getMethodName() : string
{
$method = $this->getType() . ':' . $this->getName();
$pluginPath = $this->getPluginPath();
if (!empty($pluginPath)) {
$method = $pluginPath . ':' . $method;
}
return $method;
}
/**
* @inheritDoc
*/
public function getSpecArray() : array
{
return [
'type' => $this->getType(),
'name' => $this->getName(),
'sync' => $this->getIsSync(),
'opts' => $this->prepareOpts()
];
}
/**
* Prepare opts array for spec array
*/
abstract protected function prepareOpts() : array;
/**
* @inheritDoc
*/
public function getPluginPath()
{
return $this->pluginPath;
}
/**
* @inheritDoc
*/
public function withPluginPath(string $pluginPath = null) : RpcSpec
{
$new = clone($this);
$new->pluginPath = $pluginPath;
return $new;
}
}
| <?php
declare(strict_types=1);
namespace Xerkus\Neovim\Plugin\RpcHandler;
/**
* Rpc handler that announces itself to neovim.
*
*/
trait RpcSpecTrait
{
private $name;
private $sync;
private $pluginPath;
/**
* @inheritDoc
*/
public function getName() : string
{
return $this->name;
}
/**
* @inheritDoc
*/
public function getIsSync() : bool
{
return $this->sync;
}
/**
* @inheritDoc
*/
public function getMethodName() : string
{
$method = $this->getType() . ':' . $this->getName();
$pluginPath = $this->getPluginPath();
if (!empty($pluginPath)) {
$method = $pluginPath . ':' . $method;
}
return $method;
}
/**
* @inheritDoc
*/
public function getSpecArray() : array
{
return [
'type' => $this->getType(),
'name' => $this->getName(),
'sync' => $this->getIsSync(),
'opts' => $this->prepareOpts()
];
}
/**
* Prepare opts array for spec array
*/
abstract protected function prepareOpts() : array;
/**
* @inheritDoc
*/
public function getPluginPath()
{
return $this->pluginPath;
}
/**
* @inheritDoc
*/
public function withPluginPath(string $pluginPath = null) : RpcSpec
{
$new = clone($this);
$new->pluginPath = $pluginPath;
return $new;
}
}
|
Add empty space to logging output | package com.microsoft.applicationinsights.logging;
import android.util.Log;
import com.microsoft.applicationinsights.library.ApplicationInsights;
public class InternalLogging {
private static final String PREFIX = InternalLogging.class.getPackage().getName();
private InternalLogging() {
// hide default constructor
}
/**
* Inform SDK users about SDK activities. This has 3 parameters to avoid the string
* concatenation then verbose mode is disabled.
*
* @param tag the log context
* @param message the log message
* @param payload the payload for the message
*/
public static void info(String tag, String message, String payload) {
if (ApplicationInsights.isDeveloperMode()) {
Log.i(PREFIX + " " + tag, message + ":" + payload);
}
}
/**
* Warn SDK users about non-critical SDK misuse
*
* @param tag the log context
* @param message the log message
*/
public static void warn(String tag, String message) {
if (ApplicationInsights.isDeveloperMode()) {
Log.w(PREFIX + " " + tag, message);
}
}
/**
* Log critical SDK error
*
* @param tag the log context
* @param message the log message
*/
public static void error(String tag, String message) {
Log.e(PREFIX + " " + tag, message);
}
}
| package com.microsoft.applicationinsights.logging;
import android.util.Log;
import com.microsoft.applicationinsights.library.ApplicationInsights;
public class InternalLogging {
private static final String PREFIX = InternalLogging.class.getPackage().getName();
private InternalLogging() {
// hide default constructor
}
/**
* Inform SDK users about SDK activities. This has 3 parameters to avoid the string
* concatenation then verbose mode is disabled.
*
* @param tag the log context
* @param message the log message
* @param payload the payload for the message
*/
public static void info(String tag, String message, String payload) {
if (ApplicationInsights.isDeveloperMode()) {
Log.i(PREFIX + tag, message + ":" + payload);
}
}
/**
* Warn SDK users about non-critical SDK misuse
*
* @param tag the log context
* @param message the log message
*/
public static void warn(String tag, String message) {
if (ApplicationInsights.isDeveloperMode()) {
Log.w(PREFIX + tag, message);
}
}
/**
* Log critical SDK error
*
* @param tag the log context
* @param message the log message
*/
public static void error(String tag, String message) {
Log.e(PREFIX + tag, message);
}
}
|
Fix another doc string type. | <?php
/**
* MiniAsset
* Copyright (c) Mark Story (http://mark-story.com)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Mark Story (http://mark-story.com)
* @since 1.3.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace MiniAsset\Output;
use MiniAsset\AssetTarget;
use MiniAsset\Output\Compiler;
use MiniAsset\Output\CompilerInterface;
use MiniAsset\Output\AssetCacher;
/**
* An decorator that combines a cacher and a compiler.
*/
class CachedCompiler implements CompilerInterface
{
private $compiler;
private $cacher;
public function __construct(AssetCacher $cacher, Compiler $compiler)
{
$this->cacher = $cacher;
$this->compiler = $compiler;
}
/**
* Generate a compiled asset, with all the configured filters applied.
*
* @param \MiniAsset\AssetTarget $target The target to build
* @return string The processed result of $target and it dependencies.
* @throws \RuntimeException
*/
public function generate(AssetTarget $build)
{
if ($this->cacher->isFresh($build)) {
$contents = $this->cacher->read($build);
} else {
$contents = $this->compiler->generate($build);
$this->cacher->write($build, $contents);
}
return $contents;
}
}
| <?php
/**
* MiniAsset
* Copyright (c) Mark Story (http://mark-story.com)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Mark Story (http://mark-story.com)
* @since 1.3.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace MiniAsset\Output;
use MiniAsset\AssetTarget;
use MiniAsset\Output\Compiler;
use MiniAsset\Output\CompilerInterface;
use MiniAsset\Output\AssetCacher;
/**
* An decorator that combines a cacher and a compiler.
*/
class CachedCompiler implements CompilerInterface
{
private $compiler;
private $cacher;
public function __construct(AssetCacher $cacher, Compiler $compiler)
{
$this->cacher = $cacher;
$this->compiler = $compiler;
}
/**
* Generate a compiled asset, with all the configured filters applied.
*
* @param \MiniAsset\AssetTarget $target The target to build
* @return The processed result of $target and it dependencies.
* @throws \RuntimeException
*/
public function generate(AssetTarget $build)
{
if ($this->cacher->isFresh($build)) {
$contents = $this->cacher->read($build);
} else {
$contents = $this->compiler->generate($build);
$this->cacher->write($build, $contents);
}
return $contents;
}
}
|
Add support for higher order collection messages from 5.4 | <?php namespace TightenCo\Jigsaw;
use ArrayAccess;
use Exception;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Support\HigherOrderCollectionProxy;
class IterableObject extends BaseCollection implements ArrayAccess
{
public function __get($key)
{
if (! $this->offsetExists($key) && in_array($key, static::$proxies)) {
return new HigherOrderCollectionProxy($this, $key);
}
return $this->get($key);
}
public function get($key, $default = null)
{
if ($this->offsetExists($key)) {
return $this->getElement($key);
}
return value($default);
}
public function offsetGet($key)
{
if (! isset($this->items[$key])) {
$prefix = $this->_source ? 'Error in ' . $this->_source . ': ' : 'Error: ';
throw new Exception($prefix . "The key '$key' does not exist.");
}
return $this->getElement($key);
}
public function putIterable($key, $element)
{
$this->put($key, $this->isArrayable($element) ? $this->makeIterable($element) : $element);
}
protected function getElement($key)
{
return $this->items[$key];
}
protected function makeIterable($items)
{
return new IterableObject(collect($items)->map(function ($item) {
return $this->isArrayable($item) ? $this->makeIterable($item) : $item;
}));
}
protected function isArrayable($element)
{
return is_array($element) || $element instanceof BaseCollection;
}
}
| <?php namespace TightenCo\Jigsaw;
use ArrayAccess;
use Exception;
use Illuminate\Support\Collection as BaseCollection;
class IterableObject extends BaseCollection implements ArrayAccess
{
public function __get($key)
{
return $this->get($key);
}
public function get($key, $default = null)
{
if ($this->offsetExists($key)) {
return $this->getElement($key);
}
return value($default);
}
public function offsetGet($key)
{
if (! isset($this->items[$key])) {
$prefix = $this->_source ? 'Error in ' . $this->_source . ': ' : 'Error: ';
throw new Exception($prefix . "The key '$key' does not exist.");
}
return $this->getElement($key);
}
public function putIterable($key, $element)
{
$this->put($key, $this->isArrayable($element) ? $this->makeIterable($element) : $element);
}
protected function getElement($key)
{
return $this->items[$key];
}
protected function makeIterable($items)
{
return new IterableObject(collect($items)->map(function ($item) {
return $this->isArrayable($item) ? $this->makeIterable($item) : $item;
}));
}
protected function isArrayable($element)
{
return is_array($element) || $element instanceof BaseCollection;
}
}
|
Add dependency to vcstools>=0.1.34 (to be released) | from setuptools import setup
import imp
def get_version():
ver_file = None
try:
ver_file, pathname, description = imp.find_module('__version__', ['src/wstool'])
vermod = imp.load_module('__version__', ver_file, pathname, description)
version = vermod.version
return version
finally:
if ver_file is not None:
ver_file.close()
setup(name='wstool',
version=get_version(),
packages=['wstool'],
package_dir={'': 'src'},
# rosinstall dependency to be kept in order not to break ros hydro install instructions
install_requires=['vcstools>=0.1.34', 'pyyaml'],
scripts=["scripts/wstool"],
author="Tully Foote",
author_email="[email protected]",
url="http://wiki.ros.org/wstool",
download_url="http://download.ros.org/downloads/wstool/",
keywords=["ROS"],
classifiers=["Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: BSD License"],
description="workspace multi-SCM commands",
long_description="""\
A tool for managing a workspace of multiple heterogenous SCM repositories
""",
license="BSD")
| from setuptools import setup
import imp
def get_version():
ver_file = None
try:
ver_file, pathname, description = imp.find_module('__version__', ['src/wstool'])
vermod = imp.load_module('__version__', ver_file, pathname, description)
version = vermod.version
return version
finally:
if ver_file is not None:
ver_file.close()
setup(name='wstool',
version=get_version(),
packages=['wstool'],
package_dir={'': 'src'},
# rosinstall dependency to be kept in order not to break ros hydro install instructions
install_requires=['vcstools', 'pyyaml'],
scripts=["scripts/wstool"],
author="Tully Foote",
author_email="[email protected]",
url="http://wiki.ros.org/wstool",
download_url="http://download.ros.org/downloads/wstool/",
keywords=["ROS"],
classifiers=["Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: BSD License"],
description="workspace multi-SCM commands",
long_description="""\
A tool for managing a workspace of multiple heterogenous SCM repositories
""",
license="BSD")
|
Add colorlog to reqs and fix dev req versions | from codecs import open as codecs_open
from setuptools import setup, find_packages
with codecs_open('README.md', encoding='utf-8') as f:
LONG_DESCRIPTION = f.read()
setup(name='gypsy',
version='0.0.1',
description=u"Forestry Growth and Yield Projection System",
long_description=LONG_DESCRIPTION,
classifiers=[],
keywords='',
author=u"Julianno Sambatti, Jotham Apaloo",
author_email='[email protected]',
url='',
license='',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
zip_safe=False,
include_package_data=True,
package_data={
'gypsy': ['data/*'],
},
install_requires=[
'click>=6.6',
'pandas>=0.18.1',
'matplotlib>=1.5.2',
'colorlog>=2.7.0',
],
extras_require={
'test': ['pytest==2.9.1', 'pytest-cov==2.4.0'],
'lint': ['pylint==1.5.4'],
'docs': ['sphinx==1.4.1'],
'dev': ['git-pylint-commit-hook==2.1.1'],
},
entry_points="""
[console_scripts]
gypsy=gypsy.scripts.cli:cli
"""
)
| from codecs import open as codecs_open
from setuptools import setup, find_packages
with codecs_open('README.md', encoding='utf-8') as f:
LONG_DESCRIPTION = f.read()
setup(name='gypsy',
version='0.0.1',
description=u"Forestry Growth and Yield Projection System",
long_description=LONG_DESCRIPTION,
classifiers=[],
keywords='',
author=u"Julianno Sambatti, Jotham Apaloo",
author_email='[email protected]',
url='',
license='',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
zip_safe=False,
include_package_data=True,
package_data={
'gypsy': ['data/*'],
},
install_requires=[
'click>=6.6',
'pandas>=0.18.1',
'matplotlib==1.5.2',
],
extras_require={
'test': ['pytest>=2.9.1', 'pytest-cov'],
'lint': ['pylint>=1.5.4'],
'docs': ['sphinx>=1.4.1'],
'dev': ['git-pylint-commit-hook>=2.1.1'],
},
entry_points="""
[console_scripts]
gypsy=gypsy.scripts.cli:cli
"""
)
|
[f] Add failure message test for not_to.be.true() | from robber import expect
from robber.matchers.boolean import TrueMatcher, FalseMatcher
class TestTrueMatcher:
def test_matches(self):
expect(TrueMatcher(True).matches()).to.eq(True)
expect(TrueMatcher(False).matches()).to.eq(False)
def test_failure_message(self):
true = TrueMatcher(False)
message = true.failure_message()
expect(message) == 'Expected False to be True'
def test_failure_message_with_not_to(self):
true = TrueMatcher(True, is_negated=True)
message = true.failure_message()
expect(message) == 'Expected True not to be True'
def test_failure_message_with_not_to(self):
true = TrueMatcher(True, is_negated=True)
message = true.failure_message()
expect(message) == 'Expected True not to be True'
def test_register(self):
expect(expect.matcher('true')) == TrueMatcher
class TestFalseMatcher:
def test_matches(self):
expect(FalseMatcher(False).matches()).to.eq(True)
expect(FalseMatcher(True).matches()).to.eq(False)
def test_failure_message(self):
false = FalseMatcher(True)
message = false.failure_message()
expect(message) == 'Expected True to be False'
def test_failure_message_with_not_to(self):
false = FalseMatcher(False, is_negated=True)
message = false.failure_message()
expect(message) == 'Expected False not to be False'
def test_register(self):
expect(expect.matcher('false')) == FalseMatcher
| from robber import expect
from robber.matchers.boolean import TrueMatcher, FalseMatcher
class TestTrueMatcher:
def test_matches(self):
expect(TrueMatcher(True).matches()).to.eq(True)
expect(TrueMatcher(False).matches()).to.eq(False)
def test_failure_message(self):
true = TrueMatcher(False)
message = true.failure_message()
expect(message) == 'Expected False to be True'
def test_failure_message_with_not_to(self):
true = TrueMatcher(True, is_negated=True)
message = true.failure_message()
expect(message) == 'Expected True not to be True'
def test_register(self):
expect(expect.matcher('true')) == TrueMatcher
class TestFalseMatcher:
def test_matches(self):
expect(FalseMatcher(False).matches()).to.eq(True)
expect(FalseMatcher(True).matches()).to.eq(False)
def test_failure_message(self):
false = FalseMatcher(True)
message = false.failure_message()
expect(message) == 'Expected True to be False'
def test_failure_message_with_not_to(self):
false = FalseMatcher(False, is_negated=True)
message = false.failure_message()
expect(message) == 'Expected False not to be False'
def test_register(self):
expect(expect.matcher('false')) == FalseMatcher
|
Fix issue where double clicking in char select causes game breakage. | var CharSelect = {
showing: false,
bound: false,
$ov: null,
$ui: null,
$chars: null,
bind: function () {
if (this.bound) {
return;
}
this.bound = true;
this.$ov = $('#overlay');
this.$ui = $('#charselect');
this.$chars = this.$ui.find('.leaders');
this.$chars.html('');
var leaders = Utils.shuffleArray(Leaders.leaders.slice());
var mkLeader = function (leader) {
var $leader = $('<div />')
.addClass('leader')
.addClass('option')
.append('<img src="assets/images/flag_' + leader.id + '.png" class="flag" />')
.append(leader.title + ' ' + leader.name + ' of ' + leader.nation)
.click(function() {
if (!this.showing) {
return;
}
MainMenu.hide();
this.hide();
Game.start(leader.id);
}.bind(this))
.appendTo(this.$chars)
}.bind(this);
for (var i = 0; i < leaders.length; i++) {
var leader = leaders[i];
mkLeader(leader);
}
},
show: function () {
if (this.showing) {
return;
}
this.showing = true;
this.bind();
this.$ov.fadeIn('fast');
this.$ui.slideDown();
},
hide: function () {
this.$ov.fadeOut('fast');
this.$ui.slideUp();
this.showing = false;
}
}; | var CharSelect = {
showing: false,
bound: false,
$ov: null,
$ui: null,
$chars: null,
bind: function () {
if (this.bound) {
return;
}
this.bound = true;
this.$ov = $('#overlay');
this.$ui = $('#charselect');
this.$chars = this.$ui.find('.leaders');
this.$chars.html('');
var leaders = Utils.shuffleArray(Leaders.leaders.slice());
var mkLeader = function (leader) {
var $leader = $('<div />')
.addClass('leader')
.addClass('option')
.append('<img src="assets/images/flag_' + leader.id + '.png" class="flag" />')
.append(leader.title + ' ' + leader.name + ' of ' + leader.nation)
.click(function() {
MainMenu.hide();
this.hide();
Game.start(leader.id);
}.bind(this))
.appendTo(this.$chars)
}.bind(this);
for (var i = 0; i < leaders.length; i++) {
var leader = leaders[i];
mkLeader(leader);
}
},
show: function () {
if (this.showing) {
return;
}
this.showing = true;
this.bind();
this.$ov.fadeIn('fast');
this.$ui.slideDown();
},
hide: function () {
this.$ov.fadeOut('fast');
this.$ui.slideUp();
this.showing = false;
}
}; |
Add TinyDbReader to observers init | #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
from sacred.commandline_options import CommandLineOption
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
from sacred.observers.tinydb_hashfs import TinyDbObserver, TinyDbReader
if opt.has_pymongo:
from sacred.observers.mongo import MongoObserver
else:
MongoObserver = opt.MissingDependencyMock('pymongo')
class MongoDbOption(CommandLineOption):
"""To use the MongoObserver you need to install pymongo first."""
arg = 'DB'
@classmethod
def apply(cls, args, run):
raise ImportError('cannot use -m/--mongo_db flag: '
'missing pymongo dependency')
if opt.has_sqlalchemy:
from sacred.observers.sql import SqlObserver
else:
SqlObserver = opt.MissingDependencyMock('sqlalchemy')
class SqlOption(CommandLineOption):
"""To use the SqlObserver you need to install sqlalchemy first."""
arg = 'DB_URL'
@classmethod
def apply(cls, args, run):
raise ImportError('cannot use -s/--sql flag: '
'missing sqlalchemy dependency')
__all__ = ('FileStorageObserver', 'RunObserver', 'MongoObserver',
'SqlObserver', 'TinyDbObserver', 'TinyDbReader')
| #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
from sacred.commandline_options import CommandLineOption
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
from sacred.observers.tinydb_hashfs import TinyDbObserver
if opt.has_pymongo:
from sacred.observers.mongo import MongoObserver
else:
MongoObserver = opt.MissingDependencyMock('pymongo')
class MongoDbOption(CommandLineOption):
"""To use the MongoObserver you need to install pymongo first."""
arg = 'DB'
@classmethod
def apply(cls, args, run):
raise ImportError('cannot use -m/--mongo_db flag: '
'missing pymongo dependency')
if opt.has_sqlalchemy:
from sacred.observers.sql import SqlObserver
else:
SqlObserver = opt.MissingDependencyMock('sqlalchemy')
class SqlOption(CommandLineOption):
"""To use the SqlObserver you need to install sqlalchemy first."""
arg = 'DB_URL'
@classmethod
def apply(cls, args, run):
raise ImportError('cannot use -s/--sql flag: '
'missing sqlalchemy dependency')
__all__ = ('FileStorageObserver', 'RunObserver', 'MongoObserver',
'SqlObserver', 'TinyDbObserver')
|
Allow for directories argument to be optional | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_docs: str
Any documentation to be added to the documentation produced by
`argparse`
"""
from argparse import RawDescriptionHelpFormatter
parser.formatter_class = RawDescriptionHelpFormatter
if additional_docs is not None:
parser.epilog = additional_docs
def add_verbose(parser):
"""
Add a verbose option (--verbose or -v) to parser.
Parameters:
-----------
parser : `ArgumentParser`
"""
verbose_help = "provide more information during processing"
parser.add_argument("-v", "--verbose", help=verbose_help,
action="store_true")
def add_directories(parser, nargs_in='+'):
"""
Add a positional argument that is one or more directories.
Parameters
----------
parser : `ArgumentParser`
"""
parser.add_argument("dir", metavar='dir', nargs=nargs_in,
help="Directory to process")
def construct_default_parser(docstring=None):
#import script_helpers
import argparse
parser = argparse.ArgumentParser()
if docstring is not None:
setup_parser_help(parser, docstring)
add_verbose(parser)
add_directories(parser)
return parser
| """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_docs: str
Any documentation to be added to the documentation produced by
`argparse`
"""
from argparse import RawDescriptionHelpFormatter
parser.formatter_class = RawDescriptionHelpFormatter
if additional_docs is not None:
parser.epilog = additional_docs
def add_verbose(parser):
"""
Add a verbose option (--verbose or -v) to parser.
Parameters:
-----------
parser : `ArgumentParser`
"""
verbose_help = "provide more information during processing"
parser.add_argument("-v", "--verbose", help=verbose_help,
action="store_true")
def add_directories(parser):
"""
Add a positional argument that is one or more directories.
Parameters
----------
parser : `ArgumentParser`
"""
parser.add_argument("dir", metavar='dir', nargs='+',
help="Directory to process")
def construct_default_parser(docstring=None):
#import script_helpers
import argparse
parser = argparse.ArgumentParser()
if docstring is not None:
setup_parser_help(parser, docstring)
add_verbose(parser)
add_directories(parser)
return parser
|
Add undo/redo buttons and remove sub-/superscript buttons | 'use strict';
(function (document, CKEDITOR) {
document.addEventListener('DOMContentLoaded', function () {
// RTE
Array.prototype.forEach.call(document.querySelectorAll('textarea[data-type=rte]'), function (item) {
const cfg = {
customConfig: '',
disableNativeSpellChecker: true,
extraAllowedContent: 'article section(*)',
filebrowserBrowseUrl: '/file/browser',
format_tags: 'p;h1;h2;h3',
height: '30rem',
removeButtons: 'Cut,Copy,Paste,Anchor,Strike,Subscript,Superscript,Indent,Outdent',
removeDialogTabs: 'link:advanced;link:target',
stylesSet: false,
toolbarGroups: [
{name: 'document', groups: ['mode', 'document', 'doctools']},
{name: 'clipboard', groups: ['clipboard', 'undo']},
{name: 'editing', groups: ['find', 'selection', 'spellchecker']},
{name: 'forms'},
{name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
{name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi']},
{name: 'links'},
{name: 'insert'},
{name: 'styles'},
{name: 'colors'},
{name: 'tools'},
{name: 'others'},
{name: 'about'}
]
};
CKEDITOR.replace(item, cfg);
});
});
})(document, CKEDITOR);
| 'use strict';
(function (document, CKEDITOR) {
document.addEventListener('DOMContentLoaded', function () {
// RTE
Array.prototype.forEach.call(document.querySelectorAll('textarea[data-type=rte]'), function (item) {
const cfg = {
customConfig: '',
disableNativeSpellChecker: true,
extraAllowedContent: 'article section(*)',
filebrowserBrowseUrl: '/file/browser',
format_tags: 'p;h1;h2;h3',
height: '30rem',
removeButtons: 'Cut,Copy,Paste,Undo,Redo,Anchor,Strike,Indent,Outdent',
removeDialogTabs: 'link:advanced;link:target',
stylesSet: false,
toolbarGroups: [
{name: 'document', groups: ['mode', 'document', 'doctools']},
{name: 'clipboard', groups: ['clipboard', 'undo']},
{name: 'editing', groups: ['find', 'selection', 'spellchecker']},
{name: 'forms'},
{name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
{name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi']},
{name: 'links'},
{name: 'insert'},
{name: 'styles'},
{name: 'colors'},
{name: 'tools'},
{name: 'others'},
{name: 'about'}
]
};
CKEDITOR.replace(item, cfg);
});
});
})(document, CKEDITOR);
|
Update perf scripts to use browserify rather than gulp-browserify. | var gulp = require('gulp');
var build = require('./../gulp-build');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var browserify = require('browserify');
var Transform = require('stream').Transform;
var Rx = require('rx');
var Observable = Rx.Observable;
var fs = require('fs');
var path = require('path');
var vinyl = require('vinyl-source-stream');
gulp.task('perf', ['perf-device']);
gulp.task('perf-update', runner);
gulp.task('perf-assemble', ['clean.perf'], assemble);
gulp.task('perf-device', ['perf-assemble'], runner);
gulp.task('perf-browser', ['perf-assemble-browser'], runner);
gulp.task('perf-assemble-browser', ['clean.perf'], browser);
gulp.task('perf-all', ['perf-device', 'perf-browser']);
function assemble() {
return browserify('./performance/testConfig.js', {
standalone: 'testConfig'
}).
bundle().
pipe(vinyl('assembledPerf.js')).
pipe(gulp.dest('performance/bin'));
}
function browser() {
return browserify('./performance/browser.js', {
standalone: 'browser'
}).
bundle().
pipe(vinyl('browser.js')).
pipe(gulp.dest('performance/bin'));
}
function runner() {
return gulp.
src(['performance/bin/assembledPerf.js', 'performance/device.js']).
pipe(concat({path: 'device.js'})).
pipe(gulp.dest('performance/bin'));
}
| var gulp = require('gulp');
var build = require('./../gulp-build');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var browserify = require('gulp-browserify');
var Transform = require("stream").Transform;
var Rx = require('rx');
var Observable = Rx.Observable;
var fs = require('fs');
var path = require('path');
gulp.task('perf', ['perf-device']);
gulp.task('perf-update', runner);
gulp.task('perf-assemble', ['clean.perf'], assemble);
gulp.task('perf-device', ['perf-assemble'], runner);
gulp.task('perf-browser', ['perf-assemble-browser'], runner);
gulp.task('perf-assemble-browser', ['clean.perf'], browser);
gulp.task('perf-all', ['perf-device', 'perf-browser']);
function assemble() {
return gulp.
src(['./performance/testConfig.js']).
pipe(browserify({
standalone: 'testConfig'
})).
pipe(rename('assembledPerf.js')).
pipe(gulp.dest('performance/bin'));
}
function browser() {
return gulp.
src(['./performance/browser.js']).
pipe(browserify({
standalone: 'browser'
})).
pipe(rename('browser.js')).
pipe(gulp.dest('performance/bin'));
}
function runner() {
return gulp.
src(['performance/bin/assembledPerf.js', 'performance/device.js']).
pipe(concat({path: 'device.js'})).
pipe(gulp.dest('performance/bin'));
}
|
Set test width/height via attributes | package com.snowble.android.verticalstepper;
import android.app.Activity;
import org.robolectric.Robolectric;
public class RobolectricTestUtils {
public static VerticalStepper.LayoutParams createTestLayoutParams(Activity activity,
int leftMargin, int topMargin,
int rightMargin, int bottomMargin) {
VerticalStepper.LayoutParams lp = createTestLayoutParams(activity);
lp.leftMargin = leftMargin;
lp.topMargin = topMargin;
lp.rightMargin = rightMargin;
lp.bottomMargin = bottomMargin;
return lp;
}
public static VerticalStepper.LayoutParams createTestLayoutParams(Activity activity) {
Robolectric.AttributeSetBuilder attributeSetBuilder = Robolectric.buildAttributeSet();
attributeSetBuilder.addAttribute(android.R.attr.layout_width, "match_parent");
attributeSetBuilder.addAttribute(android.R.attr.layout_height, "wrap_content");
attributeSetBuilder.addAttribute(R.attr.step_title, "title");
VerticalStepper.LayoutParams lp =
new VerticalStepper.LayoutParams(activity, attributeSetBuilder.build());
return lp;
}
}
| package com.snowble.android.verticalstepper;
import android.app.Activity;
import org.robolectric.Robolectric;
public class RobolectricTestUtils {
public static VerticalStepper.LayoutParams createTestLayoutParams(Activity activity,
int leftMargin, int topMargin,
int rightMargin, int bottomMargin) {
VerticalStepper.LayoutParams lp = createTestLayoutParams(activity);
lp.leftMargin = leftMargin;
lp.topMargin = topMargin;
lp.rightMargin = rightMargin;
lp.bottomMargin = bottomMargin;
return lp;
}
public static VerticalStepper.LayoutParams createTestLayoutParams(Activity activity) {
Robolectric.AttributeSetBuilder attributeSetBuilder = Robolectric.buildAttributeSet();
attributeSetBuilder.addAttribute(android.R.attr.layout_width, "wrap_content");
attributeSetBuilder.addAttribute(android.R.attr.layout_height, "wrap_content");
attributeSetBuilder.addAttribute(R.attr.step_title, "title");
VerticalStepper.LayoutParams lp =
new VerticalStepper.LayoutParams(activity, attributeSetBuilder.build());
lp.width = VerticalStepper.LayoutParams.MATCH_PARENT;
lp.height = VerticalStepper.LayoutParams.WRAP_CONTENT;
return lp;
}
}
|
Ch03: Declare Meta class in NewsLink model. [skip ci] | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config.')
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Startup(models.Model):
name = models.CharField(
max_length=31, db_index=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config.')
description = models.TextField()
founded_date = models.DateField(
'date founded')
contact = models.EmailField()
website = models.URLField(max_length=255)
tags = models.ManyToManyField(Tag)
class Meta:
ordering = ['name']
get_latest_by = 'founded_date'
def __str__(self):
return self.name
class NewsLink(models.Model):
title = models.CharField(max_length=63)
pub_date = models.DateField('date published')
link = models.URLField(max_length=255)
startup = models.ForeignKey(Startup)
class Meta:
verbose_name = 'news article'
ordering = ['-pub_date']
get_latest_by = 'pub_date'
def __str__(self):
return "{}: {}".format(
self.startup, self.title)
| from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config.')
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Startup(models.Model):
name = models.CharField(
max_length=31, db_index=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config.')
description = models.TextField()
founded_date = models.DateField(
'date founded')
contact = models.EmailField()
website = models.URLField(max_length=255)
tags = models.ManyToManyField(Tag)
class Meta:
ordering = ['name']
get_latest_by = 'founded_date'
def __str__(self):
return self.name
class NewsLink(models.Model):
title = models.CharField(max_length=63)
pub_date = models.DateField('date published')
link = models.URLField(max_length=255)
startup = models.ForeignKey(Startup)
def __str__(self):
return "{}: {}".format(
self.startup, self.title)
|
Update expected number of metrics | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.statistics.ContainerWatchdogMetrics;
import org.junit.Test;
import java.lang.management.ManagementFactory;
import java.time.Duration;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author bjorncs
*/
public class MetricUpdaterTest {
@Test
public void metrics_are_updated_in_scheduler_cycle() {
int gcCount = ManagementFactory.getGarbageCollectorMXBeans().size();
Metric metric = mock(Metric.class);
ContainerWatchdogMetrics containerWatchdogMetrics = mock(ContainerWatchdogMetrics.class);
new MetricUpdater(new MockScheduler(), metric, containerWatchdogMetrics);
verify(containerWatchdogMetrics, times(1)).emitMetrics(any());
verify(metric, times(9 + 2 * gcCount)).set(anyString(), any(), any());
}
private static class MockScheduler implements MetricUpdater.Scheduler {
@Override
public void schedule(Runnable runnable, Duration frequency) {
runnable.run();
}
@Override
public void cancel() {}
}
}
| // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.statistics.ContainerWatchdogMetrics;
import org.junit.Test;
import java.lang.management.ManagementFactory;
import java.time.Duration;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author bjorncs
*/
public class MetricUpdaterTest {
@Test
public void metrics_are_updated_in_scheduler_cycle() throws InterruptedException {
int gcCount = ManagementFactory.getGarbageCollectorMXBeans().size();
Metric metric = mock(Metric.class);
ContainerWatchdogMetrics containerWatchdogMetrics = mock(ContainerWatchdogMetrics.class);
new MetricUpdater(new MockScheduler(), metric, containerWatchdogMetrics);
verify(containerWatchdogMetrics, times(1)).emitMetrics(any());
verify(metric, times(5 + 2 * gcCount)).set(anyString(), any(), any());
}
private static class MockScheduler implements MetricUpdater.Scheduler {
@Override
public void schedule(Runnable runnable, Duration frequency) {
runnable.run();
}
@Override
public void cancel() {}
}
}
|
Fix an issue where binding the command would fail | <?php
namespace Spatie\MediaLibrary;
use Illuminate\Support\ServiceProvider;
use Spatie\MediaLibrary\Commands\RegenerateCommand;
class MediaLibraryServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*/
public function boot()
{
Media::observe(new MediaObserver());
$this->publishes([
__DIR__.'/../resources/config/laravel-medialibrary.php' => $this->app->configPath().'/'.'laravel-medialibrary.php',
], 'config');
if (!class_exists('CreateMediaTable')) {
// Publish the migration
$timestamp = date('Y_m_d_His', time());
$this->publishes([
__DIR__.'/../resources/migrations/create_media_table.php.stub' => $this->app->basePath().'/'.'database/migrations/'.$timestamp.'_create_media_table.php',
], 'migrations');
}
}
/**
* Register the service provider.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../resources/config/laravel-medialibrary.php', 'laravel-medialibrary');
$this->app->singleton(MediaRepository::class);
$this->app->bind('command.medialibrary:regenerate', RegenerateCommand::class);
$this->commands(['command.medialibrary:regenerate']);
}
}
| <?php
namespace Spatie\MediaLibrary;
use Illuminate\Support\ServiceProvider;
use Spatie\MediaLibrary\Commands\RegenerateCommand;
class MediaLibraryServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*/
public function boot()
{
Media::observe(new MediaObserver());
$this->publishes([
__DIR__.'/../resources/config/laravel-medialibrary.php' => $this->app->configPath().'/'.'laravel-medialibrary.php',
], 'config');
if (!class_exists('CreateMediaTable')) {
// Publish the migration
$timestamp = date('Y_m_d_His', time());
$this->publishes([
__DIR__.'/../resources/migrations/create_media_table.php.stub' => $this->app->basePath().'/'.'database/migrations/'.$timestamp.'_create_media_table.php',
], 'migrations');
}
}
/**
* Register the service provider.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../resources/config/laravel-medialibrary.php', 'laravel-medialibrary');
$this->app->singleton(MediaRepository::class);
$this->app['command.medialibrary:regenerate'] = $this->app->make(RegenerateCommand::class);
$this->commands(['command.medialibrary:regenerate']);
}
}
|
Add shadow changing support according to our new passwd. | #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 8:
keys_file = _args[1]
passwd_orig = _args[2]
passwd_new = _args[3]
passwd_log = _args[4]
shadow_orig = _args[5]
shadow_new = _args[6]
shadow_log = _args[7]
try:
with open(keys_file, 'r') as k:
keys = k.readlines()
keys = [key.strip().split('@')[0] for key in keys]
keys = [key for key in keys if key != '']
with open(passwd_orig, 'r') as po:
passwd_lines = po.readlines()
passwd_log = open(passwd_log, 'w')
passwd_new_keys = []
with open(passwd_new, 'w') as pn:
for line in passwd_lines:
if line.split(':')[0] in keys or \
line.split(':')[3] != '12':
pn.write(line)
passwd_new_keys.append(line.split(':')[0])
else:
passwd_log.write(line)
passwd_log.close()
with open(shadow_orig, 'r') as so:
shadow_lines = so.readlines()
shadow_log = open(shadow_log, 'w')
with open(shadow_new, 'w') as sn:
for line in shadow_lines:
if line.split(':')[0] in passwd_new_keys:
sn.write(line)
else:
shadow_log.write(line)
shadow_log.close()
except Exception as e:
print(str(e))
sys.exit()
else:
print('==================================================')
print('python passwd_change.py keys passwd passwd_new passwd_log' +
' shadow shadow_new shadow_log')
print('==================================================')
| #!/usr/bin/env python3
import sys
_args = sys.argv
if __name__ == "__main__":
if len(_args) == 5:
keys_file = _args[1]
target_file = _args[2]
result_file = _args[3]
log_file = _args[4]
try:
with open(keys_file, 'r') as k:
keys = k.readlines()
keys = [key.strip().split('@')[0] for key in keys]
keys = [key for key in keys if key != '']
with open(target_file, 'r') as t:
target_lines = t.readlines()
log = open(log_file, 'w')
with open(result_file, 'w') as r:
for line in target_lines:
if line.split(':')[0] in keys or \
line.split(':')[3] != '12':
r.write(line)
else:
log.write(line)
log.close()
except Exception as e:
print(str(e))
sys.exit()
else:
print('==================================================')
print('python passwd_change.py keys passwd passwd_new log')
print('==================================================')
|
Make "No Attribute Aggregation for $SP" log message level info.
This is a common case so not really deserving of notice status. | <?php
class EngineBlock_Corto_Filter_Command_AttributeAggregator extends EngineBlock_Corto_Filter_Command_Abstract
{
/**
* This command may modify the response attributes
*
* @return array
*/
public function getResponseAttributes()
{
return $this->_responseAttributes;
}
public function execute()
{
$logger = EngineBlock_ApplicationSingleton::getLog();
$serviceProvider = EngineBlock_SamlHelper::findRequesterServiceProvider(
$this->_serviceProvider,
$this->_request,
$this->_server->getRepository()
);
if (!$serviceProvider) {
$serviceProvider = $this->_serviceProvider;
}
if (!$serviceProvider->attributeAggregationRequired) {
$logger->info("No Attribute Aggregation for " . $serviceProvider->entityId);
return;
}
$spEntityId = $serviceProvider->entityId;
$logger->notice("Attribute Aggregation for $spEntityId");
$aggregator = $this->_getAggregator();
$aggregations = $aggregator->aggregate(
$this->_collabPersonId,
$spEntityId,
$this->_responseAttributes
);
$this->_responseAttributes = array_merge($this->_responseAttributes, $aggregations);
}
/**
* @return EngineBlock_AttributeAggregation_Aggregator
*/
protected function _getAggregator()
{
return new AttributeAggregation_Client(EngineBlock_ApplicationSingleton::getInstance()->getConfiguration());
}
}
| <?php
class EngineBlock_Corto_Filter_Command_AttributeAggregator extends EngineBlock_Corto_Filter_Command_Abstract
{
/**
* This command may modify the response attributes
*
* @return array
*/
public function getResponseAttributes()
{
return $this->_responseAttributes;
}
public function execute()
{
$logger = EngineBlock_ApplicationSingleton::getLog();
$serviceProvider = EngineBlock_SamlHelper::findRequesterServiceProvider(
$this->_serviceProvider,
$this->_request,
$this->_server->getRepository()
);
if (!$serviceProvider) {
$serviceProvider = $this->_serviceProvider;
}
if (!$serviceProvider->attributeAggregationRequired) {
$logger->notice("No Attribute Aggregation for " . $serviceProvider->entityId);
return;
}
$spEntityId = $serviceProvider->entityId;
$logger->notice("Attribute Aggregation for $spEntityId");
$aggregator = $this->_getAggregator();
$aggregations = $aggregator->aggregate(
$this->_collabPersonId,
$spEntityId,
$this->_responseAttributes
);
$this->_responseAttributes = array_merge($this->_responseAttributes, $aggregations);
}
/**
* @return EngineBlock_AttributeAggregation_Aggregator
*/
protected function _getAggregator()
{
return new AttributeAggregation_Client(EngineBlock_ApplicationSingleton::getInstance()->getConfiguration());
}
}
|
Revert reduced failure level for try. | package mb.statix.constraints.messages;
import java.util.Map;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableMap;
import mb.statix.constraints.CAstId;
import mb.statix.constraints.CAstProperty;
import mb.statix.constraints.CTry;
import mb.statix.solver.IConstraint;
public class MessageUtil {
// @formatter:off
private static Map<Class<? extends IConstraint>, MessageKind> KINDS =
ImmutableMap.<Class<? extends IConstraint>, MessageKind>builder()
.put(CAstId.class, MessageKind.WARNING)
.put(CAstProperty.class, MessageKind.WARNING)
.build();
// @formatter:on
public static IMessage findClosestMessage(IConstraint c) {
return findClosestMessage(c, KINDS.getOrDefault(c.getClass(), MessageKind.ERROR));
}
/**
* Find closest message in the
*/
public static IMessage findClosestMessage(IConstraint c, MessageKind kind) {
@Nullable IMessage message = null;
while(c != null) {
@Nullable IMessage m;
if((m = c.message().orElse(null)) != null && (message == null || message.kind().isWorseThan(m.kind()))) {
message = m;
}
c = c.cause().orElse(null);
}
if(message == null) {
message = new Message(kind);
}
return message;
}
}
| package mb.statix.constraints.messages;
import java.util.Map;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableMap;
import mb.statix.constraints.CAstId;
import mb.statix.constraints.CAstProperty;
import mb.statix.constraints.CTry;
import mb.statix.solver.IConstraint;
public class MessageUtil {
// @formatter:off
private static Map<Class<? extends IConstraint>, MessageKind> KINDS =
ImmutableMap.<Class<? extends IConstraint>, MessageKind>builder()
.put(CAstId.class, MessageKind.WARNING)
.put(CAstProperty.class, MessageKind.WARNING)
.put(CTry.class, MessageKind.WARNING)
.build();
// @formatter:on
public static IMessage findClosestMessage(IConstraint c) {
return findClosestMessage(c, KINDS.getOrDefault(c.getClass(), MessageKind.ERROR));
}
/**
* Find closest message in the
*/
public static IMessage findClosestMessage(IConstraint c, MessageKind kind) {
@Nullable IMessage message = null;
while(c != null) {
@Nullable IMessage m;
if((m = c.message().orElse(null)) != null && (message == null || message.kind().isWorseThan(m.kind()))) {
message = m;
}
c = c.cause().orElse(null);
}
if(message == null) {
message = new Message(kind);
}
return message;
}
}
|
Remove a legacy Markdown extension when generating e-mails.
The recent updates for using Python-Markdown 3.x removed the
`smart_strong` extension from the main Markdown procssing, but failed to
remove it for the list of extensions used in e-mails. This is a trivial
change that simply removes that entry. | from __future__ import unicode_literals
import markdown
from django import template
from django.utils.safestring import mark_safe
from djblets.markdown import markdown_unescape
register = template.Library()
@register.filter
def markdown_email_html(text, is_rich_text):
if not is_rich_text:
return text
# We use XHTML1 instead of HTML5 to ensure the results can be parsed by
# an XML parser. This is actually needed for the main Markdown renderer
# for the web UI, but consistency is good here.
return mark_safe(markdown.markdown(
text,
output_format='xhtml1',
extensions=[
'markdown.extensions.fenced_code',
'markdown.extensions.codehilite',
'markdown.extensions.tables',
'markdown.extensions.sane_lists',
'pymdownx.tilde',
'djblets.markdown.extensions.escape_html',
'djblets.markdown.extensions.wysiwyg_email',
],
extension_configs={
'codehilite': {
'noclasses': True,
},
}))
@register.filter
def markdown_email_text(text, is_rich_text):
if not is_rich_text:
return text
return markdown_unescape(text)
| from __future__ import unicode_literals
import markdown
from django import template
from django.utils.safestring import mark_safe
from djblets.markdown import markdown_unescape
register = template.Library()
@register.filter
def markdown_email_html(text, is_rich_text):
if not is_rich_text:
return text
# We use XHTML1 instead of HTML5 to ensure the results can be parsed by
# an XML parser. This is actually needed for the main Markdown renderer
# for the web UI, but consistency is good here.
return mark_safe(markdown.markdown(
text,
output_format='xhtml1',
extensions=[
'markdown.extensions.fenced_code',
'markdown.extensions.codehilite',
'markdown.extensions.tables',
'markdown.extensions.sane_lists',
'markdown.extensions.smart_strong',
'pymdownx.tilde',
'djblets.markdown.extensions.escape_html',
'djblets.markdown.extensions.wysiwyg_email',
],
extension_configs={
'codehilite': {
'noclasses': True,
},
}))
@register.filter
def markdown_email_text(text, is_rich_text):
if not is_rich_text:
return text
return markdown_unescape(text)
|
Fix bug that make go back in browserhistory to fail | var React = require('react');
var Link = require('react-router').Link;
var Login = require('./sidebar/login');
var Highscore = require('./sidebar/highscore');
module.exports = React.createClass({
getInitialState: function () {
return { message: '' };
},
componentWillMount: function () {
if (this.props.message && this.props.message[0]) {
this.setState({ message: this.props.message[0] });
}
},
render: function () {
// Display flash messages
var message = '';
if (this.state.message !== '') {
message = <div id="flash-message">{this.state.message}</div>;
}
// TODO Rename #games to something better!
return (
<div>
<header>
<Link to="index"><h1>{this.props.page_title}</h1></Link>
<p>{this.props.page_description}</p>
</header>
<main id="main">
<div id="games">
{message}
{this.props.children}
</div>
<aside id="sidebar">
<Login user={this.props.user} />
<Highscore title="Highscore" />
</aside>
</main>
<footer id="footer">Webbplatsen är skapad av <a href="http://christiann.se">Christian Nilsson</a> och koden finns på <a href="https://github.com/klambycom/Skissa-och-gissa/">Github</a>.</footer>
</div>
);
}
});
| var React = require('react');
var Link = require('react-router').Link;
var Login = require('./sidebar/login');
var Highscore = require('./sidebar/highscore');
module.exports = React.createClass({
getInitialState: function () {
return { message: '' };
},
componentWillMount: function () {
if (typeof this.props.message[0] !== 'undefined') {
this.setState({ message: this.props.message[0] });
}
},
render: function () {
// Display flash messages
var message = '';
if (this.state.message !== '') {
message = <div id="flash-message">{this.state.message}</div>;
}
// TODO Rename #games to something better!
return (
<div>
<header>
<Link to="index"><h1>{this.props.page_title}</h1></Link>
<p>{this.props.page_description}</p>
</header>
<main id="main">
<div id="games">
{message}
{this.props.children}
</div>
<aside id="sidebar">
<Login user={this.props.user} />
<Highscore title="Highscore" />
</aside>
</main>
<footer id="footer">Webbplatsen är skapad av <a href="http://christiann.se">Christian Nilsson</a> och koden finns på <a href="https://github.com/klambycom/Skissa-och-gissa/">Github</a>.</footer>
</div>
);
}
});
|
Fix Translate HOC imbrication for tests | import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import RaisedButton from 'material-ui/RaisedButton';
import ContentSave from 'material-ui/svg-icons/content/save';
import CircularProgress from 'material-ui/CircularProgress';
import Translate from '../../i18n/Translate';
class SaveButton extends Component {
handleClick = (e) => {
if (this.props.saving) {
// prevent double submission
e.preventDefault();
}
}
render() {
const { saving, label = 'aor.action.save', translate } = this.props;
return <RaisedButton
type="submit"
label={translate(label)}
icon={saving ? <CircularProgress size={25} thickness={2} /> : <ContentSave />}
onClick={this.handleClick}
primary={!saving}
style={{
margin: '10px 24px',
position: 'relative',
}}
/>;
}
}
SaveButton.propTypes = {
label: PropTypes.string,
saving: PropTypes.bool,
translate: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
saving: state.admin.saving,
});
export default connect(mapStateToProps)(Translate(SaveButton));
| import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import RaisedButton from 'material-ui/RaisedButton';
import ContentSave from 'material-ui/svg-icons/content/save';
import CircularProgress from 'material-ui/CircularProgress';
import Translate from '../../i18n/Translate';
class SaveButton extends Component {
handleClick = (e) => {
if (this.props.saving) {
// prevent double submission
e.preventDefault();
}
}
render() {
const { saving, label = 'aor.action.save', translate } = this.props;
return <RaisedButton
type="submit"
label={translate(label)}
icon={saving ? <CircularProgress size={25} thickness={2} /> : <ContentSave />}
onClick={this.handleClick}
primary={!saving}
style={{
margin: '10px 24px',
position: 'relative',
}}
/>;
}
}
SaveButton.propTypes = {
label: PropTypes.string,
saving: PropTypes.bool,
translate: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
saving: state.admin.saving,
});
export default Translate(connect(mapStateToProps)(SaveButton));
|
Add a test for the character fetching | <?php namespace Destiny;
class ClientTest extends TestCase {
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* Test fetching an Xbox player.
*
* @throws \Exception
*/
public function testFetchXboxPlayer()
{
$player = $this->destiny->fetchXboxPlayer('aFreshMelon');
$this->assertInstanceOf('Destiny\Game\Player', $player);
}
/**
* Test fetching a PSN player.
*
* @throws \Exception
*/
public function testFetchPsnPlayer()
{
$player = $this->destiny->fetchPsnPlayer('Chrakker');
$this->assertInstanceOf('Destiny\Game\Player', $player);
}
/**
* Test whether characters are being fetched.
*
* @throws \Exception
*/
public function testAutomaticCharacterFetching()
{
$this->assertInstanceOf('Destiny\Game\CharacterCollection', $this->player->characters);
$this->assertInstanceOf('Destiny\Game\Character', $this->player->characters->first());
}
/**
* Test the example in the readme.
*/
public function testExampleInReadme()
{
$firstCharacter = $this->player->characters->first();
$this->assertInstanceOf('Destiny\Game\Character', $this->player->characters->get(0));
$this->assertInternalType('int', $firstCharacter->characterLevel);
}
}
| <?php namespace Destiny;
class ClientTest extends TestCase {
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* Test fetching an Xbox player.
*
* @throws \Exception
*/
public function testFetchXboxPlayer()
{
$player = $this->destiny->fetchXboxPlayer('aFreshMelon');
$this->assertInstanceOf('Destiny\Game\Player', $player);
}
/**
* Test fetching a PSN player.
*
* @throws \Exception
*/
public function testFetchPsnPlayer()
{
$player = $this->destiny->fetchPsnPlayer('Chrakker');
$this->assertInstanceOf('Destiny\Game\Player', $player);
}
/**
* Test whether characters are being fetched.
*
* @throws \Exception
*/
public function testAutomaticCharacterFetching()
{
$this->assertInstanceOf('Destiny\Game\CharacterCollection', $this->player->characters);
}
/**
* Test the example in the readme.
*/
public function testExampleInReadme()
{
$firstCharacter = $this->player->characters->first();
$this->assertInstanceOf('Destiny\Game\Character', $this->player->characters->get(0));
$this->assertInternalType('int', $firstCharacter->characterLevel);
}
}
|
Make rethrow chain a Function | package throwing.bridge;
import java.util.Optional;
import java.util.function.Function;
@FunctionalInterface
interface RethrowChain<X extends Throwable, Y extends Throwable> extends Function<X, Optional<Y>> {
public static final RethrowChain<Throwable, Throwable> START = t -> Optional.empty();
public static final RethrowChain<Throwable, Throwable> END = t -> {
if (t instanceof Error) {
throw (Error) t;
} else if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new AssertionError(t);
}
};
@SuppressWarnings("unchecked")
public static <X extends Throwable, Y extends Throwable> RethrowChain<X, Y> start() {
return (RethrowChain<X, Y>) START;
}
@SuppressWarnings("unchecked")
public static <X extends Throwable, Y extends Throwable> RethrowChain<X, Y> end() {
return (RethrowChain<X, Y>) END;
}
default public <Z extends Throwable> RethrowChain<X, Z> rethrow(Function<? super Y, ? extends Z> mapper) {
return t -> apply(t).map(mapper);
}
default public RethrowChain<X, Y> chain(RethrowChain<X, Y> second) {
return this == START ? second : t -> {
Optional<Y> o = apply(t);
return o.isPresent() ? o : second.apply(t);
};
};
default public Function<X, Y> finish() {
RethrowChain<X, Y> c = this.chain(end());
return t -> c.apply(t).get();
}
}
| package throwing.bridge;
import java.util.Optional;
import java.util.function.Function;
@FunctionalInterface
interface RethrowChain<X extends Throwable, Y extends Throwable> {
public static final RethrowChain<Throwable, Throwable> START = t -> Optional.empty();
public static final RethrowChain<Throwable, Throwable> END = t -> {
if (t instanceof Error) {
throw (Error) t;
} else if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new AssertionError(t);
}
};
@SuppressWarnings("unchecked")
public static <X extends Throwable, Y extends Throwable> RethrowChain<X, Y> start() {
return (RethrowChain<X, Y>) START;
}
@SuppressWarnings("unchecked")
public static <X extends Throwable, Y extends Throwable> RethrowChain<X, Y> end() {
return (RethrowChain<X, Y>) END;
}
public Optional<Y> handle(X t);
default public <Z extends Throwable> RethrowChain<X, Z> rethrow(Function<? super Y, ? extends Z> mapper) {
return t -> this.handle(t).map(mapper);
}
default public RethrowChain<X, Y> chain(RethrowChain<X, Y> second) {
return this == START ? second : t -> {
Optional<Y> o = this.handle(t);
return o.isPresent() ? o : second.handle(t);
};
};
default public Function<X, Y> finish() {
return t -> this.chain(end()).handle(t).get();
}
}
|
Change to protected instead private
It's should be like this. No need to make function private. | <?php
namespace Eduardokum\LaravelMailAutoEmbed\Embedder;
use Swift_Image;
use Swift_Message;
use Swift_EmbeddedFile;
use Eduardokum\LaravelMailAutoEmbed\Models\EmbeddableEntity;
class AttachmentEmbedder extends Embedder
{
/**
* @var Swift_Message
*/
protected $message;
/**
* AttachmentEmbedder constructor.
* @param Swift_Message $message
*/
public function __construct(Swift_Message $message)
{
$this->message = $message;
}
/**
* @param string $url
*/
public function fromUrl($url)
{
$filePath = str_replace(url('/'), public_path('/'), $url);
if (!file_exists($filePath)) {
return $url;
}
return $this->embed(
Swift_Image::fromPath($filePath)
);
}
/**
* @param EmbeddableEntity $entity
*/
public function fromEntity(EmbeddableEntity $entity)
{
return $this->embed(
new Swift_EmbeddedFile(
$entity->getRawContent(),
$entity->getFileName(),
$entity->getMimeType()
)
);
}
/**
* @param Swift_EmbeddedFile $attachment
* @return string
*/
protected function embed(Swift_EmbeddedFile $attachment)
{
return $this->message->embed($attachment);
}
}
| <?php
namespace Eduardokum\LaravelMailAutoEmbed\Embedder;
use Eduardokum\LaravelMailAutoEmbed\Models\EmbeddableEntity;
use Swift_EmbeddedFile;
use Swift_Image;
use Swift_Message;
class AttachmentEmbedder extends Embedder
{
/**
* @var Swift_Message
*/
private $message;
/**
* AttachmentEmbedder constructor.
* @param Swift_Message $message
*/
public function __construct(Swift_Message $message)
{
$this->message = $message;
}
/**
* @param string $url
*/
public function fromUrl($url)
{
$filePath = str_replace(url('/'), public_path('/'), $url);
if (!file_exists($filePath)) {
return $url;
}
return $this->embed(
Swift_Image::fromPath($filePath)
);
}
/**
* @param EmbeddableEntity $entity
*/
public function fromEntity(EmbeddableEntity $entity)
{
return $this->embed(
new Swift_EmbeddedFile(
$entity->getRawContent(),
$entity->getFileName(),
$entity->getMimeType()
)
);
}
/**
* @param Swift_EmbeddedFile $attachment
* @return string
*/
private function embed(Swift_EmbeddedFile $attachment)
{
return $this->message->embed($attachment);
}
}
|
Make function name more descriptive | /*
* ready
* Watch for when an element becomes available in the DOM
* @param {String} selector
* @param {Function} fn
*/
(function(win){
'use strict';
var listeners = [],
doc = win.document,
MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
observer;
function ready(selector, fn){
// Store the selector and callback to be monitored
listeners.push({
selector: selector,
fn: fn
});
if(!observer){
// Watch for changes in the document
observer = new MutationObserver(checkListeners);
observer.observe(doc.documentElement, {
childList: true,
subtree: true
});
}
// Check if the element is currently in the DOM
checkSelector(selector, fn);
}
function checkListeners(){
// Check the DOM for elements matching a stored selector
for(var i = 0, len = listeners.length, listener; i < len; i++){
listener = listeners[i];
checkSelector(listener.selector, listener.fn);
}
}
function checkSelector(selector, fn){
// Query for elements matching the specified selector
var elements = doc.querySelectorAll(selector), i = 0, len = elements.length, element;
for(; i < len; i++){
element = elements[i];
// Make sure the callback isn't invoked with the
// same element more than once
if(!element.ready){
element.ready = true;
// Invoke the callback with the element
fn.call(element, element);
}
}
}
// Expose `ready`
win.ready = ready;
})(this); | /*
* ready
* Watch for when an element becomes available in the DOM
* @param {String} selector
* @param {Function} fn
*/
(function(win){
'use strict';
var listeners = [],
doc = win.document,
MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
observer;
function ready(selector, fn){
// Store the selector and callback to be monitored
listeners.push({
selector: selector,
fn: fn
});
if(!observer){
// Watch for changes in the document
observer = new MutationObserver(checkListeners);
observer.observe(doc.documentElement, {
childList: true,
subtree: true
});
}
// Check if the element is currently in the DOM
check(selector, fn);
}
function checkListeners(){
// Check the DOM for elements matching a stored selector
for(var i = 0, len = listeners.length, listener; i < len; i++){
listener = listeners[i];
check(listener.selector, listener.fn);
}
}
function check(selector, fn){
// Query for elements matching the specified selector
var elements = doc.querySelectorAll(selector), i = 0, len = elements.length, element;
for(; i < len; i++){
element = elements[i];
// Make sure the callback isn't invoked with the
// same element more than once
if(!element.ready){
element.ready = true;
// Invoke the callback with the element
fn.call(element, element);
}
}
}
// Expose `ready`
win.ready = ready;
})(this); |
Fix publishing im.php file to config folder | <?php
namespace CTL\XMPPMessageBase;
use BirknerAlex\XMPPHP\XMPP;
use Illuminate\Support\ServiceProvider;
class IMServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->publishFiles();
}
/**
* Publishes files that package needs
*/
public function publishFiles(){
$this->publishes([
__DIR__.'/config/im.php' => config_path('im.php'),
]);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('IM', function(){
// Configuration variables for XMPP
$host = config('services.xmpp.host');
$port = config('services.xmpp.port');
$user = config('services.xmpp.user');
$password = config('services.xmpp.password');
$resource = \Session::getId();
$im = new XMPP(
$host, $port, $user, $password, $resource
);
$im->connect();
$im->processUntil('session_started', 1);
return $im;
});
}
/**
* [provides description]
* @return void
*/
public function provides(){
return ['IM'];
}
}
| <?php
namespace CTL\XMPPMessageBase;
use BirknerAlex\XMPPHP\XMPP;
use Illuminate\Support\ServiceProvider;
class IMServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/config/im.php' => base_path('config'),
]);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('IM', function(){
// Configuration variables for XMPP
$host = config('services.xmpp.host');
$port = config('services.xmpp.port');
$user = config('services.xmpp.user');
$password = config('services.xmpp.password');
$resource = \Session::getId();
$im = new XMPP(
$host, $port, $user, $password, $resource
);
$im->connect();
$im->processUntil('session_started', 1);
return $im;
});
}
/**
* [provides description]
* @return void
*/
public function provides(){
return ['IM'];
}
}
|
Fix generator path for service provider | <?php namespace Pingpong\Modules\Commands;
use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;
class GenerateProviderCommand extends GeneratorCommand {
use ModuleCommandTrait;
/**
* The console command name.
*
* @var string
*/
protected $name = 'module:provider';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a new service provider for the specified module.';
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('name', InputArgument::REQUIRED, 'The service provider name.'),
array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
);
}
/**
* @return mixed
*/
protected function getTemplateContents()
{
return new Stub('provider', [
'MODULE' => $this->getModuleName(),
'NAME' => $this->getFileName()
]);
}
/**
* @return mixed
*/
protected function getDestinationFilePath()
{
$path = $this->laravel['modules']->getModulePath($this->getModuleName());
$generatorPath = $this->laravel['modules']->config('paths.generator.provider');
return $path . $generatorPath . '/' . $this->getFileName() . '.php';
}
/**
* @return string
*/
private function getFileName()
{
return Str::studly($this->argument('name'));
}
}
| <?php namespace Pingpong\Modules\Commands;
use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;
class GenerateProviderCommand extends GeneratorCommand {
use ModuleCommandTrait;
/**
* The console command name.
*
* @var string
*/
protected $name = 'module:provider';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a new service provider for the specified module.';
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('name', InputArgument::REQUIRED, 'The service provider name.'),
array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
);
}
/**
* @return mixed
*/
protected function getTemplateContents()
{
return new Stub('provider', [
'MODULE' => $this->getModuleName(),
'NAME' => $this->getFileName()
]);
}
/**
* @return mixed
*/
protected function getDestinationFilePath()
{
$path = $this->laravel['modules']->getModulePath($this->getModuleName());
$generatorPath = $this->laravel['modules']->get('paths.generator.provider');
return $path . $generatorPath . '/' . $this->getFileName() . '.php';
}
/**
* @return string
*/
private function getFileName()
{
return Str::studly($this->argument('name'));
}
}
|
Change default debug behavior back to false | /**
* In-Memory configuration storage
*/
let Config = {
isInitialized: false,
debug: false,
overridePublishFunction: true,
mutationDefaults: {
pushToRedis: true,
optimistic: true,
},
passConfigDown: false,
redis: {
port: 6379,
host: '127.0.0.1',
},
globalRedisPrefix: '',
retryIntervalMs: 10000,
externalRedisPublisher: false,
redisExtras: {
retry_strategy: function(options) {
return Config.retryIntervalMs;
// reconnect after
// return Math.min(options.attempt * 100, 30000);
},
events: {
end(err) {
console.error('RedisOplog - Connection to redis ended');
},
error(err) {
console.error(
`RedisOplog - An error occured: \n`,
JSON.stringify(err)
);
},
connect(err) {
if (!err) {
console.log(
'RedisOplog - Established connection to redis.'
);
} else {
console.error(
'RedisOplog - There was an error when connecting to redis',
JSON.stringify(err)
);
}
},
reconnecting(err) {
if (err) {
console.error(
'RedisOplog - There was an error when re-connecting to redis',
JSON.stringify(err)
);
}
},
},
},
};
export default Config;
| /**
* In-Memory configuration storage
*/
let Config = {
isInitialized: false,
debug: true,
overridePublishFunction: true,
mutationDefaults: {
pushToRedis: true,
optimistic: true,
},
passConfigDown: false,
redis: {
port: 6379,
host: '127.0.0.1',
},
globalRedisPrefix: '',
retryIntervalMs: 10000,
externalRedisPublisher: false,
redisExtras: {
retry_strategy: function(options) {
return Config.retryIntervalMs;
// reconnect after
// return Math.min(options.attempt * 100, 30000);
},
events: {
end(err) {
console.error('RedisOplog - Connection to redis ended');
},
error(err) {
console.error(
`RedisOplog - An error occured: \n`,
JSON.stringify(err)
);
},
connect(err) {
if (!err) {
console.log(
'RedisOplog - Established connection to redis.'
);
} else {
console.error(
'RedisOplog - There was an error when connecting to redis',
JSON.stringify(err)
);
}
},
reconnecting(err) {
if (err) {
console.error(
'RedisOplog - There was an error when re-connecting to redis',
JSON.stringify(err)
);
}
},
},
},
};
export default Config;
|
Add a system to update service worker
sw.js | this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('learn-memory-1500879945180').then(function(cache) {
return cache.addAll([
'/',
'/stylesheets/styles.css',
'/views/lessons-list.html',
'/views/lessons-id.html',
'/javascripts/scripts.js',
'/langs/locale-en.json'
]);
})
);
});
this.addEventListener('fetch', function(event) {
if (event.request.method !== 'GET' || /authenticated/.test(event.request.url)) {
return;
}
var get = function () {
return fetch(event.request).then(function(response) {
return caches.open('learn-memory').then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
};
event.respondWith(
caches
.match(event.request)
.then(function(cached) {
// get the latest updates from API
if (/api/.test(event.request.url)) {
return get().catch(function () {
return cached;
});
}
// the cached value could be undefined
if (typeof cached == 'undefined') {
return get();
}
return cached;
})
.catch(get)
);
});
this.addEventListener('activate', function(event) {
var cacheWhitelist = ['learn-memory-1500879945180'];
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (cacheWhitelist.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
});
| this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('learn-memory').then(function(cache) {
return cache.addAll([
'/',
'/stylesheets/styles.css',
'/views/lessons-list.html',
'/views/lessons-id.html',
'/javascripts/scripts.js',
'/langs/locale-en.json'
]);
})
);
});
this.addEventListener('fetch', function(event) {
if (event.request.method !== 'GET' || /authenticated/.test(event.request.url)) {
return;
}
var get = function () {
return fetch(event.request).then(function(response) {
return caches.open('learn-memory').then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
};
event.respondWith(
caches
.match(event.request)
.then(function(cached) {
// get the latest updates from API
if (/api/.test(event.request.url)) {
return get().catch(function () {
return cached;
});
}
// the cached value could be undefined
if (typeof cached == 'undefined') {
return get();
}
return cached;
})
.catch(get)
);
});
|
Add test coverage for expected nutrient retrieval behaviour | import unittest
from recipe_scrapers._exceptions import SchemaOrgException
from recipe_scrapers._schemaorg import SchemaOrg
class TestSchemaOrg(unittest.TestCase):
def setUp(self):
with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata:
self.schema = SchemaOrg(pagedata.read())
def test_total_time_with_schema_missing_all_data_should_raise_exception(self):
keys = ["totalTime", "cookTime", "prepTime"]
for k in keys:
if k in self.schema.data:
del self.schema.data[k]
with self.assertRaises(SchemaOrgException):
self.assertEqual(self.schema.total_time(), None)
def test_total_time_with_schema__all_zeros(self):
keys = ["totalTime", "cookTime", "prepTime"]
for k in keys:
self.schema.data[k] = "PT0M"
self.assertEqual(self.schema.total_time(), 0)
del self.schema.data["totalTime"]
self.assertEqual(self.schema.total_time(), 0)
def test_nutrient_retrieval(self):
expected_nutrients = {
"calories": "240 calories",
"fatContent": "9 grams fat",
}
self.assertEqual(self.schema.nutrients(), expected_nutrients)
def test_graph_schema_without_context(self):
with open(
"tests/test_data/schemaorg_graph.testhtml", encoding="utf-8"
) as pagedata:
schema = SchemaOrg(pagedata.read())
self.assertNotEqual(schema.data, {})
| import unittest
from recipe_scrapers._exceptions import SchemaOrgException
from recipe_scrapers._schemaorg import SchemaOrg
class TestSchemaOrg(unittest.TestCase):
def setUp(self):
with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata:
self.schema = SchemaOrg(pagedata.read())
def test_total_time_with_schema_missing_all_data_should_raise_exception(self):
keys = ["totalTime", "cookTime", "prepTime"]
for k in keys:
if k in self.schema.data:
del self.schema.data[k]
with self.assertRaises(SchemaOrgException):
self.assertEqual(self.schema.total_time(), None)
def test_total_time_with_schema__all_zeros(self):
keys = ["totalTime", "cookTime", "prepTime"]
for k in keys:
self.schema.data[k] = "PT0M"
self.assertEqual(self.schema.total_time(), 0)
del self.schema.data["totalTime"]
self.assertEqual(self.schema.total_time(), 0)
def test_graph_schema_without_context(self):
with open(
"tests/test_data/schemaorg_graph.testhtml", encoding="utf-8"
) as pagedata:
schema = SchemaOrg(pagedata.read())
self.assertNotEqual(schema.data, {})
|
Support group_by, em and query_builder options in entity filter
Add support for group_by, em and query_builder options in DatagridFilterTypeEntity.
Allows custom sorting and grouping of data into the DatagridFilterTypeEntity filter type. | <?php
namespace Wanjee\Shuwee\AdminBundle\Datagrid\Filter\Type;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Doctrine\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectManager as LegacyObjectManager;
/**
* Class DatagridFilterTypeEntity
* @package Wanjee\Shuwee\AdminBundle\Datagrid\Filter\Type
*/
class DatagridFilterTypeEntity extends DatagridFilterType
{
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver
->setRequired(
[
'class',
]
)
->setDefined(
[
'choice_label',
'group_by',
'em',
'query_builder',
]
)
->setDefaults([
'placeholder' => 'All',
'group_by' => null,
'em' => null,
'query_builder' => null,
])
->setAllowedTypes('placeholder', ['string'])
->setAllowedTypes('class', ['string'])
->setAllowedTypes('choice_label', ['string', 'callable'])
->setAllowedTypes('group_by', ['null', 'string'])
->setAllowedTypes('em', ['null', 'string', ObjectManager::class, LegacyObjectManager::class])
->setAllowedTypes('query_builder', ['null', 'callable', 'Doctrine\ORM\QueryBuilder']);
}
/**
* @inheritdoc
*/
public function getFormType()
{
return EntityType::class;
}
/**
* @inheritdoc
*/
public function formatValue($rawValue)
{
return $rawValue;
}
/**
* @inheritdoc
*/
public function getCriteriaExpression()
{
return 'eq';
}
}
| <?php
namespace Wanjee\Shuwee\AdminBundle\Datagrid\Filter\Type;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Class DatagridFilterTypeEntity
* @package Wanjee\Shuwee\AdminBundle\Datagrid\Filter\Type
*/
class DatagridFilterTypeEntity extends DatagridFilterType
{
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver
->setRequired(
[
'class',
]
)
->setDefined(
[
'choice_label',
]
)
->setDefault('placeholder', 'All')
->setAllowedTypes('placeholder', ['string'])
->setAllowedTypes('class', ['string'])
->setAllowedTypes('choice_label', ['string', 'callable']);
}
/**
* @inheritdoc
*/
public function getFormType()
{
return EntityType::class;
}
/**
* @inheritdoc
*/
public function formatValue($rawValue)
{
return $rawValue;
}
/**
* @inheritdoc
*/
public function getCriteriaExpression()
{
return 'eq';
}
}
|
TEST for correct an with errors S06 report | from expects import expect, equal
from primestg.report import Report
from ast import literal_eval
with description('Report S06 example'):
with before.all:
self.data_filenames = [
'spec/data/S06.xml',
'spec/data/S06_with_error.xml',
# 'spec/data/S06_empty.xml'
]
self.report = []
for data_filename in self.data_filenames:
with open(data_filename) as data_file:
self.report.append(Report(data_file))
with it('generates the expected results for the whole report'):
result_filenames = []
warnings = []
for data_filename in self.data_filenames:
result_filenames.append('{}_result.txt'.format(data_filename))
for key, result_filename in enumerate(result_filenames):
result = []
with open(result_filename) as result_file:
result_string = result_file.read()
expected_result = literal_eval(result_string)
for cnc in self.report[key].concentrators:
if cnc.meters:
for meter in cnc.meters:
for value in meter.values:
result.append(value)
warnings.append(meter.warnings)
print('Result: {} \n Expected result: {} \n Warnings: {}'.format(
result, expected_result, warnings))
expect(result).to(equal(expected_result))
expected_warnings = [[], ["ERROR: Cnc(CIR4621704174), "
"Meter(ZIV42553686). Thrown exception: "
"object of type 'NoneType' has no len()"], []]
expect(warnings).to(equal(expected_warnings))
| from expects import expect, equal
from primestg.report import Report
from ast import literal_eval
with description('Report S06 example'):
with before.all:
self.data_filenames = [
'spec/data/S06.xml',
# 'spec/data/S06_empty.xml'
]
self.report = []
for data_filename in self.data_filenames:
with open(data_filename) as data_file:
self.report.append(Report(data_file))
with it('generates the expected results for the whole report'):
result_filenames = []
for data_filename in self.data_filenames:
result_filenames.append('{}_result.txt'.format(data_filename))
for key, result_filename in enumerate(result_filenames):
with open(result_filename) as result_file:
result_string = result_file.read()
expected_result = literal_eval(result_string)
result = self.report[key].values
expect(result).to(equal(expected_result))
# result_filename = '{}_result.txt'.format(self.data_filename)
#
# with open(result_filename) as result_file:
# result_string = result_file.read()
# self.expected_result = literal_eval(result_string)
#
# result = self.report.values
#
# expect(result).to(equal(self.expected_result))
|
Use the same headline as the API | #!/usr/bin/env python
"""Setup script for The Coverage Space CLI."""
import setuptools
from coveragespace import __project__, __version__, CLI
try:
README = open("README.rst").read()
CHANGES = open("CHANGES.rst").read()
except IOError:
DESCRIPTION = "<placeholder>"
else:
DESCRIPTION = README + '\n' + CHANGES
setuptools.setup(
name=__project__,
version=__version__,
description="A place to track your code coverage metrics.",
url='https://github.com/jacebrowning/coverage-space-cli',
author='Jace Browning',
author_email='[email protected]',
packages=setuptools.find_packages(),
entry_points={'console_scripts': [
CLI + ' = coveragespace.cli:main',
]},
long_description=(DESCRIPTION),
license='MIT',
classifiers=[
# TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 1 - Planning',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=open("requirements.txt").readlines(),
)
| #!/usr/bin/env python
"""Setup script for The Coverage Space CLI."""
import setuptools
from coveragespace import __project__, __version__, CLI
try:
README = open("README.rst").read()
CHANGES = open("CHANGES.rst").read()
except IOError:
DESCRIPTION = "<placeholder>"
else:
DESCRIPTION = README + '\n' + CHANGES
setuptools.setup(
name=__project__,
version=__version__,
description="Command-line client for The Coverage Space.",
url='https://github.com/jacebrowning/coverage-space-cli',
author='Jace Browning',
author_email='[email protected]',
packages=setuptools.find_packages(),
entry_points={'console_scripts': [
CLI + ' = coveragespace.cli:main',
]},
long_description=(DESCRIPTION),
license='MIT',
classifiers=[
# TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 1 - Planning',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=open("requirements.txt").readlines(),
)
|
Add logAndSendNotifications() to deploy script by default. | <?php
namespace DeltaCli\Extension;
use DeltaCli\Console\Output\Banner;
use DeltaCli\Project;
use DeltaCli\Script\InstallFsevents;
use DeltaCli\Script\SshFixKeyPermissions as SshFixKeyPermissionsScript;
use DeltaCli\Script\SshInstallKey as SshInstallKeyScript;
use Symfony\Component\Console\Output\OutputInterface;
class DefaultScripts implements ExtensionInterface
{
public function extend(Project $project)
{
$project->addScript(new InstallFsevents($project));
$project->addScript(new SshFixKeyPermissionsScript($project));
$project->addScript(new SshInstallKeyScript($project));
$project->createScript('deploy', 'Deploy this project.')
->requireEnvironment()
->addDefaultStep($project->gitStatusIsClean())
->addDefaultStep($project->gitBranchMatchesEnvironment())
->addDefaultStep($project->fixSshKeyPermissions())
->addDefaultStep($project->logAndSendNotifications())
->setPlaceholderCallback(
function (OutputInterface $output) {
$banner = new Banner($output);
$banner->setBackground('cyan');
$banner->render('A deploy script has not yet been created for this project.');
$output->writeln(
[
'Learn more about how to write a good deploy script for your project on Github at:',
'<fg=blue;options=underscore>https://github.com/DeltaSystems/delta-cli-tools</>'
]
);
}
);
}
}
| <?php
namespace DeltaCli\Extension;
use DeltaCli\Console\Output\Banner;
use DeltaCli\Project;
use DeltaCli\Script\InstallFsevents;
use DeltaCli\Script\SshFixKeyPermissions as SshFixKeyPermissionsScript;
use DeltaCli\Script\SshInstallKey as SshInstallKeyScript;
use Symfony\Component\Console\Output\OutputInterface;
class DefaultScripts implements ExtensionInterface
{
public function extend(Project $project)
{
$project->addScript(new InstallFsevents($project));
$project->addScript(new SshFixKeyPermissionsScript($project));
$project->addScript(new SshInstallKeyScript($project));
$project->createScript('deploy', 'Deploy this project.')
->requireEnvironment()
->addDefaultStep($project->gitStatusIsClean())
->addDefaultStep($project->gitBranchMatchesEnvironment())
->addDefaultStep($project->fixSshKeyPermissions())
->setPlaceholderCallback(
function (OutputInterface $output) {
$banner = new Banner($output);
$banner->setBackground('cyan');
$banner->render('A deploy script has not yet been created for this project.');
$output->writeln(
[
'Learn more about how to write a good deploy script for your project on Github at:',
'<fg=blue;options=underscore>https://github.com/DeltaSystems/delta-cli-tools</>'
]
);
}
);
}
}
|
Fix import error for program page test | from lib.constants.test import create_new_program
from lib.page import dashboard
from lib import base
class TestProgramPage(base.Test):
def create_private_program_test(self):
dashboard_page = dashboard.DashboardPage(self.driver)
dashboard_page.navigate_to()
lhn_menu = dashboard_page.open_lhn_menu()
lhn_menu.select_all_objects()
program_dropdown = lhn_menu.open_programs()
new_program_page = program_dropdown.open_create_new_program()
new_program_page.enter_title(create_new_program.TEST_TITLE)
new_program_page.enter_description(create_new_program.TEST_DESCRIPTION)
new_program_page.enter_notes(create_new_program.TEST_NOTES)
new_program_page.enter_code(create_new_program.TEST_CODE)
new_program_page.checkbox_check_private_program()
new_program_page.enter_primary_contact(
create_new_program.TEST_PRIMARY_CONTACT
)
new_program_page.enter_secondary_contact(
create_new_program.TEST_SECONDARY_CONTACT
)
new_program_page.enter_program_url(create_new_program.TEST_PROGRAM_URL)
new_program_page.enter_reference_url(
create_new_program.TEST_REFERENCE_URL
)
new_program_page.enter_effective_date_start_month()
new_program_page.enter_stop_date_end_month()
new_program_page.save_and_close()
| from lib.constants.test import create_new_program
from lib import base, page
class TestProgramPage(base.Test):
def create_private_program_test(self):
dashboard = page.dashboard.DashboardPage(self.driver)
dashboard.navigate_to()
lhn_menu = dashboard.open_lhn_menu()
lhn_menu.select_all_objects()
program_dropdown = lhn_menu.open_programs()
new_program_page = program_dropdown.open_create_new_program()
new_program_page.enter_title(create_new_program.TEST_TITLE)
new_program_page.enter_description(create_new_program.TEST_DESCRIPTION)
new_program_page.enter_notes(create_new_program.TEST_NOTES)
new_program_page.enter_code(create_new_program.TEST_CODE)
new_program_page.checkbox_check_private_program()
new_program_page.enter_primary_contact(
create_new_program.TEST_PRIMARY_CONTACT
)
new_program_page.enter_secondary_contact(
create_new_program.TEST_SECONDARY_CONTACT
)
new_program_page.enter_program_url(create_new_program.TEST_PROGRAM_URL)
new_program_page.enter_reference_url(
create_new_program.TEST_REFERENCE_URL
)
new_program_page.enter_effective_date_start_month()
new_program_page.enter_stop_date_end_month()
new_program_page.save_and_close()
|
Fix since_id when calling Tweets.more() | YUI.add("model-list-tweets", function(Y) {
"use strict";
var tristis = Y.namespace("Tristis"),
models = Y.namespace("Tristis.Models"),
Tweets;
Tweets = Y.Base.create("tweets", Y.LazyModelList, [
Y.namespace("Extensions").ModelListMore
], {
sync : function(action, options, done) {
var args = {};
if(action === "more") {
if(this.size()) {
args.since_id = this.item(0).id_str;
}
}
args = Y.merge(
{ count : 50 },
this.get("config") || {},
args
);
tristis.twitter.get(this.get("api"), args, done);
},
// Sort tweets by date
comparator : function(model) {
return Date.parse(model.created_at);
},
// Sort tweets by newest first
_compare : function(a, b) {
return b - a;
}
}, {
ATTRS : {
api : null,
config : null
}
});
models.Tweets = Tweets;
}, "@VERSION@", {
requires : [
// YUI
"base-build",
"lazy-model-list",
// Extensions
"extension-model-list-more"
]
});
| YUI.add("model-list-tweets", function(Y) {
"use strict";
var tristis = Y.namespace("Tristis"),
models = Y.namespace("Tristis.Models"),
Tweets;
Tweets = Y.Base.create("tweets", Y.LazyModelList, [
Y.namespace("Extensions").ModelListMore
], {
sync : function(action, options, done) {
var args = {},
last;
if(action === "more") {
last = this.item(this.size() - 1);
if(last) {
args.since_id = last.id_str;
}
}
args = Y.merge(
{ count : 50 },
this.get("config") || {},
args
);
tristis.twitter.get(this.get("api"), args, done);
},
// Sort tweets by date
comparator : function(model) {
return Date.parse(model.created_at);
},
// Sort tweets by newest first
_compare : function(a, b) {
return b - a;
}
}, {
ATTRS : {
api : null,
config : null
}
});
models.Tweets = Tweets;
}, "@VERSION@", {
requires : [
// YUI
"base-build",
"lazy-model-list",
// Extensions
"extension-model-list-more"
]
});
|
Make the service worker get the payload from the server if the push message didn't contain any | importScripts('localforage.min.js');
self.addEventListener('push', function(event) {
function getPayload() {
if (event.data) {
return Promise.resolve(event.data.json());
} else {
return fetch('./getPayload')
.then(function(response) {
return response.json();
});
}
}
event.waitUntil(
getPayload()
.then(function(data) {
var title = data ? data.title : 'Mercurius';
var body = data ? data.body : 'Notification';
event.waitUntil(self.registration.showNotification(title, {
body: body,
}));
})
);
});
self.addEventListener('pushsubscriptionchange', function(event) {
event.waitUntil(
localforage.getItem('token')
.then(function(token) {
if (!token) {
return;
}
localforage.getItem('machineId')
.then(function(machineId) {
return self.registration.pushManager.subscribe({ userVisibleOnly: true })
.then(function(subscription) {
var key = subscription.getKey ? subscription.getKey('p256dh') : '';
return fetch('./updateRegistration', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
token: token,
machineId: machineId,
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : '',
}),
});
});
});
})
);
});
| importScripts('localforage.min.js');
self.addEventListener('push', function(event) {
var data = event.data ? event.data.json() : null;
var title = data ? data.title : 'Mercurius';
var body = data ? data.body : 'Notification';
event.waitUntil(self.registration.showNotification(title, {
body: body,
}));
});
self.addEventListener('pushsubscriptionchange', function(event) {
event.waitUntil(
localforage.getItem('token')
.then(function(token) {
if (!token) {
return;
}
localforage.getItem('machineId')
.then(function(machineId) {
return self.registration.pushManager.subscribe({ userVisibleOnly: true })
.then(function(subscription) {
var key = subscription.getKey ? subscription.getKey('p256dh') : '';
return fetch('./updateRegistration', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
token: token,
machineId: machineId,
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : '',
}),
});
});
});
})
);
});
|
Use new translated string placeholder style | # coding: utf-8
from django.conf import settings
from django.utils.translation import gettext as _
from rest_framework import exceptions
from onadata.apps.main.models.user_profile import UserProfile
class MFABlockerMixin:
def validate_mfa_not_active(self, user: 'auth.User'):
"""
Raise an exception if MFA is enabled for user's account.
"""
# This condition is kind of temporary. We can activate/deactivate
# class based on settings. Useful until we decide whether
# TokenAuthentication should be deactivated with MFA
# ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged
class_path = f'{self.__module__}.{self.__class__.__name__}'
if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES:
try:
is_mfa_active = user.profile.is_mfa_active
except UserProfile.DoesNotExist:
pass
else:
if is_mfa_active:
raise exceptions.AuthenticationFailed(_(
'Multi-factor authentication is enabled for this '
'account. ##authentication class## cannot be used.'
).replace('##authentication class##', self.verbose_name))
| # coding: utf-8
from django.conf import settings
from django.utils.translation import gettext as _
from rest_framework import exceptions
from onadata.apps.main.models.user_profile import UserProfile
class MFABlockerMixin:
def validate_mfa_not_active(self, user: 'auth.User'):
"""
Raise an exception if MFA is enabled for user's account.
"""
# This condition is kind of temporary. We can activate/deactivate
# class based on settings. Useful until we decide whether
# TokenAuthentication should be deactivated with MFA
# ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged
class_path = f'{self.__module__}.{self.__class__.__name__}'
if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES:
try:
is_mfa_active = user.profile.is_mfa_active
except UserProfile.DoesNotExist:
pass
else:
if is_mfa_active:
raise exceptions.AuthenticationFailed(_(
'Multi-factor authentication is enabled for '
'this account. {verbose_name} cannot be used.'
).format(verbose_name=self.verbose_name))
|
Revert change to make user data private
I'll need to just move any private data to another table because we need
to be able to search usernames in order to add people to a chronicle. | // Includes file dependencies
define([
"jquery",
"backbone",
"parse"
], function( $, Backbone, Parse ) {
// Extends Backbone.View
var SignupView = Backbone.View.extend( {
events: {
"submit form.signup-form": "signUp"
},
el: "#signup",
initialize: function() {
_.bindAll(this, "signUp");
this.render();
},
signUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
Parse.User.signUp(username, password, { }, {
success: function(user) {
location.reload();
self.undelegateEvents();
},
error: function(user, error) {
self.$(".signup-form .error").html(_.escape(error.message)).show();
self.$(".signup-form button").removeAttr("disabled");
}
});
this.$(".signup-form button").attr("disabled", "disabled");
return false;
},
render: function() {
this.template = _.template($("#signup-template").html())();
this.$el.find("div[role='main']").html(this.template);
this.$el.enhanceWithin();
this.delegateEvents();
}
});
// Returns the View class
return SignupView;
} ); | // Includes file dependencies
define([
"jquery",
"backbone",
"parse"
], function( $, Backbone, Parse ) {
// Extends Backbone.View
var SignupView = Backbone.View.extend( {
events: {
"submit form.signup-form": "signUp"
},
el: "#signup",
initialize: function() {
_.bindAll(this, "signUp");
this.render();
},
signUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
Parse.User.signUp(username, password, { ACL: new Parse.ACL() }, {
success: function(user) {
location.reload();
self.undelegateEvents();
},
error: function(user, error) {
self.$(".signup-form .error").html(_.escape(error.message)).show();
self.$(".signup-form button").removeAttr("disabled");
}
});
this.$(".signup-form button").attr("disabled", "disabled");
return false;
},
render: function() {
this.template = _.template($("#signup-template").html())();
this.$el.find("div[role='main']").html(this.template);
this.$el.enhanceWithin();
this.delegateEvents();
}
});
// Returns the View class
return SignupView;
} ); |
Add comment about Provider not being used in userland code | <?php
namespace Neos\Flow\Http;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Central authority to get hold of the active HTTP request.
* When no active HTTP request can be determined (for example in CLI context) a new instance is built using a ServerRequestFactoryInterface implementation
*
* Note: Naturally this class is not being used explicitly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances
*
* @Flow\Scope("singleton")
*/
final class ActiveHttpRequestProvider
{
/**
* @Flow\Inject
* @var Bootstrap
*/
protected $bootstrap;
/**
* @Flow\Inject
* @var BaseUriProvider
*/
protected $baseUriProvider;
/**
* @Flow\Inject
* @var ServerRequestFactoryInterface
*/
protected $serverRequestFactory;
/**
* Returns the currently active HTTP request, if available.
* If the HTTP request can't be determined, a new instance is created using an instance of ServerRequestFactoryInterface
*
* @return ServerRequestInterface
*/
public function getActiveHttpRequest(): ServerRequestInterface
{
$requestHandler = $this->bootstrap->getActiveRequestHandler();
if ($requestHandler instanceof HttpRequestHandlerInterface) {
return $requestHandler->getHttpRequest();
}
try {
$baseUri = $this->baseUriProvider->getConfiguredBaseUriOrFallbackToCurrentRequest();
} catch (Exception $e) {
$baseUri = 'http://localhost';
}
return $this->serverRequestFactory->createServerRequest('GET', $baseUri);
}
}
| <?php
namespace Neos\Flow\Http;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Central authority to get hold of the active HTTP request.
* When no active HTTP request can be determined (for example in CLI context) a new instance is built using a ServerRequestFactoryInterface implementation
*
* @Flow\Scope("singleton")
*/
final class ActiveHttpRequestProvider
{
/**
* @Flow\Inject
* @var Bootstrap
*/
protected $bootstrap;
/**
* @Flow\Inject
* @var BaseUriProvider
*/
protected $baseUriProvider;
/**
* @Flow\Inject
* @var ServerRequestFactoryInterface
*/
protected $serverRequestFactory;
/**
* Returns the currently active HTTP request, if available.
* If the HTTP request can't be determined, a new instance is created using an instance of ServerRequestFactoryInterface
*
* @return ServerRequestInterface
*/
public function getActiveHttpRequest(): ServerRequestInterface
{
$requestHandler = $this->bootstrap->getActiveRequestHandler();
if ($requestHandler instanceof HttpRequestHandlerInterface) {
return $requestHandler->getHttpRequest();
}
try {
$baseUri = $this->baseUriProvider->getConfiguredBaseUriOrFallbackToCurrentRequest();
} catch (Exception $e) {
$baseUri = 'http://localhost';
}
return $this->serverRequestFactory->createServerRequest('GET', $baseUri);
}
}
|
Remove getInstance thanks to DI | <?php
namespace Core;
class Router
{
private $routes = array();
public function __construct()
{
$this->routes = require dirname(__DIR__) . '/config/routes.php';
}
public function get($key)
{
if(array_key_exists($key, $this->routes))
{
return $this->routes[$key];
}
else
{
return $this->_findWithoutArgs($key);
}
}
public function getController($key)
{
if($this->get($key))
{
return $this->get($key)[0];
}
else
{
return null;
}
}
public function getMethod($key)
{
if($this->get($key))
{
return $this->get($key)[1];
}
else
{
return null;
}
}
private function _findWithoutArgs($key)
{
$next_key = substr_replace($key, '', strrpos($key, '/'));
if(strlen($next_key) > 0)
{
return $this->get($next_key);
}
else
{
return null;
}
}
}
| <?php
namespace Core;
class Router
{
private $routes = array();
private static $_instance;
public static function getInstance()
{
if(is_null(self::$_instance))
{
self::$_instance = new Router();
}
return self::$_instance;
}
public function __construct()
{
$this->routes = require dirname(__DIR__) . '/config/routes.php';
}
public function get($key)
{
if(array_key_exists($key, $this->routes))
{
return $this->routes[$key];
}
else
{
return $this->_findWithoutArgs($key);
}
}
public function getController($key)
{
if($this->get($key))
{
return $this->get($key)[0];
}
else
{
return null;
}
}
public function getMethod($key)
{
if($this->get($key))
{
return $this->get($key)[1];
}
else
{
return null;
}
}
private function _findWithoutArgs($key)
{
$next_key = substr_replace($key, '', strrpos($key, '/'));
if(strlen($next_key) > 0)
{
return $this->get($next_key);
}
else
{
return null;
}
}
}
|
Add method isDirectory to File model | define([
"hr/hr",
"hr/utils",
"core/rpc"
], function(hr, _, rpc) {
var File = hr.Model.extend({
defaults: {
path: null,
name: null,
directory: false,
size: 0,
mtime: 0,
atime: 0
},
idAttribute: "name",
// Check if is a directory
isDirectory: function() {
return this.get("directory");
},
// List files in this directory
list: function() {
return rpc.execute("fs/list", {
'path': this.get("path")
})
.then(function(files) {
return _.map(files, function(file) {
return new File({}, file);
});
});
},
// Get a specific file
stat: function(path) {
var that = this;
return rpc.execute("fs/stat", {
'path': path
})
.then(function(file) {
return that.set(file);
})
.thenResolve(that);
}
}, {
// Get a specific file
get: function(path) {
var f = new File();
return f.stat(path);
}
});
return File;
}); | define([
"hr/hr",
"hr/utils",
"core/rpc"
], function(hr, _, rpc) {
var File = hr.Model.extend({
defaults: {
path: null,
name: null,
directory: false,
size: 0,
mtime: 0,
atime: 0
},
idAttribute: "name",
// List files in this directory
list: function() {
return rpc.execute("fs/list", {
'path': this.get("path")
})
.then(function(files) {
return _.map(files, function(file) {
return new File({}, file);
});
});
},
// Get a specific file
stat: function(path) {
var that = this;
return rpc.execute("fs/stat", {
'path': path
})
.then(function(file) {
return that.set(file);
})
.thenResolve(that);
}
}, {
// Get a specific file
get: function(path) {
var f = new File();
return f.stat(path);
}
});
return File;
}); |
Add stop waiter to call buffer | from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiter = None
self.queue = collections.deque(maxlen=CALL_QUEUE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback):
self.stop_waiter()
calls = []
while True:
try:
calls.append(self.queue.popleft())
except IndexError:
break
if calls:
callback(calls)
return
self.waiter = callback
def cancel_waiter(self):
self.waiter = None
def stop_waiter(self):
if self.waiter:
self.waiter(None)
self.waiter = None
def return_call(self, id, response):
callback = self.call_waiters.pop(id, None)
if callback:
callback(response)
def create_call(self, command, args, callback=None):
call_id = uuid.uuid4().hex
call = {
'id': call_id,
'command': command,
'args': args,
}
if callback:
self.call_waiters[call_id] = callback
if self.waiter:
self.waiter([call])
self.waiter = None
else:
self.queue.append(call)
| from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiter = None
self.queue = collections.deque(maxlen=CALL_QUEUE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback):
if self.waiter:
self.waiter([])
self.waiter = None
calls = []
while True:
try:
calls.append(self.queue.popleft())
except IndexError:
break
if calls:
callback(calls)
return
self.waiter = callback
def cancel_waiter(self):
self.waiter = None
def return_call(self, id, response):
callback = self.call_waiters.pop(id, None)
if callback:
callback(response)
def create_call(self, command, args, callback=None):
call_id = uuid.uuid4().hex
call = {
'id': call_id,
'command': command,
'args': args,
}
if callback:
self.call_waiters[call_id] = callback
if self.waiter:
self.waiter([call])
self.waiter = None
else:
self.queue.append(call)
|
Allow to filter expert bids by a customer [WAL-1169] | import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.ExpertProvider
fields = []
class ExpertRequestFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
project = core_filters.URLFilter(view_name='project-detail', name='project__uuid')
project_uuid = django_filters.UUIDFilter(name='project__uuid')
o = django_filters.OrderingFilter(fields=(
('name', 'name'),
('type', 'type'),
('state', 'state'),
('project__customer__name', 'customer_name'),
('project__name', 'project_name'),
('created', 'created'),
('modified', 'modified'),
))
class Meta(object):
model = models.ExpertRequest
fields = ['state']
class ExpertBidFilter(django_filters.FilterSet):
request = core_filters.URLFilter(view_name='expert-request-detail', name='request__uuid')
request_uuid = django_filters.UUIDFilter(name='request__uuid')
customer = core_filters.URLFilter(view_name='customer-detail', name='team__customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='team__customer__uuid')
class Meta(object):
model = models.ExpertBid
fields = []
| import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.ExpertProvider
fields = []
class ExpertRequestFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
project = core_filters.URLFilter(view_name='project-detail', name='project__uuid')
project_uuid = django_filters.UUIDFilter(name='project__uuid')
o = django_filters.OrderingFilter(fields=(
('name', 'name'),
('type', 'type'),
('state', 'state'),
('project__customer__name', 'customer_name'),
('project__name', 'project_name'),
('created', 'created'),
('modified', 'modified'),
))
class Meta(object):
model = models.ExpertRequest
fields = ['state']
class ExpertBidFilter(django_filters.FilterSet):
request = core_filters.URLFilter(view_name='expert-request-detail', name='request__uuid')
request_uuid = django_filters.UUIDFilter(name='request__uuid')
class Meta(object):
model = models.ExpertBid
fields = []
|
Add immediate checkbox to admin form | <?php
namespace Mapbender\CoreBundle\Element\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
*
*/
class RulerAdminType extends AbstractType
{
/**
* @inheritdoc
*/
public function getName()
{
return 'ruler';
}
/**
* @inheritdoc
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'application' => null
));
}
/**
* @inheritdoc
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('tooltip', 'text', array('required' => false))
->add('target', 'target_element',
array(
'element_class' => 'Mapbender\\CoreBundle\\Element\\Map',
'application' => $options['application'],
'property_path' => '[target]',
'required' => false))
->add('type', 'choice',
array(
'required' => true,
'choices' => array("line" => "line", "area" => "area")))
->add('immediate', 'checkbox',
array(
'required' => false,
'label' => 'Immediate'
));
}
} | <?php
namespace Mapbender\CoreBundle\Element\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
*
*/
class RulerAdminType extends AbstractType
{
/**
* @inheritdoc
*/
public function getName()
{
return 'ruler';
}
/**
* @inheritdoc
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'application' => null
));
}
/**
* @inheritdoc
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('tooltip', 'text', array('required' => false))
->add('target', 'target_element',
array(
'element_class' => 'Mapbender\\CoreBundle\\Element\\Map',
'application' => $options['application'],
'property_path' => '[target]',
'required' => false))
->add('type', 'choice',
array(
'required' => true,
'choices' => array("line" => "line", "area" => "area")));
}
} |
Rework condition on cutom filter example | <?php
/**
* PlumSearch plugin for CakePHP Rapid Development Framework
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @author Evgeny Tomenko
* @since PlumSearch 0.1
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace PlumSearch\Test\App\Model\Filter;
use Cake\Database\Expression\UnaryExpression;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
use PlumSearch\Model\Filter\AbstractFilter;
class TagsFilter extends AbstractFilter
{
/**
* Returns query with applied filter
*
* @param \Cake\ORM\Query $query Query.
* @param string $field Field name.
* @param string $value Field value.
* @param array $data Filters values.
* @return \Cake\ORM\Query
*/
protected function _buildQuery(Query $query, $field, $value, array $data = [])
{
// @todo bind to parent Articles.id using initialization parameter
$alias = $query->repository()->alias();
$tags = TableRegistry::get('ArticlesTags')->find('all')
->matching('Tags', function ($q) use ($value, $alias) {
return $q->where([
'Tags.name' => $value,
]);
})
->where([
"ArticlesTags.article_id = $alias.id"
]);
return $query
->where([new UnaryExpression('EXISTS', $tags)]);
}
}
| <?php
/**
* PlumSearch plugin for CakePHP Rapid Development Framework
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @author Evgeny Tomenko
* @since PlumSearch 0.1
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace PlumSearch\Test\App\Model\Filter;
use Cake\Database\Expression\UnaryExpression;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
use PlumSearch\Model\Filter\AbstractFilter;
class TagsFilter extends AbstractFilter
{
/**
* Returns query with applied filter
*
* @param \Cake\ORM\Query $query Query.
* @param string $field Field name.
* @param string $value Field value.
* @param array $data Filters values.
* @return \Cake\ORM\Query
*/
protected function _buildQuery(Query $query, $field, $value, array $data = [])
{
// @todo bind to parent Articles.id using initialization parameter
$alias = $query->repository()->alias();
$tags = TableRegistry::get('ArticlesTags')->find('all')
->matching('Tags', function ($q) use ($value, $alias) {
return $q->where([
'Tags.name' => $value,
"ArticlesTags.article_id = $alias.id",
]);
});
return $query
->where([new UnaryExpression('EXISTS', $tags)]);
}
}
|
Repair validate single shape validator | import pyblish.api
class ValidateMindbenderSingleShape(pyblish.api.InstancePlugin):
"""Transforms with a mesh must ever only contain a single mesh
This ensures models only contain a single shape node.
"""
label = "Validate Single Shape"
order = pyblish.api.ValidatorOrder
hosts = ["maya"]
families = [
"mindbender.model",
]
def process(self, instance):
from maya import cmds
has_multiple_shapes = list()
# Consider entire hierarchy of nodes included in an Instance
hierarchy = cmds.listRelatives(instance, allDescendents=True)
# Consider only nodes of type="mesh"
meshes = cmds.ls(hierarchy, type="mesh", long=True)
transforms = cmds.listRelatives(meshes, parent=True)
for transform in set(transforms):
shapes = cmds.listRelatives(transform, shapes=True) or list()
# Ensure the one child is a shape
has_single_shape = len(shapes) == 1
self.log.info("has single shape: %s" % has_single_shape)
# Ensure the one shape is of type "mesh"
has_single_mesh = (
has_single_shape and
cmds.nodeType(shapes[0]) == "mesh"
)
self.log.info("has single mesh: %s" % has_single_mesh)
if not all([has_single_shape, has_single_mesh]):
has_multiple_shapes.append(transform)
assert not has_multiple_shapes, (
"\"%s\" has transforms with multiple shapes: %s" % (
instance, ", ".join(
"\"" + member + "\"" for member in has_multiple_shapes))
)
| import pyblish.api
class ValidateMindbenderSingleShape(pyblish.api.InstancePlugin):
"""One mesh per transform"""
label = "Validate Single Shape"
order = pyblish.api.ValidatorOrder
hosts = ["maya"]
active = False
optional = True
families = [
"mindbender.model",
"mindbender.lookdev"
]
def process(self, instance):
from maya import cmds
has_multiple_shapes = list()
for node in instance:
children = cmds.listRelatives(node, allDescendents=True) or list()
shapes = cmds.listRelatives(node, shapes=True) or list()
# Ensure there is only one child; there could be many,
# including other transform nodes.
has_single_shape = len(children) == 1
# Ensure the one child is a shape
has_single_child = len(shapes) == 1
# Ensure the one child is of type "mesh"
has_single_mesh = cmds.nodeType(shapes[0]) == "mesh"
if not all([has_single_child,
has_single_shape,
has_single_mesh]):
has_multiple_shapes.append(node)
assert not has_multiple_shapes, (
"\"%s\" has transforms with multiple shapes: %s" % (
instance, ", ".join(
"\"" + member + "\"" for member in has_multiple_shapes))
)
|
Add ability to generate a Job easily.
Signed-off-by: Chris Lamb <[email protected]> | import sys
import time
from django.utils import simplejson
from .utils import get_path, get_middleware
class Job(object):
def __init__(self, path, args, kwargs):
self.path = path
self.args = args
self.kwargs = kwargs
@classmethod
def from_json(cls, json):
return cls(**simplejson.loads(json))
def run(self):
start = time.time()
middleware = get_middleware()
for instance in middleware:
if hasattr(instance, 'process_job'):
instance.process_job(self)
try:
result = self.get_fn().fn(*self.args, **self.kwargs)
time_taken = time.time() - start
for instance in middleware:
if hasattr(instance, 'process_result'):
instance.process_result(self, result, time_taken)
except Exception, exc:
time_taken = time.time() - start
exc_info = sys.exc_info()
for instance in middleware:
if hasattr(instance, 'process_exception'):
instance.process_exception(self, time_taken, *exc_info)
def validate(self):
# Ensure these execute without exception so that we cannot enqueue
# things that are impossible to dequeue.
self.get_fn()
self.to_json()
def get_fn(self):
return get_path(self.path)
def to_json(self):
return simplejson.dumps({
'path': self.path,
'args': self.args,
'kwargs': self.kwargs,
})
| import sys
import time
from django.utils import simplejson
from .utils import get_path, get_middleware
class Job(object):
def __init__(self, path, args, kwargs):
self.path = path
self.args = args
self.kwargs = kwargs
def run(self):
start = time.time()
middleware = get_middleware()
for instance in middleware:
if hasattr(instance, 'process_job'):
instance.process_job(self)
try:
result = self.get_fn().fn(*self.args, **self.kwargs)
time_taken = time.time() - start
for instance in middleware:
if hasattr(instance, 'process_result'):
instance.process_result(self, result, time_taken)
except Exception, exc:
time_taken = time.time() - start
exc_info = sys.exc_info()
for instance in middleware:
if hasattr(instance, 'process_exception'):
instance.process_exception(self, time_taken, *exc_info)
def validate(self):
# Ensure these execute without exception so that we cannot enqueue
# things that are impossible to dequeue.
self.get_fn()
self.to_json()
def get_fn(self):
return get_path(self.path)
def to_json(self):
return simplejson.dumps({
'path': self.path,
'args': self.args,
'kwargs': self.kwargs,
})
|
Include superusers in web user domaing access record | from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin
from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY
from corehq.util.quickcache import quickcache
from corehq.apps.users.tasks import update_domain_date
class ProjectAccessMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(request, 'couch_user', None) and request.couch_user.is_superuser \
and hasattr(request, 'domain'):
self.record_superuser_entry(request.domain, request.couch_user.username)
if getattr(request, 'couch_user', None) and request.couch_user.is_web_user() \
and hasattr(request, 'domain'):
self.record_web_user_entry(request.couch_user, request.domain)
@quickcache(['domain', 'username'], timeout=ENTRY_RECORD_FREQUENCY.seconds)
def record_superuser_entry(self, domain, username):
if not SuperuserProjectEntryRecord.entry_recently_recorded(username, domain):
SuperuserProjectEntryRecord.record_entry(username, domain)
return None
@staticmethod
def record_web_user_entry(user, domain):
yesterday = datetime.today() - timedelta(hours=24)
if domain not in user.domains_accessed or user.domains_accessed[domain] < yesterday:
update_domain_date.delay(user, domain)
| from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin
from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY
from corehq.util.quickcache import quickcache
from corehq.apps.users.tasks import update_domain_date
class ProjectAccessMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(request, 'couch_user', None) and request.couch_user.is_superuser \
and hasattr(request, 'domain'):
return self.record_entry(request.domain, request.couch_user.username)
if getattr(request, 'couch_user', None) and request.couch_user.is_web_user() \
and hasattr(request, 'domain'):
self.record_web_user_entry(request.couch_user, request.domain)
@quickcache(['domain', 'username'], timeout=ENTRY_RECORD_FREQUENCY.seconds)
def record_entry(self, domain, username):
if not SuperuserProjectEntryRecord.entry_recently_recorded(username, domain):
SuperuserProjectEntryRecord.record_entry(username, domain)
return None
@staticmethod
def record_web_user_entry(user, domain):
yesterday = datetime.today() - timedelta(hours=24)
if domain not in user.domains_accessed or user.domains_accessed[domain] < yesterday:
update_domain_date.delay(user, domain)
|
Add support for query relatives in simple example | from aiohttp_json_api.schema import BaseSchema, fields, relationships
from .models import Article, Comment, People
class SchemaWithStorage(BaseSchema):
@property
def storage(self):
return self.app['storage'][self.resource_class.__name__]
async def fetch_resource(self, resource_id, context, **kwargs):
return self.storage.get(resource_id)
async def query_collection(self, context, **kwargs):
return self.storage
async def query_resource(self, resource_id, context, **kwargs):
return await self.fetch_resource(resource_id, context, **kwargs)
class PeopleSchema(SchemaWithStorage):
type = 'people'
resource_class = People
first_name = fields.String()
last_name = fields.String(allow_blank=True)
twitter = fields.String(allow_none=True)
async def delete_resource(self, resource_id, context, **kwargs):
pass
class CommentSchema(SchemaWithStorage):
resource_class = Comment # type will be "comments"
body = fields.String()
author = relationships.ToOne(foreign_types=(PeopleSchema.type,))
async def delete_resource(self, resource_id, context, **kwargs):
pass
class ArticleSchema(SchemaWithStorage):
resource_class = Article # type will be "articles"
title = fields.String()
author = relationships.ToOne(foreign_types=(PeopleSchema.type,))
comments = relationships.ToMany(foreign_types=(CommentSchema.type,))
async def delete_resource(self, resource_id, context, **kwargs):
pass
| from aiohttp_json_api.schema import BaseSchema, fields, relationships
from .models import Article, Comment, People
class SchemaWithStorage(BaseSchema):
@property
def storage(self):
return self.app['storage'][self.resource_class.__name__]
async def query_collection(self, context, **kwargs):
return self.storage
async def query_resource(self, resource_id, context, **kwargs):
return self.storage.get(resource_id)
class PeopleSchema(SchemaWithStorage):
type = 'people'
resource_class = People
first_name = fields.String()
last_name = fields.String(allow_blank=True)
twitter = fields.String(allow_none=True)
async def fetch_resource(self, resource_id, context, **kwargs):
pass
async def delete_resource(self, resource_id, context, **kwargs):
pass
class CommentSchema(SchemaWithStorage):
resource_class = Comment
body = fields.String()
author = relationships.ToOne(foreign_types=(PeopleSchema.type,))
async def fetch_resource(self, resource_id, context, **kwargs):
pass
async def delete_resource(self, resource_id, context, **kwargs):
pass
class ArticleSchema(SchemaWithStorage):
resource_class = Article
title = fields.String()
author = relationships.ToOne(foreign_types=(PeopleSchema.type,))
comments = relationships.ToMany(foreign_types=(CommentSchema.type,))
async def fetch_resource(self, resource_id, context, **kwargs):
pass
async def delete_resource(self, resource_id, context, **kwargs):
pass
|
Fix exit code handling in Promise. | var spawn = require("cross-spawn");
export default function (cmd, subcmd = [], options = {}) {
return new Promise((resolve, reject) => {
options.maxBuffer = 1024 * 1024;
let cp = spawn(cmd, subcmd, options);
let stdout = [], stderr = [];
let error = "";
let setup = (stream, msgs) => {
if (stream) {
stream.on("data", buf => msgs.push(buf));
}
};
setup(cp.stdout, stdout);
setup(cp.stderr, stderr);
cp.on("error", err => {
error = err;
});
let concat = (msgs) => 0 < msgs.length ? Buffer.concat(msgs).toString() : "";
cp.on("close", code => {
let result = {
error: error,
errorcode: code,
stdout: concat(stdout),
stderr: concat(stderr)
};
if (code != 0 && code != 1) {
reject(result);
} else {
resolve(result);
}
});
});
}
| var spawn = require("cross-spawn");
export default function (cmd, subcmd = [], options = {}) {
return new Promise((resolve, reject) => {
options.maxBuffer = 1024 * 1024;
let cp = spawn(cmd, subcmd, options);
let stdout = [], stderr = [];
let error = "";
let setup = (stream, msgs) => {
if (stream) {
stream.on("data", buf => msgs.push(buf));
}
};
setup(cp.stdout, stdout);
setup(cp.stderr, stderr);
cp.on("error", err => {
error = err;
});
let concat = (msgs) => 0 < msgs.length ? Buffer.concat(msgs).toString() : "";
cp.on("close", code => {
let result = {
error: error,
errorcode: code,
stdout: concat(stdout),
stderr: concat(stderr)
};
if (code) {
reject(result);
} else {
resolve(result);
}
});
});
}
|
Add get operation to JSON wrapper | """
Hamcrest matching support for JSON responses.
"""
from json import dumps, loads
from hamcrest.core.base_matcher import BaseMatcher
def prettify(value):
return dumps(
value,
sort_keys=True,
indent=4,
separators=(',', ': '),
)
class JSON(object):
"""
Dictionary wrapper with JSON pretty-printing for Hamcrest's description.
"""
def __init__(self, dct):
self.dct = dct
def __getitem__(self, key):
return self.dct[key]
def get(self, key):
return self.dct.get(key)
def describe_to(self, description):
description.append(prettify(self.dct))
def json_for(value):
if not isinstance(value, (dict, list)):
value = loads(value)
return JSON(value)
class JSONMatcher(BaseMatcher):
"""
Hamcrest matcher of a JSON encoded resource.
Subclasses must define `_matcher` and invoke `assert_that` within a request
context to ensure that Flask's `url_for` can be resolved.
Example:
with graph.app.test_request_context():
assert_that(json(response.data), matches_myresource(expected))
"""
def __init__(self, resource):
self.resource = resource
self.schema = self.schema_class()
self.expected = self.schema.dump(self.resource).data
@property
def schema_class(self):
raise NotImplementedError
def describe_to(self, description):
description.append_text("expected {}".format(prettify(self.expected)))
| """
Hamcrest matching support for JSON responses.
"""
from json import dumps, loads
from hamcrest.core.base_matcher import BaseMatcher
def prettify(value):
return dumps(
value,
sort_keys=True,
indent=4,
separators=(',', ': '),
)
class JSON(object):
"""
Dictionary wrapper with JSON pretty-printing for Hamcrest's description.
"""
def __init__(self, dct):
self.dct = dct
def __getitem__(self, key):
return self.dct[key]
def describe_to(self, description):
description.append(prettify(self.dct))
def json_for(value):
if not isinstance(value, (dict, list)):
value = loads(value)
return JSON(value)
class JSONMatcher(BaseMatcher):
"""
Hamcrest matcher of a JSON encoded resource.
Subclasses must define `_matcher` and invoke `assert_that` within a request
context to ensure that Flask's `url_for` can be resolved.
Example:
with graph.app.test_request_context():
assert_that(json(response.data), matches_myresource(expected))
"""
def __init__(self, resource):
self.resource = resource
self.schema = self.schema_class()
self.expected = self.schema.dump(self.resource).data
@property
def schema_class(self):
raise NotImplementedError
def describe_to(self, description):
description.append_text("expected {}".format(prettify(self.expected)))
|
Add value alias to script routine... | <?php
/** config.init.php
* @author Team22mars <[email protected]>
* @version 1.0
* @desc Set up the application
*/
// MySQL Database settings
// -----------------------
if (strstr($_SERVER['SERVER_NAME'], 'influencenetworks.org') ):
/* *** PROD ENVIRONMENT *** */
define('MYSQL_HOST', 'localhost');
define('MYSQL_DB', '@@MYSQL_DB@@');
define('MYSQL_USER', '@@MYSQL_USER@@');
define('MYSQL_PASS', '@@MYSQL_PASS@@');
define('TABLE_PREFIX', 'inf_');
else :
/* *** DEV ENVIRONMENT *** */
define('MYSQL_HOST', 'localhost');
define('MYSQL_DB', 'influence_networks');
define('MYSQL_USER', 'root');
define('MYSQL_PASS', 'root');
define('TABLE_PREFIX', 'inf_');
endif;
// Sharing configuration
// -----------------------
define("DOC_URL" , "http://influencenetworks.org");
define("DOC_TITLE" , "[APP] Influence Networks lets you see how public figures know each other" );
define("DOC_TWUSER", "owni");
define("GA_PROFILE", "UA-18463169-5");
?> | <?php
/** config.init.php
* @author Team22mars <[email protected]>
* @version 1.0
* @desc Set up the application
*/
// MySQL Database settings
// -----------------------
if (strstr($_SERVER['SERVER_NAME'], 'influencenetworks.org') ):
/* *** PROD ENVIRONMENT *** */
define('MYSQL_HOST', 'localhost');
define('MYSQL_DB', '');
define('MYSQL_USER', '');
define('MYSQL_PASS', '');
define('TABLE_PREFIX', 'inf_');
else :
/* *** DEV ENVIRONMENT *** */
define('MYSQL_HOST', 'localhost');
define('MYSQL_DB', 'influence_networks');
define('MYSQL_USER', 'root');
define('MYSQL_PASS', 'root');
define('TABLE_PREFIX', 'inf_');
endif;
// Sharing configuration
// -----------------------
define("DOC_URL" , "http://influencenetworks.org");
define("DOC_TITLE" , "[APP] Influence Networks lets you see how public figures know each other" );
define("DOC_TWUSER", "owni");
define("GA_PROFILE", "UA-18463169-5");
?> |
Add PHP-CS-Fixer with a simple baseline | <?php
namespace SimpleBus\Asynchronous\Tests\Properties;
use PHPUnit\Framework\TestCase;
use SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver;
use SimpleBus\Asynchronous\Properties\DelegatingAdditionalPropertiesResolver;
class DelegatingAdditionalPropertiesResolverTest extends TestCase
{
/**
* @test
*/
public function it_should_merge_multiple_resolvers()
{
$message = $this->messageDummy();
$resolver = new DelegatingAdditionalPropertiesResolver([
$this->getResolver($message, ['test' => 'a']),
$this->getResolver($message, ['test' => 'b', 'priority' => 123]),
]);
$this->assertSame(['test' => 'b', 'priority' => 123], $resolver->resolveAdditionalPropertiesFor($message));
}
/**
* @param object $message
* @param array $data
*
* @return \PHPUnit\Framework\MockObject\MockObject|AdditionalPropertiesResolver
*/
private function getResolver($message, array $data)
{
$resolver = $this->createMock('SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver');
$resolver->expects($this->once())
->method('resolveAdditionalPropertiesFor')
->with($this->identicalTo($message))
->will($this->returnValue($data));
return $resolver;
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject|object
*/
private function messageDummy()
{
return new \stdClass();
}
}
| <?php
namespace SimpleBus\Asynchronous\Tests\Properties;
use PHPUnit\Framework\TestCase;
use SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver;
use SimpleBus\Asynchronous\Properties\DelegatingAdditionalPropertiesResolver;
class DelegatingAdditionalPropertiesResolverTest extends TestCase
{
/**
* @test
*/
public function it_should_merge_multiple_resolvers()
{
$message = $this->messageDummy();
$resolver = new DelegatingAdditionalPropertiesResolver(array(
$this->getResolver($message, array('test' => 'a')),
$this->getResolver($message, array('test' => 'b', 'priority' => 123)),
));
$this->assertSame(['test' => 'b', 'priority' => 123], $resolver->resolveAdditionalPropertiesFor($message));
}
/**
* @param object $message
* @param array $data
*
* @return \PHPUnit\Framework\MockObject\MockObject|AdditionalPropertiesResolver
*/
private function getResolver($message, array $data)
{
$resolver = $this->createMock('SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver');
$resolver->expects($this->once())
->method('resolveAdditionalPropertiesFor')
->with($this->identicalTo($message))
->will($this->returnValue($data));
return $resolver;
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject|object
*/
private function messageDummy()
{
return new \stdClass();
}
}
|
Increase perfs when loading a product's page | 'use strict';
var set_taxon_select = function(selector){
if ($(selector).length > 0) {
$(selector).select2({
placeholder: Spree.translations.taxon_placeholder,
multiple: true,
initSelection: function (element, callback) {
var url = Spree.url(Spree.routes.taxons_search, {
ids: element.val(),
without_children: true,
token: Spree.api_key
});
return $.getJSON(url, null, function (data) {
return callback(data['taxons']);
});
},
ajax: {
url: Spree.routes.taxons_search,
datatype: 'json',
data: function (term, page) {
return {
per_page: 50,
page: page,
without_children: true,
q: {
name_cont: term
},
token: Spree.api_key
};
},
results: function (data, page) {
var more = page < data.pages;
return {
results: data['taxons'],
more: more
};
}
},
formatResult: function (taxon) {
return taxon.pretty_name;
},
formatSelection: function (taxon) {
return taxon.pretty_name;
}
});
}
}
$(document).ready(function () {
set_taxon_select('#product_taxon_ids')
});
| 'use strict';
var set_taxon_select = function(selector){
if ($(selector).length > 0) {
$(selector).select2({
placeholder: Spree.translations.taxon_placeholder,
multiple: true,
initSelection: function (element, callback) {
var url = Spree.url(Spree.routes.taxons_search, {
ids: element.val(),
token: Spree.api_key
});
return $.getJSON(url, null, function (data) {
return callback(data['taxons']);
});
},
ajax: {
url: Spree.routes.taxons_search,
datatype: 'json',
data: function (term, page) {
return {
per_page: 50,
page: page,
without_children: true,
q: {
name_cont: term
},
token: Spree.api_key
};
},
results: function (data, page) {
var more = page < data.pages;
return {
results: data['taxons'],
more: more
};
}
},
formatResult: function (taxon) {
return taxon.pretty_name;
},
formatSelection: function (taxon) {
return taxon.pretty_name;
}
});
}
}
$(document).ready(function () {
set_taxon_select('#product_taxon_ids')
});
|
Fix tests by passing default settings object rather than empty dict. | from contextlib import contextmanager
from os import path
from unittest import TestCase
from dictdiffer import diff
from jsontest import JsonTest
from mock import patch
from canaryd_packages import six
from canaryd.plugin import get_plugin_by_name
from canaryd.settings import CanarydSettings
class TestPluginRealStates(TestCase):
def test_meta_plugin(self):
plugin = get_plugin_by_name('meta')
plugin.get_state({})
@six.add_metaclass(JsonTest)
class TestPluginStates(TestCase):
jsontest_files = path.join('tests/plugins')
test_settings = CanarydSettings()
@contextmanager
def patch_commands(self, commands):
def handle_command(command, *args, **kwargs):
command = command[0]
if command not in commands:
raise ValueError('Broken tests: {0} not in commands: {1}'.format(
command, commands.keys(),
))
return '\n'.join(commands[command])
check_output_patch = patch(
'canaryd.subprocess.check_output',
handle_command,
)
check_output_patch.start()
yield
check_output_patch.stop()
def jsontest_function(self, test_name, test_data):
plugin = get_plugin_by_name(test_data['plugin'])
with self.patch_commands(test_data['commands']):
state = plugin.get_state(self.test_settings)
try:
self.assertEqual(state, test_data['state'])
except AssertionError:
print(list(diff(test_data['state'], state)))
raise
| from contextlib import contextmanager
from os import path
from unittest import TestCase
from dictdiffer import diff
from jsontest import JsonTest
from mock import patch
from canaryd_packages import six
from canaryd.plugin import get_plugin_by_name
class TestPluginRealStates(TestCase):
def test_meta_plugin(self):
plugin = get_plugin_by_name('meta')
plugin.get_state({})
@six.add_metaclass(JsonTest)
class TestPluginStates(TestCase):
jsontest_files = path.join('tests/plugins')
@contextmanager
def patch_commands(self, commands):
def handle_command(command, *args, **kwargs):
command = command[0]
if command not in commands:
raise ValueError('Broken tests: {0} not in commands: {1}'.format(
command, commands.keys(),
))
return '\n'.join(commands[command])
check_output_patch = patch(
'canaryd.subprocess.check_output',
handle_command,
)
check_output_patch.start()
yield
check_output_patch.stop()
def jsontest_function(self, test_name, test_data):
plugin = get_plugin_by_name(test_data['plugin'])
with self.patch_commands(test_data['commands']):
state = plugin.get_state({})
try:
self.assertEqual(state, test_data['state'])
except AssertionError:
print(list(diff(test_data['state'], state)))
raise
|
Remove un-needed field in epoch serializer.
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@2115 0d517254-b314-0410-acde-c619094fa49f | package edu.northwestern.bioinformatics.studycalendar.xml.writers;
import edu.northwestern.bioinformatics.studycalendar.dao.EpochDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.xml.AbstractStudyCalendarXmlSerializer;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
public class EpochXmlSerializer extends AbstractStudyCalendarXmlSerializer<Epoch> {
// Elements
public static final String EPOCH = "epoch";
private EpochDao epochDao;
public Element createElement(Epoch epoch) {
// Using QName is the only way to attach the namespace to the element
QName qEpoch = DocumentHelper.createQName(EPOCH, DEFAULT_NAMESPACE);
Element eEpoch = DocumentHelper.createElement(qEpoch)
.addAttribute(ID, epoch.getGridId())
.addAttribute(NAME, epoch.getName());
return eEpoch;
}
public Epoch readElement(Element element) {
String key = element.attributeValue(ID);
Epoch epoch = epochDao.getByGridId(key);
if (epoch == null) {
epoch = new Epoch();
epoch.setGridId(key);
epoch.setName(element.attributeValue(NAME));
}
return epoch;
}
public void setEpochDao(EpochDao epochDao) {
this.epochDao = epochDao;
}
}
| package edu.northwestern.bioinformatics.studycalendar.xml.writers;
import edu.northwestern.bioinformatics.studycalendar.dao.EpochDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.xml.AbstractStudyCalendarXmlSerializer;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
public class EpochXmlSerializer extends AbstractStudyCalendarXmlSerializer<Epoch> {
// Elements
public static final String EPOCH = "epoch";
public static final String PLANNDED_CALENDAR = "planned-calendar";
private EpochDao epochDao;
public Element createElement(Epoch epoch) {
// Using QName is the only way to attach the namespace to the element
QName qEpoch = DocumentHelper.createQName(EPOCH, DEFAULT_NAMESPACE);
Element eEpoch = DocumentHelper.createElement(qEpoch)
.addAttribute(ID, epoch.getGridId())
.addAttribute(NAME, epoch.getName());
return eEpoch;
}
public Epoch readElement(Element element) {
String key = element.attributeValue(ID);
Epoch epoch = epochDao.getByGridId(key);
if (epoch == null) {
epoch = new Epoch();
epoch.setGridId(key);
epoch.setName(element.attributeValue(NAME));
}
return epoch;
}
public void setEpochDao(EpochDao epochDao) {
this.epochDao = epochDao;
}
}
|
Set base path for ace |
hqDefine('app_manager/js/download_index_main',[
'jquery',
'underscore',
'ace-builds/src-min-noconflict/ace',
'app_manager/js/download_async_modal',
'app_manager/js/source_files',
],function ($, _, ace) {
ace.config.set('basePath', '/ace-builds/src-noconflict');
$(function () {
var elements = $('.prettyprint');
_.each(elements, function (elem) {
var editor = ace.edit(
elem,
{
showPrintMargin: false,
maxLines: 40,
minLines: 3,
fontSize: 14,
wrap: true,
useWorker: false, // enable the worker to show syntax errors
}
);
var fileName = $(elem).data('filename');
if (fileName.endsWith('json')) {
editor.session.setMode('ace/mode/json');
} else {
editor.session.setMode('ace/mode/xml');
}
editor.setReadOnly(true);
});
});
}); |
hqDefine('app_manager/js/download_index_main',[
'jquery',
'underscore',
'ace-builds/src-min-noconflict/ace',
'app_manager/js/download_async_modal',
'app_manager/js/source_files',
],function ($, _, ace) {
$(function () {
var elements = $('.prettyprint');
_.each(elements, function (elem) {
var editor = ace.edit(
elem,
{
showPrintMargin: false,
maxLines: 40,
minLines: 3,
fontSize: 14,
wrap: true,
useWorker: false, // enable the worker to show syntax errors
}
);
var fileName = $(elem).data('filename');
if (fileName.endsWith('json')) {
editor.session.setMode('ace/mode/json');
} else {
editor.session.setMode('ace/mode/xml');
}
editor.setReadOnly(true);
});
});
}); |
Add name to the snapshot extension | from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
directory. It is used to support resuming the training loop from the saved
state.
This extension is called once for each epoch by default.
.. note::
This extension first writes the serialized object to a temporary file
and then rename it to the target file name. Thus, if the program stops
right before the renaming, the temporary file might be left in the
output directory.
Args:
savefun: Function to save the trainer. It takes two arguments: the
output file path and the trainer object.
filename (str): Name of the file into which the trainer is serialized.
It can be a format string, where the trainer object is passed to
the :meth:`str.format` method.
"""
@extension.make_extension(name='snapshot', trigger=(1, 'epoch'))
def ext(trainer):
fname = filename.format(trainer)
fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out)
try:
savefun(tmppath, trainer)
finally:
os.close(fd)
os.rename(tmppath, os.path.join(trainer.out, fname))
return ext
| from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
directory. It is used to support resuming the training loop from the saved
state.
This extension is called once for each epoch by default.
.. note::
This extension first writes the serialized object to a temporary file
and then rename it to the target file name. Thus, if the program stops
right before the renaming, the temporary file might be left in the
output directory.
Args:
savefun: Function to save the trainer. It takes two arguments: the
output file path and the trainer object.
filename (str): Name of the file into which the trainer is serialized.
It can be a format string, where the trainer object is passed to
the :meth:`str.format` method.
"""
@extension.make_extension(trigger=(1, 'epoch'))
def ext(trainer):
fname = filename.format(trainer)
fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out)
try:
savefun(tmppath, trainer)
finally:
os.close(fd)
os.rename(tmppath, os.path.join(trainer.out, fname))
return ext
|
Make empty notifications message localisable | <style>
.notificationsCounter {
animation-duration: .5s;
}
.notificationIcon {
font-size: 30px;
}
</style>
<li class="dropdown messages-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
<i class="fa fa-bell-o"></i>
<span class="label label-success notificationsCounter animated">{{ $notifications->count() }}</span>
</a>
<ul class="dropdown-menu">
<li>
<div class="slimScrollDiv">
<ul class="menu notifications-list">
<?php if ($notifications->count() === 0): ?>
<li class="noNotifications">
<a href="#">
{{ trans('notification::messages.no notifications') }}
</a>
</li>
<?php endif; ?>
<?php foreach ($notifications as $notification): ?>
<li>
<a href="{{ $notification->link }}">
<div class="pull-left notificationIcon">
<i class="{{ $notification->icon_class }}"></i>
</div>
<h4>
{{ $notification->title }}
<small><i class="fa fa-clock-o"></i> {{ $notification->time_ago }}</small>
</h4>
<p>{{ $notification->message }}</p>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
</li>
</ul>
</li>
| <style>
.notificationsCounter {
animation-duration: .5s;
}
.notificationIcon {
font-size: 30px;
}
</style>
<li class="dropdown messages-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
<i class="fa fa-bell-o"></i>
<span class="label label-success notificationsCounter animated">{{ $notifications->count() }}</span>
</a>
<ul class="dropdown-menu">
<li>
<div class="slimScrollDiv">
<ul class="menu notifications-list">
<?php if ($notifications->count() === 0): ?>
<li class="noNotifications">
<a href="">
No notifications
</a>
</li>
<?php endif; ?>
<?php foreach ($notifications as $notification): ?>
<li>
<a href="{{ $notification->link }}">
<div class="pull-left notificationIcon">
<i class="{{ $notification->icon_class }}"></i>
</div>
<h4>
{{ $notification->title }}
<small><i class="fa fa-clock-o"></i> {{ $notification->time_ago }}</small>
</h4>
<p>{{ $notification->message }}</p>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
</li>
</ul>
</li>
|
Fix console script to mirror git repos even if it has never been done before | <?php
namespace REBELinBLUE\Deployer\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use REBELinBLUE\Deployer\Jobs\UpdateGitMirror;
use REBELinBLUE\Deployer\Project;
/**
* Updates the mirrors for all git repositories.
*/
class UpdateGitMirrors extends Command
{
use DispatchesJobs;
const UPDATES_TO_QUEUE = 3;
const UPDATE_FREQUENCY_MINUTES = 5;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'deployer:update-mirrors';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Pulls in updates for git mirrors';
/**
* Execute the console command.
*
* @return mixed
*
* @dispatches UpdateGitMirror
*/
public function handle()
{
$last_mirrored_since = Carbon::now()->subMinutes(self::UPDATE_FREQUENCY_MINUTES);
$todo = self::UPDATES_TO_QUEUE;
$projects = Project::where('last_mirrored', '<', $last_mirrored_since)->orWhereNull('last_mirrored');
$projects->chunk($todo, function ($projects) {
foreach ($projects as $project) {
$this->dispatch(new UpdateGitMirror($project));
}
});
}
}
| <?php
namespace REBELinBLUE\Deployer\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use REBELinBLUE\Deployer\Jobs\UpdateGitMirror;
use REBELinBLUE\Deployer\Project;
/**
* Updates the mirrors for all git repositories.
*/
class UpdateGitMirrors extends Command
{
use DispatchesJobs;
const UPDATES_TO_QUEUE = 3;
const UPDATE_FREQUENCY_MINUTES = 5;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'deployer:update-mirrors';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Pulls in updates for git mirrors';
/**
* Execute the console command.
*
* @return mixed
*
* @dispatches UpdateGitMirror
*/
public function handle()
{
$last_mirrored_since = Carbon::now()->subMinutes(self::UPDATE_FREQUENCY_MINUTES);
$todo = self::UPDATES_TO_QUEUE;
Project::where('last_mirrored', '<', $last_mirrored_since)->chunk($todo, function ($projects) {
foreach ($projects as $project) {
$this->dispatch(new UpdateGitMirror($project));
}
});
}
}
|
Join callback lists returned from backends | from django.utils.module_loading import import_string
def _get_backends():
backends = []
for backend_path in ['mama_cas.services.backends.SettingsBackend']:
backend = import_string(backend_path)()
backends.append(backend)
return backends
def _is_allowed(attr, *args):
for backend in _get_backends():
try:
if getattr(backend, attr)(*args):
return True
except AttributeError:
raise NotImplementedError("%s does not implement %s()" % (backend, attr))
return False
def get_callbacks(service):
callbacks = []
for backend in _get_backends():
try:
callbacks = callbacks + backend.get_callbacks(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_callbacks()" % backend)
return callbacks
def get_logout_url(service):
for backend in _get_backends():
try:
return backend.get_logout_url(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_logout_url()" % backend)
return None
def logout_allowed(service):
return _is_allowed('logout_allowed', service)
def proxy_allowed(service):
return _is_allowed('proxy_allowed', service)
def proxy_callback_allowed(service, pgturl):
return _is_allowed('proxy_callback_allowed', service, pgturl)
def service_allowed(service):
return _is_allowed('service_allowed', service)
| from django.utils.module_loading import import_string
def _get_backends():
backends = []
for backend_path in ['mama_cas.services.backends.SettingsBackend']:
backend = import_string(backend_path)()
backends.append(backend)
return backends
def _is_allowed(attr, *args):
for backend in _get_backends():
try:
if getattr(backend, attr)(*args):
return True
except AttributeError:
raise NotImplementedError("%s does not implement %s()" % (backend, attr))
return False
def get_callbacks(service):
for backend in _get_backends():
try:
callbacks = backend.get_callbacks(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_callbacks()" % backend)
if callbacks:
# TODO merge callback dicts?
return callbacks
return []
def get_logout_url(service):
for backend in _get_backends():
try:
logout_url = backend.get_logout_url(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_logout_url()" % backend)
if logout_url:
return logout_url
return None
def logout_allowed(service):
return _is_allowed('logout_allowed', service)
def proxy_allowed(service):
return _is_allowed('proxy_allowed', service)
def proxy_callback_allowed(service, pgturl):
return _is_allowed('proxy_callback_allowed', service, pgturl)
def service_allowed(service):
return _is_allowed('service_allowed', service)
|
Use HashSet instead of List | package com.aware.plugin.term_collector;
import android.content.Context;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
/**
* Created by wmb on 08.01.14.
*/
public class StopWords {
private HashSet<String> stopwords;
public StopWords(Context context){
//GERMAN STOPWORDS by Marco Götze, Steffen Geyer: http://solariz.de/649/deutsche-stopwords.htm;
this.stopwords = new HashSet<String>();
InputStream buildinginfo = context.getResources().openRawResource(R.raw.stopwords);
DataInputStream myDIS = new DataInputStream(buildinginfo);
String myLine;
//now loop through and check if we have input, if so append it to list
try{
while((myLine=myDIS.readLine())!=null) stopwords.add(myLine);
} catch(IOException e){
e.printStackTrace();
}
}
public String[] filteredArray(String[] arrayToFilter) {
ArrayList<String> resultList = new ArrayList<String>();
for(String token : arrayToFilter ){
if(!stopwords.contains(token.toLowerCase())){
resultList.add(token);
}
}
String[] result = new String[resultList.size()];
return(resultList.toArray(result));
}
public boolean isStopWord(String token){
return stopwords.contains(token.toLowerCase());
}
}
| package com.aware.plugin.term_collector;
import android.content.Context;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wmb on 08.01.14.
*/
public class StopWords {
private List<String> stopwords;
public StopWords(Context context){
this.stopwords = new ArrayList<String>();
//GERMAN STOPWORDS by Marco Götze, Steffen Geyer: http://solariz.de/649/deutsche-stopwords.htm;
this.stopwords = new ArrayList<String>();
InputStream buildinginfo = context.getResources().openRawResource(R.raw.stopwords);
DataInputStream myDIS = new DataInputStream(buildinginfo);
String myLine;
//now loop through and check if we have input, if so append it to list
try{
while((myLine=myDIS.readLine())!=null) stopwords.add(myLine);
} catch(IOException e){
e.printStackTrace();
}
}
public String[] filteredArray(String[] arrayToFilter) {
ArrayList<String> resultList = new ArrayList<String>();
for(String token : arrayToFilter ){
if(!stopwords.contains(token.toLowerCase())){
resultList.add(token);
}
}
String[] result = new String[resultList.size()];
return(resultList.toArray(result));
}
public boolean isStopWord(String token){
return stopwords.contains(token.toLowerCase());
}
}
|
Remove !$temp check to fix loading an empty array | <?php
namespace Noodlehaus\FileParser;
use Exception;
use Noodlehaus\Exception\ParseException;
use Noodlehaus\Exception\UnsupportedFormatException;
/**
* PHP file parser
*
* @package Config
* @author Jesus A. Domingo <[email protected]>
* @author Hassan Khan <[email protected]>
* @link https://github.com/noodlehaus/config
* @license MIT
*/
class Php implements FileParserInterface
{
/**
* {@inheritDoc}
* Loads a PHP file and gets its' contents as an array
*
* @throws ParseException If the PHP file throws an exception
* @throws UnsupportedFormatException If the PHP file does not return an array
*/
public function parse($path)
{
// Require the file, if it throws an exception, rethrow it
try {
$temp = require $path;
} catch (Exception $exception) {
throw new ParseException(
array(
'message' => 'PHP file threw an exception',
'exception' => $exception,
)
);
}
// If we have a callable, run it and expect an array back
if (is_callable($temp)) {
$temp = call_user_func($temp);
}
// Check for array, if its anything else, throw an exception
if (!is_array($temp)) {
throw new UnsupportedFormatException('PHP file does not return an array');
}
return $temp;
}
/**
* {@inheritDoc}
*/
public function getSupportedExtensions()
{
return array('php');
}
}
| <?php
namespace Noodlehaus\FileParser;
use Exception;
use Noodlehaus\Exception\ParseException;
use Noodlehaus\Exception\UnsupportedFormatException;
/**
* PHP file parser
*
* @package Config
* @author Jesus A. Domingo <[email protected]>
* @author Hassan Khan <[email protected]>
* @link https://github.com/noodlehaus/config
* @license MIT
*/
class Php implements FileParserInterface
{
/**
* {@inheritDoc}
* Loads a PHP file and gets its' contents as an array
*
* @throws ParseException If the PHP file throws an exception
* @throws UnsupportedFormatException If the PHP file does not return an array
*/
public function parse($path)
{
// Require the file, if it throws an exception, rethrow it
try {
$temp = require $path;
} catch (Exception $exception) {
throw new ParseException(
array(
'message' => 'PHP file threw an exception',
'exception' => $exception,
)
);
}
// If we have a callable, run it and expect an array back
if (is_callable($temp)) {
$temp = call_user_func($temp);
}
// Check for array, if its anything else, throw an exception
if (!$temp || !is_array($temp)) {
throw new UnsupportedFormatException('PHP file does not return an array');
}
return $temp;
}
/**
* {@inheritDoc}
*/
public function getSupportedExtensions()
{
return array('php');
}
}
|
Remove random numbers at bottom | $(function() {
$('.atml-description--title').click(function(e) {
e.preventDefault();
var $this = $(this);
var $contentId = $this.data('content');
var $content = $this.parent().next('div');
var $descriptions = $('.atml-description--content');
var $listItems = $('.atml-description--list-item')
var $selectedListWrapper = $this.closest('li');
var $images = $('.atml-image--image');
var $relatedImage = $('.atml-image--image[data-content="' + $contentId + '"]');
var $title = $('.atml-header h1');
$descriptions.removeClass('active')
$images.removeClass('active')
$content.addClass('active')
$relatedImage.addClass('active');
$listItems.removeClass('active');
$selectedListWrapper.addClass('active');
console.log('Content ID', $contentId);
switch ($contentId) {
case 4:
case 5:
case 6:
case 7:
$title.text('Loss Pathways');
break;
case 1:
case 8:
case 2:
case 3:
default:
$title.text('Atmospheric Lifetimes');
break;
}
return false;
});
}); | $(function() {
$('.atml-description--title').click(function(e) {
e.preventDefault();
var $this = $(this);
var $contentId = $this.data('content');
var $content = $this.parent().next('div');
var $descriptions = $('.atml-description--content');
var $listItems = $('.atml-description--list-item')
var $selectedListWrapper = $this.closest('li');
var $images = $('.atml-image--image');
var $relatedImage = $('.atml-image--image[data-content="' + $contentId + '"]');
var $title = $('.atml-header h1');
$descriptions.removeClass('active')
$images.removeClass('active')
$content.addClass('active')
$relatedImage.addClass('active');
$listItems.removeClass('active');
$selectedListWrapper.addClass('active');
console.log('Content ID', $contentId);
switch ($contentId) {
case 4:
case 5:
case 6:
case 7:
$title.text('Loss Pathways');
break;
case 1:
case 8:
case 2:
case 3:
default:
$title.text('Atmospheric Lifetimes');
break;
}
return false;
});
});
26 115 164 |
Clean PostgreSQL - commit after each change not to keep state in memory | from selinon import StoragePool
from cucoslib.models import WorkerResult, Analysis
from .base import BaseHandler
class CleanPostgres(BaseHandler):
""" Clean JSONB columns in Postgres """
def execute(self):
s3 = StoragePool.get_connected_storage('S3Data')
results = self.postgres.session.query(WorkerResult).join(Analysis).\
filter(Analysis.finished_at != None).\
filter(WorkerResult.external_request_id == None)
for entry in results:
if entry.worker[0].isupper() or entry.worker in ('recommendation', 'stack_aggregator'):
continue
if 'VersionId' in entry.task_result:
continue
result_object_key = s3._construct_task_result_object_key(entry.ecosystem.name,
entry.package.name,
entry.version.identifier,
entry.worker)
if s3.object_exists(result_object_key):
entry.task_result = {'VersionId': s3.retrieve_latest_version_id(result_object_key)}
else:
entry.task_result = None
entry.error = True
self.postgres.session.commit()
| from selinon import StoragePool
from cucoslib.models import WorkerResult, Analysis
from .base import BaseHandler
class CleanPostgres(BaseHandler):
""" Clean JSONB columns in Postgres """
def execute(self):
s3 = StoragePool.get_connected_storage('S3Data')
results = self.postgres.session.query(WorkerResult).join(Analysis).\
filter(Analysis.finished_at != None).\
filter(WorkerResult.external_request_id == None)
for entry in results:
if entry.worker[0].isupper() or entry.worker in ('recommendation', 'stack_aggregator'):
continue
if 'VersionId' in entry.task_result:
continue
result_object_key = s3._construct_task_result_object_key(entry.ecosystem.name,
entry.package.name,
entry.version.identifier,
entry.worker)
if s3.object_exists(result_object_key):
entry.task_result = {'VersionId': s3.retrieve_latest_version_id(result_object_key)}
else:
entry.task_result = None
entry.error = True
self.postgres.session.commit()
|
chore: Use different port for server task | module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
clean: {
all: {
src: ['.tmp', 'dist']
}
},
concat: {
all: {
src: [
'less/mixins.less',
'less/variables.less',
'less/*.less',
],
dest: '.tmp/styles.less'
}
},
less: {
all: {
src: '<%= concat.all.dest %>',
dest: 'dist/styles.css'
}
},
cssmin: {
all: {
src: '<%= less.all.dest %>',
dest: 'dist/styles.min.css'
}
},
connect: {
server: {
options: {
base: ['demo', 'dist'],
port: 9090,
open: 'http://localhost:9090/index.html',
livereload: true
},
}
},
watch: {
all: {
options: {
livereload: true
},
files: '<%= concat.all.src %>',
tasks: ['default']
}
}
});
// Load plugins
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
// Register task(s)
grunt.registerTask('default', [
'clean',
'concat',
'less',
'cssmin'
]);
grunt.registerTask('server', [
'default',
'connect',
'watch'
]);
};
| module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
clean: {
all: {
src: ['.tmp', 'dist']
}
},
concat: {
all: {
src: [
'less/mixins.less',
'less/variables.less',
'less/*.less',
],
dest: '.tmp/styles.less'
}
},
less: {
all: {
src: '<%= concat.all.dest %>',
dest: 'dist/styles.css'
}
},
cssmin: {
all: {
src: '<%= less.all.dest %>',
dest: 'dist/styles.min.css'
}
},
connect: {
server: {
options: {
base: ['demo', 'dist'],
open: 'http://localhost:8000/index.html',
livereload: true
},
}
},
watch: {
all: {
options: {
livereload: true
},
files: '<%= concat.all.src %>',
tasks: ['default']
}
}
});
// Load plugins
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
// Register task(s)
grunt.registerTask('default', [
'clean',
'concat',
'less',
'cssmin'
]);
grunt.registerTask('server', [
'default',
'connect',
'watch'
]);
};
|
Fix local opts from CLI | # -*- coding: utf-8 -*-
'''
React by calling async runners
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# import salt libs
import salt.runner
def cmd(
name,
func=None,
arg=(),
**kwargs):
'''
Execute a runner asynchronous:
USAGE:
.. code-block:: yaml
run_cloud:
runner.cmd:
- func: cloud.create
- arg:
- my-ec2-config
- myinstance
run_cloud:
runner.cmd:
- func: cloud.create
- kwargs:
provider: my-ec2-config
instances: myinstance
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
if func is None:
func = name
local_opts = {}
local_opts.update(__opts__)
local_opts['asynchronous'] = True # ensure this will be run asynchronous
local_opts.update({
'fun': func,
'arg': arg,
'kwarg': kwargs
})
runner = salt.runner.Runner(local_opts)
runner.run()
return ret
| # -*- coding: utf-8 -*-
'''
React by calling async runners
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# import salt libs
import salt.runner
def cmd(
name,
func=None,
arg=(),
**kwargs):
'''
Execute a runner asynchronous:
USAGE:
.. code-block:: yaml
run_cloud:
runner.cmd:
- func: cloud.create
- arg:
- my-ec2-config
- myinstance
run_cloud:
runner.cmd:
- func: cloud.create
- kwargs:
provider: my-ec2-config
instances: myinstance
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
if func is None:
func = name
local_opts = {}
local_opts.update(__opts__)
local_opts['async'] = True # ensure this will be run async
local_opts.update({
'fun': func,
'arg': arg,
'kwarg': kwargs
})
runner = salt.runner.Runner(local_opts)
runner.run()
return ret
|
Fix metadata addition when the results are empty | <?php
/*
* This file is part of Packagist.
*
* (c) Jordi Boggiano <[email protected]>
* Nils Adermann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Packagist\WebBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController;
/**
* @author Jordi Boggiano <[email protected]>
*/
class Controller extends BaseController
{
protected function getPackagesMetadata($packages)
{
$metadata = null;
try {
$dlKeys = array();
foreach ($packages as $package) {
$id = $package instanceof \Solarium_Document_ReadOnly ? $package->id : $package->getId();
$dlKeys[$id] = 'dl:'.$id;
}
if (!$dlKeys) {
return $metadata;
}
$res = $this->get('snc_redis.default')->mget(array_values($dlKeys));
$metadata = array(
'downloads' => array_combine(array_keys($dlKeys), $res),
'favers' => $this->get('packagist.favorite_manager')->getFaverCounts(array_keys($dlKeys)),
);
} catch (\Predis\Network\ConnectionException $e) {}
return $metadata;
}
}
| <?php
/*
* This file is part of Packagist.
*
* (c) Jordi Boggiano <[email protected]>
* Nils Adermann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Packagist\WebBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController;
/**
* @author Jordi Boggiano <[email protected]>
*/
class Controller extends BaseController
{
protected function getPackagesMetadata($packages)
{
$metadata = null;
try {
$dlKeys = array();
foreach ($packages as $package) {
$id = $package instanceof \Solarium_Document_ReadOnly ? $package->id : $package->getId();
$dlKeys[$id] = 'dl:'.$id;
}
$res = $this->get('snc_redis.default')->mget(array_values($dlKeys));
$metadata = array(
'downloads' => array_combine(array_keys($dlKeys), $res),
'favers' => $this->get('packagist.favorite_manager')->getFaverCounts(array_keys($dlKeys)),
);
} catch (\Predis\Network\ConnectionException $e) {}
return $metadata;
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.