text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix test if server started in xrootd cleanup code
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@17920 4e558342-562e-0410-864c-e07659590f8c
|
import os
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
import unittest
class TestStopXrootd(osgunittest.OSGTestCase):
def test_01_stop_xrootd(self):
if (core.config['xrootd.gsi'] == "ON") and (core.state['xrootd.backups-exist'] == True):
files.restore('/etc/xrootd/xrootd-clustered.cfg',"xrootd")
files.restore('/etc/xrootd/auth_file',"xrootd")
files.restore('/etc/grid-security/xrd/xrdmapfile',"xrootd")
core.skip_ok_unless_installed('xrootd')
self.skip_ok_if(core.state['xrootd.started-server'] == False, 'did not start server')
command = ('service', 'xrootd', 'stop')
stdout, _, fail = core.check_system(command, 'Stop Xrootd server')
self.assert_(stdout.find('FAILED') == -1, fail)
self.assert_(not os.path.exists(core.config['xrootd.pid-file']),
'Xrootd server PID file still present')
|
import os
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
import unittest
class TestStopXrootd(osgunittest.OSGTestCase):
def test_01_stop_xrootd(self):
if (core.config['xrootd.gsi'] == "ON") and (core.state['xrootd.backups-exist'] == True):
files.restore('/etc/xrootd/xrootd-clustered.cfg',"xrootd")
files.restore('/etc/xrootd/auth_file',"xrootd")
files.restore('/etc/grid-security/xrd/xrdmapfile',"xrootd")
core.skip_ok_unless_installed('xrootd')
self.skip_ok_if(['xrootd.started-server'] == False, 'did not start server')
command = ('service', 'xrootd', 'stop')
stdout, _, fail = core.check_system(command, 'Stop Xrootd server')
self.assert_(stdout.find('FAILED') == -1, fail)
self.assert_(not os.path.exists(core.config['xrootd.pid-file']),
'Xrootd server PID file still present')
|
Add support for program editor to create and update snapshots
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
A user with authorization to edit mapping objects related to an access
controlled program.<br/><br/>When a person has this role they can map and
unmap objects to the Program and edit the Program info, but they are unable
to delete the Program or assign other people roles for that program.
"""
permissions = {
"read": [
"ObjectDocument",
"ObjectObjective",
"ObjectPerson",
"Program",
"Relationship",
"UserRole",
"Context",
],
"create": [
"Audit",
"Snapshot",
"ObjectDocument",
"ObjectObjective",
"ObjectPerson",
"Relationship",
],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [
"Snapshot",
"ObjectDocument",
"ObjectObjective",
"ObjectPerson",
"Program",
"Relationship"
],
"delete": [
"Program",
"ObjectDocument",
"ObjectObjective",
"ObjectPerson",
"Relationship",
]
}
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
A user with authorization to edit mapping objects related to an access
controlled program.<br/><br/>When a person has this role they can map and
unmap objects to the Program and edit the Program info, but they are unable
to delete the Program or assign other people roles for that program.
"""
permissions = {
"read": [
"ObjectDocument",
"ObjectObjective",
"ObjectPerson",
"Program",
"Relationship",
"UserRole",
"Context",
],
"create": [
"Audit",
"ObjectDocument",
"ObjectObjective",
"ObjectPerson",
"Relationship",
],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [
"ObjectDocument",
"ObjectObjective",
"ObjectPerson",
"Program",
"Relationship"
],
"delete": [
"Program",
"ObjectDocument",
"ObjectObjective",
"ObjectPerson",
"Relationship",
]
}
|
Update Twisted requirement to add a minimum version.
|
import os.path
from setuptools import setup, find_packages
def readme():
path = os.path.join(os.path.dirname(__file__), 'README.rst')
return open(path, 'r').read()
setup(
name="txTwitter",
version="0.1.1a",
url='https://github.com/jerith/txTwitter',
license='MIT',
description="A Twisted-based client library for Twitter's API.",
long_description=readme(),
author='Jeremy Thurgood',
author_email='firxen@gmail.com',
packages=find_packages(),
include_package_data=True,
install_requires=['Twisted>=13.1.0', 'oauthlib', 'pyOpenSSL'],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Twisted',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
import os.path
from setuptools import setup, find_packages
def readme():
path = os.path.join(os.path.dirname(__file__), 'README.rst')
return open(path, 'r').read()
setup(
name="txTwitter",
version="0.1.1a",
url='https://github.com/jerith/txTwitter',
license='MIT',
description="A Twisted-based client library for Twitter's API.",
long_description=readme(),
author='Jeremy Thurgood',
author_email='firxen@gmail.com',
packages=find_packages(),
include_package_data=True,
install_requires=['Twisted', 'oauthlib', 'pyOpenSSL'],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Twisted',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
RDL-4689: Add six to the requirements.
|
#!/usr/bin/env python
import re
from setuptools import find_packages, setup
with open('py_mstr/__init__.py', 'rb') as f:
version = str(re.search('__version__ = "(.+?)"', f.read().decode('utf-8')).group(1))
setup(
name='py-mstr',
version=version,
packages=find_packages(),
description='Python API for Microstrategy Web Tasks',
url='http://github.com/infoscout/py-mstr',
author='InfoScout',
author_email='oss@infoscoutinc.com',
license='MIT',
install_requires=[
'pyquery >= 1.2.8, < 1.3.0',
'requests >= 2.3.0',
'six >= 1.9.0'
],
tests_require=['discover', 'mock'],
test_suite="tests",
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries',
],
)
|
#!/usr/bin/env python
import re
from setuptools import find_packages, setup
with open('py_mstr/__init__.py', 'rb') as f:
version = str(re.search('__version__ = "(.+?)"', f.read().decode('utf-8')).group(1))
setup(
name='py-mstr',
version=version,
packages=find_packages(),
description='Python API for Microstrategy Web Tasks',
url='http://github.com/infoscout/py-mstr',
author='InfoScout',
author_email='oss@infoscoutinc.com',
license='MIT',
install_requires=[
'pyquery >= 1.2.8, < 1.3.0',
'requests >= 2.3.0',
],
tests_require=['discover', 'mock'],
test_suite="tests",
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries',
],
)
|
Use a tokenless client by default.
|
<?php
/**
* AbstractTask.php
*
* @author Frederic Dewinne <frederic@continuousphp.com>
* @copyright Copyright (c) 2015 Continuous S.A. (http://continuousphp.com)
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
* @file AbstractTask.php
* @link http://github.com/continuousphp/phing-tasks the canonical source repo
*/
namespace Continuous\Task;
use Continuous\Sdk\Client;
use Continuous\Sdk\Service;
/**
* AbstractTask
*
* @package phing-tasks
* @author Frederic Dewinne <frederic@continuousphp.com>
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
*/
abstract class AbstractTask extends \ProjectComponent
{
/**
* @var Client
*/
static protected $client;
/**
* @param Client $client
*/
public function setClient(Client $client)
{
self::$client = $client;
}
/**
* @return Client
*/
protected function getClient()
{
// If no client has been set previously, default to a client without an
// access token. This is useful for accessing public repositories.
if (self::$client === NULL) {
$this->setClient(Service::factory([]));
}
return self::$client;
}
}
|
<?php
/**
* AbstractTask.php
*
* @author Frederic Dewinne <frederic@continuousphp.com>
* @copyright Copyright (c) 2015 Continuous S.A. (http://continuousphp.com)
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
* @file AbstractTask.php
* @link http://github.com/continuousphp/phing-tasks the canonical source repo
*/
namespace Continuous\Task;
use Continuous\Sdk\Client;
/**
* AbstractTask
*
* @package phing-tasks
* @author Frederic Dewinne <frederic@continuousphp.com>
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
*/
abstract class AbstractTask extends \ProjectComponent
{
/**
* @var Client
*/
static protected $client;
/**
* @param Client $client
*/
public function setClient(Client $client)
{
self::$client = $client;
}
/**
* @return Client
*/
protected function getClient()
{
return self::$client;
}
}
|
Set the service_type for the builder
If we don't do this we can't lookup the endpoint.
Change-Id: I7eae87afc9e4d9ef9dd4f5877b71a4ebe299df0a
|
# Copyright 2014 - Noorul Islam K M
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from solumclient.builder.v1 import image
from solumclient.openstack.common.apiclient import client
class Client(client.BaseClient):
"""Client for the Solum v1 API."""
service_type = "image_builder"
def __init__(self, http_client, extensions=None):
"""Initialize a new client for the Builder v1 API."""
super(Client, self).__init__(http_client, extensions)
self.images = image.ImageManager(self)
|
# Copyright 2014 - Noorul Islam K M
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from solumclient.builder.v1 import image
from solumclient.openstack.common.apiclient import client
class Client(client.BaseClient):
"""Client for the Solum v1 API."""
def __init__(self, http_client, extensions=None):
"""Initialize a new client for the Builder v1 API."""
super(Client, self).__init__(http_client, extensions)
self.images = image.ImageManager(self)
|
admin_calendar: Fix to work on the latest django-imagekit
|
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
class CalendarEvent(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
start = models.DateTimeField(u'Alku', help_text=u'Tapahtuman alkamisaika.')
end = models.DateTimeField(u'Loppe', help_text=u'Tapahtuman loppumisaika.', blank=True)
description = models.TextField(u'Kuvaus', help_text=u'Tapahtuman kuvaus.', blank=True)
title = models.CharField(u'Otsikko', help_text=u'Lyhyt otsikko.', max_length=32)
image_original = models.ImageField(u'Kuva', upload_to='calendar/images/', help_text=u"Kuva tapahtumalle.", blank=True)
image_small = ImageSpecField([ResizeToFill(48, 48)], image_field='imagefile_original', format='PNG')
EVENT_TYPES = (
(0, u'Aikaraja'),
(1, u'Aikavaraus'),
)
type = models.IntegerField(u'Tyyppi', help_text=u'Tapahtuman tyyppi', choices=EVENT_TYPES, default=0)
try:
admin.site.register(CalendarEvent)
except:
pass
|
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
from imagekit.models import ImageSpec
from imagekit.processors import resize
class CalendarEvent(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
start = models.DateTimeField(u'Alku', help_text=u'Tapahtuman alkamisaika.')
end = models.DateTimeField(u'Loppe', help_text=u'Tapahtuman loppumisaika.', blank=True)
description = models.TextField(u'Kuvaus', help_text=u'Tapahtuman kuvaus.', blank=True)
title = models.CharField(u'Otsikko', help_text=u'Lyhyt otsikko.', max_length=32)
image_original = models.ImageField(u'Kuva', upload_to='calendar/images/', help_text=u"Kuva tapahtumalle.", blank=True)
image_small = ImageSpec([resize.Fit(48, 48)], image_field='imagefile_original', format='PNG')
EVENT_TYPES = (
(0, u'Aikaraja'),
(1, u'Aikavaraus'),
)
type = models.IntegerField(u'Tyyppi', help_text=u'Tapahtuman tyyppi', choices=EVENT_TYPES, default=0)
try:
admin.site.register(CalendarEvent)
except:
pass
|
fix: Remove unnecessary call to findDOMNode
|
/* eslint-env browser */
import {findSingleNode, getFindDOMNode} from './helpers';
let findDOMNode = findDOMNode || (global && global.findDOMNode);
function haveDomNodeWithXpath(domNode, expression) {
document.body.appendChild(domNode);
const xpathNode = findSingleNode(expression, domNode.parentNode);
document.body.removeChild(domNode);
return xpathNode !== null;
}
export default function haveXpath(Chai) {
Chai.Assertion.addMethod('xpath', function evaluateXpath(xpath) {
findDOMNode = findDOMNode || getFindDOMNode();
const domNode = findDOMNode(this._obj);
this.assert(
haveDomNodeWithXpath(domNode, xpath),
'Expected "' + domNode.outerHTML + '" to have xpath \'' + xpath + '\'',
'Expected "' + domNode.outerHTML + '" to not have xpath \'' + xpath + '\''
);
});
}
|
/* eslint-env browser */
import {findSingleNode, getFindDOMNode} from './helpers';
let findDOMNode = findDOMNode || (global && global.findDOMNode);
function haveComponentWithXpath(component, expression) {
findDOMNode = findDOMNode || getFindDOMNode();
const domNode = findDOMNode(component);
document.body.appendChild(domNode);
const xpathNode = findSingleNode(expression, domNode.parentNode);
document.body.removeChild(domNode);
return xpathNode !== null;
}
export default function haveXpath(Chai) {
Chai.Assertion.addMethod('xpath', function evaluateXpath(xpath) {
findDOMNode = findDOMNode || getFindDOMNode();
const dom = findDOMNode(this._obj).outerHTML;
this.assert(
haveComponentWithXpath(this._obj, xpath),
'Expected "' + dom + '" to have xpath \'' + xpath + '\'',
'Expected "' + dom + '" to not have xpath \'' + xpath + '\''
);
});
}
|
Use metric types from index.js in example
|
'use strict';
var express = require('express');
var server = express();
var register = require('../lib/register');
var Histogram = require('../').Histogram;
var h = new Histogram('test_histogram', 'Example of a histogram', [ 'code' ]);
var Counter = require('../').Counter;
var c = new Counter('test_counter', 'Example of a counter', [ 'code' ]);
var Gauge = require('../').Gauge;
var g = new Gauge('test_gauge', 'Example of a gauge', [ 'method', 'code' ]);
setTimeout(function() {
h.labels('200').observe(Math.random());
h.labels('300').observe(Math.random());
}, 10);
setInterval(function() {
c.inc({ code: 200 });
}, 5000);
setInterval(function() {
c.inc({ code: 400 });
}, 2000);
setInterval(function() {
c.inc();
}, 2000);
setInterval(function() {
g.set({ method: 'get', code: 200 }, Math.random());
g.set(Math.random());
g.labels('post', '300').inc();
}, 100);
server.get('/metrics', function(req, res) {
res.end(register.metrics());
});
server.listen(3000);
|
'use strict';
var express = require('express');
var server = express();
var register = require('../lib/register');
var Histogram = require('../lib/histogram');
var h = new Histogram('test_histogram', 'Example of a histogram', [ 'code' ]);
var Counter = require('../lib/counter');
var c = new Counter('test_counter', 'Example of a counter', [ 'code' ]);
var Gauge = require('../lib/gauge');
var g = new Gauge('test_gauge', 'Example of a gauge', [ 'method', 'code' ]);
setTimeout(function() {
h.labels('200').observe(Math.random());
h.labels('300').observe(Math.random());
}, 10);
setInterval(function() {
c.inc({ code: 200 });
}, 5000);
setInterval(function() {
c.inc({ code: 400 });
}, 2000);
setInterval(function() {
c.inc();
}, 2000);
setInterval(function() {
g.set({ method: 'get', code: 200 }, Math.random());
g.set(Math.random());
g.labels('post', '300').inc();
}, 100);
server.get('/metrics', function(req, res) {
res.end(register.metrics());
});
server.listen(3000);
|
Fix calling nonexistent config value
|
<?php
namespace Aviator\Helpdesk\Models;
use Illuminate\Database\Eloquent\Model;
class Pool extends Model
{
protected $guarded = [];
/**
* Set the table name from the Helpdesk config
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->setTable(config('helpdesk.tables.pools'));
}
public function agents() {
return $this->belongsToMany(Agent::class)->withPivot('is_team_lead')->withTimestamps();
}
public function teamLeads() {
return $this->belongsToMany(Agent::class, config('helpdesk.tables.agent_pool'))
->withPivot('is_team_lead')
->withTimestamps()
->wherePivot('is_team_lead', 1);
}
}
|
<?php
namespace Aviator\Helpdesk\Models;
use Illuminate\Database\Eloquent\Model;
class Pool extends Model
{
protected $guarded = [];
/**
* Set the table name from the Helpdesk config
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->setTable(config('helpdesk.tables.pool'));
}
public function agents() {
return $this->belongsToMany(Agent::class)->withPivot('is_team_lead')->withTimestamps();
}
public function teamLeads() {
return $this->belongsToMany(Agent::class, config('helpdesk.tables.agent_pool'))
->withPivot('is_team_lead')
->withTimestamps()
->wherePivot('is_team_lead', 1);
}
}
|
Change name getbusline name method
|
"""Busine-me API
Universidade de Brasilia - FGA
Técnicas de Programação, 2/2015
@file views.py
Views (on classic MVC, controllers) with methods that control the requisitions
for the user authentication and manipulation.
"""
from django.views.generic import View
from core.serializers import serialize_objects
from .models import Busline
from django.http import JsonResponse
STATUS_OK = 200
STATUS_NOT_FOUND = 404
STATUS_CREATED = 201
STATUS_SERVER_ERROR = 500
class BuslineSearchResultView(View):
http_method_names = [u'get', u'post']
def get(self, request):
"""Returns all users."""
json_data = serialize_objects(Busline.objects.all())
return JsonResponse(json_data, content_type='application/json')
def get_busline(self, line_number):
busline = Busline.api_filter_startswith(line_number)
json_data = serialize_objects(busline)
return JsonResponse(json_data, content_type='application/json')
|
"""Busine-me API
Universidade de Brasilia - FGA
Técnicas de Programação, 2/2015
@file views.py
Views (on classic MVC, controllers) with methods that control the requisitions
for the user authentication and manipulation.
"""
from django.views.generic import View
from core.serializers import serialize_objects
from .models import Busline
from django.http import JsonResponse
STATUS_OK = 200
STATUS_NOT_FOUND = 404
STATUS_CREATED = 201
STATUS_SERVER_ERROR = 500
class BuslineSearchResultView(View):
http_method_names = [u'get', u'post']
def get(self, request):
"""Returns all users."""
json_data = serialize_objects(Busline.objects.all())
return JsonResponse(json_data, content_type='application/json')
def getbusline(self, line_number):
busline = Busline.api_filter_startswith(line_number)
json_data = serialize_objects(busline)
return JsonResponse(json_data, content_type='application/json')
|
Add noop importer to isExportsOrModuleAssignment tests
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import { statement, noopImporter } from '../../../tests/utils';
import isExportsOrModuleAssignment from '../isExportsOrModuleAssignment';
describe('isExportsOrModuleAssignment', () => {
it('detects "module.exports = ...;"', () => {
expect(
isExportsOrModuleAssignment(
statement('module.exports = foo;'),
noopImporter,
),
).toBe(true);
});
it('detects "exports.foo = ..."', () => {
expect(
isExportsOrModuleAssignment(
statement('exports.foo = foo;'),
noopImporter,
),
).toBe(true);
});
it('does not accept "exports = foo;"', () => {
// That doesn't actually export anything
expect(
isExportsOrModuleAssignment(statement('exports = foo;'), noopImporter),
).toBe(false);
});
});
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import { statement } from '../../../tests/utils';
import isExportsOrModuleAssignment from '../isExportsOrModuleAssignment';
describe('isExportsOrModuleAssignment', () => {
it('detects "module.exports = ...;"', () => {
expect(
isExportsOrModuleAssignment(statement('module.exports = foo;')),
).toBe(true);
});
it('detects "exports.foo = ..."', () => {
expect(isExportsOrModuleAssignment(statement('exports.foo = foo;'))).toBe(
true,
);
});
it('does not accept "exports = foo;"', () => {
// That doesn't actually export anything
expect(isExportsOrModuleAssignment(statement('exports = foo;'))).toBe(
false,
);
});
});
|
Make sure modals are correctly positioned
|
var Backbone = require('backbone');
var ModalContainerView = Backbone.View.extend({
events: {
'mousedown': 'closeOnOutsideClick'
},
initialize: function() {
},
closeOnOutsideClick: function(e) {
if (this.modal && this.$el.is(e.target) && this.modal.closable) {
this.closeCurrentModal();
}
},
showBackground: function() {
this.$el.removeClass('disabled');
},
hideBackground: function() {
this.$el.addClass('disabled');
},
empty: function() {
this.$el.html('');
},
setCurrentModal: function(ModalType, path) {
var topMargin = 150;
var scrollTop = $(window).scrollTop();
// Load HTML then create view object asynchronously
$.get(path).done(function(html) {
this.$el.html(html);
this.showBackground();
this.modal = new ModalType({ el: this.$('.js-modal') });
this.modal.$el.css('marginTop', topMargin + scrollTop);
this.modal.on('close', this.closeCurrentModal.bind(this));
}.bind(this));
},
closeCurrentModal: function() {
this.hideBackground();
this.empty();
this.modal.remove();
this.modal = null;
}
});
module.exports = ModalContainerView;
|
var Backbone = require('backbone');
var ModalContainerView = Backbone.View.extend({
events: {
'mousedown': 'closeOnOutsideClick'
},
initialize: function() {
},
closeOnOutsideClick: function(e) {
if (this.modal && this.$el.is(e.target) && this.modal.closable) {
this.closeCurrentModal();
}
},
showBackground: function() {
this.$el.removeClass('disabled');
},
hideBackground: function() {
this.$el.addClass('disabled');
},
empty: function() {
this.$el.html('');
},
setCurrentModal: function(ModalType, path) {
// Load HTML then create view object asynchronously
$.get(path).done(function(html) {
this.$el.html(html);
this.showBackground();
this.modal = new ModalType({ el: this.$('.js-modal') });
this.modal.on('close', this.closeCurrentModal.bind(this));
}.bind(this));
},
closeCurrentModal: function() {
this.hideBackground();
this.empty();
this.modal.remove();
this.modal = null;
}
});
module.exports = ModalContainerView;
|
Add modify to keyed methods to enable patch with id
|
var Router = require('express').Router;
var keyed = ['get', 'read', 'put', 'update', 'patch', 'modify', 'del', 'delete'],
map = { index:'get', list:'get', read:'get', create:'post', update:'put', modify:'patch' };
module.exports = function ResourceRouter(route) {
route.mergeParams = route.mergeParams ? true : false;
var router = Router({mergeParams: route.mergeParams}),
key, fn, url;
if (route.middleware) router.use(route.middleware);
if (route.load) {
router.param(route.id, function(req, res, next, id) {
route.load(req, id, function(err, data) {
if (err) return res.status(404).send(err);
req[route.id] = data;
next();
});
});
}
for (key in route) {
fn = map[key] || key;
if (typeof router[fn]==='function') {
url = ~keyed.indexOf(key) ? ('/:'+route.id) : '/';
router[fn](url, route[key]);
}
}
return router;
};
module.exports.keyed = keyed;
|
var Router = require('express').Router;
var keyed = ['get', 'read', 'put', 'patch', 'update', 'del', 'delete'],
map = { index:'get', list:'get', read:'get', create:'post', update:'put', modify:'patch' };
module.exports = function ResourceRouter(route) {
route.mergeParams = route.mergeParams ? true : false;
var router = Router({mergeParams: route.mergeParams}),
key, fn, url;
if (route.middleware) router.use(route.middleware);
if (route.load) {
router.param(route.id, function(req, res, next, id) {
route.load(req, id, function(err, data) {
if (err) return res.status(404).send(err);
req[route.id] = data;
next();
});
});
}
for (key in route) {
fn = map[key] || key;
if (typeof router[fn]==='function') {
url = ~keyed.indexOf(key) ? ('/:'+route.id) : '/';
router[fn](url, route[key]);
}
}
return router;
};
module.exports.keyed = keyed;
|
Upgrade to the new Domgen API
|
package org.realityforge.replicant.example.server.service.tyrell.replicate;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.enterprise.context.Dependent;
import org.realityforge.replicant.example.server.entity.TyrellRouter;
import org.realityforge.replicant.example.server.entity.tyrell.Building;
import org.realityforge.replicant.example.server.entity.tyrell.Room;
@Dependent
public class EntityRouter
implements TyrellRouter
{
public static final String BUILDING_KEY = "Tyrell.BuildingID";
@Nonnull
@Override
public Map<String, Serializable> routeBuilding( @Nonnull final Building entity )
{
final HashMap<String, Serializable> map = new HashMap<>();
map.put( BUILDING_KEY, entity.getID() );
return map;
}
@Nonnull
@Override
public Map<String, Serializable> routeRoom( @Nonnull final Room entity )
{
return routeBuilding( entity.getBuilding() );
}
}
|
package org.realityforge.replicant.example.server.service.tyrell.replicate;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.enterprise.context.Dependent;
import org.realityforge.replicant.example.server.entity.tyrell.Building;
import org.realityforge.replicant.example.server.entity.tyrell.Room;
import org.realityforge.replicant.example.server.entity.tyrell.TyrellRouter;
@Dependent
public class EntityRouter
implements TyrellRouter
{
public static final String BUILDING_KEY = "Tyrell.BuildingID";
@Nonnull
@Override
public Map<String, Serializable> routeBuilding( @Nonnull final Building entity )
{
final HashMap<String, Serializable> map = new HashMap<>();
map.put( BUILDING_KEY, entity.getID() );
return map;
}
@Nonnull
@Override
public Map<String, Serializable> routeRoom( @Nonnull final Room entity )
{
return routeBuilding( entity.getBuilding() );
}
}
|
Increase timeout a lot because Windows is slow.
|
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
release: {},
simplemocha: {
options: {
timeout: 600000,
reporter: 'spec'
},
all: { src: ['test/**/*.js'] }
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
lib: ['lib/**/*.js', 'Gruntfile.js'],
test: ['test/**/*.js']
}
});
grunt.registerTask('default', 'test');
grunt.registerTask('test', [ 'jshint', 'simplemocha' ]);
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-release');
grunt.loadNpmTasks('grunt-simple-mocha');
};
|
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
release: {},
simplemocha: {
options: {
timeout: 60000,
reporter: 'spec'
},
all: { src: ['test/**/*.js'] }
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
lib: ['lib/**/*.js', 'Gruntfile.js'],
test: ['test/**/*.js']
}
});
grunt.registerTask('default', 'test');
grunt.registerTask('test', [ 'jshint', 'simplemocha' ]);
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-release');
grunt.loadNpmTasks('grunt-simple-mocha');
};
|
Use 8 characters for email address rather than 10.
|
from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 8 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 8 = 1.11429157 x 10 ** 14
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(8) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
|
from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 10 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 10 = 3.62033331 x 10 ** 17
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(10) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
|
Disable a pointless override warning.
This is a valid warning, but only on python3. On python2, the default
is False. I don't want to crud up the code with a bunch of conditionals
for stuff like this.
|
#!/usr/bin/python
import unittest
from decimal import Decimal
from blivet import util
class MiscTest(unittest.TestCase):
# Disable this warning, which will only be triggered on python3. For
# python2, the default is False.
longMessage = True # pylint: disable=pointless-class-attribute-override
def test_power_of_two(self):
self.assertFalse(util.power_of_two(None))
self.assertFalse(util.power_of_two("not a number"))
self.assertFalse(util.power_of_two(Decimal(2.2)))
self.assertFalse(util.power_of_two(-1))
self.assertFalse(util.power_of_two(0))
self.assertFalse(util.power_of_two(1))
for i in range(1, 60, 5):
self.assertTrue(util.power_of_two(2 ** i), msg=i)
self.assertFalse(util.power_of_two(2 ** i + 1), msg=i)
self.assertFalse(util.power_of_two(2 ** i - 1), msg=i)
|
#!/usr/bin/python
import unittest
from decimal import Decimal
from blivet import util
class MiscTest(unittest.TestCase):
longMessage = True
def test_power_of_two(self):
self.assertFalse(util.power_of_two(None))
self.assertFalse(util.power_of_two("not a number"))
self.assertFalse(util.power_of_two(Decimal(2.2)))
self.assertFalse(util.power_of_two(-1))
self.assertFalse(util.power_of_two(0))
self.assertFalse(util.power_of_two(1))
for i in range(1, 60, 5):
self.assertTrue(util.power_of_two(2 ** i), msg=i)
self.assertFalse(util.power_of_two(2 ** i + 1), msg=i)
self.assertFalse(util.power_of_two(2 ** i - 1), msg=i)
|
Use headless Chrome for Protractor tests
(see https://github.com/angular/protractor/blob/master/docs/browser-setup.md)
|
'use strict'
exports.config = {
directConnect: true,
allScriptsTimeout: 80000,
specs: [
'test/e2e/*.js'
],
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: [ "--headless", "--disable-gpu", "--window-size=800,600" ]
}
},
baseUrl: 'http://localhost:3000',
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 80000
},
onPrepare: function () {
var jasmineReporters = require('jasmine-reporters')
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'build/reports/e2e_results'
}))
// Get cookie consent popup out of the way
browser.get('/#')
browser.manage().addCookie({ name: 'cookieconsent_status', value: 'dismiss' })
}
}
|
'use strict'
exports.config = {
directConnect: true,
allScriptsTimeout: 80000,
specs: [
'test/e2e/*.js'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:3000',
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 80000
},
onPrepare: function () {
var jasmineReporters = require('jasmine-reporters')
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'build/reports/e2e_results'
}))
// Get cookie consent popup out of the way
browser.get('/#')
browser.manage().addCookie({ name: 'cookieconsent_status', value: 'dismiss' })
}
}
|
Fix type in overridden setting
|
import urlparse
from django.test import TestCase, override_settings
from django.conf import settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
mock_request = Mock()
with patch('opendebates.utils.cache') as mock_cache:
mock_cache.get.return_value = 2
context = global_vars(mock_request)
self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
class ThemeTests(TestCase):
def setUp(self):
self.idea = SubmissionFactory()
@override_settings(SITE_THEME={'HASHTAG': 'TestHashtag'})
def test_email_url(self):
email_url = self.idea.email_url()
fields = urlparse.parse_qs(urlparse.urlparse(email_url).query)
self.assertTrue('subject' in fields, fields)
self.assertTrue('#TestHashtag' in fields['subject'][0], fields['subject'][0])
|
import urlparse
from django.test import TestCase, override_settings
from django.conf import settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
mock_request = Mock()
with patch('opendebates.utils.cache') as mock_cache:
mock_cache.get.return_value = 2
context = global_vars(mock_request)
self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
class ThemeTests(TestCase):
def setUp(self):
self.idea = SubmissionFactory()
@override_settings(SITE_THEME={'HASHTAG': 'TestHastag'})
def test_email_url(self):
settings.SITE_THEME['HASHTAG'] = 'TestHashtag'
email_url = self.idea.email_url()
fields = urlparse.parse_qs(urlparse.urlparse(email_url).query)
self.assertTrue('subject' in fields, fields)
self.assertTrue('#TestHashtag' in fields['subject'][0], fields['subject'][0])
|
Add dependency on the dataclasses library
This dependency is optional in Python 3.7 or later,
as [PEP 557] made it part of the standard library.
[PEP 557]: https://www.python.org/dev/peps/pep-0557/
|
from setuptools import setup
def readme():
with open('README.md') as file:
return file.read()
setup(
name='ppb-vector',
version='0.4.0rc1',
packages=['ppb_vector'],
url='http://github.com/pathunstrom/ppb-vector',
license='',
author='Piper Thunstrom',
author_email='pathunstrom@gmail.com',
description='A basic game development Vector2 class.',
install_requires=[
"dataclasses; python_version < '3.7'",
],
long_description=readme(),
long_description_content_type="text/markdown",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
'Topic :: Scientific/Engineering :: Mathematics',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
zip_safe=True,
)
|
from setuptools import setup
def readme():
with open('README.md') as file:
return file.read()
setup(
name='ppb-vector',
version='0.4.0rc1',
packages=['ppb_vector'],
url='http://github.com/pathunstrom/ppb-vector',
license='',
author='Piper Thunstrom',
author_email='pathunstrom@gmail.com',
description='A basic game development Vector2 class.',
long_description=readme(),
long_description_content_type="text/markdown",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
'Topic :: Scientific/Engineering :: Mathematics',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
zip_safe=True,
)
|
Fix editor card header duplicate prefix
|
import React, { PropTypes } from 'react';
import { StyleSheet, css } from 'aphrodite';
import { Card, CardHeader, CardText, CardActions} from 'material-ui/Card';
const styles = StyleSheet.create({
blockEditor: {
margin: '0 0 1.4em',
}
});
const EditorCard = ({ title, children, actions }) => (
<Card
className={css(styles.blockEditor)}
>
<CardHeader title={title} />
<CardText>
{children}
</CardText>
{actions && (
<CardActions>
{actions}
</CardActions>
)}
</Card>
);
EditorCard.propTypes = {
title: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
actions: PropTypes.node,
};
export default EditorCard;
|
import React, { PropTypes } from 'react';
import { StyleSheet, css } from 'aphrodite';
import { Card, CardHeader, CardText, CardActions} from 'material-ui/Card';
const styles = StyleSheet.create({
blockEditor: {
margin: '0 0 1.4em',
}
});
const EditorCard = ({ title, children, actions }) => (
<Card
className={css(styles.blockEditor)}
>
<CardHeader title={`Block: ${title}`}/>
<CardText>
{children}
</CardText>
{actions && (
<CardActions>
{actions}
</CardActions>
)}
</Card>
);
EditorCard.propTypes = {
title: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
actions: PropTypes.node,
};
export default EditorCard;
|
Work with custom user models in django >= 1.5
|
from django.contrib import admin
from django.conf import settings
from django.db.models import get_model
from django.contrib.auth.models import Group
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.forms import UserChangeForm
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except:
from django.contrib.auth.models import User
try:
module_name, class_name = settings.AUTH_USER_ADMIN_CLASS.rsplit('.', 1)
mod = __import__(module_name, fromlist=[class_name])
UserAdmin = getattr(mod, class_name)
except:
from django.contrib.auth.admin import UserAdmin
from mptt.forms import TreeNodeMultipleChoiceField
if getattr(settings, 'MPTT_USE_FEINCMS', False):
from mptt.admin import FeinCMSModelAdmin
class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin):
pass
else:
from mptt.admin import MPTTModelAdmin
class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin):
pass
admin.site.unregister(Group)
admin.site.register(Group, GroupMPTTModelAdmin)
class UserWithMPTTChangeForm(UserChangeForm):
groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all())
class UserWithMPTTAdmin(UserAdmin):
form = UserWithMPTTChangeForm
admin.site.unregister(User)
admin.site.register(User, UserWithMPTTAdmin)
|
from django.contrib import admin
from django.conf import settings
from django.db.models import get_model
from django.contrib.auth.models import Group
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.forms import UserChangeForm
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except:
from django.contrib.auth.models import User
try:
module_name, class_name = settings.AUTH_USER_ADMIN_MODEL.rsplit('.', 1)
mod = __import__(module_name, fromlist=[class_name])
UserAdmin = getattr(mod, class_name)
except:
from django.contrib.auth.admin import UserAdmin
from mptt.forms import TreeNodeMultipleChoiceField
if getattr(settings, 'MPTT_USE_FEINCMS', False):
from mptt.admin import FeinCMSModelAdmin
class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin):
pass
else:
from mptt.admin import MPTTModelAdmin
class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin):
pass
admin.site.unregister(Group)
admin.site.register(Group, GroupMPTTModelAdmin)
class UserWithMPTTChangeForm(UserChangeForm):
groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all())
class UserWithMPTTAdmin(UserAdmin):
form = UserWithMPTTChangeForm
admin.site.unregister(User)
admin.site.register(User, UserWithMPTTAdmin)
|
Fix imports for management command
|
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from twitter import OAuth, Twitter
from latest_tweets.models import Tweet
from latest_tweets.utils import update_tweets
@transaction.atomic
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
tweet_list = update_tweets(messages=messages)
# To ensure we delete any deleted tweets
oldest_date = None
tweet_id_list = []
for i in tweet_list:
# Help prune out deleted tweets
if not oldest_date or i.created < oldest_date:
oldest_date = i.created
tweet_id_list.append(i.id)
# Remove any deleted tweets in our date range
Tweet.objects.filter(user=user, created__gt=oldest_date).exclude(id__in=tweet_id_list).delete()
class Command(BaseCommand):
args = 'user [user ...]'
def handle(self, *args, **options):
for i in args:
update_user(i)
|
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from twitter import OAuth, Twitter
from ..models import Tweet
from ..utils import update_tweets
@transaction.atomic
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
tweet_list = update_tweets(messages=messages)
# To ensure we delete any deleted tweets
oldest_date = None
tweet_id_list = []
for i in tweet_list:
# Help prune out deleted tweets
if not oldest_date or i.created < oldest_date:
oldest_date = i.created
tweet_id_list.append(i.id)
# Remove any deleted tweets in our date range
Tweet.objects.filter(user=user, created__gt=oldest_date).exclude(id__in=tweet_id_list).delete()
class Command(BaseCommand):
args = 'user [user ...]'
def handle(self, *args, **options):
for i in args:
update_user(i)
|
Refactor addUser function for readability.
|
'use strict';
module.exports = function(app) {
app.controller('CreateGameController', ['$rootScope', 'UserService', 'FriendService', 'GameService', function($rs, UserService, FriendService, GameService) {
let ctrl = this;
ctrl.user = UserService.data.user;
ctrl.allFriends = FriendService.data.allFriends;
ctrl.players = [];
ctrl.editing = false;
ctrl.createGame = function(gameData) {
gameData.players = ctrl.players;
GameService.createGame(gameData);
}
ctrl.addUser = function(user) {
let friendsArray = ctrl.allFriends.friends;
ctrl.players.push(user);
friendsArray.splice(friendsArray.indexOf(user), 1);
}
ctrl.removeUser = function(user) {
ctrl.players.splice(ctrl.players.indexOf(user), 1);
ctrl.allFriends.friends.push(user);
}
ctrl.init = function() {
let userData = {
_id: ctrl.user._id,
fullName: ctrl.user.fullName,
email: ctrl.user.email,
};
ctrl.players.push(userData);
FriendService.getAllFriends(ctrl.user.email);
}
ctrl.init();
}]);
}
|
'use strict';
module.exports = function(app) {
app.controller('CreateGameController', ['$rootScope', 'UserService', 'FriendService', 'GameService', function($rs, UserService, FriendService, GameService) {
let ctrl = this;
ctrl.user = UserService.data.user;
ctrl.allFriends = FriendService.data.allFriends;
ctrl.players = [];
ctrl.editing = false;
ctrl.createGame = function(gameData) {
gameData.players = ctrl.players;
GameService.createGame(gameData);
}
ctrl.addUser = function(user) {
ctrl.players.push(user);
ctrl.allFriends.friends.splice(ctrl.allFriends.friends.indexOf(user), 1);
}
ctrl.removeUser = function(user) {
ctrl.players.splice(ctrl.players.indexOf(user), 1);
ctrl.allFriends.friends.push(user);
}
ctrl.init = function() {
let userData = {
_id: ctrl.user._id,
fullName: ctrl.user.fullName,
email: ctrl.user.email,
};
ctrl.players.push(userData);
FriendService.getAllFriends(ctrl.user.email);
}
ctrl.init();
}]);
}
|
Add site log received SNS topic
|
from amazonia.classes.sns import SNS
from troposphere import Ref, Join, cloudwatch
from troposphere.sns import Topic, Subscription
def user_registration_topic(emails):
return topic("UserRegistrationReceived", emails)
def new_cors_site_request_received_topic(emails):
return topic("NewCorsSiteRequestReceived", emails)
def site_log_received_topic(emails):
return topic("SiteLogReceived", emails)
def topic(topic_title, emails):
topic = Topic(topic_title,
DisplayName=Join("", [Ref("AWS::StackName"), "-", topic_title]))
topic.Subscription = []
for index, email in enumerate(emails):
topic.Subscription.append(Subscription(
topic_title + "Subscription" + str(index),
Endpoint=email,
Protocol="email"))
return topic
def customise_stack_template(template):
template.add_resource(user_registration_topic([]))
template.add_resource(new_cors_site_request_received_topic([]))
template.add_resource(site_log_received_topic([]))
return template
|
from amazonia.classes.sns import SNS
from troposphere import Ref, Join, cloudwatch
from troposphere.sns import Topic, Subscription
def user_registration_topic(emails):
return topic("UserRegistrationReceived", emails)
def new_cors_site_request_received_topic(emails):
return topic("NewCorsSiteRequestReceived", emails)
def topic(topic_title, emails):
topic = Topic(topic_title,
DisplayName=Join("", [Ref("AWS::StackName"), "-", topic_title]))
topic.Subscription = []
for index, email in enumerate(emails):
topic.Subscription.append(Subscription(
topic_title + "Subscription" + str(index),
Endpoint=email,
Protocol="email"))
return topic
def customise_stack_template(template):
template.add_resource(user_registration_topic([]))
template.add_resource(new_cors_site_request_received_topic([]))
return template
|
Add app root dir to settings.
|
/**
* ActiveRules implemented on top of Koa.
*
* @module arkoa
* @copyright 2015 - Brian Winkers
* @license MIT
*/
"use strict";
/**
* System wide settings, most settings will be in ActiveRules sites
* File-based Configuration support, using nconf for bow
*
* Setup nconf to use (in-order):
* 1. Command-line arguments
* 2. Environment variables
* 3. A file located at 'path/to/config.json'
*
* @type {exports}
*/
var settings = require('nconf');
settings.argv()
.env()
.file({ file: './config/settings.json' });
// Add the app root to the settings
settings.add('app', { type: 'literal', store: { 'rootDir': __dirname} });
/**
* Koala provides a Koa app with good default middleware
*
* @type {function(): app|exports}
*/
var koa = require('koala');
/**
* Create the Koa app with Koala middleware
*/
var app = koa();
/**
* Include the controller routes and handlers
*/
var router = require('./lib/controllers');
/**
* Load the service controllers and their configured routes
*/
router.loadControllers(settings);
/**
* Use the routes in our app
*/
app
.use(router.routes())
.use(router.allowedMethods());
/**
* Have the App accept Requests
*/
app.listen(3000);
|
/**
* ActiveRules implemented on top of Koa.
*
* @module arkoa
* @copyright 2015 - Brian Winkers
* @license MIT
*/
"use strict";
/**
* System wide settings, most settings will be in ActiveRules sites
* File-based Configuration support, using nconf for bow
*
* Setup nconf to use (in-order):
* 1. Command-line arguments
* 2. Environment variables
* 3. A file located at 'path/to/config.json'
*
* @type {exports}
*/
var settings = require('nconf');
settings.argv()
.env()
.file({ file: './config/settings.json' });
/**
* Koala provides a Koa app with good default middleware
*
* @type {function(): app|exports}
*/
var koa = require('koala');
/**
* Create the Koa app with Koala middleware
*/
var app = koa();
/**
* Include the controller routes and handlers
*/
var router = require('./lib/controllers');
/**
* Load the service controllers and their configured routes
*/
router.loadControllers(settings.get('services'));
/**
* Use the routes in our app
*/
app
.use(router.routes())
.use(router.allowedMethods());
/**
* Have the App accept Requests
*/
app.listen(3000);
|
Increase number of photos downloaded to 50 at once
fixes issue where on 10in screen images dont fill the screen and scroll doesnt work, disabling loading of more images
|
package com.michaldabski.panoramio.requests;
import com.android.volley.Response;
/**
* Created by Michal on 10/08/2014.
*/
public class NearbyPhotosRequest extends PanoramioRequest
{
public static final int NUM_PHOTOS = 50;
private static final float
LAT_MULTIPLIER = 0.4f,
LON_MULTIPLIER = 1f;
private final float userLat, userLong;
public NearbyPhotosRequest(Response.ErrorListener listener, float latitude, float longitude, int from, int to, float distance)
{
super(listener, longitude-(distance* LON_MULTIPLIER), latitude-(distance* LAT_MULTIPLIER), longitude+(distance*LON_MULTIPLIER), latitude+(distance*LAT_MULTIPLIER), from, to);
userLat = latitude;
userLong = longitude;
}
public NearbyPhotosRequest(Response.ErrorListener listener, float latitude, float longitude, int from, float distance)
{
this(listener, latitude, longitude, from, from+NUM_PHOTOS, distance);
}
}
|
package com.michaldabski.panoramio.requests;
import com.android.volley.Response;
/**
* Created by Michal on 10/08/2014.
*/
public class NearbyPhotosRequest extends PanoramioRequest
{
public static final int NUM_PHOTOS = 30;
private static final float
LAT_MULTIPLIER = 0.4f,
LON_MULTIPLIER = 1f;
private final float userLat, userLong;
public NearbyPhotosRequest(Response.ErrorListener listener, float latitude, float longitude, int from, int to, float distance)
{
super(listener, longitude-(distance* LON_MULTIPLIER), latitude-(distance* LAT_MULTIPLIER), longitude+(distance*LON_MULTIPLIER), latitude+(distance*LAT_MULTIPLIER), from, to);
userLat = latitude;
userLong = longitude;
}
public NearbyPhotosRequest(Response.ErrorListener listener, float latitude, float longitude, int from, float distance)
{
this(listener, latitude, longitude, from, from+NUM_PHOTOS, distance);
}
}
|
Reformat SQLLogger comments to fit in godoc HTML page.
|
package sqlstmt
import (
"database/sql"
)
// DB is the interface that wraps the database access methods
// used by this package.
//
// The *DB and *Tx types in the standard library package "database/sql"
// both implement this interface.
type DB interface {
// Exec executes a query without returning any rows.
// The args are for any placeholder parameters in the query.
Exec(query string, args ...interface{}) (sql.Result, error)
// Query executes a query that returns rows, typically a SELECT.
// The args are for any placeholder parameters in the query.
Query(query string, args ...interface{}) (*sql.Rows, error)
}
// SQLLogger is an interface for logging SQL statements executed
// by the sqlstmt package.
type SQLLogger interface {
// LogSQL is called by the sqlstmt package after it executes
// an SQL query or statement.
//
// The query and args variables provide the query and associated
// arguments supplied to the database server. The rowsAffected
// and err variables provide a summary of the query results.
// If the number of rows affected cannot be determined for any reason,
// then rowsAffected is set to -1.
LogSQL(query string, args []interface{}, rowsAffected int, err error)
}
|
package sqlstmt
import (
"database/sql"
)
// DB is the interface that wraps the database access methods
// used by this package.
//
// The *DB and *Tx types in the standard library package "database/sql"
// both implement this interface.
type DB interface {
// Exec executes a query without returning any rows.
// The args are for any placeholder parameters in the query.
Exec(query string, args ...interface{}) (sql.Result, error)
// Query executes a query that returns rows, typically a SELECT.
// The args are for any placeholder parameters in the query.
Query(query string, args ...interface{}) (*sql.Rows, error)
}
// SQLLogger is an interface for logging SQL statements executed
// by the sqlstmt package.
type SQLLogger interface {
// LogSQL is called by the sqlstmt package after it executes an SQL query or statement.
//
// The query and args variables provide the query and associated arguments supplied to
// the database server. The rowsAffected and err variables provide a summary of the
// query results. If the number of rows affected cannot be determined for any reason,
// then rowsAffected is set to -1.
LogSQL(query string, args []interface{}, rowsAffected int, err error)
}
|
Add singer-tools as a dev dependency
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import subprocess
setup(name="singer-python",
version='5.0.7',
description="Singer.io utility library",
author="Stitch",
classifiers=['Programming Language :: Python :: 3 :: Only'],
url="http://singer.io",
install_requires=[
'jsonschema==2.6.0',
'pendulum==1.2.0',
'simplejson==3.11.1',
'python-dateutil>=2.6.0',
'backoff==1.3.2',
],
extras_require={
'dev': [
'pylint',
'nose',
'singer-tools'
]
},
packages=find_packages(),
package_data = {
'singer': [
'logging.conf'
]
},
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import subprocess
setup(name="singer-python",
version='5.0.7',
description="Singer.io utility library",
author="Stitch",
classifiers=['Programming Language :: Python :: 3 :: Only'],
url="http://singer.io",
install_requires=[
'jsonschema==2.6.0',
'pendulum==1.2.0',
'simplejson==3.11.1',
'python-dateutil>=2.6.0',
'backoff==1.3.2',
],
extras_require={
'dev': [
'pylint',
'nose'
]
},
packages=find_packages(),
package_data = {
'singer': [
'logging.conf'
]
},
)
|
Improve efficiency of queue loop
This commit avoids a property lookup on every iteration of the
queue-consuming loop by first storing it in a variable, since we don't
expect the size of the array to change within the duration of the loop.
This will make the initialization slightly more efficient.
Change-Id: Ied891fd5fd360c9732e61c7cf8a645ec63801cc6
Reviewed-on: https://gerrit.causes.com/23783
Tested-by: Joe Lencioni <1dd72cf724deaab5db236f616560fc7067b734e1@causes.com>
Reviewed-by: Greg Hurrell <79e2475f81a6317276bf7cbb3958b20d289b78df@causes.com>
|
var MethodProxy = function(object, queue) {
this.init = function(object, queue) {
this.object = object;
for (var i = 0, len = queue.length; i < len; ++i) {
this.forward(queue[i]);
}
};
// payload : ['methodName', arguments*]
this.push = this.forward = function(payload) {
var methodName = payload.shift().split('.'),
object = this.object,
method;
while (methodName.length) {
// dig into the object as many levels as needed (e.g. `FB.XFBML.parse`)
if (method) {
object = object[method];
}
method = methodName.shift();
}
return object[method].apply(object, payload);
};
this.init(object, queue);
};
|
var MethodProxy = function(object, queue) {
this.init = function(object, queue) {
this.object = object;
for (var i = 0; i < queue.length; ++i) {
this.forward(queue[i]);
}
};
// payload : ['methodName', arguments*]
this.push = this.forward = function(payload) {
var methodName = payload.shift().split('.'),
object = this.object,
method;
while (methodName.length) {
// dig into the object as many levels as needed (e.g. `FB.XFBML.parse`)
if (method) {
object = object[method];
}
method = methodName.shift();
}
return object[method].apply(object, payload);
};
this.init(object, queue);
};
|
Add block structure to perception handler. Slightly change perception handler logic.
|
"""
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import structure
class PerceptionHandler(object):
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a percept given an agent and a world.
:param agent: The agent to generate the percept for.
:param world: The world to generate the percept for.
:return: The percept.
"""
raise NotImplementedError("Should be implemented by child")
class EmptyPerceptionHandler(PerceptionHandler):
def perceive(self, agent, world):
return ""
class BasicPerceptionHandler(PerceptionHandler):
def perceive(self, agent_, world_):
for delta in range(0, 10):
pos = world.Position(agent_.get_position())
pos.add(agent_.get_move_delta(delta))
entities = world_.get_entities_at(pos)
for entity in entities:
if entity == agent_:
continue
if isinstance(entity, structure.Wall):
return "w%s" % delta
elif isinstance(entity, structure.Block):
return "b%s" % delta
return ""
|
"""
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import structure
class PerceptionHandler(object):
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a percept given an agent and a world.
:param agent: The agent to generate the percept for.
:param world: The world to generate the percept for.
:return: The percept.
"""
raise NotImplementedError("Should be implemented by child")
class EmptyPerceptionHandler(PerceptionHandler):
def perceive(self, agent, world):
return ""
class BasicPerceptionHandler(PerceptionHandler):
def perceive(self, agent_, world_):
for delta in range(1, 10):
pos = world.Position(agent_.get_position())
pos.add(agent_.get_move_delta(delta))
entities = world_.get_entities_at(pos)
if len(entities) > 0:
if isinstance(entities[0], structure.Wall):
return "w%s" % delta
return ""
|
Change something so tests are not skipped
|
"""Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported via
an import statement.
"""
import runpy
import sys
import types
from importlib.machinery import ModuleSpec, PathFinder
from os.path import dirname
from typing import Optional, Sequence, Union
PIP_SOURCES_ROOT = dirname(dirname(__file__))
class PipImportRedirectingFinder:
@classmethod
def find_spec(
self,
fullname: str,
path: Optional[Sequence[Union[bytes, str]]] = None,
target: Optional[types.ModuleType] = None,
) -> Optional[ModuleSpec]:
if fullname != "pip":
return None
spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)
assert spec, (PIP_SOURCES_ROOT, fullname)
return spec
# TODO https://github.com/pypa/pip/issues/11294
sys.meta_path.insert(0, PipImportRedirectingFinder())
assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
runpy.run_module("pip", run_name="__main__", alter_sys=True)
|
"""Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported via
an import statement.
"""
import runpy
import sys
import types
from importlib.machinery import ModuleSpec, PathFinder
from os.path import dirname
from typing import Optional, Sequence, Union
PIP_SOURCES_ROOT = dirname(dirname(__file__))
class PipImportRedirectingFinder:
@classmethod
def find_spec(
self,
fullname: str,
path: Optional[Sequence[Union[bytes, str]]] = None,
target: Optional[types.ModuleType] = None,
) -> Optional[ModuleSpec]:
if fullname != "pip":
return None
spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)
assert spec, (PIP_SOURCES_ROOT, fullname)
return spec
sys.meta_path.insert(0, PipImportRedirectingFinder())
assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
runpy.run_module("pip", run_name="__main__", alter_sys=True)
|
Modify Parameter trait to get all not null properties
|
<?php
namespace AdobeConnectClient\Traits;
trait ParameterTrait
{
/**
* Retrieves all not null attributes as an associative array
*
* @return array An associative array
*/
public function toArray()
{
$values = [];
foreach ($this as $prop => $value) {
if (!isset($value)) {
continue;
}
if (is_bool($value)) {
$value = \AdobeConnectClient\Helper\BooleanTransform::toString($value);
} elseif ($value instanceof \DateTime) {
$value = $value->format(\DateTime::W3C);
}
$values[\AdobeConnectClient\Helper\StringCaseTransform::toHyphen($prop)] = $value;
}
return $values;
}
}
|
<?php
namespace AdobeConnectClient\Traits;
use \AdobeConnectClient\Helper\StringCaseTransform as SCT;
use \AdobeConnectClient\Helper\BooleanTransform as B;
/**
* Converts the public properties into an array to use in the WS call
*
* Works only for the not empty properties. False and null are considered empty values.
*/
trait ParameterTrait
{
/**
* Convert the public properties into an array to use in the WS call
*
* @return array
*/
public function toArray()
{
$parameters = [];
foreach ($this as $field => $value) {
if (empty($value)) {
continue;
}
if (is_bool($value)) {
$value = B::toString($value);
} elseif ($value instanceof \DateTimeInterface) {
$value = $value->format(\DateTime::W3C);
}
$parameters[SCT::toHyphen($field)] = $value;
}
return $parameters;
}
}
|
Fix DB name in NIST tests
|
package com.splicemachine.test.connection;
import com.splicemachine.constants.SpliceConstants;
import java.sql.Connection;
import java.sql.DriverManager;
import org.apache.log4j.Logger;
/**
* Static helper class to get an client connection to Splice
*/
public class SpliceNetConnection extends BaseConnection {
private static final Logger LOG = Logger.getLogger(SpliceNetConnection.class);
private static String driver = "org.apache.derby.jdbc.ClientDriver";
private static String protocol = "jdbc:derby://localhost:";
private static String db = "/splicedb";
private static String createProtocol(String port, boolean createDB) {
return protocol+(port != null?port: SpliceConstants.DEFAULT_DERBY_BIND_PORT)+db+(createDB?create:"");
}
private static synchronized Connection createConnection(String port) throws Exception {
loadDriver(clientDriver);
return DriverManager.getConnection(createProtocol(port, true), props);
}
/**
* Acquire a connection
* @param port optional port to connect to
* @return a new connection
* @throws Exception for any failure
*/
public static Connection getConnection(String port) throws Exception {
if (!loaded) {
return createConnection(port);
} else {
return DriverManager.getConnection(createProtocol(port,false), props);
}
}
}
|
package com.splicemachine.test.connection;
import com.splicemachine.constants.SpliceConstants;
import java.sql.Connection;
import java.sql.DriverManager;
import org.apache.log4j.Logger;
/**
* Static helper class to get an client connection to Splice
*/
public class SpliceNetConnection extends BaseConnection {
private static final Logger LOG = Logger.getLogger(SpliceNetConnection.class);
private static String driver = "org.apache.derby.jdbc.ClientDriver";
private static String protocol = "jdbc:derby://localhost:";
private static String db = "/spliceDB";
private static String createProtocol(String port, boolean createDB) {
return protocol+(port != null?port: SpliceConstants.DEFAULT_DERBY_BIND_PORT)+db+(createDB?create:"");
}
private static synchronized Connection createConnection(String port) throws Exception {
loadDriver(clientDriver);
return DriverManager.getConnection(createProtocol(port, true), props);
}
/**
* Acquire a connection
* @param port optional port to connect to
* @return a new connection
* @throws Exception for any failure
*/
public static Connection getConnection(String port) throws Exception {
if (!loaded) {
return createConnection(port);
} else {
return DriverManager.getConnection(createProtocol(port,false), props);
}
}
}
|
Use accessor to use in sort.
|
# -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(input, collection, accessor=lambda x: x):
"""
Args:
input (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
based on the `input`.
Returns:
suggestions (generator): A generator object that produces a list of
suggestions narrowed down from `collection` using the `input`.
"""
suggestions = []
input = str(input) if not isinstance(input, str) else input
pat = '.*?'.join(map(re.escape, input))
regex = re.compile(pat)
for item in collection:
r = regex.search(accessor(item))
if r:
suggestions.append((len(r.group()), r.start(), accessor(item), item))
return (z[-1] for z in sorted(suggestions))
|
# -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(input, collection, accessor=lambda x: x):
"""
Args:
input (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
based on the `input`.
Returns:
suggestions (generator): A generator object that produces a list of
suggestions narrowed down from `collection` using the `input`.
"""
suggestions = []
input = str(input) if not isinstance(input, str) else input
pat = '.*?'.join(map(re.escape, input))
regex = re.compile(pat)
for item in collection:
r = regex.search(accessor(item))
if r:
suggestions.append((len(r.group()), r.start(), item))
return (z for _, _, z in sorted(suggestions))
|
Change validation handler to use array input instead of assuming a request
|
<?php
namespace Fuzz\ApiServer\Validation;
use Illuminate\Validation\Validator;
use Fuzz\ApiServer\Exception\BadRequestException;
trait ValidatesRequests
{
/**
* Validate the given request with the given rules.
*
* @param array $request
* @param array $rules
* @param array $messages
* @return void
*/
public function validate(array $input, array $rules, array $messages = [])
{
$validator = $this->getValidationFactory()->make($input, $rules, $messages);
if ($validator->fails()) {
$this->throwValidationException($validator);
}
}
/**
* Throw the failed validation exception.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*/
protected function throwValidationException(Validator $validator)
{
throw new BadRequestException('Request validation failed.', $validator->errors()->getMessages());
}
/**
* Get a validation factory instance.
*
* @return \Illuminate\Contracts\Validation\Factory
*/
protected function getValidationFactory()
{
return app('Illuminate\Contracts\Validation\Factory');
}
}
|
<?php
namespace Fuzz\ApiServer\Validation;
use Fuzz\ApiServer\Exception\BadRequestException;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Validator;
use Illuminate\Http\Exception\HttpResponseException;
trait ValidatesRequests
{
/**
* Validate the given request with the given rules.
*
* @param \Illuminate\Http\Request $request
* @param array $rules
* @param array $messages
* @return void
*/
public function validate(Request $request, array $rules, array $messages = [])
{
$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages);
if ($validator->fails()) {
$this->throwValidationException($request, $validator);
}
}
/**
* Throw the failed validation exception.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*/
protected function throwValidationException(Request $request, Validator $validator)
{
throw new BadRequestException('Request validation failed.', $validator->errors()->getMessages());
}
/**
* Get a validation factory instance.
*
* @return \Illuminate\Contracts\Validation\Factory
*/
protected function getValidationFactory()
{
return app('Illuminate\Contracts\Validation\Factory');
}
}
|
Remove JSONP callback function once done
|
var _paramanders$elm_twitch_chat$Native_Jsonp = function() {
function jsonp(url, callbackName)
{
return _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) {
window[callbackName] = function(content)
{
callback(_elm_lang$core$Native_Scheduler.succeed(JSON.stringify(content)));
delete window[callbackName];
};
var scriptTag = createScript(url, callbackName);
document.head.appendChild(scriptTag);
document.head.removeChild(scriptTag);
});
}
function createScript(url, callbackName)
{
var s = document.createElement('script');
s.type = 'text/javascript';
if (url.indexOf('?') >= 0)
{
s.src = url + '&callback=' + callbackName;
}
else {
s.src = url + '?callback=' + callbackName;
}
return s;
}
return {
jsonp: F2(jsonp)
};
}();
|
var _paramanders$elm_twitch_chat$Native_Jsonp = function() {
function jsonp(url, callbackName)
{
return _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) {
window[callbackName] = function(content)
{
callback(_elm_lang$core$Native_Scheduler.succeed(JSON.stringify(content)));
};
var scriptTag = createScript(url, callbackName);
document.head.appendChild(scriptTag);
document.head.removeChild(scriptTag);
});
}
function createScript(url, callbackName)
{
var s = document.createElement('script');
s.type = 'text/javascript';
if (url.indexOf('?') >= 0)
{
s.src = url + '&callback=' + callbackName;
}
else {
s.src = url + '?callback=' + callbackName;
}
return s;
}
return {
jsonp: F2(jsonp)
};
}();
|
[Bugfix] Correct validators generator command description
Merge pull request #42 from SirLamer/patch-1
Correct make:json-api:validators description typo
|
<?php
/**
* Copyright 2016 Cloud Creativity Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace CloudCreativity\LaravelJsonApi\Console\Commands;
/**
* Class ValidatorsMakeCommand
*
* @package CloudCreativity\LaravelJsonApi
*/
class ValidatorsMakeCommand extends AbstractGeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:json-api:validators';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new JSON API resource validator';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Validators';
/**
* Whether the resource type is non-dependent on eloquent
*
* @var boolean
*/
protected $isIndependent = true;
}
|
<?php
/**
* Copyright 2016 Cloud Creativity Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace CloudCreativity\LaravelJsonApi\Console\Commands;
/**
* Class ValidatorsMakeCommand
*
* @package CloudCreativity\LaravelJsonApi
*/
class ValidatorsMakeCommand extends AbstractGeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:json-api:validators';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new JSON API resource search';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Validators';
/**
* Whether the resource type is non-dependent on eloquent
*
* @var boolean
*/
protected $isIndependent = true;
}
|
Replace requestNamespace by xmlNamespace method
|
<?php
/**
* This file is part of the Zimbra API in PHP library.
*
* © Nguyen Van Nguyen <nguyennv1981@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zimbra\Voice\Request;
use Zimbra\Soap\Request;
/**
* Base voice request class
*
* @package Zimbra
* @subpackage Voice
* @category Request
* @author Nguyen Van Nguyen - nguyennv1981@gmail.com
* @copyright Copyright © 2013 by Nguyen Van Nguyen.
*/
abstract class Base extends Request
{
/**
* Constructor method for base request
* @param string $value
* @return self
*/
public function __construct($value = null)
{
parent::__construct($value);
$this->xmlNamespace('urn:zimbraVoice');
}
}
|
<?php
/**
* This file is part of the Zimbra API in PHP library.
*
* © Nguyen Van Nguyen <nguyennv1981@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zimbra\Voice\Request;
use Zimbra\Soap\Request;
/**
* Base voice request class
*
* @package Zimbra
* @subpackage Voice
* @category Request
* @author Nguyen Van Nguyen - nguyennv1981@gmail.com
* @copyright Copyright © 2013 by Nguyen Van Nguyen.
*/
abstract class Base extends Request
{
/**
* Constructor method for base request
* @param string $value
* @return self
*/
public function __construct($value = null)
{
parent::__construct($value);
$this->requestNamespace('urn:zimbraVoice');
}
}
|
Fix the entrypoint missing the path prefix
|
import SubmissionError from '../error/SubmissionError'
import { ENTRYPOINT } from '../config/entrypoint';
const MIME_TYPE = 'application/ld+json'
export default function (id, options = {}) {
if (typeof options.headers === 'undefined') Object.assign(options, { headers: new Headers() })
if (options.headers.get('Accept') === null) options.headers.set('Accept', MIME_TYPE)
if (options.body !== undefined && !(options.body instanceof FormData) && options.headers.get('Content-Type') === null) {
options.headers.set('Content-Type', MIME_TYPE)
}
const entryPoint = ENTRYPOINT + (ENTRYPOINT.endsWith('/') ? '' : '/')
return fetch(new URL(id, entryPoint), options).then((response) => {
if (response.ok) return response
return response
.json()
.then((json) => {
const error = json['{{{hydraPrefix}}}description'] ? json['{{{hydraPrefix}}}description'] : response.statusText
if (!json.violations) throw Error(error)
const errors = { _error: error }
json.violations.map(violation =>
Object.assign(errors, { [violation.propertyPath]: violation.message }))
throw new SubmissionError(errors)
})
})
}
|
import SubmissionError from '../error/SubmissionError'
import { ENTRYPOINT } from '../config/entrypoint';
const MIME_TYPE = 'application/ld+json'
export default function (id, options = {}) {
if (typeof options.headers === 'undefined') Object.assign(options, { headers: new Headers() })
if (options.headers.get('Accept') === null) options.headers.set('Accept', MIME_TYPE)
if (options.body !== undefined && !(options.body instanceof FormData) && options.headers.get('Content-Type') === null) {
options.headers.set('Content-Type', MIME_TYPE)
}
return fetch(new URL(id, ENTRYPOINT).toString(), options).then((response) => {
if (response.ok) return response
return response
.json()
.then((json) => {
const error = json['{{{hydraPrefix}}}description'] ? json['{{{hydraPrefix}}}description'] : response.statusText
if (!json.violations) throw Error(error)
const errors = { _error: error }
json.violations.map(violation =>
Object.assign(errors, { [violation.propertyPath]: violation.message }))
throw new SubmissionError(errors)
})
})
}
|
Use fail() method in tests
|
package com.sanction.thunder.authentication;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.basic.BasicCredentials;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ThunderAuthenticatorTest {
private final Key key = new Key("application", "secret");
private final List<Key> keys = Lists.newArrayList(key);
private final ThunderAuthenticator authenticator = new ThunderAuthenticator(keys);
@Test
public void testAuthenticateWithValidCredentials() {
BasicCredentials credentials = new BasicCredentials("application", "secret");
Optional<Key> result = Optional.absent();
try {
result = authenticator.authenticate(credentials);
} catch (AuthenticationException e) {
// This shouldn't happen, so fail the test.
fail();
}
assertTrue(result.isPresent());
assertEquals(key, result.get());
}
@Test
public void testAuthenticateWithInvalidCredentials() {
BasicCredentials credentials = new BasicCredentials("invalidApplication", "secret");
Optional<Key> result = Optional.absent();
try {
result = authenticator.authenticate(credentials);
} catch (AuthenticationException e) {
// This shouldn't happen, so fail the test.
fail();
}
assertFalse(result.isPresent());
}
}
|
package com.sanction.thunder.authentication;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.basic.BasicCredentials;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ThunderAuthenticatorTest {
private final Key key = new Key("application", "secret");
private final List<Key> keys = Lists.newArrayList(key);
private final ThunderAuthenticator authenticator = new ThunderAuthenticator(keys);
@Test
public void testAuthenticateWithValidCredentials() {
BasicCredentials credentials = new BasicCredentials("application", "secret");
Optional<Key> result = Optional.absent();
try {
result = authenticator.authenticate(credentials);
} catch (AuthenticationException e) {
// This shouldn't happen, so fail the test.
assertTrue(false);
}
assertTrue(result.isPresent());
assertEquals(key, result.get());
}
@Test
public void testAuthenticateWithInvalidCredentials() {
BasicCredentials credentials = new BasicCredentials("invalidApplication", "secret");
Optional<Key> result = Optional.absent();
try {
result = authenticator.authenticate(credentials);
} catch (AuthenticationException e) {
// This shouldn't happen, so fail the test.
assertTrue(false);
}
assertFalse(result.isPresent());
}
}
|
Make extension work in dev env too
|
var iframe;
function initFrame() {
iframe = document.createElement('iframe');
document.body.appendChild(iframe);
}
// Listen to the parent window send src info to be set on the nested frame
function receiveNestedFrameData() {
var handler = function(e) {
if (e.source !== window.parent && !e.data.src) return;
iframe.src = e.data.src;
iframe.style.cssText = e.data.css;
window.removeEventListener('message', handler);
};
window.addEventListener('message', handler);
}
// Listen to messages from nested frame and pass them up the window stack
function setupMessageRelay() {
window.addEventListener('message', function(e) {
var origin = e.origin || e.originalEvent.origin;
if ((origin !== 'https://buffer.com' && origin !== 'https://local.buffer.com') || e.source !== iframe.contentWindow) {
return;
}
window.parent.postMessage(e.data, '*');
});
}
initFrame();
receiveNestedFrameData();
setupMessageRelay();
|
var iframe;
function initFrame() {
iframe = document.createElement('iframe');
document.body.appendChild(iframe);
}
// Listen to the parent window send src info to be set on the nested frame
function receiveNestedFrameData() {
var handler = function(e) {
if (e.source !== window.parent && !e.data.src) return;
iframe.src = e.data.src;
iframe.style.cssText = e.data.css;
window.removeEventListener('message', handler);
};
window.addEventListener('message', handler);
}
// Listen to messages from nested frame and pass them up the window stack
function setupMessageRelay() {
window.addEventListener('message', function(e) {
var origin = e.origin || e.originalEvent.origin;
if (origin !== 'https://buffer.com' || e.source !== iframe.contentWindow) {
return;
}
window.parent.postMessage(e.data, '*');
});
}
initFrame();
receiveNestedFrameData();
setupMessageRelay();
|
Add uuid to the patient bean in Android
|
package org.msf.records.model;
import java.io.Serializable;
/**
* Created by Gil on 03/10/2014.
*/
public class Patient implements Serializable {
public String id;
public String uuid;
public String given_name;
public String family_name;
public String important_information;
/**
* Accepted values:
* suspected, probable, confirmed, non-case, convalescent,
* can_be_discharged, dischraged, suspected_dead, confirmed_dead
*/
public String status;
public boolean pregnant;
// Must be "M" or "F".
public String gender;
@Deprecated
public String movement;
@Deprecated
public String eating;
public Long admission_timestamp;
public Long created_timestamp;
public Long first_showed_symptoms_timestamp;
public String origin_location;
// Not yet ready.
public String next_of_kin;
public PatientLocation assigned_location;
public PatientAge age;
}
|
package org.msf.records.model;
import java.io.Serializable;
/**
* Created by Gil on 03/10/2014.
*/
public class Patient implements Serializable {
public String id;
public String given_name;
public String family_name;
public String important_information;
/**
* Accepted values:
* suspected, probable, confirmed, non-case, convalescent,
* can_be_discharged, dischraged, suspected_dead, confirmed_dead
*/
public String status;
public boolean pregnant;
// Must be "M" or "F".
public String gender;
@Deprecated
public String movement;
@Deprecated
public String eating;
public Long admission_timestamp;
public Long created_timestamp;
public Long first_showed_symptoms_timestamp;
public String origin_location;
// Not yet ready.
public String next_of_kin;
public PatientLocation assigned_location;
public PatientAge age;
}
|
Update HTML validation error handling for Bootstrap 4
|
<?php
namespace SebastiaanLuca\Helpers\Html;
use Collective\Html\HtmlBuilder as CollectiveHtmlBuilder;
class HtmlBuilder extends CollectiveHtmlBuilder
{
/**
* Get the Bootstrap error class if the given field has a validation error.
*
* @param string $field
*
* @return string
*/
public function highlightOnError(string $field) : string
{
/** @var \Illuminate\Contracts\Support\MessageBag $errors */
$errors = app('session')->get('errors');
if (! $errors || ! $errors->has($field)) {
return '';
}
return 'has-danger';
}
/**
* Get the Bootstrap error help block if the given field has a validation error.
*
* @param string $field
*
* @return string
*/
public function error(string $field) : string
{
/** @var \Illuminate\Contracts\Support\MessageBag $errors */
$errors = app('session')->get('errors');
if (! $errors || ! $errors->has($field)) {
return '';
}
return '<div class="form-control-feedback">' . $errors->first($field) . '</div>';
}
}
|
<?php
namespace SebastiaanLuca\Helpers\Html;
use Collective\Html\HtmlBuilder as CollectiveHtmlBuilder;
class HtmlBuilder extends CollectiveHtmlBuilder
{
/**
* Get the Bootstrap error class if the given field has a validation error.
*
* @param string $field
*
* @return string
*/
public function highlightOnError(string $field) : string
{
/** @var \Illuminate\Contracts\Support\MessageBag $errors */
$errors = app('session')->get('errors');
if (! $errors || ! $errors->has($field)) {
return '';
}
return 'has-error';
}
/**
* Get the Bootstrap error help block if the given field has a validation error.
*
* @param string $field
*
* @return string
*/
public function error(string $field) : string
{
/** @var \Illuminate\Contracts\Support\MessageBag $errors */
$errors = app('session')->get('errors');
if (! $errors || ! $errors->has($field)) {
return '';
}
return '<p class="help-block">' . $errors->first($field) . '</p>';
}
}
|
Use empty to check for empty array
|
<?php
/**
* Wingman
*
* @link http://github.com/mleko/wingman
* @copyright Copyright (c) 2017 Daniel Król
* @license MIT
*/
namespace Mleko\Wingman;
use Mleko\Wingman\IO\Output;
class MistakeChecker
{
private static $possibleMistakes = [
"tags" => "keywords",
"desc" => "description",
"author" => "authors",
"bugs" => "support",
"dependencies" => "require",
"devDependencies" => "require-dev",
"optionalDependencies" => "suggests"
];
private $rules = [];
/**
* MistakeChecker constructor.
* @param array $rules
*/
public function __construct(array $rules = null)
{
$this->rules = null === $rules ? self::$possibleMistakes : $rules;
}
public function checkForMistakes($composerJson, Output $output)
{
$mistakes = array_intersect_key($this->rules, (array)$composerJson);
if (empty($mistakes)) {
return;
}
$output->write("Potential mistakes have been found\n");
foreach ($mistakes as $from => $to) {
$output->write("$from => $to\n");
}
}
}
|
<?php
/**
* Wingman
*
* @link http://github.com/mleko/wingman
* @copyright Copyright (c) 2017 Daniel Król
* @license MIT
*/
namespace Mleko\Wingman;
use Mleko\Wingman\IO\Output;
class MistakeChecker
{
private static $possibleMistakes = [
"tags" => "keywords",
"desc" => "description",
"author" => "authors",
"bugs" => "support",
"dependencies" => "require",
"devDependencies" => "require-dev",
"optionalDependencies" => "suggests"
];
private $rules = [];
/**
* MistakeChecker constructor.
* @param array $rules
*/
public function __construct(array $rules = null)
{
$this->rules = null === $rules ? static::$possibleMistakes : $rules;
}
public function checkForMistakes($composerJson, Output $output)
{
$mistakes = array_intersect_key($this->rules, (array)$composerJson);
if (!$mistakes) {
return;
}
$output->write("Potential mistakes have been found\n");
foreach ($mistakes as $from => $to) {
$output->write("$from => $to\n");
}
}
}
|
Add a logging message to indicate start.
|
/*
___ usage ___ en_US ___
mingle static [address:port, address:port...]
options:
-b, --bind <address:port> address and port to bind to
--help display help message
___ $ ___ en_US ___
bind is required:
the `--bind` argument is a required argument
___ . ___
*/
require('arguable')(module, require('cadence')(function (async, program) {
var http = require('http')
var Shuttle = require('prolific.shuttle')
var Static = require('./http.js')
var logger = require('prolific.logger').createLogger('mingle.static')
var shuttle = Shuttle.shuttle(program, logger)
program.helpIf(program.ultimate.help)
program.required('bind')
program.validate(require('arguable/bindable'), 'bind')
var bind = program.ultimate.bind
var mingle = new Static(program.argv)
var dispatcher = mingle.dispatcher.createWrappedDispatcher()
var server = http.createServer(dispatcher)
server.listen(bind.port, bind.address, async())
program.on('shutdown', server.close.bind(server))
program.on('shutdown', shuttle.close.bind(shuttle))
logger.info('started', { parameters: program.ultimate })
}))
|
/*
___ usage ___ en_US ___
mingle static [address:port, address:port...]
options:
-b, --bind <address:port> address and port to bind to
--help display help message
___ $ ___ en_US ___
bind is required:
the `--bind` argument is a required argument
___ . ___
*/
require('arguable')(module, require('cadence')(function (async, program) {
var http = require('http')
var Shuttle = require('prolific.shuttle')
var Static = require('./http.js')
var logger = require('prolific.logger').createLogger('mingle.static')
var shuttle = Shuttle.shuttle(program, logger)
program.helpIf(program.ultimate.help)
program.required('bind')
program.validate(require('arguable/bindable'), 'bind')
var bind = program.ultimate.bind
var mingle = new Static(program.argv)
var dispatcher = mingle.dispatcher.createWrappedDispatcher()
var server = http.createServer(dispatcher)
server.listen(bind.port, bind.address, async())
program.on('shutdown', server.close.bind(server))
program.on('shutdown', shuttle.close.bind(shuttle))
}))
|
Write two zeros when 0 minutes. Looks nicer
|
Ext.define('MusicSearch.App', {
extend: 'Deft.mvc.Application',
init: function() {
Ext.fly('followingBallsG').destroy();
Ext.tip.QuickTipManager.init();
Deft.Injector.configure({
searchResultStore: 'MusicSearch.SongsStore',
playlistStore: 'MusicSearch.PlaylistStore'
});
Ext.create('MusicSearch.Viewport');
}
});
Ext.namespace('MusicSearch.Utils');
MusicSearch.Utils.secondsToHms = function(d) {
var no = Number(d);
var h = Math.floor(no / 3600);
var m = Math.floor(no % 3600 / 60);
var s = Math.floor(no % 3600 % 60);
return ((h > 0 ? h + ":" : "")
+ (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "00:")
+ (s < 10 ? "0" : "") + s);
};
soundManager.setup({
url: app_context_path + '/resources/swf/',
flashVersion: 9,
preferFlash: true,
onready: function() {
Ext.create('MusicSearch.App');
}
});
|
Ext.define('MusicSearch.App', {
extend: 'Deft.mvc.Application',
init: function() {
Ext.fly('followingBallsG').destroy();
Ext.tip.QuickTipManager.init();
Deft.Injector.configure({
searchResultStore: 'MusicSearch.SongsStore',
playlistStore: 'MusicSearch.PlaylistStore'
});
Ext.create('MusicSearch.Viewport');
}
});
Ext.namespace('MusicSearch.Utils');
MusicSearch.Utils.secondsToHms = function(d) {
var no = Number(d);
var h = Math.floor(no / 3600);
var m = Math.floor(no % 3600 / 60);
var s = Math.floor(no % 3600 % 60);
return ((h > 0 ? h + ":" : "")
+ (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "0:")
+ (s < 10 ? "0" : "") + s);
};
soundManager.setup({
url: app_context_path + '/resources/swf/',
flashVersion: 9,
preferFlash: true,
debugMode: true,
onready: function() {
Ext.create('MusicSearch.App');
}
});
|
Move description constant to test
Since it's specific to the Description test
|
package dsl
import (
"testing"
"github.com/goadesign/goa/design"
"github.com/goadesign/goa/eval"
)
func TestDescription(t *testing.T) {
const (
description = "test description"
)
cases := map[string]struct {
Expr eval.Expression
Desc string
DescFunc func(e eval.Expression) string
}{
"api": {&design.APIExpr{}, description, apiDesc},
"attr": {&design.AttributeExpr{}, description, attrDesc},
"docs": {&design.DocsExpr{}, description, docsDesc},
}
for k, tc := range cases {
eval.Context = &eval.DSLContext{}
eval.Execute(func() { Description(tc.Desc) }, tc.Expr)
if eval.Context.Errors != nil {
t.Errorf("%s: Description failed unexpectedly with %s", k, eval.Context.Errors)
}
if tc.DescFunc(tc.Expr) != tc.Desc {
t.Errorf("%s: Description not set on %+v, expected %s, got %+v", k, tc.Expr, tc.Desc, tc.DescFunc(tc.Expr))
}
}
}
func apiDesc(e eval.Expression) string { return e.(*design.APIExpr).Description }
func attrDesc(e eval.Expression) string { return e.(*design.AttributeExpr).Description }
func docsDesc(e eval.Expression) string { return e.(*design.DocsExpr).Description }
|
package dsl
import (
"testing"
"github.com/goadesign/goa/design"
"github.com/goadesign/goa/eval"
)
const (
description = "test description"
)
func TestDescription(t *testing.T) {
cases := map[string]struct {
Expr eval.Expression
Desc string
DescFunc func(e eval.Expression) string
}{
"api": {&design.APIExpr{}, description, apiDesc},
"attr": {&design.AttributeExpr{}, description, attrDesc},
"docs": {&design.DocsExpr{}, description, docsDesc},
}
for k, tc := range cases {
eval.Context = &eval.DSLContext{}
eval.Execute(func() { Description(tc.Desc) }, tc.Expr)
if eval.Context.Errors != nil {
t.Errorf("%s: Description failed unexpectedly with %s", k, eval.Context.Errors)
}
if tc.DescFunc(tc.Expr) != tc.Desc {
t.Errorf("%s: Description not set on %+v, expected %s, got %+v", k, tc.Expr, tc.Desc, tc.DescFunc(tc.Expr))
}
}
}
func apiDesc(e eval.Expression) string { return e.(*design.APIExpr).Description }
func attrDesc(e eval.Expression) string { return e.(*design.AttributeExpr).Description }
func docsDesc(e eval.Expression) string { return e.(*design.DocsExpr).Description }
|
Improve precision of related post s
|
var _ = require('lodash');
function parseId(postData, type) {
type = type || 'tags';
return postData[type].data.map(function(t) { return t._id; });
}
function getSimilarityScore(arrA, arrB) {
if (!arrA.length || !arrB.length) return 0;
return Math.sqrt(
_.intersection(arrA, arrB).length / Math.max(arrA.length, arrB.length)
);
}
function getPostSimilarity(postA, postB) {
return getSimilarityScore(
parseId(postA, 'tags'),
parseId(postB, 'tags')
) * 2 + getSimilarityScore(
parseId(postA, 'categories'),
parseId(postB, 'categories')
);
}
/**
* Related Posts helper
* @description Find related posts.
* @example
* related_posts(post, 3);
*/
hexo.extend.helper.register('related_posts', function (target, max) {
var posts, relatedPosts;
max = max || 3;
posts = hexo.locals.get('posts').data;
return posts.map(function(p) {
p.similarityScore = getPostSimilarity(target, p);
return p;
}).sort(function(a, b) {
return b.similarityScore - a.similarityScore;
}).filter(function(p) {
return (p._id !== target._id) && (p.similarityScore > 0);
}).slice(0, max);
});
|
var _ = require('lodash');
function parseId(postData, type) {
type = type || 'tags';
return postData[type].data.map(function(t) { return t._id; });
}
function getSimilarityScore(arrA, arrB) {
if (!arrA.length || !arrB.length) return 0;
return _.intersection(arrA, arrB).length / (arrA.length + arrB.length);
}
function getPostSimilarity(postA, postB) {
return getSimilarityScore(
parseId(postA, 'tags'),
parseId(postB, 'tags')
) + getSimilarityScore(
parseId(postA, 'categories'),
parseId(postB, 'categories')
);
}
/**
* Related Posts helper
* @description Find related posts.
* @example
* related_posts(post, 3);
*/
hexo.extend.helper.register('related_posts', function (target, max) {
var posts, relatedPosts;
max = max || 3;
posts = hexo.locals.get('posts').data;
return posts.map(function(p) {
p.similarityScore = getPostSimilarity(target, p);
return p;
}).sort(function(a, b) {
return b.similarityScore - a.similarityScore;
}).filter(function(p) {
return (p._id !== target._id) && (p.similarityScore > 0);
}).slice(0, max);
});
|
Use action bar icon to move up from Mail details
|
package net.rdrei.android.wakimail.ui;
import net.rdrei.android.wakimail.R;
import roboguice.activity.RoboFragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
public class MailDetailActivity extends RoboFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Uri uri = this.getIntent().getData();
final ActionBar actionBar = this.getSupportActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
setContentView(R.layout.activity_singlepane_empty);
// First-time init; create fragment to embed in activity.
final FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
final MailDetailFragment newFragment = MailDetailFragment
.newInstance(uri);
ft.replace(R.id.root_container, newFragment);
ft.commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// The app icon was clicked, move up to list.
final Intent intent = new Intent(this, MailListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package net.rdrei.android.wakimail.ui;
import net.rdrei.android.wakimail.R;
import roboguice.activity.RoboFragmentActivity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import com.actionbarsherlock.app.ActionBar;
public class MailDetailActivity extends RoboFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri uri = this.getIntent().getData();
ActionBar actionBar = this.getSupportActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
setContentView(R.layout.activity_singlepane_empty);
// First-time init; create fragment to embed in activity.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
MailDetailFragment newFragment = MailDetailFragment.newInstance(uri);
ft.replace(R.id.root_container, newFragment);
ft.commit();
}
}
|
Bring code implementation in line with documentation
Remove option for passing assetpath as an explicit parameter, just load oit from options instead
|
var path = require('path'),
servestatic = require('serve-static');
module.exports = {
setup: function (app, options) {
options = options || {};
options.path = options.path || '/govuk-assets';
app.use(options.path, servestatic(path.join(__dirname, './node_modules/govuk_template_mustache/assets'), options));
app.use(function (req, res, next) {
res.locals.govukAssetPath = options.path + '/';
res.locals.partials = res.locals.partials || {};
res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template');
next();
});
}
};
|
var path = require('path'),
static = require('serve-static');
module.exports = {
setup: function (app, assetpath, options) {
if (arguments.length === 2 && typeof assetpath === 'object') {
options = assetpath;
assetpath = '';
}
options = options || {};
assetpath = assetpath || options.path || '/govuk-assets';
app.use(assetpath, static(path.join(__dirname, './node_modules/govuk_template_mustache/assets'), options));
app.use(function (req, res, next) {
res.locals.govukAssetPath = assetpath + '/';
res.locals.partials = res.locals.partials || {};
res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template');
next();
});
}
};
|
[Join] Make sure the 'channel' argument is not Unicode when we send it, because Twisted doesn't like that
|
from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['join']
helptext = "Makes me join another channel, if I'm allowed to at least"
def execute(self, message):
"""
:type message: IrcMessage
"""
replytext = u""
if message.messagePartsLength < 1:
replytext = u"Please provide a channel for me to join"
else:
allowedChannels = message.bot.factory.settings.get('connection', 'allowedChannels').split(',')
channel = message.messageParts[0].encode('utf8') #Make sure it's a str and not unicode, otherwise Twisted chokes on it
if channel.startswith('#'):
channel = channel[1:]
if channel not in allowedChannels and not message.bot.factory.isUserAdmin(message.user):
replytext = u"I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission"
else:
channel = '#' + channel
replytext = u"All right, I'll go to {}. See you there!".format(channel)
message.bot.join(channel)
message.bot.say(message.source, replytext)
|
from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['join']
helptext = "Makes me join another channel, if I'm allowed to at least"
def execute(self, message):
"""
:type message: IrcMessage
"""
replytext = u""
if message.messagePartsLength < 1:
replytext = u"Please provide a channel for me to join"
else:
allowedChannels = message.bot.factory.settings.get('connection', 'allowedChannels').split(',')
channel = message.messageParts[0]
if channel.startswith('#'):
channel = channel[1:]
if channel not in allowedChannels and not message.bot.factory.isUserAdmin(message.user):
replytext = u"I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission"
else:
channel = '#' + channel
replytext = u"All right, I'll go to {}. See you there!".format(channel)
message.bot.join(channel)
message.bot.say(message.source, replytext)
|
Update index for Debug class location
|
<?php
error_reporting(E_ALL);
if (! defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', __DIR__ . \DS . '..' . \DS . 'app' . \DS);
}
$config = include ROOT . 'config/config.php';
$sConfig = include __DIR__ . \DS . 'config.php';
$config["siteUrl"] = 'http://' . $sConfig['host'] . ':' . $sConfig['port'] . '/';
$config['sessionName'] = $sConfig['sessionName'];
require ROOT . './../vendor/autoload.php';
$config['debug'] = true;
if (class_exists("\\Monolog\\Logger")) {
$config['logger'] = function () use ($sConfig) {
return new \Ubiquity\log\libraries\UMonolog($sConfig['sessionName'], \Monolog\Logger::INFO);
};
\Ubiquity\log\Logger::init($config);
}
require ROOT . 'config/services.php';
if (\Ubiquity\debug\Debug::hasLiveReload()) {
echo \Ubiquity\debug\Debug::liveReload();
}
\Ubiquity\controllers\Startup::run($config);
|
<?php
error_reporting(E_ALL);
if (! defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', __DIR__ . \DS . '..' . \DS . 'app' . \DS);
}
$config = include ROOT . 'config/config.php';
$sConfig = include __DIR__ . \DS . 'config.php';
$config["siteUrl"] = 'http://' . $sConfig['host'] . ':' . $sConfig['port'] . '/';
$config['sessionName'] = $sConfig['sessionName'];
require ROOT . './../vendor/autoload.php';
$config['debug'] = true;
if (class_exists("\\Monolog\\Logger")) {
$config['logger'] = function () use ($sConfig) {
return new \Ubiquity\log\libraries\UMonolog($sConfig['sessionName'], \Monolog\Logger::INFO);
};
\Ubiquity\log\Logger::init($config);
}
require ROOT . 'config/services.php';
if (Ubiquity\devtools\debug\Debug::hasLiveReload()) {
echo Ubiquity\devtools\debug\Debug::liveReload();
}
\Ubiquity\controllers\Startup::run($config);
|
Update regexp due to changes in stylint
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
npm_name = 'stylint'
syntax = 'stylus'
cmd = 'stylint @ *'
executable = 'stylint'
version_requirement = '>= 1.5.6, < 1.6.0'
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
(?P<line>\d+):(?P<near>\d+)\s*\w+\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
#
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
npm_name = 'stylint'
syntax = 'stylus'
cmd = 'stylint @ *'
executable = 'stylint'
version_requirement = '>= 0.9.3'
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# 'Near' can contain trailing whitespace, which we avoid capturing
# Warning: commas must be followed by a space for readability
^((?P<warning>warning)|(?P<error>Error)):\s*(?P<message>.+)$\s*
# File: /path/to/file/example.styl
^.*$\s*
# Line: 46: color rgba(0,0,0,.5)
^Line:\s*(?P<line>\d+):\s*(?P<near>.*\S)
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
[HOPS-1360] Fix Tuple does not exist in removeSafeBlock
|
/*
* Copyright (C) 2015 hops.io.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hops.metadata.hdfs.dal;
import io.hops.exception.StorageException;
import io.hops.metadata.common.EntityDataAccess;
import java.util.Collection;
public interface SafeBlocksDataAccess extends EntityDataAccess {
void insert(Collection<Long> safeBlocks) throws StorageException;
void remove(Long safeBlock) throws StorageException;
int countAll() throws StorageException;
void removeAll() throws StorageException;
boolean isSafe(Long BlockId) throws StorageException;
}
|
/*
* Copyright (C) 2015 hops.io.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hops.metadata.hdfs.dal;
import io.hops.exception.StorageException;
import io.hops.metadata.common.EntityDataAccess;
import java.util.Collection;
public interface SafeBlocksDataAccess extends EntityDataAccess {
void insert(Collection<Long> safeBlocks) throws StorageException;
void remove(Long safeBlock) throws StorageException;
int countAll() throws StorageException;
void removeAll() throws StorageException;
}
|
Change cached file extension to .json.tmp
|
<?php
class Cache {
private static $_config = false;
private static function getConfig() {
if(static::$_config)
return static::$_config;
static::$_config = require(__DIR__ . '/../../../config/cache.php');
}
public static function store($key, $value, $ttl) {
$dir = static::getConfig()['dir'];
if(!$dir)
return false;
$data = [
'expires' => time() + $ttl,
'data' => $value,
];
mkdir($dir, 0777, true);
$file = fopen($dir . strval($key) . '.json.tmp', 'w');
fwrite($file, json_encode($data));
fclose($file);
return true;
}
public static function fetch($key) {
$dir = static::getConfig()['dir'];
if(!$dir)
return false;
$data = json_decode(file_get_contents($dir . strval($key) . '.json.tmp'), true);
if($data['expires'] < time()) {
return false;
} else {
return $data['data'];
}
}
}
|
<?php
class Cache {
private static $_config = false;
private static function getConfig() {
if(static::$_config)
return static::$_config;
static::$_config = require(__DIR__ . '/../../../config/cache.php');
}
public static function store($key, $value, $ttl) {
$dir = static::getConfig()['dir'];
if(!$dir)
return false;
$data = [
'expires' => time() + $ttl,
'data' => $value,
];
mkdir($dir, 0777, true);
$file = fopen($dir . strval($key) . '.tmp', 'w');
fwrite($file, json_encode($data));
fclose($file);
return true;
}
public static function fetch($key) {
$dir = static::getConfig()['dir'];
if(!$dir)
return false;
$data = json_decode(file_get_contents($dir . strval($key) . '.tmp'), true);
if($data['expires'] < time()) {
return false;
} else {
return $data['data'];
}
}
}
|
Complete solution for overlapping rectangles
|
import sys
def over_rect(line):
line = line.rstrip()
if line:
xula, yula, xlra, ylra, xulb, yulb, xlrb, ylrb = (int(i) for i
in line.split(','))
h_overlap = True
v_overlap = True
if xlrb < xula or xulb > xlra:
h_overlap = False
if yulb < ylra or ylrb > yula:
v_overlap = False
return h_overlap and v_overlap
if __name__ == '__main__':
with open(sys.argv[1], 'rt') as f:
for line in f:
print over_rect(line)
|
import sys
def over_rect(line):
line = line.rstrip()
if line:
line = line.split(',')
rect_a = [int(item) for item in line[:4]]
rect_b = [int(item) for item in line[4:]]
return (rect_a[0] <= rect_b[0] <= rect_a[2] and
(rect_a[3] <= rect_b[1] <= rect_a[1] or
rect_a[3] <= rect_b[3] <= rect_a[1])) or \
(rect_b[0] <= rect_a[0] <= rect_b[2] and
(rect_b[3] <= rect_a[1] <= rect_b[1] or
rect_b[3] <= rect_a[3] <= rect_b[1]))
if __name__ == '__main__':
with open(sys.argv[1], 'rt') as f:
for line in f:
print over_rect(line)
|
Implement group form type extension.
|
<?php declare(strict_types=1);
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2019, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\AdminBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Group form type extension
*/
class GroupFormTypeExtension extends AbstractTypeExtension
{
/**
* {@inheritDoc}
*/
public function finishView(FormView $view, FormInterface $form, array $options): void
{
$view->vars['admin_group'] = $options['admin_group'];
}
/**
* {@inheritDoc}
*/
public function configureOptions(OptionsResolver $resolver): void
{
$resolver
->setDefault('admin_group', null)
->setAllowedTypes('admin_group', ['string', 'null']);
}
/**
* {@inheritDoc}
*/
public static function getExtendedTypes(): iterable
{
yield FormType::class;
}
}
|
<?php declare(strict_types=1);
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2019, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\AdminBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Group form type extension
*/
class GroupFormTypeExtension extends AbstractTypeExtension
{
/**
* {@inheritDoc}
*/
public function finishView(FormView $view, FormInterface $form, array $options): void
{
$view->vars['darvin_admin_group'] = $options['darvin_admin_group'];
}
/**
* {@inheritDoc}
*/
public function configureOptions(OptionsResolver $resolver): void
{
$resolver
->setDefault('darvin_admin_group', null)
->setAllowedTypes('darvin_admin_group', ['string', 'null']);
}
/**
* {@inheritDoc}
*/
public static function getExtendedTypes(): iterable
{
yield FormType::class;
}
}
|
Remove dev mode, that should really be configured by the configuration
|
'use strict';
let irc = require( 'irc' );
let plugins = require( './plugins' );
const config = {
channels: [ '#kokarn' ],
plugins: [ 'Telegram', 'Urlchecker', 'Github', 'RSS', 'DagensMix', 'Pushbullet', 'HttpCat' ],
server: 'irc.freenode.net',
botName: 'BoilBot'
};
let bot = new irc.Client(
config.server,
config.botName,
{
channels: config.channels
}
);
for( let i = 0; i < config.channels.length; i = i + 1 ){
console.log( 'Joining', config.channels[ i ], 'as', config.botName );
}
bot.addListener( 'error', function( message ){
console.log( 'error: ', message );
});
for( let i = 0; i < config.plugins.length; i = i + 1 ){
if( plugins[ config.plugins[ i ] ] ){
console.log( 'Starting plugin', config.plugins[ i ] );
new plugins[ config.plugins[ i ] ]( bot );
}
}
|
'use strict';
let irc = require( 'irc' );
let plugins = require( './plugins' );
const config = {
channels: [ '#kokarn' ],
plugins: [ 'Telegram', 'Urlchecker', 'Github', 'RSS', 'DagensMix', 'Pushbullet', 'HttpCat' ],
server: 'irc.freenode.net',
botName: 'BoilBot'
};
if( process.argv.indexOf( '--dev' ) > -1 ){
console.log( 'Starting in debug mode' );
config.channels[ 0 ] = config.channels[ 0 ] + 'dev';
config.botName = config.botName + 'dev';
}
let bot = new irc.Client(
config.server,
config.botName,
{
channels: config.channels
}
);
for( let i = 0; i < config.channels.length; i = i + 1 ){
console.log( 'Joining', config.channels[ i ], 'as', config.botName );
}
bot.addListener( 'error', function( message ){
console.log( 'error: ', message );
});
for( let i = 0; i < config.plugins.length; i = i + 1 ){
if( plugins[ config.plugins[ i ] ] ){
console.log( 'Starting plugin', config.plugins[ i ] );
new plugins[ config.plugins[ i ] ]( bot );
}
}
|
Fix Rainforest Plains not being generated
|
package net.tropicraft.core.common.dimension.layer;
import net.minecraft.world.gen.INoiseRandom;
import net.minecraft.world.gen.layer.traits.IC0Transformer;
public final class TropicraftAddSubBiomesLayer implements IC0Transformer {
final int baseID;
final int[] subBiomeIDs;
TropicraftAddSubBiomesLayer(final int baseID, final int[] subBiomeIDs) {
this.baseID = baseID;
this.subBiomeIDs = subBiomeIDs;
}
public static TropicraftAddSubBiomesLayer rainforest(TropicraftBiomeIds biomeIds) {
return new TropicraftAddSubBiomesLayer(biomeIds.rainforestPlains, new int[] { biomeIds.rainforestPlains, biomeIds.rainforestHills, biomeIds.rainforestMountains });
}
@Override
public int apply(INoiseRandom random, int center) {
if (center == baseID) {
return subBiomeIDs[random.random(subBiomeIDs.length)];
} else {
return center;
}
}
}
|
package net.tropicraft.core.common.dimension.layer;
import net.minecraft.world.gen.INoiseRandom;
import net.minecraft.world.gen.layer.traits.IC0Transformer;
public final class TropicraftAddSubBiomesLayer implements IC0Transformer {
final int baseID;
final int[] subBiomeIDs;
TropicraftAddSubBiomesLayer(final int baseID, final int[] subBiomeIDs) {
this.baseID = baseID;
this.subBiomeIDs = subBiomeIDs;
}
public static TropicraftAddSubBiomesLayer rainforest(TropicraftBiomeIds biomeIds) {
return new TropicraftAddSubBiomesLayer(biomeIds.rainforestPlains, new int[] { biomeIds.rainforestHills, biomeIds.rainforestMountains });
}
@Override
public int apply(INoiseRandom random, int center) {
if (center == baseID) {
return subBiomeIDs[random.random(subBiomeIDs.length)];
} else {
return center;
}
}
}
|
Enable passing str to echo
|
import sys
from functools import partial, wraps
import click
def verify_response(func):
"""Decorator verifies response from the function.
It expects function to return (bool, []), when bool is False
content of list is printed out and program exits with error code.
With successful execution results are returned to the caller.
"""
@wraps(func)
def wrapper(*args, **kwargs):
result, errors = func(*args, **kwargs)
if result: # call succeeded
return result, errors
# call returned error
error_exit(errors)
return wrapper
def _echo_exit(messages, exit_, color):
"""Iterate over list of messages and print them using passed color.
Method calls sys.exit() if exit_ is different than 0.
:param messages: list of messages to be printed out
:type messages: list(str) or str
:param exit_: exit code
:type exit_: int
:param color: color of text, 'red' or 'green'
:type color: str
"""
if isinstance(messages, str):
messages = [messages]
for m in messages:
click.secho(m, fg=color)
if exit_:
sys.exit(exit_)
error_exit = partial(_echo_exit, exit_=1, color='red')
ok_exit = partial(_echo_exit, exit_=0, color='green')
|
import sys
from functools import partial, wraps
import click
def verify_response(func):
"""Decorator verifies response from the function.
It expects function to return (bool, []), when bool is False
content of list is printed out and program exits with error code.
With successful execution results are returned to the caller.
"""
@wraps(func)
def wrapper(*args, **kwargs):
result, errors = func(*args, **kwargs)
if result: # call succeeded
return result, errors
# call returned error
error_exit(errors)
return wrapper
def _echo_exit(messages, exit_, color):
"""Iterate over list of messages and print them using passed color.
Method calls sys.exit() if exit_ is different than 0.
:param messages: list of messages to be printed out
:type messages: list(str)
:param exit_: exit code
:type exit_: int
:param color: color of text, 'red' or 'green'
:type color: str
"""
for m in messages:
click.secho(m, fg=color)
if exit_:
sys.exit(exit_)
error_exit = partial(_echo_exit, exit_=1, color='red')
ok_exit = partial(_echo_exit, exit_=0, color='green')
|
Fix wrong boolean on account creation
|
orion.accounts = {};
/**
* Initialize the profile schema option with its default value
*/
Options.init('profileSchema', {
name: { type: String }
});
/**
* Updates the profile schema reactively
*/
Tracker.autorun(function () {
orion.accounts.profileSchema = new SimpleSchema({
profile: {
type: new SimpleSchema(Options.get('profileSchema'))
}
});
});
/**
* Initialize accounts options
* If there is no admin, we allow to create accounts
*/
Options.init('defaultRoles', []);
Options.init('forbidClientAccountCreation');
AccountsTemplates.configure({
forbidClientAccountCreation: !!orion.adminExists
});
/**
* We will use listen instead of tracker because on client tracker starts after meteor.startup
*/
Options.listen('forbidClientAccountCreation', function(value) {
AccountsTemplates.configure({
forbidClientAccountCreation: orion.adminExists && value,
});
})
/**
* Adds the "name" field to the sign up form
*/
AccountsTemplates.addField({
_id: 'name',
type: 'text',
displayName: 'Name',
placeholder: 'Your name',
required: true,
});
|
orion.accounts = {};
/**
* Initialize the profile schema option with its default value
*/
Options.init('profileSchema', {
name: { type: String }
});
/**
* Updates the profile schema reactively
*/
Tracker.autorun(function () {
orion.accounts.profileSchema = new SimpleSchema({
profile: {
type: new SimpleSchema(Options.get('profileSchema'))
}
});
});
/**
* Initialize accounts options
* If there is no admin, we allow to create accounts
*/
Options.init('defaultRoles', []);
Options.init('forbidClientAccountCreation');
AccountsTemplates.configure({
forbidClientAccountCreation: !orion.adminExists
});
/**
* We will use listen instead of tracker because on client tracker starts after meteor.startup
*/
Options.listen('forbidClientAccountCreation', function(value) {
AccountsTemplates.configure({
forbidClientAccountCreation: orion.adminExists && value,
});
})
/**
* Adds the "name" field to the sign up form
*/
AccountsTemplates.addField({
_id: 'name',
type: 'text',
displayName: 'Name',
placeholder: 'Your name',
required: true,
});
|
Update /users/login endpoint to return serialized metadata
|
from .blueprint import root_blueprint as root_route
from ...core.node import node
# syft absolute
from syft.core.common.message import SignedImmediateSyftMessageWithReply
from syft.core.common.message import SignedImmediateSyftMessageWithoutReply
from syft.core.common.serde.deserialize import _deserialize
from flask import request, Response
import json
@root_route.route("/pysyft", methods=["POST"])
def root_route():
data = request.get_data()
obj_msg = _deserialize(blob=data, from_bytes=True)
if isinstance(obj_msg, SignedImmediateSyftMessageWithReply):
reply = node.recv_immediate_msg_with_reply(msg=obj_msg)
r = Response(response=reply.serialize(to_bytes=True), status=200)
r.headers["Content-Type"] = "application/octet-stream"
return r
elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply):
node.recv_immediate_msg_without_reply(msg=obj_msg)
else:
node.recv_eventual_msg_without_reply(msg=obj_msg)
return ""
|
from .blueprint import root_blueprint as root_route
from ...core.node import node
# syft absolute
from syft.core.common.message import SignedImmediateSyftMessageWithReply
from syft.core.common.message import SignedImmediateSyftMessageWithoutReply
from syft.core.common.serde.deserialize import _deserialize
from flask import request, Response
import json
@root_route.route("/pysyft", methods=["POST"])
def root_route():
json_msg = request.get_json()
obj_msg = _deserialize(blob=json_msg, from_json=True)
if isinstance(obj_msg, SignedImmediateSyftMessageWithReply):
reply = node.recv_immediate_msg_with_reply(msg=obj_msg)
return reply.json()
elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply):
node.recv_immediate_msg_without_reply(msg=obj_msg)
else:
node.recv_eventual_msg_without_reply(msg=obj_msg)
return ""
|
Throw exception if procedure is empty.
|
<?php
namespace Retrinko\CottonTail\Message\Payloads;
use Retrinko\CottonTail\Exceptions\PayloadException;
class RpcRequestPayload extends DefaultPayload
{
const KEY_PARAMS = 'params';
const KEY_PROCEDURE = 'procedure';
/**
* @var array
*/
protected $requiredFields = [self::KEY_PROCEDURE, self::KEY_PARAMS];
/**
* @param string $procedure
* @param array $params
*
* @return RpcRequestPayload
* @throws PayloadException
*/
public static function create($procedure, $params = [])
{
if (empty($procedure))
{
throw PayloadException::emptyProcedute();
}
$data = [self::KEY_PROCEDURE => $procedure,
self::KEY_PARAMS => $params];
return new self($data);
}
/**
* @return array
*/
public function getParams()
{
return $this->data[self::KEY_PARAMS];
}
/**
* @return string
*/
public function getProcedure()
{
return $this->data[self::KEY_PROCEDURE];
}
}
|
<?php
namespace Retrinko\CottonTail\Message\Payloads;
class RpcRequestPayload extends DefaultPayload
{
const KEY_PARAMS = 'params';
const KEY_PROCEDURE = 'procedure';
/**
* @var array
*/
protected $requiredFields = [self::KEY_PROCEDURE, self::KEY_PARAMS];
/**
* @param string $procedure
* @param array $params
*
* @return RpcRequestPayload
*/
public static function create($procedure, $params = [])
{
$data = [self::KEY_PROCEDURE => $procedure,
self::KEY_PARAMS => $params];
return new self($data);
}
/**
* @return array
*/
public function getParams()
{
return $this->data[self::KEY_PARAMS];
}
/**
* @return string
*/
public function getProcedure()
{
return $this->data[self::KEY_PROCEDURE];
}
}
|
Rename args variable to pairs for clarity
|
import hasCallback from 'has-callback';
import promisify from 'es6-promisify';
import yargsBuilder from 'yargs-builder';
import renamerArgsBuilder from './renamerArgsBuilder';
import fsRenamer from './fsRenamer';
import getExistingFilenames from './getExistingFilenames';
import {ERROR_ON_MISSING_FILE} from './flags';
const parseArgs = (argv) => {
const args = yargsBuilder({
options: {
[ERROR_ON_MISSING_FILE]: { default: false, describe: 'Fail if source file missing', type: 'boolean' }
}
}, argv).argv;
return [ args._, args ];
}
const batchFileRenamer = async ({ rule, argv }) => {
rule = hasCallback(rule) ? promisify(rule) : rule;
const [filenames, options] = parseArgs(argv);
const oldnames = await getExistingFilenames(filenames, options);
let newnames = [];
for (let oldname of oldnames) {
let newname = await rule(oldname, options);
newnames.push(newname);
}
let pairs = renamerArgsBuilder(oldnames, newnames);
await fsRenamer(pairs);
}
export default batchFileRenamer;
|
import hasCallback from 'has-callback';
import promisify from 'es6-promisify';
import yargsBuilder from 'yargs-builder';
import renamerArgsBuilder from './renamerArgsBuilder';
import fsRenamer from './fsRenamer';
import getExistingFilenames from './getExistingFilenames';
import {ERROR_ON_MISSING_FILE} from './flags';
const parseArgs = (argv) => {
const args = yargsBuilder({
options: {
[ERROR_ON_MISSING_FILE]: { default: false, describe: 'Fail if source file missing', type: 'boolean' }
}
}, argv).argv;
return [ args._, args ];
}
const batchFileRenamer = async ({ rule, argv }) => {
rule = hasCallback(rule) ? promisify(rule) : rule;
const [filenames, options] = parseArgs(argv);
const oldnames = await getExistingFilenames(filenames, options);
let newnames = [];
for (let oldname of oldnames) {
let newname = await rule(oldname, options);
newnames.push(newname);
}
let args = renamerArgsBuilder(oldnames, newnames);
await fsRenamer(args)
}
export default batchFileRenamer;
|
Fix autoremove in wrong place
|
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from slacksync.membersync import SlackMemberSync
from slacksync.utils import api_configured
class Command(BaseCommand):
help = 'Make sure all members are in Slack and optionally kick non-members'
def add_arguments(self, parser):
parser.add_argument('--autodeactivate', action='store_true', help='Automatically deactivate users that are no longer members')
pass
def handle(self, *args, **options):
if not api_configured():
raise CommandError("API not configured")
autoremove = False
if options['autodeactivate']:
autoremove = True
sync = SlackMemberSync()
tbd = sync.sync_members(autoremove)
if options['verbosity'] > 1:
for dm in tbd:
if autoremove:
print("User {uid} ({email}) was removed".format(uid=dm[0], email=dm[1]))
else:
print("User {uid} ({email}) should be removed".format(uid=dm[0], email=dm[1]))
|
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from slacksync.membersync import SlackMemberSync
from slacksync.utils import api_configured
class Command(BaseCommand):
help = 'Make sure all members are in Slack and optionally kick non-members'
def add_arguments(self, parser):
parser.add_argument('--autodeactivate', action='store_true', help='Automatically deactivate users that are no longer members')
pass
def handle(self, *args, **options):
if not api_configured():
raise CommandError("API not configured")
autoremove = False
if options['autodeactivate']:
autoremove = True
sync = SlackMemberSync(autoremove)
tbd = sync.sync_members()
if options['verbosity'] > 1:
for dm in tbd:
if autoremove:
print("User {uid} ({email}) was removed".format(uid=dm[0], email=dm[1]))
else:
print("User {uid} ({email}) should be removed".format(uid=dm[0], email=dm[1]))
|
Use currenUser instead of getting it from session
|
import Ember from "ember";
import config from "../config/environment";
export default Ember.Service.extend({
session: Ember.inject.service(),
rollbar: Ember.inject.service(),
getReason(reason) {
return reason instanceof Error || typeof reason !== "object" ?
reason : JSON.stringify(reason);
},
error: function(reason) {
if (reason.status === 0) {
return;
}
console.info(reason);
if (config.environment === "production" || config.staging) {
var currentUser = this.get("session.currentUser");
var userName = currentUser.get("fullName");
var userId = currentUser.get("id");
var error = this.getReason(reason);
var environment = config.staging ? "staging" : config.environment;
var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`;
var airbrake = new airbrakeJs.Client({
projectId: config.APP.AIRBRAKE_PROJECT_ID,
projectKey: config.APP.AIRBRAKE_PROJECT_KEY
});
airbrake.setHost(config.APP.AIRBRAKE_HOST);
airbrake.notify({ error, context: { userId, userName, environment, version } });
this.set('rollbar.currentUser', currentUser);
this.get('rollbar').error(error, data = { id: userId, username: userName, environment: environment});
}
}
});
|
import Ember from "ember";
import config from "../config/environment";
export default Ember.Service.extend({
session: Ember.inject.service(),
rollbar: Ember.inject.service(),
getReason(reason) {
return reason instanceof Error || typeof reason !== "object" ?
reason : JSON.stringify(reason);
},
error: function(reason) {
if (reason.status === 0) {
return;
}
console.info(reason);
if (config.environment === "production" || config.staging) {
var userName = this.get("session.currentUser.fullName");
var currentUser = this.get("session.currentUser");
var userId = this.get("session.currentUser.id");
var error = this.getReason(reason);
var environment = config.staging ? "staging" : config.environment;
var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`;
var airbrake = new airbrakeJs.Client({
projectId: config.APP.AIRBRAKE_PROJECT_ID,
projectKey: config.APP.AIRBRAKE_PROJECT_KEY
});
airbrake.setHost(config.APP.AIRBRAKE_HOST);
airbrake.notify({ error, context: { userId, userName, environment, version } });
this.set('rollbar.currentUser', currentUser);
this.get('rollbar').error(error, data = { id: userId, username: userName, environment: environment});
}
}
});
|
Add `--no-sandbox` to Chrome args in CI.
|
/* jshint node:true */
var options = {
"framework": "qunit",
"test_page": "tests/index.html?hidepassed",
"disable_watching": true,
"launch_in_ci": [
"Chrome",
"Firefox",
],
"launch_in_dev": [
"Chrome",
"Firefox",
"Safari",
],
browser_args: {
Chrome: {
mode: 'ci',
args: [
'--disable-gpu',
'--headless',
'--no-sandbox',
'--remote-debugging-port=0',
'--window-size=1440,900'
]
},
Firefox: {
mode: 'ci',
args: [
'--headless',
'--window-size=1440,900'
]
},
}
};
module.exports = options;
|
/* jshint node:true */
var options = {
"framework": "qunit",
"test_page": "tests/index.html?hidepassed",
"disable_watching": true,
"launch_in_ci": [
"Chrome",
"Firefox",
],
"launch_in_dev": [
"Chrome",
"Firefox",
"Safari",
],
browser_args: {
Chrome: {
mode: 'ci',
args: [
'--disable-gpu',
'--headless',
'--remote-debugging-port=0',
'--window-size=1440,900'
]
},
Firefox: {
mode: 'ci',
args: [
'--headless',
'--window-size=1440,900'
]
},
}
};
module.exports = options;
|
Add and pass tests for gardenLocation
|
package umm3601.plant;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import umm3601.digitalDisplayGarden.Plant;
import umm3601.digitalDisplayGarden.PlantController;
import umm3601.plant.PopulateMockDatabase;
import java.io.IOException;
import static junit.framework.TestCase.assertEquals;
public class FilterPlantsByGardenLocation {
@Before
public void setUpDB() throws IOException{
PopulateMockDatabase mockDatabase = new PopulateMockDatabase();
mockDatabase.clearAndPopulateDBAgain();
}
@Test
public void findByGardenLocation() throws IOException {
PlantController plantController = new PlantController();
GardenLocation[] filteredPlants;
Gson gson = new Gson();
//System.out.println();
String rawPlants = plantController.getGardenLocations();
filteredPlants = gson.fromJson(rawPlants, GardenLocation[].class);
assertEquals("Incorrect number of unique garden locations", 2, filteredPlants.length);
assertEquals("Incorrect zero index", "10.0", filteredPlants[0]._id);
assertEquals("Incorrect value for index 1", "7.0", filteredPlants[1]._id);
}
}
|
package umm3601.plant;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import umm3601.digitalDisplayGarden.Plant;
import umm3601.digitalDisplayGarden.PlantController;
import umm3601.plant.PopulateMockDatabase;
import java.io.IOException;
import static junit.framework.TestCase.assertEquals;
public class FilterPlantsByGardenLocation {
@Before
public void setUpDB() throws IOException{
PopulateMockDatabase mockDatabase = new PopulateMockDatabase();
mockDatabase.clearAndPopulateDBAgain();
}
@Test
public void findByGardenLocation() throws IOException {
PlantController plantController = new PlantController();
Plant[] filteredPlants;
Gson gson = new Gson();
String rawPlants = plantController.getGardenLocations();
filteredPlants = gson.fromJson(rawPlants, Plant[].class);
assertEquals("Incorrect", 1, filteredPlants.length);
}
}
|
Add a model for Object.assign
|
export default function(state, ctx, model, helpers) {
const ConcretizeIfNative = helpers.ConcretizeIfNative;
//TODO: Test IsNative for apply, bind & call
model.add(Function.prototype.apply, ConcretizeIfNative(Function.prototype.apply));
model.add(Function.prototype.call, ConcretizeIfNative(Function.prototype.call));
model.add(Function.prototype.bind, ConcretizeIfNative(Function.prototype.bind));
model.add(Object.prototype.hasOwnProperty, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
Function.prototype.hasOwnProperty.apply(state.getConcrete(base), args);
});
model.add(Object.prototype.keys, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
return Object.prototype.keys.apply(this.getConcrete(base), args);
});
model.add(Object.assign, (base, args) => {
return Object.assign.call(base, this.getConcrete(args[0]), this.getConcrete(args[1]));
});
model.add(console.log, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
console.log.apply(base, args);
});
}
|
export default function(state, ctx, model, helpers) {
const ConcretizeIfNative = helpers.ConcretizeIfNative;
//TODO: Test IsNative for apply, bind & call
model.add(Function.prototype.apply, ConcretizeIfNative(Function.prototype.apply));
model.add(Function.prototype.call, ConcretizeIfNative(Function.prototype.call));
model.add(Function.prototype.bind, ConcretizeIfNative(Function.prototype.bind));
model.add(Object.prototype.hasOwnProperty, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
Function.prototype.hasOwnProperty.apply(state.getConcrete(base), args);
});
model.add(Object.prototype.keys, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
return Object.prototype.keys.apply(this.getConcrete(base), args);
});
model.add(console.log, function(base, args) {
for (let i = 0; i < args.length; i++) {
args[i] = state.getConcrete(args[i]);
}
console.log.apply(base, args);
});
}
|
Fix crash when starting new bike activity
|
package fr.cph.chicago.listener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import fr.cph.chicago.App;
import fr.cph.chicago.R;
import fr.cph.chicago.activity.BikeStationActivity;
import fr.cph.chicago.entity.BikeStation;
public class BikeStationOnClickListener implements View.OnClickListener {
private final BikeStation station;
public BikeStationOnClickListener(final BikeStation station) {
this.station = station;
}
@Override
public void onClick(final View v) {
final Intent intent = new Intent(App.getContext(), BikeStationActivity.class);
final Bundle extras = new Bundle();
extras.putParcelable(App.getContext().getString(R.string.bundle_bike_station), station);
intent.putExtras(extras);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
App.getContext().startActivity(intent);
}
}
|
package fr.cph.chicago.listener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import fr.cph.chicago.App;
import fr.cph.chicago.R;
import fr.cph.chicago.activity.BikeStationActivity;
import fr.cph.chicago.entity.BikeStation;
public class BikeStationOnClickListener implements View.OnClickListener {
private final BikeStation station;
public BikeStationOnClickListener(final BikeStation station) {
this.station = station;
}
@Override
public void onClick(final View v) {
final Intent intent = new Intent(App.getContext(), BikeStationActivity.class);
final Bundle extras = new Bundle();
extras.putParcelable(App.getContext().getString(R.string.bundle_bike_station), station);
intent.putExtras(extras);
App.getContext().startActivity(intent);
}
}
|
Fix for Friendly tips when Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS
i forget add SOCIAL_AUTH_ALLOWED_REDIRECT_URIS to my config
it return 400 error, i don't know why , i pay more time find the issues
so i add Friendly tips
-- sorry , my english is not well
and thank you all
|
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from social_django.utils import load_backend, load_strategy
from djoser.conf import settings
from djoser.social.serializers import ProviderAuthSerializer
class ProviderAuthView(generics.CreateAPIView):
permission_classes = [permissions.AllowAny]
serializer_class = ProviderAuthSerializer
def get(self, request, *args, **kwargs):
redirect_uri = request.GET.get("redirect_uri")
if redirect_uri not in settings.SOCIAL_AUTH_ALLOWED_REDIRECT_URIS:
return Response("Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS", status=status.HTTP_400_BAD_REQUEST)
strategy = load_strategy(request)
strategy.session_set("redirect_uri", redirect_uri)
backend_name = self.kwargs["provider"]
backend = load_backend(strategy, backend_name, redirect_uri=redirect_uri)
authorization_url = backend.auth_url()
return Response(data={"authorization_url": authorization_url})
|
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from social_django.utils import load_backend, load_strategy
from djoser.conf import settings
from djoser.social.serializers import ProviderAuthSerializer
class ProviderAuthView(generics.CreateAPIView):
permission_classes = [permissions.AllowAny]
serializer_class = ProviderAuthSerializer
def get(self, request, *args, **kwargs):
redirect_uri = request.GET.get("redirect_uri")
if redirect_uri not in settings.SOCIAL_AUTH_ALLOWED_REDIRECT_URIS:
return Response(status=status.HTTP_400_BAD_REQUEST)
strategy = load_strategy(request)
strategy.session_set("redirect_uri", redirect_uri)
backend_name = self.kwargs["provider"]
backend = load_backend(strategy, backend_name, redirect_uri=redirect_uri)
authorization_url = backend.auth_url()
return Response(data={"authorization_url": authorization_url})
|
Remove reference to web activity file
|
'use strict';
define([
'backbone',
'app',
'views/app'
], function(Backbone, App, AppView) {
var appView;
var AppRouter = Backbone.Router.extend({
routes:{
'': 'index'
},
initialize: function() {
return this;
},
index: function() {
if (!appView) {
// Initialize the application view and assign it as a global.
appView = new AppView();
window.app = appView;
}
}
})
return AppRouter;
});
|
'use strict';
define([
'backbone',
'app',
'views/app',
'views/webactivities'
], function(Backbone, App, AppView, WebActivityViews) {
var appView;
var AppRouter = Backbone.Router.extend({
routes:{
'subscribeFromWebActivity': 'webActivitySubscribe',
'': 'index'
},
initialize: function() {
return this;
},
index: function() {
if (!appView) {
// Initialize the application view and assign it as a global.
appView = new AppView();
window.app = appView;
}
},
webActivitySubscribe: function(feed) {
var subscribeView = new WebActivityViews.Subscribe();
subscribeView.subscribeTo(feed);
}
})
return AppRouter;
});
|
Adjust minidump dependency to >= 0.0.10
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='cle',
description='CLE Loads Everything (at least, many binary formats!) and provides a pythonic interface to analyze what they are and what they would look like in memory.',
version='8.20.5.27',
python_requires='>=3.6',
packages=packages,
install_requires=[
'pyelftools>=0.25',
'cffi',
'pyvex==8.20.5.27',
'pefile',
'sortedcontainers>=2.0',
],
extras_require={
"minidump": ["minidump>=0.0.10"],
"xbe": ["pyxbe==0.0.2"],
"ar": ["arpy==1.1.1"],
}
)
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='cle',
description='CLE Loads Everything (at least, many binary formats!) and provides a pythonic interface to analyze what they are and what they would look like in memory.',
version='8.20.5.27',
python_requires='>=3.6',
packages=packages,
install_requires=[
'pyelftools>=0.25',
'cffi',
'pyvex==8.20.5.27',
'pefile',
'sortedcontainers>=2.0',
],
extras_require={
"minidump": ["minidump==0.0.10"],
"xbe": ["pyxbe==0.0.2"],
"ar": ["arpy==1.1.1"],
}
)
|
Fix typo in tests_require parameter
|
from setuptools import setup, find_packages
VERSION = __import__('location_field').__version__
setup(
name='django-location-field',
version=VERSION,
description="Location field for Django",
long_description="This module provides a location field for Django applications.",
author="Caio Ariede",
author_email="caio.ariede@gmail.com",
url="http://github.com/caioariede/django-location-field",
license="MIT",
zip_safe=False,
platforms=["any"],
packages=find_packages(),
package_data={'location_field': [
'static/location_field/js/*',
'templates/location_field/*',
]},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Framework :: Django",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
],
include_package_data=True,
install_requires=[
'Django>=1.7,<1.9',
'six',
],
tests_require=[
'pyquery',
],
test_suite="runtests.runtests",
)
|
from setuptools import setup, find_packages
VERSION = __import__('location_field').__version__
setup(
name='django-location-field',
version=VERSION,
description="Location field for Django",
long_description="This module provides a location field for Django applications.",
author="Caio Ariede",
author_email="caio.ariede@gmail.com",
url="http://github.com/caioariede/django-location-field",
license="MIT",
zip_safe=False,
platforms=["any"],
packages=find_packages(),
package_data={'location_field': [
'static/location_field/js/*',
'templates/location_field/*',
]},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Framework :: Django",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
],
include_package_data=True,
install_requires=[
'Django>=1.7,<1.9',
'six',
],
test_requires=[
'pyquery',
],
test_suite="runtests.runtests",
)
|
Deploy ember app to dist
For fastboot-app-server
|
module.exports = function(deployTarget) {
var ENV = {
build: {}
// include other plugin configuration that applies to all deploy targets here
};
if (deployTarget === 'development') {
ENV.build.environment = 'development';
// configure other plugins for development deploy target here
}
if (deployTarget === 'staging') {
ENV.build.environment = 'staging';
ENV['scp'] = {
nodes: [{
username: 'rschafer',
host: 'roschaefer.de',
path: '/home/rschafer/rundfunk-frontend/dist'
}]
}
// configure other plugins for staging deploy target here
}
if (deployTarget === 'production') {
ENV.build.environment = 'production';
ENV['scp'] = {
nodes: [{
username: 'rfmb',
host: 'rundfunk-mitbestimmen.de',
path: '/home/rfmb/html/'
}]
}
}
// Note: if you need to build some configuration asynchronously, you can return
// a promise that resolves with the ENV object instead of returning the
// ENV object synchronously.
return ENV;
};
|
module.exports = function(deployTarget) {
var ENV = {
build: {}
// include other plugin configuration that applies to all deploy targets here
};
if (deployTarget === 'development') {
ENV.build.environment = 'development';
// configure other plugins for development deploy target here
}
if (deployTarget === 'staging') {
ENV.build.environment = 'staging';
ENV['scp'] = {
nodes: [{
username: 'rschafer',
host: 'roschaefer.de',
path: '/home/rschafer/rundfunk-frontend'
}]
}
// configure other plugins for staging deploy target here
}
if (deployTarget === 'production') {
ENV.build.environment = 'production';
ENV['scp'] = {
nodes: [{
username: 'rfmb',
host: 'rundfunk-mitbestimmen.de',
path: '/home/rfmb/html/'
}]
}
}
// Note: if you need to build some configuration asynchronously, you can return
// a promise that resolves with the ENV object instead of returning the
// ENV object synchronously.
return ENV;
};
|
Move importing of the server module inside the scope of the worker process. This change saves us unnecessary redis connections to the master process
|
'use strict';
/* eslint-disable global-require */
// Load environment vars.
require('dotenv').config();
const cluster = require('cluster');
const config = require('./config');
const logger = require('./lib/logger');
/**
* exitHandler - When any of the workers die the cluster module will emit the 'exit' event.
*
* @see https://nodejs.org/docs/latest-v8.x/api/cluster.html#cluster_event_exit_1
* @param {cluster.Worker} worker
* @param {Number} code
* @param {String} signal
*/
function exitHandler(worker, code, signal) {
logger.debug(`Worker ${worker.process.pid} died.\n\nReason: (${signal || code}).\n\nrestarting...`);
// Respawn a worker when it dies
cluster.fork();
}
if (cluster.isMaster) {
// Fork workers
for (let workers = 0; workers < config.workers; workers++) { // eslint-disable-line
cluster.fork();
}
// Register exit handler
cluster.on('exit', exitHandler);
logger.debug('Master process');
} else {
const server = require('./server');
server();
}
|
'use strict';
// Load environment vars.
require('dotenv').config();
const cluster = require('cluster');
const config = require('./config');
const logger = require('./lib/logger');
const server = require('./server');
/**
* exitHandler - When any of the workers die the cluster module will emit the 'exit' event.
*
* @see https://nodejs.org/docs/latest-v8.x/api/cluster.html#cluster_event_exit_1
* @param {cluster.Worker} worker
* @param {Number} code
* @param {String} signal
*/
function exitHandler(worker, code, signal) {
logger.debug(`Worker ${worker.process.pid} died.\n\nReason: (${signal || code}).\n\nrestarting...`);
// Respawn a worker when it dies
cluster.fork();
}
if (cluster.isMaster) {
// Fork workers
for (let workers = 0; workers < config.workers; workers++) { // eslint-disable-line
cluster.fork();
}
// Register exit handler
cluster.on('exit', exitHandler);
logger.debug('Master process');
} else {
server();
}
|
Drop argparse as a dependency
argparse has been part of the standard library since Python 2.7,
so there's no reason to declare this as a dependency, since it cannot
be satisfied by anyone running a modern Linux distribution including
a supported version of Python.
|
#!/usr/bin/env python3
from setuptools import setup
exec(open('manatools/version.py').read())
try:
import yui
except ImportError:
import sys
print('Please install python3-yui in order to install this package',
file=sys.stderr)
sys.exit(1)
setup(
name=__project_name__,
version=__project_version__,
author='Angelo Naselli',
author_email='anaselli@linux.it',
packages=['manatools', 'manatools.ui'],
#scripts=['scripts/'],
license='LGPLv2+',
description='Python ManaTools framework.',
long_description=open('README.md').read(),
#data_files=[('conf/manatools', ['XXX.yy',]), ],
install_requires=[
"dbus-python",
"python-gettext",
"PyYAML",
],
)
|
#!/usr/bin/env python3
from setuptools import setup
exec(open('manatools/version.py').read())
try:
import yui
except ImportError:
import sys
print('Please install python3-yui in order to install this package',
file=sys.stderr)
sys.exit(1)
setup(
name=__project_name__,
version=__project_version__,
author='Angelo Naselli',
author_email='anaselli@linux.it',
packages=['manatools', 'manatools.ui'],
#scripts=['scripts/'],
license='LGPLv2+',
description='Python ManaTools framework.',
long_description=open('README.md').read(),
#data_files=[('conf/manatools', ['XXX.yy',]), ],
install_requires=[
"argparse",
"dbus-python",
"python-gettext",
"PyYAML",
],
)
|
Use expect.shift instead of building an array of arguments for expect when delegating to the next assertion.
|
var BufferedStream = require('bufferedstream');
var createMockCouchAdapter = require('./createMockCouchAdapter');
var http = require('http');
var mockCouch = require('mock-couch-alexjeffburke');
var url = require('url');
function generateCouchdbResponse(databases, req, res) {
var responseObject = null;
var couchdbHandler = createMockCouchAdapter();
var couchdb = new mockCouch.MockCouch(couchdbHandler, {});
Object.keys(databases).forEach(function (databaseName) {
couchdb.addDB(databaseName, databases[databaseName].docs || []);
});
// run the handler
couchdbHandler(req, res, function () {});
}
module.exports = {
name: 'unexpected-couchdb',
installInto: function (expect) {
expect.installPlugin(require('unexpected-mitm'));
expect.addAssertion('<any> with couchdb mocked out <object> <assertion>', function (expect, subject, couchdb) {
expect.errorMode = 'nested';
return expect(function () {
return expect.shift();
}, 'with http mocked out', {
response: generateCouchdbResponse.bind(null, couchdb)
}, 'not to error');
});
}
};
|
var BufferedStream = require('bufferedstream');
var createMockCouchAdapter = require('./createMockCouchAdapter');
var http = require('http');
var mockCouch = require('mock-couch-alexjeffburke');
var url = require('url');
function generateCouchdbResponse(databases, req, res) {
var responseObject = null;
var couchdbHandler = createMockCouchAdapter();
var couchdb = new mockCouch.MockCouch(couchdbHandler, {});
Object.keys(databases).forEach(function (databaseName) {
couchdb.addDB(databaseName, databases[databaseName].docs || []);
});
// run the handler
couchdbHandler(req, res, function () {});
}
module.exports = {
name: 'unexpected-couchdb',
installInto: function (expect) {
expect.installPlugin(require('unexpected-mitm'));
expect.addAssertion('<any> with couchdb mocked out <object> <assertion>', function (expect, subject, couchdb) {
expect.errorMode = 'nested';
var nextAssertionArgs = this.args.slice(1);
var args = [subject, 'with http mocked out', {
response: generateCouchdbResponse.bind(null, couchdb)
}].concat(nextAssertionArgs);
return expect.apply(expect, args);
});
}
};
|
Add stack trace to exceptions in detailed mode
|
<?php
namespace Light\ObjectService\Formats\Json\Serializers;
use Light\ObjectService\Service\Protocol\ExceptionSerializer;
class DefaultExceptionSerializer extends BaseSerializer implements ExceptionSerializer
{
/** @var bool */
protected $detailed;
public function __construct($detailed = false, $contentType = "application/json")
{
parent::__construct($contentType);
$this->detailed = $detailed;
}
/**
* Serializes an exception.
* @param \Exception $e
* @return string
*/
public function serialize(\Exception $e)
{
return json_encode($this->serializeToObject($e));
}
public function serializeToObject(\Exception $e)
{
$json = new \stdClass();
$json->exceptionClass = get_class($e);
$json->message = $e->getMessage();
if ($previous = $e->getPrevious())
{
$json->previous = $this->serializeToObject($previous);
}
if ($this->detailed)
{
$json->trace = $e->getTrace();
}
return $json;
}
}
|
<?php
namespace Light\ObjectService\Formats\Json\Serializers;
use Light\ObjectService\Service\Protocol\ExceptionSerializer;
class DefaultExceptionSerializer extends BaseSerializer implements ExceptionSerializer
{
/** @var bool */
protected $detailed;
public function __construct($detailed = false, $contentType = "application/json")
{
parent::__construct($contentType);
$this->detailed = $detailed;
}
/**
* Serializes an exception.
* @param \Exception $e
* @return string
*/
public function serialize(\Exception $e)
{
return json_encode($this->serializeToObject($e));
}
public function serializeToObject(\Exception $e)
{
$json = new \stdClass();
$json->exceptionClass = get_class($e);
$json->message = $e->getMessage();
if ($previous = $e->getPrevious())
{
$json->previous = $this->serializeToObject($previous);
}
return $json;
}
}
|
Transform ESM to CJS when BABEL_ENV is "test"
|
const pluginLodash = require('babel-plugin-lodash')
const pluginReactRequire = require('babel-plugin-react-require').default
const presetEnv = require('babel-preset-env')
const presetStage1 = require('babel-preset-stage-1')
const presetReact = require('babel-preset-react')
const {BABEL_ENV} = process.env
const defaultOptions = {
lodash: true,
modules: ['cjs', 'test'].includes(BABEL_ENV) ? 'commonjs' : false,
targets: {
browsers: ['IE 11', 'last 2 Edge versions', 'Firefox >= 45', 'last 2 Chrome versions'],
node: 8,
},
}
module.exports = (context, userOptions) => {
const options = Object.assign({}, defaultOptions, userOptions)
return {
plugins: [options.lodash && pluginLodash, pluginReactRequire].filter(Boolean),
presets: [
[presetEnv, {modules: options.modules, targets: options.targets}],
presetStage1,
presetReact,
],
}
}
|
const pluginLodash = require('babel-plugin-lodash')
const pluginReactRequire = require('babel-plugin-react-require').default
const presetEnv = require('babel-preset-env')
const presetStage1 = require('babel-preset-stage-1')
const presetReact = require('babel-preset-react')
const {BABEL_ENV} = process.env
const defaultOptions = {
lodash: true,
modules: BABEL_ENV === 'cjs' ? 'commonjs' : false,
targets: {
browsers: ['IE 11', 'last 2 Edge versions', 'Firefox >= 45', 'last 2 Chrome versions'],
node: 8,
},
}
module.exports = (context, userOptions) => {
const options = Object.assign({}, defaultOptions, userOptions)
return {
plugins: [options.lodash && pluginLodash, pluginReactRequire].filter(Boolean),
presets: [
[presetEnv, {modules: options.modules, targets: options.targets}],
presetStage1,
presetReact,
],
}
}
|
Remove unused Python 2 support
|
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from wagtail.wagtailcore.templatetags import wagtailcore_tags
from wagtail.wagtailadmin.templatetags import wagtailuserbar
from jinja2 import Environment
from compressor.contrib.jinja2ext import CompressorExtension
def environment(**options):
options.setdefault('extensions', []).append(CompressorExtension)
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'reverse': reverse,
'wagtailuserbar': wagtailuserbar.wagtailuserbar
})
env.filters.update({
'slugify': slugify,
'richtext': wagtailcore_tags.richtext
})
return env
|
from __future__ import absolute_import # Python 2 only
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from wagtail.wagtailcore.templatetags import wagtailcore_tags
from wagtail.wagtailadmin.templatetags import wagtailuserbar
from jinja2 import Environment
from compressor.contrib.jinja2ext import CompressorExtension
def environment(**options):
options.setdefault('extensions', []).append(CompressorExtension)
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'reverse': reverse,
'wagtailuserbar': wagtailuserbar.wagtailuserbar
})
env.filters.update({
'slugify': slugify,
'richtext': wagtailcore_tags.richtext
})
return env
|
Add build-raw-files log; fixes 12603
BS3 commits: 7100e3a37eedf31f6ba005bb045ee3074a6ee5ed
|
/* global btoa: true */
/*!
* Bootstrap Grunt task for generating raw-files.min.js for the Customizer
* http://getbootstrap.com
* Copyright 2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
'use strict';
var fs = require('fs');
var btoa = require('btoa');
var grunt = require('grunt');
function getFiles(type) {
var files = {};
fs.readdirSync(type)
.filter(function (path) {
return type === 'fonts' ? true : new RegExp('\\.' + type + '$').test(path);
})
.forEach(function (path) {
var fullPath = type + '/' + path;
files[path] = (type === 'fonts' ? btoa(fs.readFileSync(fullPath)) : fs.readFileSync(fullPath, 'utf8'));
});
return 'var __' + type + ' = ' + JSON.stringify(files) + '\n';
}
module.exports = function generateRawFilesJs(banner) {
if (!banner) {
banner = '';
}
var files = banner + getFiles('js') + getFiles('less') + getFiles('fonts');
var rawFilesJs = 'docs/assets/js/raw-files.min.js';
try {
fs.writeFileSync(rawFilesJs, files);
}
catch (err) {
grunt.fail.warn(err);
}
grunt.log.writeln('File ' + rawFilesJs.cyan + ' created.');
};
|
/* global btoa: true */
/*!
* Bootstrap Grunt task for generating raw-files.min.js for the Customizer
* http://getbootstrap.com
* Copyright 2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
'use strict';
var btoa = require('btoa');
var fs = require('fs');
function getFiles(type) {
var files = {};
fs.readdirSync(type)
.filter(function (path) {
return type === 'fonts' ? true : new RegExp('\\.' + type + '$').test(path);
})
.forEach(function (path) {
var fullPath = type + '/' + path;
files[path] = (type === 'fonts' ? btoa(fs.readFileSync(fullPath)) : fs.readFileSync(fullPath, 'utf8'));
});
return 'var __' + type + ' = ' + JSON.stringify(files) + '\n';
}
module.exports = function generateRawFilesJs(banner) {
if (!banner) {
banner = '';
}
var files = banner + getFiles('js') + getFiles('less') + getFiles('fonts');
fs.writeFileSync('docs/assets/js/raw-files.min.js', files);
};
|
feature/oop-api-refactoring: Remove redundant parentheses around if conditions
|
# -*- coding: utf-8 -*-
from os.path import sep
KEY = 'go'
LABEL = 'Go'
DEPENDENCIES = ['go']
TEMP_DIR = 'go'
SUFFIX = 'go'
# go build -o tmp/estimator tmp/estimator.go
CMD_COMPILE = 'go build -o {dest_dir}' + sep + '{dest_file} {src_dir}' + sep + '{src_file}'
# tmp/estimator <args>
CMD_EXECUTE = '{dest_dir}' + sep + '{dest_file}'
TEMPLATES = {
# if/else condition:
'if': 'if {0} {1} {2} {{',
'else': '} else {',
'endif': '}',
# Basics:
'indent': '\t',
'join': '',
'type': '{0}',
# Arrays:
'in_brackets': '{{{0}}}',
'arr[]': '{name} := []{type} {{{values}}}', # ages := []int {1, 2}
'arr[][]': '{name} := [][]{type} {{{values}}}',
# Primitive data types:
'int': 'int',
'double': 'float64'
}
|
# -*- coding: utf-8 -*-
from os.path import sep
KEY = 'go'
LABEL = 'Go'
DEPENDENCIES = ['go']
TEMP_DIR = 'go'
SUFFIX = 'go'
# go build -o tmp/estimator tmp/estimator.go
CMD_COMPILE = 'go build -o {dest_dir}' + sep + '{dest_file} {src_dir}' + sep + '{src_file}'
# tmp/estimator <args>
CMD_EXECUTE = '{dest_dir}' + sep + '{dest_file}'
TEMPLATES = {
# if/else condition:
'if': 'if ({0} {1} {2}) {{',
'else': '} else {',
'endif': '}',
# Basics:
'indent': '\t',
'join': '',
'type': '{0}',
# Arrays:
'in_brackets': '{{{0}}}',
'arr[]': '{name} := []{type} {{{values}}}', # ages := []int {1, 2}
'arr[][]': '{name} := [][]{type} {{{values}}}',
# Primitive data types:
'int': 'int',
'double': 'float64'
}
|
[auth] Connect to www not beta (which no longer exists)
|
"use strict";
var BaobabControllers; //globals
BaobabControllers
.controller('AppCtrl', ['$scope', '$me', '$inbox', '$auth', '$location', '$cookieStore', '$sce', function($scope, $me, $inbox, $auth, $location, $cookieStore, $sce) {
var self = this;
window.AppCtrl = this;
this.inboxAuthURL = $sce.trustAsResourceUrl('https://www.inboxapp.com/oauth/authorize');
this.inboxClientID = $inbox.appId();
this.inboxRedirectURL = window.location.protocol + "//" + window.location.host + "/";
this.loginHint = '';
this.clearToken = $auth.clearToken;
this.token = function() {
return $auth.token;
};
this.namespace = function() {
return $me._namespace;
};
this.theme = $cookieStore.get('baobab_theme') || 'light';
this.setTheme = function(theme) {
self.theme = theme;
$cookieStore.put('baobab_theme', theme);
};
this.cssForTab = function(path) {
return ($location.path().indexOf(path) != -1) ? 'active' : '';
};
}]);
|
"use strict";
var BaobabControllers; //globals
BaobabControllers
.controller('AppCtrl', ['$scope', '$me', '$inbox', '$auth', '$location', '$cookieStore', '$sce', function($scope, $me, $inbox, $auth, $location, $cookieStore, $sce) {
var self = this;
window.AppCtrl = this;
this.inboxAuthURL = $sce.trustAsResourceUrl('https://beta.inboxapp.com/oauth/authorize');
this.inboxClientID = $inbox.appId();
this.inboxRedirectURL = window.location.protocol + "//" + window.location.host + "/";
this.loginHint = '';
this.clearToken = $auth.clearToken;
this.token = function() {
return $auth.token;
};
this.namespace = function() {
return $me._namespace;
};
this.theme = $cookieStore.get('baobab_theme') || 'light';
this.setTheme = function(theme) {
self.theme = theme;
$cookieStore.put('baobab_theme', theme);
};
this.cssForTab = function(path) {
return ($location.path().indexOf(path) != -1) ? 'active' : '';
};
}]);
|
Use explicit null check in `getNamesFromPattern`.
|
"use strict";
exports.getNamesFromPattern = function (pattern) {
var queue = [pattern];
var names = [];
for (var i = 0; i < queue.length; ++i) {
var pattern = queue[i];
if (pattern === null) {
// The ArrayPattern .elements array can contain null to indicate that
// the position is a hole.
continue;
}
switch (pattern.type) {
case "Identifier":
names.push(pattern.name);
break;
case "Property":
case "ObjectProperty":
queue.push(pattern.value);
break;
case "AssignmentPattern":
queue.push(pattern.left);
break;
case "ObjectPattern":
queue.push.apply(queue, pattern.properties);
break;
case "ArrayPattern":
queue.push.apply(queue, pattern.elements);
break;
case "RestElement":
queue.push(pattern.argument);
break;
}
}
return names;
};
|
"use strict";
exports.getNamesFromPattern = function (pattern) {
var queue = [pattern];
var names = [];
for (var i = 0; i < queue.length; ++i) {
var pattern = queue[i];
if (! pattern) {
// The ArrayPattern .elements array can contain null to indicate the
// element at that position that should not be bound.
continue;
}
switch (pattern.type) {
case "Identifier":
names.push(pattern.name);
break;
case "Property":
case "ObjectProperty":
queue.push(pattern.value);
break;
case "AssignmentPattern":
queue.push(pattern.left);
break;
case "ObjectPattern":
queue.push.apply(queue, pattern.properties);
break;
case "ArrayPattern":
queue.push.apply(queue, pattern.elements);
break;
case "RestElement":
queue.push(pattern.argument);
break;
}
}
return names;
};
|
Remove int enum values, as they are unneeded
|
package com.openxc.measurements;
import java.util.Locale;
import com.openxc.units.State;
/**
* The ClimateMode measurement is used to start the AC/Heater/Fan
*/
public class ClimateMode extends BaseMeasurement<State<ClimateMode.ClimateControls>> {
public final static String ID = "climate_mode";
public enum ClimateControls {
OFF,
PANEL_VENT,
PANEL_FLOOR,
FLOOR,
FAN_SPEED_INCREMENT,
FAN_SPEED_DECREMENT,
AUTO,
MAX_AC,
RECIRCULATION,
FRONT_DEFROST,
REAR_DEFROST,
MAX_DEFROST
}
public ClimateMode(State<ClimateControls> value) {
super(value);
}
public ClimateMode(ClimateControls value) {
this(new State<ClimateControls>(value));
}
public ClimateMode(String value) {
this(ClimateControls.valueOf(value.toUpperCase(Locale.US)));
}
@Override
public String getGenericName() {
return ID;
}
}
|
package com.openxc.measurements;
import java.util.Locale;
import com.openxc.units.State;
/**
* The ClimateMode measurement is used to start the AC/Heater/Fan
*/
public class ClimateMode extends BaseMeasurement<State<ClimateMode.ClimateControls>> {
public final static String ID = "climate_mode";
public enum ClimateControls {
UNUSED(0),
PANEL_VENT(1),
PANEL_FLOOR(2),
FLOOR(3),
FAN_SPEED_INCREMENT(11),
FAN_SPEED_DECREMENT(12),
AUTO(13),
MAX_AC(14),
RECIRCULATION(15),
FRONT_DEFROST(16),
REAR_DEFROST(17),
MAX_DEFROTS(22)
}
public ClimateMode(State<ClimateControls> value) {
super(value);
}
public ClimateMode(ClimateControls value) {
this(new State<ClimateControls>(value));
}
public ClimateMode(String value) {
this(ClimateControls.valueOf(value.toUpperCase(Locale.US)));
}
@Override
public String getGenericName() {
return ID;
}
}
|
Include decorator requirement for tests as well
One would think setup.py would include runtime deps with test deps, but
no...
References #6
|
import codecs
from setuptools import find_packages, setup
import digestive
requires = ['decorator']
setup(
name='digestive',
version=digestive.__version__,
url='https://github.com/akaIDIOT/Digestive',
packages=find_packages(),
description='Run several digest algorithms on the same data efficiently',
author='Mattijs Ugen',
author_email=codecs.encode('nxnvqvbg@hfref.abercyl.tvguho.pbz', 'rot_13'),
license='ISC',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
install_requires=requires,
tests_require=requires + ['pytest', 'mock', 'decorator'],
entry_points={
'console_scripts': {
'digestive = digestive.main:main'
}
}
)
|
import codecs
from setuptools import find_packages, setup
import digestive
setup(
name='digestive',
version=digestive.__version__,
url='https://github.com/akaIDIOT/Digestive',
packages=find_packages(),
description='Run several digest algorithms on the same data efficiently',
author='Mattijs Ugen',
author_email=codecs.encode('nxnvqvbg@hfref.abercyl.tvguho.pbz', 'rot_13'),
license='ISC',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
install_requires=['decorator'],
tests_require=['pytest', 'mock'],
entry_points={
'console_scripts': {
'digestive = digestive.main:main'
}
}
)
|
Expand the sentence segmentation tests a little()
|
#
import pytest
from sdsc import sentencesegmenter
@pytest.mark.parametrize("sentence,expected",
(
# 0 - a single simple sentence
("This is a simple sentence.",
["This is a simple sentence"]),
# 1 - two simple sentences
("This is a simple ##@command-2## sentence. This one is too.",
["This is a simple ##@command-2## sentence", "This one is too"]),
# 2 - lowercase letter starts second sentence
("This is not a test in one go. openSUSE is not written with a capital letter.",
["This is not a test in one go",
"openSUSE is not written with a capital letter"]),
# 3 - abbreviation in the middle of the sentence
("This is a sentence, e.g. for me.",
["This is a sentence, e.g. for me"]),
# 4 - abbreviation at the start of the sentence
("E. g. this is a sentence.",
["E. g. this is a sentence"]),
# 5 - abbreviation in the middle of sentence before a capital letter
("An above average chance stands e.g. Michael. Marta is also on the list.",
["An above average chance stands e.g. Michael",
"Marta is also on the list"]),
# 6 - sentences with parentheses around them
("(We speak in circles. We dance in code.)",
["We speak in circles",
"We dance in code"]),
# 6 - sentences with parentheses around them
("We speak in circles. (We dance in code.)",
["We speak in circles",
"We dance in code"]),
))
def test_sentencesegmenter(sentence, expected):
"""checks whether sentencesegmenter behaves sanely"""
sentences = sentencesegmenter(sentence)
assert sentences == expected
|
#
import pytest
from sdsc import sentencesegmenter
@pytest.mark.parametrize("sentence,expected",
(
# 1
("This is a simple ##@command-2## sentence. This one too.",
["This is a simple ##@command-2## sentence", "This one too"]),
# 2
("This is not a test in one go. openSUSE is not written with a capital letter.",
["This is not a test in one go",
"openSUSE is not written with a capital letter"]),
# 3
("This is a sentence, e.g. for me.",
["This is a sentence, e.g. for me"]),
# 4
("E. g. this is a sentence.",
["E. g. this is a sentence"]),
# 5
("An above average chance stands e.g. Michael. Marta is also on the list.",
["An above average chance stands e.g. Michael",
"Marta is also on the list"]),
# Add more entries here:
))
def test_sentencesegmenter(sentence, expected):
"""checks whether sentencesegmenter behaves sane"""
sentences = sentencesegmenter(sentence)
assert sentences == expected
|
Add callback call after promise finishes.
|
'use strict';
const assert = require('assert');
const gulp = require('gulp');
const helper = require('gulp/helper');
const _ = require('lodash');
const Promise = require('bluebird').Promise;
const sandbox = require('sandboxjs');
gulp.task('build:webtasks', cb => {
const config = helper.getConfig();
assert(config.sandbox.token, 'Sandbox Token is required!');
assert(config.webtasks.length, 'List of Webtasks is empty!');
const profile = sandbox.fromToken(config.sandbox.token, config.sandbox);
let webtasks = [];
Promise.each(config.webtasks, wt => {
// Add config params but don't override if setting already exists
let claims = _.defaults({
url: wt.secrets.WEBTASK_URL,
ectx: wt.secrets
}, wt.metadata.claims);
return profile.createTokenRaw(claims).then(token =>
webtasks.push(_.merge(wt, {
token: token
}))
);
}).then(() =>
helper.updateConfig('webtasks', webtasks).then(() => cb())
).catch(cb);
});
|
'use strict';
const assert = require('assert');
const gulp = require('gulp');
const helper = require('gulp/helper');
const _ = require('lodash');
const Promise = require('bluebird').Promise;
const sandbox = require('sandboxjs');
gulp.task('build:webtasks', cb => {
const config = helper.getConfig();
assert(config.sandbox.token, 'Sandbox Token is required!');
assert(config.webtasks.length, 'List of Webtasks is empty!');
const profile = sandbox.fromToken(config.sandbox.token, config.sandbox);
let webtasks = [];
Promise.each(config.webtasks, wt => {
// Add config params but don't override if setting already exists
let claims = _.defaults({
url: wt.secrets.WEBTASK_URL,
ectx: wt.secrets
}, wt.metadata.claims);
return profile.createTokenRaw(claims).then(token =>
webtasks.push(_.merge(wt, {
token: token
}))
);
}).then(() => helper.updateConfig('webtasks', webtasks))
.catch(cb);
});
|
Enable inhomogeneous packets in the main simulation runner
|
"""The WaveBlocks Project
This file is main script for running simulations with WaveBlocks.
@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""
import sys
from WaveBlocksND import ParameterLoader
# Read the path for the configuration file we use for this simulation.
try:
parametersfile = sys.argv[1]
except IndexError:
raise ValueError("No configuration file given!")
print("Using configuration from file: " + parametersfile)
# Set up the parameter provider singleton
PA = ParameterLoader().load_from_file(parametersfile)
# Print the parameters that apply for this simulation
print(PA)
# Decide which simulation loop to use
if PA["algorithm"] == "fourier":
from WaveBlocksND import SimulationLoopFourier
SL = SimulationLoopFourier(PA)
elif PA["algorithm"] == "hagedorn":
from WaveBlocksND import SimulationLoopHagedorn
SL = SimulationLoopHagedorn(PA)
elif PA["algorithm"] == "hagedorn_inhomog":
from WaveBlocksND import SimulationLoopHagedornInhomogeneous
SL = SimulationLoopHagedornInhomogeneous(PA)
# TODO: Add new algorithms here
else:
raise ValueError("Invalid propagator algorithm.")
# Initialize and run the simulation
SL.prepare_simulation()
SL.run_simulation()
# End the simulation, close output files etc.
SL.end_simulation()
|
"""The WaveBlocks Project
This file is main script for running simulations with WaveBlocks.
@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""
import sys
from WaveBlocksND import ParameterLoader
# Read the path for the configuration file we use for this simulation.
try:
parametersfile = sys.argv[1]
except IndexError:
raise ValueError("No configuration file given!")
print("Using configuration from file: " + parametersfile)
# Set up the parameter provider singleton
PA = ParameterLoader().load_from_file(parametersfile)
# Print the parameters that apply for this simulation
print(PA)
# Decide which simulation loop to use
if PA["algorithm"] == "fourier":
from WaveBlocksND import SimulationLoopFourier
SL = SimulationLoopFourier(PA)
elif PA["algorithm"] == "hagedorn":
from WaveBlocksND import SimulationLoopHagedorn
SL = SimulationLoopHagedorn(PA)
# TODO: Add new algorithms here
else:
raise ValueError("Invalid propagator algorithm.")
# Initialize and run the simulation
SL.prepare_simulation()
SL.run_simulation()
# End the simulation, close output files etc.
SL.end_simulation()
|
Remove key while opening a door
|
from onirim.card._base import ColorCard
from onirim.card._location import LocationKind
def _is_openable(door_card, card):
"""Check if the door can be opened by another card."""
return card.kind == LocationKind.key and door_card.color == card.color
def _may_open(door_card, content):
"""Check if the door may be opened by agent."""
return any(_is_openable(door_card, card) for card in content.hand)
class _Door(ColorCard):
def drawn(self, agent, content):
do_open = agent.open_door(content, self) if _may_open(self, content) else False
if do_open:
content.opened.append(self)
for card in content.hand:
if _openable(self, card):
content.hand.remove(card)
break
else:
content.deck.put_limbo(self)
def door(color):
"""Make a door card."""
return _Door(color)
|
from onirim.card._base import ColorCard
from onirim.card._location import LocationKind
def _openable(door_card, card):
"""Check if the door can be opened by another card."""
return card.kind == LocationKind.key and door_card.color == card.color
def _may_open(door_card, content):
"""Check if the door may be opened by agent."""
return any(_openable(door_card, card) for card in content.hand)
class _Door(ColorCard):
def drawn(self, agent, content):
# TODO discard that key card.
do_open = agent.open_door(content, self) if _may_open(self, content) else False
if do_open:
content.opened.append(self)
else:
content.deck.put_limbo(self)
def door(color):
"""Make a door card."""
return _Door(color)
|
Fix property name in test
|
import hoomd
def test_before_attaching():
filt = hoomd.filter.All()
thermoHMA = hoomd.md.compute.ThermoHMA(filt, 1.0)
assert thermoHMA._filter == filt
assert thermoHMA.temperature == 1.0
assert thermoHMA.harmonic_pressure == 0.0
assert thermoHMA.potential_energyHMA is None
assert thermoHMA.pressureHMA is None
thermoHMA = hoomd.md.compute.ThermoHMA(filt, 2.5, 0.6)
assert thermoHMA.temperature == 2.5
assert thermoHMA.harmonic_pressure == 0.6
def test_after_attaching(simulation_factory, two_particle_snapshot_factory):
filt = hoomd.filter.All()
thermoHMA = hoomd.md.compute.ThermoHMA(filt, 1.0)
sim = simulation_factory(two_particle_snapshot_factory())
sim.operations.add(thermoHMA)
assert len(sim.operations.computes) == 1
sim.run(0)
assert isinstance(thermoHMA.potential_energyHMA, float)
assert isinstance(thermoHMA.pressureHMA, float)
sim.operations.remove(thermoHMA)
assert len(sim.operations.computes) == 0
assert thermoHMA.potential_energyHMA is None
assert thermoHMA.pressureHMA is None
|
import hoomd
def test_before_attaching():
filt = hoomd.filter.All()
thermoHMA = hoomd.md.compute.ThermoHMA(filt, 1.0)
assert thermoHMA._filter == filt
assert thermoHMA.temperature == 1.0
assert thermoHMA.harmonicPressure == 0.0
assert thermoHMA.potential_energyHMA is None
assert thermoHMA.pressureHMA is None
thermoHMA = hoomd.md.compute.ThermoHMA(filt, 2.5, 0.6)
assert thermoHMA.temperature == 2.5
assert thermoHMA.harmonicPressure == 0.6
def test_after_attaching(simulation_factory, two_particle_snapshot_factory):
filt = hoomd.filter.All()
thermoHMA = hoomd.md.compute.ThermoHMA(filt, 1.0)
sim = simulation_factory(two_particle_snapshot_factory())
sim.operations.add(thermoHMA)
assert len(sim.operations.computes) == 1
sim.run(0)
assert isinstance(thermoHMA.potential_energyHMA, float)
assert isinstance(thermoHMA.pressureHMA, float)
sim.operations.remove(thermoHMA)
assert len(sim.operations.computes) == 0
assert thermoHMA.potential_energyHMA is None
assert thermoHMA.pressureHMA is None
|
Fix user profile not serializing.
|
package io.github.vcuswimlab.stackintheflow.controller.component;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
/**
* <h1>PersistProfileComponent</h1>
* Created on: 8/1/2017
*
* @author Tyler John Haden
*/
@State(
name = "ProfileState", storages = {
@Storage("stackoverflow-profile.xml")
})
public class PersistProfileComponent implements PersistentStateComponent<PersistProfileComponent> {
public Map<String, Integer> userStatMap;
public Map<String, Integer> getUserStatMap() {
return userStatMap;
}
@Override
public void noStateLoaded() {
userStatMap = new HashMap<>();
}
@Override
public void loadState(PersistProfileComponent state) {
XmlSerializerUtil.copyBean(state, this);
}
@Nullable
@Override
public PersistProfileComponent getState() {
return this;
}
}
|
package io.github.vcuswimlab.stackintheflow.controller.component;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
/**
* <h1>PersistProfileComponent</h1>
* Created on: 8/1/2017
*
* @author Tyler John Haden
*/
@State(
name = "ProfileState", storages = {
@Storage(
id = "stack-overflow",
file = "$PROJECT_CONFIG_DIR$/stackoverflow-profile.xml")
})
public class PersistProfileComponent implements PersistentStateComponent<PersistProfileComponent> {
private Map<String, Integer> userStatMap;
public Map<String, Integer> getUserStatMap() {
return userStatMap;
}
@Override
public void noStateLoaded() {
userStatMap = new HashMap<>();
}
@Override
public void loadState(PersistProfileComponent state) {
XmlSerializerUtil.copyBean(state, this);
}
@Nullable
@Override
public PersistProfileComponent getState() {
return this;
}
}
|
Fix ConvertAndFreeCoTaskMemString for 32 bit platforms
|
package interop
import (
"syscall"
"unsafe"
)
//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go interop.go
//sys coTaskMemFree(buffer unsafe.Pointer) = ole32.CoTaskMemFree
func ConvertAndFreeCoTaskMemString(buffer *uint16) string {
str := syscall.UTF16ToString((*[1 << 29]uint16)(unsafe.Pointer(buffer))[:])
coTaskMemFree(unsafe.Pointer(buffer))
return str
}
func ConvertAndFreeCoTaskMemBytes(buffer *uint16) []byte {
return []byte(ConvertAndFreeCoTaskMemString(buffer))
}
func Win32FromHresult(hr uintptr) syscall.Errno {
if hr&0x1fff0000 == 0x00070000 {
return syscall.Errno(hr & 0xffff)
}
return syscall.Errno(hr)
}
|
package interop
import (
"syscall"
"unsafe"
)
//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go interop.go
//sys coTaskMemFree(buffer unsafe.Pointer) = ole32.CoTaskMemFree
func ConvertAndFreeCoTaskMemString(buffer *uint16) string {
str := syscall.UTF16ToString((*[1 << 30]uint16)(unsafe.Pointer(buffer))[:])
coTaskMemFree(unsafe.Pointer(buffer))
return str
}
func ConvertAndFreeCoTaskMemBytes(buffer *uint16) []byte {
return []byte(ConvertAndFreeCoTaskMemString(buffer))
}
func Win32FromHresult(hr uintptr) syscall.Errno {
if hr&0x1fff0000 == 0x00070000 {
return syscall.Errno(hr & 0xffff)
}
return syscall.Errno(hr)
}
|
Allow unsetting of configuration (for testing)
|
# -*- coding: utf-8 -*-
"""
Ziggy
~~~~~~~~
:copyright: (c) 2012 by Rhett Garber
:license: ISC, see LICENSE for more details.
"""
__title__ = 'ziggy'
__version__ = '0.0.1'
__build__ = 0
__author__ = 'Rhett Garber'
__license__ = 'ISC'
__copyright__ = 'Copyright 2012 Rhett Garber'
import logging
from . import utils
from . import network
from .context import Context, set, append, add
from . import context as _context_mod
from .errors import Error
from .timer import timeit
log = logging.getLogger(__name__)
def configure(host, port, recorder=None):
"""Initialize ziggy
This instructs the ziggy system where to send it's logging data. If ziggy is not configured, log data will
be silently dropped.
Currently we support logging through the network (and the configured host and port) to a ziggyd instances, or
to the specified recorder function
"""
global _record_function
if recorder:
context._recorder_function = recorder
elif host and port:
network.init(host, port)
context._recorder_function = network.send
else:
log.warning("Empty ziggy configuration")
context._recorder_function = None
|
# -*- coding: utf-8 -*-
"""
Ziggy
~~~~~~~~
:copyright: (c) 2012 by Rhett Garber
:license: ISC, see LICENSE for more details.
"""
__title__ = 'ziggy'
__version__ = '0.0.1'
__build__ = 0
__author__ = 'Rhett Garber'
__license__ = 'ISC'
__copyright__ = 'Copyright 2012 Rhett Garber'
import logging
from . import utils
from . import network
from .context import Context, set, append, add
from . import context as _context_mod
from .errors import Error
from .timer import timeit
log = logging.getLogger(__name__)
def configure(host, port, recorder=None):
"""Initialize ziggy
This instructs the ziggy system where to send it's logging data. If ziggy is not configured, log data will
be silently dropped.
Currently we support logging through the network (and the configured host and port) to a ziggyd instances, or
to the specified recorder function
"""
global _record_function
if recorder:
context._recorder_function = recorder
elif host and port:
network.init(host, port)
context._recorder_function = network.send
else:
log.warning("Empty ziggy configuration")
|
Add github3.py depedency to be able to list all plugins from Github.
|
from setuptools import setup, find_packages
setup(
name='weaveserver',
version='0.8',
author='Srivatsan Iyer',
author_email='supersaiyanmode.rox@gmail.com',
packages=find_packages(),
license='MIT',
description='Library to interact with Weave Server',
long_description=open('README.md').read(),
install_requires=[
'weavelib',
'eventlet!=0.22',
'bottle',
'GitPython',
'redis',
'appdirs',
'peewee',
'virtualenv',
'github3.py',
],
entry_points={
'console_scripts': [
'weave-launch = app:handle_launch',
'weave-main = app:handle_main'
]
}
)
|
from setuptools import setup, find_packages
setup(
name='weaveserver',
version='0.8',
author='Srivatsan Iyer',
author_email='supersaiyanmode.rox@gmail.com',
packages=find_packages(),
license='MIT',
description='Library to interact with Weave Server',
long_description=open('README.md').read(),
install_requires=[
'weavelib',
'eventlet!=0.22',
'bottle',
'GitPython',
'redis',
'appdirs',
'peewee',
'virtualenv',
],
entry_points={
'console_scripts': [
'weave-launch = app:handle_launch',
'weave-main = app:handle_main'
]
}
)
|
Disable test not working on GitHub workflow
|
/*
* Copyright (c) 2014-2021 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const frisby = require('frisby')
const Joi = frisby.Joi
const URL = 'http://localhost:3000'
describe('/snippet/:challenge', () => {
it('GET code snippet retrieval for unknown challenge key throws error', () => {
return frisby.get(URL + '/snippet/doesNotExistChallenge')
.expect('status', 412)
.expect('json', 'error', 'Unknown challenge key: doesNotExistChallenge')
})
xit('GET code snippet retrieval for challenge without code snippet throws error', () => { // FIXME Re-enable once hard-coded demo file is replaced with actual file search
return frisby.get(URL + '/snippet/easterEggLevelTwoChallenge')
.expect('status', 404)
.expect('json', 'error', 'No code snippet available for: easterEggLevelTwoChallenge')
})
xit('GET code snippet retrieval for challenge with code snippet', () => { // FIXME fails on GitHub workflow, works on Bjoern's Win 10 machine
return frisby.get(URL + '/snippet/loginAdminChallenge')
.expect('status', 200)
.expect('jsonTypes', {
snippet: Joi.string(),
vulnLine: Joi.number()
})
})
})
|
/*
* Copyright (c) 2014-2021 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const frisby = require('frisby')
const Joi = frisby.Joi
const URL = 'http://localhost:3000'
describe('/snippet/:challenge', () => {
it('GET code snippet retrieval for unknown challenge key throws error', () => {
return frisby.get(URL + '/snippet/doesNotExistChallenge')
.expect('status', 412)
.expect('json', 'error', 'Unknown challenge key: doesNotExistChallenge')
})
xit('GET code snippet retrieval for challenge without code snippet throws error', () => {
return frisby.get(URL + '/snippet/easterEggLevelTwoChallenge')
.expect('status', 404)
.expect('json', 'error', 'No code snippet available for: easterEggLevelTwoChallenge')
})
it('GET code snippet retrieval for challenge with code snippet', () => {
return frisby.get(URL + '/snippet/loginAdminChallenge')
.expect('status', 200)
.expect('jsonTypes', {
snippet: Joi.string(),
vulnLine: Joi.number()
})
})
})
|
OpenFile: Use *.bob over *.opi when called from alarm UI, cmd line
|
/*******************************************************************************
* Copyright (c) 2015-2016 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.csstudio.display.builder.rcp;
import org.csstudio.display.builder.model.macros.MacroXMLUtil;
import org.csstudio.display.builder.model.macros.Macros;
import org.csstudio.openfile.IOpenDisplayAction;
/** Handler for opening files from command line
*
* <p>See
* Opening Files from Command-Line - org.csstudio.openfile
* in CS-Studio docbook.
*
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class OpenDisplayFile implements IOpenDisplayAction
{
@Override
public void openDisplay(final String path, final String data) throws Exception
{
final Macros macros = MacroXMLUtil.readMacros(data);
// 'resolve', i.e. use *.bob over *.opi if found
final DisplayInfo info = new DisplayInfo(path, "Display from command line", macros, true);
new OpenDisplayAction(info).run();
}
}
|
/*******************************************************************************
* Copyright (c) 2015-2016 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.csstudio.display.builder.rcp;
import org.csstudio.display.builder.model.macros.MacroXMLUtil;
import org.csstudio.display.builder.model.macros.Macros;
import org.csstudio.openfile.IOpenDisplayAction;
/** Handler for opening files from command line
*
* <p>See
* Opening Files from Command-Line - org.csstudio.openfile
* in CS-Studio docbook.
*
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class OpenDisplayFile implements IOpenDisplayAction
{
@Override
public void openDisplay(final String path, final String data) throws Exception
{
final Macros macros = MacroXMLUtil.readMacros(data);
final DisplayInfo info = new DisplayInfo(path, "Display from command line", macros);
new OpenDisplayAction(info).run();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.