text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
FIX (revisions): Fix revision history link | 'use strict';
angular.module('gisto.service.githubUrlBuilder', [], function ($provide) {
$provide.factory('githubUrlBuilderService', function (ghAPI, $filter, $rootScope, $routeParams) {
var githubFileNameFilter = $filter('githubFileName');
var publicGithubUrl = 'https://gist.github.com/';
var baseUrl = publicGithubUrl;
$rootScope.$watch('enterpriseMode', function(enterpriseMode, oldMode) {
if (enterpriseMode) {
var endpoint = ghAPI.getEndpoint();
console.log(endpoint);
if (endpoint.hasOwnProperty('api_url')) {
baseUrl = endpoint.api_url.replace('/api/v3', '/gist/');
console.log(baseUrl);
}
} else {
baseUrl = publicGithubUrl;
}
});
var service = {
buildFileLink: function(gist, file) {
return baseUrl + gist.single.owner.login + '/' + gist.single.id + '/#file-' + githubFileNameFilter(file.filename);
},
buildGistLink: function(gist) {
return baseUrl + gist.owner.login + '/' + gist.id +'.js';
},
buildHistoryLink: function(gist, file) {
console.warn(gist);
var url = baseUrl + gist.owner.login + '/' + gist.id + '/' + $routeParams.gistRevisionId;
if (file) {
url +='/#file-' + githubFileNameFilter(file.filename);
}
return url;
},
buildDownloadLink: function(gist) {
return baseUrl + gist.owner.login + '/' + gist.id + '/download';
}
};
return service;
});
}); | 'use strict';
angular.module('gisto.service.githubUrlBuilder', [], function ($provide) {
$provide.factory('githubUrlBuilderService', function (ghAPI, $filter, $rootScope) {
var githubFileNameFilter = $filter('githubFileName');
var publicGithubUrl = 'https://gist.github.com/';
var baseUrl = publicGithubUrl;
$rootScope.$watch('enterpriseMode', function(enterpriseMode, oldMode) {
if (enterpriseMode) {
var endpoint = ghAPI.getEndpoint();
console.log(endpoint);
if (endpoint.hasOwnProperty('api_url')) {
baseUrl = endpoint.api_url.replace('/api/v3', '/gist/');
console.log(baseUrl);
}
} else {
baseUrl = publicGithubUrl;
}
});
var service = {
buildFileLink: function(gist, file) {
return baseUrl + gist.single.owner.login + '/' + gist.single.id + '/#file-' + githubFileNameFilter(file.filename);
},
buildGistLink: function(gist) {
return baseUrl + gist.owner.login + '/' + gist.id +'.js';
},
buildHistoryLink: function(gist, file) {
var url = baseUrl + gist.history.owner.login + '/' + gist.history.id + '/' + gist.history.history[0].version;
if (file) {
url +='/#file-' + githubFileNameFilter(file.filename);
}
return url;
},
buildDownloadLink: function(gist) {
return baseUrl + gist.owner.login + '/' + gist.id + '/download';
}
};
return service;
});
}); |
Handle enter key on tenant switch. | (function ($) {
var _accountService = abp.services.app.account;
var _$form = $('form[name=TenantChangeForm]');
function switchToSelectedTenant () {
var tenancyName = _$form.find('input[name=TenancyName]').val();
if (!tenancyName) {
abp.multiTenancy.setTenantIdCookie(null);
location.reload();
return;
}
_accountService.isTenantAvailable({
tenancyName: tenancyName
}).done(function (result) {
switch (result.state) {
case 1: //Available
abp.multiTenancy.setTenantIdCookie(result.tenantId);
//_modalManager.close();
location.reload();
return;
case 2: //InActive
abp.message.warn(abp.utils.formatString(abp.localization
.localize("TenantIsNotActive", "AbpProjectName"),
this.tenancyName));
break;
case 3: //NotFound
abp.message.warn(abp.utils.formatString(abp.localization
.localize("ThereIsNoTenantDefinedWithName{0}", "AbpProjectName"),
this.tenancyName));
break;
}
});
}
//Handle save button click
_$form.closest('div.modal-content').find(".save-button").click(function(e) {
e.preventDefault();
switchToSelectedTenant();
});
//Handle enter key
_$form.find('input').on('keypress', function (e) {
if (e.which === 13) {
e.preventDefault();
switchToSelectedTenant();
}
});
})(jQuery); | (function ($) {
var _accountService = abp.services.app.account;
var _$form = $('form[name=TenantChangeForm]');
_$form.closest('div.modal-content').find(".save-button").click(function (e) {
e.preventDefault();
var tenancyName = _$form.find('input[name=TenancyName]').val();
if (!tenancyName) {
abp.multiTenancy.setTenantIdCookie(null);
location.reload();
return;
}
_accountService.isTenantAvailable({
tenancyName: tenancyName
}).done(function (result) {
switch (result.state) {
case 1: //Available
abp.multiTenancy.setTenantIdCookie(result.tenantId);
//_modalManager.close();
location.reload();
return;
case 2: //InActive
abp.message.warn(abp.utils.formatString(abp.localization
.localize("TenantIsNotActive", "AbpProjectName"),
this.tenancyName));
break;
case 3: //NotFound
abp.message.warn(abp.utils.formatString(abp.localization
.localize("ThereIsNoTenantDefinedWithName{0}", "AbpProjectName"),
this.tenancyName));
break;
}
});
});
})(jQuery); |
Make return character an attribute | import time
from netmiko.base_connection import BaseConnection
class NetscalerSSH(BaseConnection):
""" Netscaler SSH class. """
def session_preparation(self):
"""Prepare the session after the connection has been established."""
# 0 will defer to the global delay factor
delay_factor = self.select_delay_factor(delay_factor=0)
self._test_channel_read()
self.set_base_prompt()
cmd = "{}set cli mode -page OFF{}".format(self.RETURN, self.RETURN)
self.disable_paging(command=cmd)
time.sleep(1 * delay_factor)
self.set_base_prompt()
time.sleep(.3 * delay_factor)
self.clear_buffer()
def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):
"""Nothing to exit"""
return super(NetscalerSSH, self).send_config_set(config_commands=config_commands,
exit_config_mode=False, **kwargs)
def strip_prompt(self, a_string):
""" Strip 'Done' from command output """
output = super(NetscalerSSH, self).strip_prompt(a_string)
lines = output.split(self.RESPONSE_RETURN)
if "Done" in lines[-1]:
return 'self.RESPONSE_RETURN'.join(lines[:-1])
else:
return output
| import time
from netmiko.base_connection import BaseConnection
class NetscalerSSH(BaseConnection):
""" Netscaler SSH class. """
def session_preparation(self):
"""Prepare the session after the connection has been established."""
# 0 will defer to the global delay factor
delay_factor = self.select_delay_factor(delay_factor=0)
self._test_channel_read()
self.set_base_prompt()
self.disable_paging(command="\nset cli mode -page OFF\n")
time.sleep(1 * delay_factor)
self.set_base_prompt()
time.sleep(.3 * self.global_delay_factor)
self.clear_buffer()
def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):
""" Nothing to exit"""
return super(NetscalerSSH, self).send_config_set(config_commands=config_commands,
exit_config_mode=False, **kwargs)
def strip_prompt(self, a_string):
""" Strip 'Done' from command output """
output = super(NetscalerSSH, self).strip_prompt(a_string)
lines = output.split('\n')
if "Done" in lines[-1]:
return '\n'.join(lines[:-1])
else:
return output
|
Mark class abstract as it contains abstract methods | <?php
use Symfony\Component\HttpKernel\Kernel;
use Doctrine\Common\Annotations\AnnotationRegistry;
abstract class Kwf_SymfonyKernel extends Kernel
{
public function __construct()
{
if (Kwf_Exception::isDebug()) {
$environment = 'dev';
$debug = true;
//Debug::enable();
} else {
$environment = 'prod';
$debug = false;
}
parent::__construct($environment, $debug);
AnnotationRegistry::registerLoader(array('Kwf_Loader', 'loadClass'));
}
public function locateResource($name, $dir = null, $first = true)
{
if (substr($name, 0, 4) == '@Kwc') {
if (!$first) throw new \Kwf_Exception_NotYetImplemented();
$componentClass = substr($name, 4, strpos($name, '/')-4);
$name = substr($name, strpos($name, '/')+1);
$paths = \Kwc_Abstract::getSetting($componentClass, 'parentFilePaths');
foreach ($paths as $path=>$cls) {
if (file_exists($path.'/'.$name)) {
return $path.'/'.$name;
}
}
throw new \Kwf_Exception();
} else {
return parent::locateResource($name, $dir, $first);
}
}
}
| <?php
use Symfony\Component\HttpKernel\Kernel;
use Doctrine\Common\Annotations\AnnotationRegistry;
class Kwf_SymfonyKernel extends Kernel
{
public function __construct()
{
if (Kwf_Exception::isDebug()) {
$environment = 'dev';
$debug = true;
//Debug::enable();
} else {
$environment = 'prod';
$debug = false;
}
parent::__construct($environment, $debug);
AnnotationRegistry::registerLoader(array('Kwf_Loader', 'loadClass'));
}
public function locateResource($name, $dir = null, $first = true)
{
if (substr($name, 0, 4) == '@Kwc') {
if (!$first) throw new \Kwf_Exception_NotYetImplemented();
$componentClass = substr($name, 4, strpos($name, '/')-4);
$name = substr($name, strpos($name, '/')+1);
$paths = \Kwc_Abstract::getSetting($componentClass, 'parentFilePaths');
foreach ($paths as $path=>$cls) {
if (file_exists($path.'/'.$name)) {
return $path.'/'.$name;
}
}
throw new \Kwf_Exception();
} else {
return parent::locateResource($name, $dir, $first);
}
}
}
|
Fix OpenFlow packets getting stuffed with \0 bytes. | package eu.netide.lib.netip;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Class representing a message of type OPENFLOW.
* Note that this only serves as a convenience class - if the MessageType is manipulated, the class will not recognize that.
*/
public class OpenFlowMessage extends Message {
private OFMessage ofMessage;
/**
* Instantiates a new Open flow message.
*/
public OpenFlowMessage() {
super(new MessageHeader(), new byte[0]);
header.setMessageType(MessageType.OPENFLOW);
}
/**
* Gets of message.
*
* @return the of message
*/
public OFMessage getOfMessage() {
return ofMessage;
}
/**
* Sets of message.
*
* @param ofMessage the of message
*/
public void setOfMessage(OFMessage ofMessage) {
this.ofMessage = ofMessage;
}
@Override
public byte[] getPayload() {
ChannelBuffer dcb = ChannelBuffers.dynamicBuffer();
ofMessage.writeTo(dcb);
this.payload = new byte[dcb.readableBytes()];
dcb.readBytes(this.payload, 0, this.payload.length);
return this.payload;
}
@Override
public String toString() {
return "OpenFlowMessage [Header=" + header.toString() + ",Type=" + ofMessage.getType().toString() + ",OFMessage=" + ofMessage.toString() + "]";
}
}
| package eu.netide.lib.netip;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Class representing a message of type OPENFLOW.
* Note that this only serves as a convenience class - if the MessageType is manipulated, the class will not recognize that.
*/
public class OpenFlowMessage extends Message {
private OFMessage ofMessage;
/**
* Instantiates a new Open flow message.
*/
public OpenFlowMessage() {
super(new MessageHeader(), new byte[0]);
header.setMessageType(MessageType.OPENFLOW);
}
/**
* Gets of message.
*
* @return the of message
*/
public OFMessage getOfMessage() {
return ofMessage;
}
/**
* Sets of message.
*
* @param ofMessage the of message
*/
public void setOfMessage(OFMessage ofMessage) {
this.ofMessage = ofMessage;
}
@Override
public byte[] getPayload() {
ChannelBuffer dcb = ChannelBuffers.dynamicBuffer();
ofMessage.writeTo(dcb);
this.payload = dcb.array();
return this.payload;
}
@Override
public String toString() {
return "OpenFlowMessage [Header=" + header.toString() + ",Type=" + ofMessage.getType().toString() + ",OFMessage=" + ofMessage.toString() + "]";
}
}
|
Change ncmbClassName,apiPath to class constants. | <?php
namespace Ncmb;
/**
* Role - Representation of an access Role.
*/
class Role extends Object
{
const NCMB_CLASS_NAME = 'role';
const API_PATH = 'roles';
/**
* Create a Role object with a given name and ACL.
*
* @param string $name
* @param \Ncmb\Acl|null $acl
*
* @return \Ncmb\Role
*/
public static function createRole($name, $acl = null)
{
$role = new self(self::NCMB_CLASS_NAME);
$role->setName($name);
if ($acl) {
$role->setAcl($acl);
}
return $role;
}
/**
* Get path string
* @return string path string
*/
public function getApiPath()
{
return self::API_PATH;
}
/**
* Returns the role name.
*
* @return string
*/
public function getName()
{
return $this->get('roleName');
}
/**
* Sets the role name.
*
* @param string $name The role name
* @throws \Ncmb\Exception
*/
public function setName($name)
{
if ($this->getObjectId()) {
throw new Exception(
"A role's name can only be set before it has been saved.");
}
if (!is_string($name)) {
throw new Exception("A role's name must be a string.");
}
return $this->set('roleName', $name);
}
}
| <?php
namespace Ncmb;
/**
* Role - Representation of an access Role.
*/
class Role extends Object
{
public static $ncmbClassName = 'role';
public static $apiPath = 'roles';
/**
* Create a Role object with a given name and ACL.
*
* @param string $name
* @param \Ncmb\Acl|null $acl
*
* @return \Ncmb\Role
*/
public static function createRole($name, $acl = null)
{
$role = new self(self::$ncmbClassName);
$role->setName($name);
if ($acl) {
$role->setAcl($acl);
}
return $role;
}
/**
* Get path string
* @return string path string
*/
public function getApiPath()
{
return self::$apiPath;
}
/**
* Returns the role name.
*
* @return string
*/
public function getName()
{
return $this->get('roleName');
}
/**
* Sets the role name.
*
* @param string $name The role name
* @throws \Ncmb\Exception
*/
public function setName($name)
{
if ($this->getObjectId()) {
throw new Exception(
"A role's name can only be set before it has been saved.");
}
if (!is_string($name)) {
throw new Exception("A role's name must be a string.");
}
return $this->set('roleName', $name);
}
}
|
Throw exception if the config.path is not valid | <?php
/*
* This file is part of the Cilex framework.
*
* (c) Mike van Riel <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cilex\Provider;
use Cilex\Application;
use Cilex\ServiceProviderInterface;
use Symfony\Component\Yaml;
class ConfigServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['config'] = $app->share(function () use ($app) {
if (!file_exists($app['config.path'])) {
throw new \InvalidArgumentException(
$app['config.path'] . ' is not a valid path to the '
.'configuration'
);
}
$fullpath = explode('.', $app['config.path']);
switch (strtolower(end($fullpath))) {
case 'yml':
$parser = new Yaml\Parser();
$result = new \ArrayObject(
$parser->parse($app['config.path'])
);
break;
case 'xml':
$result = simplexml_load_file($app['config.path']);
break;
default:
throw new \InvalidArgumentException(
'Unable to load configuration; the provided file '
.'extension was not recognized. Only yml or xml allowed'
);
}
return $result;
});
}
} | <?php
/*
* This file is part of the Cilex framework.
*
* (c) Mike van Riel <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cilex\Provider;
use Cilex\Application;
use Cilex\ServiceProviderInterface;
use Symfony\Component\Yaml;
class ConfigServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['config'] = $app->share(function () use ($app) {
$fullpath = explode('.', $app['config.path']);
switch (strtolower(end($fullpath))) {
case 'yml':
$parser = new Yaml\Parser();
$result = new \ArrayObject(
$parser->parse($app['config.path'])
);
break;
case 'xml':
$result = simplexml_load_file($app['config.path']);
break;
default:
throw new \InvalidArgumentException(
'Unable to load configuration; the provided file '
.'extension was not recognized. Only yml or xml allowed'
);
}
return $result;
});
}
} |
Fix shadow for wide screens. | from asciimatics.renderers import FigletText, Fire
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.effects import Print
from asciimatics.exceptions import ResizeScreenError
from pyfiglet import Figlet
import sys
def demo(screen):
scenes = []
text = Figlet(font="banner", width=200).renderText("ASCIIMATICS")
width = max([len(x) for x in text.split("\n")])
effects = [
Print(screen,
Fire(screen.height, 80, text, 100),
0,
speed=1,
transparent=False),
Print(screen,
FigletText("ASCIIMATICS", "banner"),
screen.height - 9, x=(screen.width - width) // 2 + 1,
colour=Screen.COLOUR_BLACK,
speed=1),
Print(screen,
FigletText("ASCIIMATICS", "banner"),
screen.height - 9,
colour=Screen.COLOUR_WHITE,
speed=1),
]
scenes.append(Scene(effects, 600))
screen.play(scenes, stop_on_resize=True)
if __name__ == "__main__":
while True:
try:
Screen.wrapper(demo)
sys.exit(0)
except ResizeScreenError:
pass
| from asciimatics.renderers import FigletText, Fire
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.effects import Print
from asciimatics.exceptions import ResizeScreenError
from pyfiglet import Figlet
import sys
def demo(screen):
scenes = []
effects = [
Print(screen,
Fire(screen.height, 80,
Figlet(font="banner", width=200).renderText("ASCIIMATICS"),
100),
0,
speed=1,
transparent=False),
Print(screen,
FigletText("ASCIIMATICS", "banner"),
screen.height - 9, x=3,
colour=Screen.COLOUR_BLACK,
speed=1),
Print(screen,
FigletText("ASCIIMATICS", "banner"),
screen.height - 9,
colour=Screen.COLOUR_WHITE,
speed=1),
]
scenes.append(Scene(effects, 600))
screen.play(scenes, stop_on_resize=True)
if __name__ == "__main__":
while True:
try:
Screen.wrapper(demo)
sys.exit(0)
except ResizeScreenError:
pass
|
Move main code to function because of pylint warning 'Invalid constant name' | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import grp
import pwd
import inspect
import argparse
def list_all_users_in_group(groupname):
"""Get list of all users of group.
Get sorted list of all users of group GROUP,
including users with main group GROUP.
Origin in https://github.com/vazhnov/list_all_users_in_group
"""
try:
group = grp.getgrnam(groupname)
# On error "KeyError: 'getgrnam(): name not found: GROUP'"
except KeyError:
return None
group_all_users_set = set(group.gr_mem)
for user in pwd.getpwall():
if user.pw_gid == group.gr_gid:
group_all_users_set.add(user.pw_name)
return sorted(group_all_users_set)
def main():
parser = argparse.ArgumentParser(description=inspect.getdoc(list_all_users_in_group),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-d', '--delimiter', default='\n', help='Use DELIMITER instead of newline for users delimiter')
parser.add_argument('groupname', help='Group name')
args = parser.parse_args()
result = list_all_users_in_group(args.groupname)
if result:
print (args.delimiter.join(result))
if __name__ == "__main__":
main()
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import grp
import pwd
import inspect
import argparse
def list_all_users_in_group(groupname):
"""Get list of all users of group.
Get sorted list of all users of group GROUP,
including users with main group GROUP.
Origin in https://github.com/vazhnov/list_all_users_in_group
"""
try:
group = grp.getgrnam(groupname)
# On error "KeyError: 'getgrnam(): name not found: GROUP'"
except KeyError:
return None
group_all_users_set = set(group.gr_mem)
for user in pwd.getpwall():
if user.pw_gid == group.gr_gid:
group_all_users_set.add(user.pw_name)
return sorted(group_all_users_set)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=inspect.getdoc(list_all_users_in_group),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-d', '--delimiter', default='\n', help='Use DELIMITER instead of newline for users delimiter')
parser.add_argument('groupname', help='Group name')
args = parser.parse_args()
result = list_all_users_in_group(args.groupname)
if result:
print (args.delimiter.join(result))
|
Make Grunt copy bullet.js into example js libs dir | module.exports = function (grunt) {
'use strict';
var jsSrcFile = 'src/bullet.js';
var jsDistDir = 'dist/';
var jsExampleLibsDir = 'example/js/libs/';
var testDir = 'test/spec/';
grunt.initConfig({
watch : {
js: {
files: [
jsSrcFile,
testDir + '**/*.js'
],
tasks: ['dist']
}
},
simplemocha : {
options: {
timeout: 3000,
ignoreLeaks: false,
},
testAll : {
src: testDir + '**/*.js'
}
},
uglify : {
options : {
compress : {
drop_console: true
},
mangle : true,
sourceMap : false,
preserveComments : false,
report : 'gzip' // TODO : does this report option still work?
},
dist : {
src : jsSrcFile,
dest : jsDistDir + 'bullet.min.js'
}
},
copy : {
dist : {
src : jsSrcFile,
dest : jsDistDir + 'bullet.js'
},
example : {
src : jsSrcFile,
dest : jsExampleLibsDir + 'bullet.js'
}
}
});
require('load-grunt-tasks')(grunt, {pattern: ['grunt-*']});
grunt.registerTask('default', ['simplemocha', 'uglify', 'copy', 'watch']);
grunt.registerTask('dist', ['simplemocha', 'uglify', 'copy']);
grunt.registerTask('test', ['simplemocha']);
}; | module.exports = function (grunt) {
'use strict';
var jsSrcFile = 'src/bullet.js';
var jsDistDir = 'dist/';
var testDir = 'test/spec/';
grunt.initConfig({
watch : {
js: {
files: [
jsSrcFile,
testDir + '**/*.js'
],
tasks: ['dist']
}
},
simplemocha : {
options: {
timeout: 3000,
ignoreLeaks: false,
},
testAll : {
src: testDir + '**/*.js'
}
},
uglify : {
options : {
compress : {
drop_console: true
},
mangle : true,
sourceMap : false,
preserveComments : false,
report : 'gzip' // TODO : does this report option still work?
},
dist : {
src : jsSrcFile,
dest : jsDistDir + 'bullet.min.js'
}
},
copy : {
dist : {
src : jsSrcFile,
dest : jsDistDir + 'bullet.js'
}
}
});
require('load-grunt-tasks')(grunt, {pattern: ['grunt-*']});
grunt.registerTask('default', ['simplemocha', 'uglify', 'copy', 'watch']);
grunt.registerTask('dist', ['simplemocha', 'uglify', 'copy']);
grunt.registerTask('test', ['simplemocha']);
}; |
Increase timeout for slow test | from doajtest.helpers import DoajTestCase
from portality.core import app
from portality.tasks import sitemap
from portality.background import BackgroundApi
import time
from portality.store import StoreFactory
class TestSitemap(DoajTestCase):
store_impl = None
@classmethod
def setUpClass(cls) -> None:
super(TestSitemap, cls).setUpClass()
cls.store_impl = app.config["STORE_IMPL"]
app.config["STORE_IMPL"] = "portality.store.StoreLocal"
@classmethod
def tearDownClass(cls) -> None:
super(TestSitemap, cls).tearDownClass()
app.config["STORE_IMPL"] = cls.store_impl
def setUp(self):
super(TestSitemap, self).setUp()
self.container_id = app.config.get("STORE_CACHE_CONTAINER")
self.mainStore = StoreFactory.get("cache")
def tearDown(self):
super(TestSitemap, self).tearDown()
self.mainStore.delete_container(self.container_id)
def test_01_sitemap(self):
user = app.config.get("SYSTEM_USERNAME")
job = sitemap.SitemapBackgroundTask.prepare(user)
task = sitemap.SitemapBackgroundTask(job)
BackgroundApi.execute(task)
time.sleep(2)
assert len(self.mainStore.list(self.container_id)) == 1
| from doajtest.helpers import DoajTestCase
from portality.core import app
from portality.tasks import sitemap
from portality.background import BackgroundApi
import os, shutil, time
from portality.lib import paths
from portality.store import StoreFactory
class TestSitemap(DoajTestCase):
store_impl = None
@classmethod
def setUpClass(cls) -> None:
super(TestSitemap, cls).setUpClass()
cls.store_impl = app.config["STORE_IMPL"]
app.config["STORE_IMPL"] = "portality.store.StoreLocal"
@classmethod
def tearDownClass(cls) -> None:
super(TestSitemap, cls).tearDownClass()
app.config["STORE_IMPL"] = cls.store_impl
def setUp(self):
super(TestSitemap, self).setUp()
self.container_id = app.config.get("STORE_CACHE_CONTAINER")
self.mainStore = StoreFactory.get("cache")
def tearDown(self):
super(TestSitemap, self).tearDown()
self.mainStore.delete_container(self.container_id)
def test_01_sitemap(self):
user = app.config.get("SYSTEM_USERNAME")
job = sitemap.SitemapBackgroundTask.prepare(user)
task = sitemap.SitemapBackgroundTask(job)
BackgroundApi.execute(task)
time.sleep(1.5)
assert len(self.mainStore.list(self.container_id)) == 1 |
Add Options class
Add field filters lists
Start proper model field introspection |
from django.db.models.fields import NOT_PROVIDED
from django.utils.six import with_metaclass
from . import filters
from .fields import Field
from .views import DataView
# Map of ModelField name -> list of filters
FIELD_FILTERS = {
'DateField': [filters.DateFilter],
'TimeField': [filters.TimeFilter],
'DateTimeField': [filters.DateTimeFilter],
}
class Options(object):
def __init__(self, meta):
self.model = getattr(meta, 'model', None)
self.fields = getattr(meta, 'fields', [])
self.exclude = getattr(meta, 'exclude', [])
self.required = getattr(meta, 'required', {})
class MetaView(type):
def __new__(mcs, name, bases, attrs):
meta = Options(attrs.get('Meta', None))
if meta.model is None:
if name != 'ModelDataView':
raise ValueError('model not defined on class Meta')
else:
# XXX Does the top base have all fields?
for model_field in meta.model._meta.fields:
if model_field.name in attrs:
continue
if model_field.name in meta.exclude:
continue
if meta.fields != '__all__' and model_field.name not in meta.fields:
continue
# XXX Magic for field types
kwargs = {}
kwargs['default'] = model_field.default
kwargs['required'] = any([
not model_field.blank,
model_field.default is not NOT_PROVIDED,
])
kwargs['filters'] = FIELD_FILTERS.get(model_field.__class__.__name__, [])
attrs[model_field.name] = Field(model_field.name, **kwargs)
attrs['_meta'] = meta
return super(MetaView, mcs).__new__(mcs, name, bases, attrs)
class ModelDataView(with_metaclass(MetaView, DataView)):
pass
|
from .fields import Field
from .views import DataView
from django.utils.six import with_metaclass
class MetaView(type):
def __new__(mcs, name, bases, attrs):
meta = attrs.get('Meta', None)
try:
model = meta.model
except AttributeError:
if name != 'ModelDataView':
raise
else:
include = getattr(meta, 'fields', None)
exclude = getattr(meta, 'exclude', [])
# XXX Does the top base have all fields?
for model_field in model._meta.fields:
if model_field.name in attrs:
continue
if model_field.name in exclude:
continue
if include != '__all__' and model_field.name not in include:
continue
# XXX Magic for field types
attrs[model_field.name] = Field(model_field.name)
attrs['_meta'] = meta
return super(MetaView, mcs).__new__(mcs, name, bases, attrs)
class ModelDataView(with_metaclass(MetaView, DataView)):
pass
|
Reset error message when dialog re-opened. | //
// nav-controller.js
// Contains the controller for the nav-bar.
//
(function () {
'use strict';
angular.module('movieFinder.controllers')
.controller('NavCtrl', function ($scope, $modal, user) {
var _this = this;
var signInModal;
this.error = {
signIn: ''
};
this.showSignInModal = function () {
this.error.signIn = '';
signInModal = $modal({
scope: $scope,
template: 'partials/modals/sign-in.html',
container: 'body'
});
};
this.login = function (username, password) {
user.login(username, password).success(function(){
signInModal.$promise.then(signInModal.hide);
}).error(function(){
_this.error.signIn = 'Some error message';
});
};
this.logout = function() {
user.logout();
};
});
})(); | //
// nav-controller.js
// Contains the controller for the nav-bar.
//
(function () {
'use strict';
angular.module('movieFinder.controllers')
.controller('NavCtrl', function ($scope, $modal, user) {
var _this = this;
var signInModal;
this.error = {
signIn: ''
};
this.showSignInModal = function () {
signInModal = $modal({
scope: $scope,
template: 'partials/modals/sign-in.html',
container: 'body'
});
};
this.login = function (username, password) {
user.login(username, password).success(function(){
signInModal.$promise.then(signInModal.hide);
}).error(function(){
_this.error.signIn = 'Some error message';
});
};
this.logout = function() {
user.logout();
};
});
})(); |
Fix a test class name | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
from __future__ import print_function
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from .common import print_traceback
from .dataset import complex_json
class Test_url_subcommand(object):
@responses.activate
def test_normal(self):
url = "https://example.com/complex_jeson.json"
responses.add(
responses.GET,
url,
body=complex_json,
content_type='text/plain; charset=utf-8',
status=200)
runner = CliRunner()
db_path = "test_complex_json.sqlite"
with runner.isolated_filesystem():
result = runner.invoke(cmd, ["url", url, "-o", db_path])
print_traceback(result)
assert result.exit_code == ExitCode.SUCCESS
con = simplesqlite.SimpleSQLite(db_path, "r")
expected = set([
'ratings', 'screenshots_4', 'screenshots_3', 'screenshots_5', 'screenshots_1',
'screenshots_2', 'tags', 'versions', 'root'])
assert set(con.get_table_name_list()) == expected
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
from __future__ import print_function
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from .common import print_traceback
from .dataset import complex_json
class Test_TableUrlLoader(object):
@responses.activate
def test_normal(self):
url = "https://example.com/complex_jeson.json"
responses.add(
responses.GET,
url,
body=complex_json,
content_type='text/plain; charset=utf-8',
status=200)
runner = CliRunner()
db_path = "test_complex_json.sqlite"
with runner.isolated_filesystem():
result = runner.invoke(cmd, ["url", url, "-o", db_path])
print_traceback(result)
assert result.exit_code == ExitCode.SUCCESS
con = simplesqlite.SimpleSQLite(db_path, "r")
expected = set([
'ratings', 'screenshots_4', 'screenshots_3', 'screenshots_5', 'screenshots_1',
'screenshots_2', 'tags', 'versions', 'root'])
assert set(con.get_table_name_list()) == expected
|
Add removeTestResults to the signout button | import React from "react";
import { Link } from "react-router-dom";
import fetchContainer from "../../containers/fetch-container";
import "./Controls.css";
const handleSignOut = (props) => {
localStorage.removeItem('user');
props.removeTestsFromStore();
props.removeTestResultsFromStore();
props.removeUserFromStore();
}
const Controls = (props) => {
const { user } = props
const userName = user ? `${user.name.toUpperCase()}` : 'user'
return(
<div className='outer-container'>
<div className='controls-container'>
<div className='welcome-container'>
<h2 className='welcome-msg'>Welcome, {userName}!</h2>
<Link className='sign-out-link' to='/'><button className='sign-out-btn' onClick={() => handleSignOut(props)}>
Sign Out
</button>
</Link>
</div>
<div className='controls-links'>
<Link to='/profile'
className='profile-page'>
my profile.
</Link>
<Link to='/personality-types'
className='personality-types-page'>
personalities.
</Link>
<Link to='/assessments'
className='assessments-page'>
assessments.
</Link>
</div>
</div>
</div>
);
};
export default fetchContainer(Controls);
| import React from "react";
import { Link } from "react-router-dom";
import fetchContainer from "../../containers/fetch-container";
import "./Controls.css";
const handleSignOut = (props) => {
localStorage.removeItem('user');
props.removeTestsFromStore();
props.removeUserFromStore();
}
const Controls = (props) => {
const { user } = props
const userName = user ? `${user.name.toUpperCase()}` : 'user'
return(
<div className='outer-container'>
<div className='controls-container'>
<div className='welcome-container'>
<h2 className='welcome-msg'>Welcome, {userName}!</h2>
<Link className='sign-out-link' to='/'><button className='sign-out-btn' onClick={() => handleSignOut(props)}>
Sign Out
</button>
</Link>
</div>
<div className='controls-links'>
<Link to='/profile'
className='profile-page'>
my profile.
</Link>
<Link to='/personality-types'
className='personality-types-page'>
personalities.
</Link>
<Link to='/assessments'
className='assessments-page'>
assessments.
</Link>
</div>
</div>
</div>
);
};
export default fetchContainer(Controls);
|
Fix default of grouping option for AAT | #! /usr/bin/env python
from pbhla.typing.sequences import type_sequences
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
add = parser.add_argument
add('amplicon_analysis', metavar='INPUT',
help="Fasta/Fastq/Folder of Amplicon Analysis output")
add('-g', '--grouping', metavar='METHOD', default='both',
help="Method of selecting output sequences {locus, barcode, both, all} default=both")
add('-e', '--exon_reference', metavar='REFERENCE', default=None,
help='Dictionary file of Locus-specific exon references')
add('-n', '--nucleotide_reference', metavar='FASTA', default=None,
help='File of FASTA sequences from nucleotide references')
add('-c', '--cDNA_reference', metavar='FASTA', default=None,
help='File of FASTA sequences from cDNA references')
add('--debug', action='store_true',
help="Flag to enable Debug mode")
args = parser.parse_args()
type_sequences( args.amplicon_analysis, args.grouping,
args.exon_reference,
args.nucleotide_reference,
args.cDNA_reference ) | #! /usr/bin/env python
from pbhla.typing.sequences import type_sequences
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
add = parser.add_argument
add('amplicon_analysis', metavar='INPUT',
help="Fasta/Fastq/Folder of Amplicon Analysis output")
add('-g', '--grouping', metavar='METHOD', default='all',
help="BasH5 or FOFN of sequence data")
add('-e', '--exon_reference', metavar='REFERENCE', default=None,
help='Dictionary file of Locus-specific exon references')
add('-n', '--nucleotide_reference', metavar='FASTA', default=None,
help='File of FASTA sequences from nucleotide references')
add('-c', '--cDNA_reference', metavar='FASTA', default=None,
help='File of FASTA sequences from cDNA references')
add('--debug', action='store_true',
help="Flag to enable Debug mode")
args = parser.parse_args()
type_sequences( args.amplicon_analysis, args.grouping,
args.exon_reference,
args.nucleotide_reference,
args.cDNA_reference )
|
Include the status code in the string, and nicer messages | package org.intermine.webservice.server;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.intermine.webservice.server.output.Output;
/**
* HTTP status code dictionary.
* @author Jakub Kulaviak
**/
public class StatusDictionary
{
/**
* @param statusCode status code
* @return short description of specified status code
*/
public static String getDescription(int statusCode) {
String ret;
switch (statusCode) {
case Output.SC_BAD_REQUEST:
ret = "Bad request. There was a problem with your request parameters:"; break;
case Output.SC_FORBIDDEN:
ret = "Forbidden. You do not have access to some part of this query - please log in."; break;
case Output.SC_INTERNAL_SERVER_ERROR:
ret = "Internal server error."; break;
case Output.SC_NO_CONTENT:
ret = "Resource representation is empty."; break;
case Output.SC_NOT_FOUND:
ret = "Resource not found."; break;
case Output.SC_OK:
ret = "OK"; break;
default:
ret = "Unknown Status";
}
return statusCode + " " + ret;
}
}
| package org.intermine.webservice.server;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.intermine.webservice.server.output.Output;
/**
* Http status code dictionary.
* @author Jakub Kulaviak
**/
public class StatusDictionary
{
/**
* @param statusCode status code
* @return short description of specified status code
*/
public static String getDescription(int statusCode) {
switch (statusCode) {
case Output.SC_BAD_REQUEST:
return "There is a problem on the client side (in the browser). Bad request. ";
case Output.SC_FORBIDDEN:
return "Forbidden. ";
case Output.SC_INTERNAL_SERVER_ERROR:
return "Internal server error. ";
case Output.SC_NO_CONTENT:
return "Resource representation is empty. ";
case Output.SC_NOT_FOUND:
return "Resource not found. ";
case Output.SC_OK:
return "OK";
default:
return "";
}
}
}
|
Update workshops as well as talks | from django.core.management.base import BaseCommand, CommandError
from events.models import Event
class Command(BaseCommand):
help = "Copies talk title and descriptions from the application."
def add_arguments(self, parser):
parser.add_argument('event_id', type=int)
def handle(self, *args, **options):
event_id = options["event_id"]
event = Event.objects.filter(pk=event_id).first()
if not event:
raise CommandError("Event id={} does not exist.".format(event_id))
talks = event.talks.all().order_by("title")
talk_count = talks.count()
workshops = event.workshops.all().order_by("title")
workshop_count = workshops.count()
if not talk_count and not workshops:
raise CommandError("No talks or workshops matched.")
print(f"Matched {talk_count} talks:")
for talk in talks:
print("> ", talk)
print(f"\nMatched {workshop_count} workshops:")
for workshop in workshops:
print("> ", workshop)
print("\nUpdate talk descriptions from talks?")
input("Press any key to continue or Ctrl+C to abort")
for talk in talks:
talk.update_from_application()
talk.save()
for workshop in workshops:
workshop.update_from_application()
workshop.save()
print("Done.")
| from django.core.management.base import BaseCommand, CommandError
from events.models import Event
class Command(BaseCommand):
help = "Copies talk title and descriptions from the application."
def add_arguments(self, parser):
parser.add_argument('event_id', type=int)
def handle(self, *args, **options):
event_id = options["event_id"]
event = Event.objects.filter(pk=event_id).first()
if not event:
raise CommandError("Event id={} does not exist.".format(event_id))
talks = event.talks.all().order_by("title")
talk_count = talks.count()
workshops = event.workshops.all().order_by("title")
workshop_count = workshops.count()
if not talk_count and not workshops:
raise CommandError("No talks or workshops matched.")
print(f"Matched {talk_count} talks:")
for talk in talks:
print("> ", talk)
print(f"\nMatched {workshop_count} workshops:")
for workshop in workshops:
print("> ", workshop)
print("\nUpdate talk descriptions from talks?")
input("Press any key to continue or Ctrl+C to abort")
for talk in talks:
talk.update_from_application()
talk.save()
print("Done.")
|
tests: Update run_test.py to fix coverage | #!/usr/bin/env python3
import os
import tempfile
from distutils.sysconfig import get_python_lib
from coalib.tests.TestHelper import TestHelper
if __name__ == '__main__':
parser = TestHelper.create_argparser(description="Runs coalas tests.")
parser.add_argument("-b",
"--ignore-bear-tests",
help="ignore bear tests",
action="store_true")
parser.add_argument("-m",
"--ignore-main-tests",
help="ignore main program tests",
action="store_true")
testhelper = TestHelper(parser)
if not testhelper.args.ignore_main_tests:
testhelper.add_test_files(os.path.abspath(os.path.join("coalib",
"tests")))
if not testhelper.args.ignore_bear_tests:
testhelper.add_test_files(os.path.abspath(os.path.join("bears",
"tests")))
ignore_list = [
os.path.join(tempfile.gettempdir(), "**"),
os.path.join(os.path.dirname(get_python_lib()), "**"),
os.path.join("coalib", "tests", "**"),
os.path.join("bears", "tests", "**")
]
exit(testhelper.execute_python3_files(ignore_list))
| #!/usr/bin/env python3
import os
import tempfile
from distutils.sysconfig import get_python_lib
from coalib.tests.TestHelper import TestHelper
if __name__ == '__main__':
parser = TestHelper.create_argparser(description="Runs coalas tests.")
parser.add_argument("-b",
"--ignore-bear-tests",
help="ignore bear tests",
action="store_true")
parser.add_argument("-m",
"--ignore-main-tests",
help="ignore main program tests",
action="store_true")
testhelper = TestHelper(parser)
if not testhelper.args.ignore_main_tests:
testhelper.add_test_files(os.path.abspath(os.path.join("coalib",
"tests")))
if not testhelper.args.ignore_bear_tests:
testhelper.add_test_files(os.path.abspath(os.path.join("bears",
"tests")))
ignore_list = [
os.path.join(tempfile.gettempdir(), "**"),
os.path.join(get_python_lib(), "**"),
os.path.join("coalib", "tests", "**"),
os.path.join("bears", "tests", "**")
]
exit(testhelper.execute_python3_files(ignore_list))
|
Add logging message when plugin fails to render custom panels | import logging
import sys
import traceback
from django.conf import settings
from django.views.debug import ExceptionReporter
from error_report.models import Error
from plugin.registry import registry
logger = logging.getLogger('inventree')
class InvenTreePluginViewMixin:
"""
Custom view mixin which adds context data to the view,
based on loaded plugins.
This allows rendered pages to be augmented by loaded plugins.
"""
def get_plugin_panels(self, ctx):
"""
Return a list of extra 'plugin panels' associated with this view
"""
panels = []
for plug in registry.with_mixin('panel'):
try:
panels += plug.render_panels(self, self.request, ctx)
except Exception:
# Prevent any plugin error from crashing the page render
kind, info, data = sys.exc_info()
# Log the error to the database
Error.objects.create(
kind=kind.__name__,
info=info,
data='\n'.join(traceback.format_exception(kind, info, data)),
path=self.request.path,
html=ExceptionReporter(self.request, kind, info, data).get_traceback_html(),
)
logger.error(f"Plugin '{plug.slug}' could not render custom panels at '{self.request.path}'")
return panels
def get_context_data(self, **kwargs):
"""
Add plugin context data to the view
"""
ctx = super().get_context_data(**kwargs)
if settings.PLUGINS_ENABLED:
ctx['plugin_panels'] = self.get_plugin_panels(ctx)
return ctx
| import sys
import traceback
from django.conf import settings
from django.views.debug import ExceptionReporter
from error_report.models import Error
from plugin.registry import registry
class InvenTreePluginViewMixin:
"""
Custom view mixin which adds context data to the view,
based on loaded plugins.
This allows rendered pages to be augmented by loaded plugins.
"""
def get_plugin_panels(self, ctx):
"""
Return a list of extra 'plugin panels' associated with this view
"""
panels = []
for plug in registry.with_mixin('panel'):
try:
panels += plug.render_panels(self, self.request, ctx)
except Exception:
# Prevent any plugin error from crashing the page render
kind, info, data = sys.exc_info()
# Log the error to the database
Error.objects.create(
kind=kind.__name__,
info=info,
data='\n'.join(traceback.format_exception(kind, info, data)),
path=self.request.path,
html=ExceptionReporter(self.request, kind, info, data).get_traceback_html(),
)
return panels
def get_context_data(self, **kwargs):
"""
Add plugin context data to the view
"""
ctx = super().get_context_data(**kwargs)
if settings.PLUGINS_ENABLED:
ctx['plugin_panels'] = self.get_plugin_panels(ctx)
return ctx
|
Replace keyword delete with doDelete for method name. | define(['jquery', 'backbone', 'tiddlerFormView', 'hbt!Tiddler'],
function ($, Backbone, TiddlerFormView, template) {
return Backbone.View.extend({
events: {
'click .edit-button': 'edit',
'click .delete-button': 'doDelete'
},
render: function () {
$(this.el).html(template(this.model.toJSON()));
return this;
},
edit: function () {
this.newTiddlerForm = new TiddlerFormView({ model: this.model });
$('section').html(this.newTiddlerForm.render().el);
//TODO: this is a bad way to trick Backbone into reloading this view when edit is finished.
document.location.href = '#editTiddler/' + this.model.get('title');
},
doDelete: function () {
this.model.destroy({
success:function () {
document.location.href = '#home';
}
});
return false;
}
});
}); | define(['jquery', 'backbone', 'tiddlerFormView', 'hbt!Tiddler'],
function ($, Backbone, TiddlerFormView, template) {
return Backbone.View.extend({
events: {
'click .edit-button': 'edit',
'click .delete-button': 'delete'
},
render: function () {
$(this.el).html(template(this.model.toJSON()));
return this;
},
edit: function () {
this.newTiddlerForm = new TiddlerFormView({ model: this.model });
$('section').html(this.newTiddlerForm.render().el);
//TODO: this is a bad way to trick Backbone into reloading this view when edit is finished.
document.location.href = '#editTiddler/' + this.model.get('title');
},
delete: function () {
this.model.destroy({
success:function () {
document.location.href = '#home';
}
});
return false;
}
});
}); |
Check for ajax errors before checking if term is created | import $ from 'jquery';
class Taxonomy {
/**
* Initialize Papi taxonomy class.
*/
static init() {
new Taxonomy().binds();
}
/**
* Bind elements with functions.
*/
binds() {
$('#submit').on('click', this.addNewTerm.bind(this));
}
/**
* Redirect if a new term is added and redirect is activated.
*
* @param {object} e
*/
addNewTerm(e) {
e.preventDefault();
const $title = $('#tag-name');
const title = $title.val();
const $pageType = $('[data-papi-page-type-key=true]');
if (!$pageType.data('redirect') && !$pageType.find(':selected').data('redirect')) {
return;
}
if (!title.length) {
return;
}
let interval;
interval = setInterval(() => {
if ($('#ajax-response').children().length) {
clearInterval(interval);
}
const $thelist = $('#the-list');
const $rowTitles = $thelist.find('td.column-name a.row-title');
const $rows = $rowTitles.contents().filter(function () {
return $(this).text().trim() === title.trim();
});
if ($rows.length) {
clearInterval(interval);
window.location = $rows[0].parentElement.href;
}
}, 500);
}
}
export default Taxonomy;
| import $ from 'jquery';
class Taxonomy {
/**
* Initialize Papi taxonomy class.
*/
static init() {
new Taxonomy().binds();
}
/**
* Bind elements with functions.
*/
binds() {
$('#submit').on('click', this.addNewTerm.bind(this));
}
/**
* Redirect if a new term is added and redirect is activated.
*
* @param {object} e
*/
addNewTerm(e) {
e.preventDefault();
const $title = $('#tag-name');
const title = $title.val();
const $pageType = $('[data-papi-page-type-key=true]');
if (!$pageType.data('redirect') && !$pageType.find(':selected').data('redirect')) {
return;
}
if (!title.length) {
return;
}
let interval;
interval = setInterval(() => {
const $thelist = $('#the-list');
const $rowTitles = $thelist.find('td.column-name a.row-title');
const $rows = $rowTitles.contents().filter(function () {
return $(this).text().trim() === title.trim();
});
if ($rows.length) {
clearInterval(interval);
window.location = $rows[0].parentElement.href;
}
if ($('#ajax-response').children().length) {
clearInterval(interval);
}
}, 500);
}
}
export default Taxonomy;
|
Fix link to PDF Confirm Report
Steps to reproduce:
# Open a family in Family View.
# Activate Verify Info button.
# Activate PDF Report button.
What happens: A new tab opens in the browser with a 404 error. The path contains "churchcrmReports/ConfirmReport.php".
What is expected: A PDF file is downloaded. The path is correct. | $(document).ready(function () {
$("#pledge-payment-table").DataTable(window.CRM.plugin.dataTable);
$("#onlineVerify").click(function () {
$.ajax({
type: 'POST',
url: window.CRM.root + '/api/families/' + window.CRM.currentFamily + '/verify'
})
.done(function(data, textStatus, xhr) {
$('#confirm-verify').modal('hide');
if (xhr.status == 200) {
showGlobalMessage(i18next.t("Verification email sent"), "success")
} else {
showGlobalMessage(i18next.t("Failed to send verification email"), "danger")
}
});
});
$("#verifyNow").click(function () {
$.ajax({
type: 'POST',
url: window.CRM.root + '/api/families/verify/' + window.CRM.currentFamily + '/now'
})
.done(function(data, textStatus, xhr) {
$('#confirm-verify').modal('hide');
if (xhr.status == 200) {
location.reload();
} else {
showGlobalMessage(i18next.t("Failed to add verification"), "danger")
}
});
});
$("#verifyDownloadPDF").click(function () {
window.open(window.CRM.root + '/Reports/ConfirmReport.php?familyId=' + window.CRM.currentFamily, '_blank');
$('#confirm-verify').modal('hide');
});
});
| $(document).ready(function () {
$("#pledge-payment-table").DataTable(window.CRM.plugin.dataTable);
$("#onlineVerify").click(function () {
$.ajax({
type: 'POST',
url: window.CRM.root + '/api/families/' + window.CRM.currentFamily + '/verify'
})
.done(function(data, textStatus, xhr) {
$('#confirm-verify').modal('hide');
if (xhr.status == 200) {
showGlobalMessage(i18next.t("Verification email sent"), "success")
} else {
showGlobalMessage(i18next.t("Failed to send verification email"), "danger")
}
});
});
$("#verifyNow").click(function () {
$.ajax({
type: 'POST',
url: window.CRM.root + '/api/families/verify/' + window.CRM.currentFamily + '/now'
})
.done(function(data, textStatus, xhr) {
$('#confirm-verify').modal('hide');
if (xhr.status == 200) {
location.reload();
} else {
showGlobalMessage(i18next.t("Failed to add verification"), "danger")
}
});
});
$("#verifyDownloadPDF").click(function () {
window.open(window.CRM.root + 'Reports/ConfirmReport.php?familyId=' + window.CRM.currentFamily, '_blank');
$('#confirm-verify').modal('hide');
});
});
|
Replace star inport with explicit ones | package com.novoda.downloadmanager;
import android.support.annotation.WorkerThread;
import java.util.List;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETING;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETED;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.PAUSED;
final class DownloadBatchSizeCalculator {
private DownloadBatchSizeCalculator() {
// non instantiable
}
@WorkerThread
static long getTotalSize(List<DownloadFile> downloadFiles, DownloadBatchStatus.Status status, DownloadBatchId downloadBatchId) {
long totalBatchSize = 0;
for (DownloadFile downloadFile : downloadFiles) {
if (status == DELETING || status == DELETED || status == PAUSED) {
Logger.w("abort getTotalSize file " + downloadFile.id().rawId()
+ " from batch " + downloadBatchId.rawId()
+ " with status " + status
+ " returns 0 as totalFileSize");
return 0;
}
long totalFileSize = downloadFile.getTotalSize();
if (totalFileSize == 0) {
Logger.w("file " + downloadFile.id().rawId()
+ " from batch " + downloadBatchId.rawId()
+ " with status " + status
+ " returns 0 as totalFileSize");
return 0;
}
totalBatchSize += totalFileSize;
}
return totalBatchSize;
}
}
| package com.novoda.downloadmanager;
import android.support.annotation.WorkerThread;
import java.util.List;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.*;
final class DownloadBatchSizeCalculator {
private DownloadBatchSizeCalculator() {
// non instantiable
}
@WorkerThread
static long getTotalSize(List<DownloadFile> downloadFiles, DownloadBatchStatus.Status status, DownloadBatchId downloadBatchId) {
long totalBatchSize = 0;
for (DownloadFile downloadFile : downloadFiles) {
if (status == DELETING || status == DELETED || status == PAUSED) {
Logger.w("abort getTotalSize file " + downloadFile.id().rawId()
+ " from batch " + downloadBatchId.rawId()
+ " with status " + status
+ " returns 0 as totalFileSize");
return 0;
}
long totalFileSize = downloadFile.getTotalSize();
if (totalFileSize == 0) {
Logger.w("file " + downloadFile.id().rawId()
+ " from batch " + downloadBatchId.rawId()
+ " with status " + status
+ " returns 0 as totalFileSize");
return 0;
}
totalBatchSize += totalFileSize;
}
return totalBatchSize;
}
}
|
examples: Add name to position-offset shader | FamousFramework.scene('famous-tests:webgl:custom-shader:vertex', {
behaviors: {
'$camera': {
'set-depth': 1000
},
'.sphere': {
'size': [200, 200],
'align': [0.5, 0.5],
'origin': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'base-color': 'whitesmoke',
'geometry': {
'shape': 'GeodesicSphere',
'dynamic': true,
'options': {
'detail': 3
}
},
'position-offset': {
'name': 'sphereVertex',
'glsl': 'vec3(v_normal * 3.0);',
'output': 3
}
},
'.light': {
'size': [200, 200],
'align': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'position-z': 500,
'light': {
'type': 'point',
'color': 'white'
}
},
'.background': {
'size': [undefined, undefined],
'align': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'geometry': {
'shape': 'Plane'
}
}
},
events: {},
states: {},
tree: `
<node class="background"></node>
<node class="sphere"></node>
<node class="light"></node>
`
}); | FamousFramework.scene('famous-tests:webgl:custom-shader:vertex', {
behaviors: {
'$camera': {
'set-depth': 1000
},
'.sphere': {
'size': [200, 200],
'align': [0.5, 0.5],
'origin': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'base-color': 'whitesmoke',
'geometry': {
'shape': 'GeodesicSphere',
'dynamic': true,
'options': {
'detail': 3
}
},
'position-offset': {
'glsl': 'vec3(v_normal * 3.0);',
'output': 3
}
},
'.light': {
'size': [200, 200],
'align': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'position-z': 500,
'light': {
'type': 'point',
'color': 'white'
}
},
'.background': {
'size': [undefined, undefined],
'align': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'geometry': {
'shape': 'Plane'
}
}
},
events: {},
states: {},
tree: `
<node class="background"></node>
<node class="sphere"></node>
<node class="light"></node>
`
}); |
Add explicit reasoning for session sniff
From https://vip.wordpress.com/documentation/code-review-what-we-look-for/#session_start-and-other-session-related-functions, linked in #75 | <?php
/**
* WordPress_Sniffs_VIP_SessionVariableUsageSniff
*
* Discourages the use of the session variable.
* Creating a session writes a file to the server and is unreliable in a multi-server environment.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Shady Sharaf <[email protected]>
* @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75
*/
class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_VARIABLE,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @todo Allow T_CONSTANT_ENCAPSED_STRING?
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ( $tokens[$stackPtr]['content'] == '$_SESSION' ) {
$phpcsFile->addError('Usage of $_SESSION variable is prohibited.', $stackPtr);
}
}//end process()
}//end class
| <?php
/**
* WordPress_Sniffs_VIP_SessionVariableUsageSniff
*
* Discourages the use of the session variable
*
* @category PHP
* @package PHP_CodeSniffer
* @author Shady Sharaf <[email protected]>
* @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75
*/
class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_VARIABLE,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @todo Allow T_CONSTANT_ENCAPSED_STRING?
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ( $tokens[$stackPtr]['content'] == '$_SESSION' ) {
$phpcsFile->addError('Usage of $_SESSION variable is prohibited.', $stackPtr);
}
}//end process()
}//end class
|
Remove hard coded realm and assume any is fine | import urllib2
from urlparse import urljoin
from gocd.api import Pipeline
class Server(object):
def __init__(self, host, user=None, password=None):
self.host = host
self.user = user
self.password = password
if self.user and self.password:
self._add_basic_auth()
def get(self, path):
return urllib2.urlopen(self._request(path))
def pipeline(self, name):
return Pipeline(self, name)
def _add_basic_auth(self):
auth_handler = urllib2.HTTPBasicAuthHandler(
urllib2.HTTPPasswordMgrWithDefaultRealm()
)
auth_handler.add_password(
realm=None,
uri=self.host,
user=self.user,
passwd=self.password,
)
urllib2.install_opener(urllib2.build_opener(auth_handler))
def _request(self, path, data=None, headers=None):
default_headers = {
'User-Agent': 'py-gocd',
}
default_headers.update(headers or {})
return urllib2.Request(
self._url(path),
data=data,
headers=default_headers
)
def _url(self, path):
return urljoin(self.host, path)
| import urllib2
from urlparse import urljoin
from gocd.api import Pipeline
class Server(object):
def __init__(self, host, user=None, password=None):
self.host = host
self.user = user
self.password = password
if self.user and self.password:
self._add_basic_auth()
def get(self, path):
return urllib2.urlopen(self._request(path))
def pipeline(self, name):
return Pipeline(self, name)
def _add_basic_auth(self):
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(
realm='Cruise', # This seems to be hard coded.
uri=self.host,
user=self.user,
passwd=self.password,
)
urllib2.install_opener(urllib2.build_opener(auth_handler))
def _request(self, path, data=None, headers=None):
default_headers = {
'User-Agent': 'py-gocd',
}
default_headers.update(headers or {})
return urllib2.Request(
self._url(path),
data=data,
headers=default_headers
)
def _url(self, path):
return urljoin(self.host, path)
|
Remove unittest and mock for now | from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
| import mock
import unittest
from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
|
Use DOMContendLoaded event instead of load event to verify opening compose window definitely | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function (aGlobal) {
var tbBug766495 = {
init: function() {
window.removeEventListener('DOMContentLoaded', this, false);
window.addEventListener('unload', this, false);
document.documentElement.addEventListener('compose-window-init', this, false);
document.documentElement.addEventListener('compose-window-close', this, false);
},
destroy: function() {
window.removeEventListener('unload', this, false);
document.documentElement.removeEventListener('compose-window-init', this, false);
document.documentElement.removeEventListener('compose-window-close', this, false);
},
activateComposeWindow: function() {
},
deactivateComposeWindow: function() {
},
handleEvent: function(aEvent) {
switch (aEvent.type) {
case 'DOMContentLoaded':
this.init();
return;
case 'unload':
this.destroy();
return;
case 'compose-window-init':
this.activateComposeWindow();
break;
case 'compose-window-close':
this.deactivateComposeWindow();
break;
}
}
};
window.addEventListener('DOMContentLoaded', tbBug766495, false);
aGlobal.tbBug766495 = tbBug766495;
})(this);
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function (aGlobal) {
var tbBug766495 = {
init: function() {
window.removeEventListener('load', this, false);
window.addEventListener('unload', this, false);
document.documentElement.addEventListener('compose-window-init', this, false);
document.documentElement.addEventListener('compose-window-close', this, false);
},
destroy: function() {
window.removeEventListener('unload', this, false);
document.documentElement.removeEventListener('compose-window-init', this, false);
document.documentElement.removeEventListener('compose-window-close', this, false);
},
activateComposeWindow: function() {
},
deactivateComposeWindow: function() {
},
handleEvent: function(aEvent) {
switch (aEvent.type) {
case 'load':
this.init();
return;
case 'unload':
this.destroy();
return;
case 'compose-window-init':
this.activateComposeWindow();
break;
case 'compose-window-close':
this.deactivateComposeWindow();
break;
}
}
};
window.addEventListener('load', tbBug766495, false);
aGlobal.tbBug766495 = tbBug766495;
})(this);
|
Update the home slider, add auto play | var LightSliderHomeInit = function() {
//
// Init
//
this.init();
};
LightSliderHomeInit.prototype.init = function() {
var that = this;
$('[data-slider-home]').lightSlider({
item: 1,
slideMargin: 0,
pager: false,
loop: true,
auto: true,
pauseOnHover: true,
pause: 3000,
onAfterSlide: function(slider) {
var $pages = slider.parents('.slider-home').find('.slider-home__pager li');
$pages.removeClass('active');
$($pages[slider.getCurrentSlideCount()-1]).addClass('active');
},
onSliderLoad: function(slider) {
var $pages = slider.parents('.slider-home').find('.slider-home__pager li');
$pages.each(function(idx) {
var that = $(this);
that.click(function(e) {
e.preventDefault();
$pages.removeClass('active');
that.addClass('active');
slider.goToSlide(idx+1);
return false;
});
});
}
});
};
module.exports = LightSliderHomeInit;
| var LightSliderHomeInit = function() {
//
// Init
//
this.init();
};
LightSliderHomeInit.prototype.init = function() {
var that = this;
$('[data-slider-home]').lightSlider({
item: 1,
slideMargin: 0,
pager: false,
loop: true,
onAfterSlide: function(slider) {
var $pages = slider.parents('.slider-home').find('.slider-home__pager li');
$pages.removeClass('active');
$($pages[slider.getCurrentSlideCount()-1]).addClass('active');
},
onSliderLoad: function(slider) {
var $pages = slider.parents('.slider-home').find('.slider-home__pager li');
$pages.each(function(idx) {
var that = $(this);
that.click(function(e) {
e.preventDefault();
$pages.removeClass('active');
that.addClass('active');
slider.goToSlide(idx+1);
return false;
});
});
}
});
};
module.exports = LightSliderHomeInit;
|
Use server-side collname in event payloads | 'use strict';
const { getReason } = require('../../error');
const { MODEL_TYPES } = require('../../constants');
const { DEFAULT_FORMAT } = require('../../formats');
const { normalizeCompress } = require('../../compress');
// Builds requestinfo from request mInput
const buildRequestinfo = function ({
requestid,
timestamp,
duration,
ip,
protocol,
origin,
path,
method,
status = 'SERVER_ERROR',
queryvars,
headers,
format: { name: format = 'raw' } = DEFAULT_FORMAT,
compressResponse,
compressRequest,
charset,
payload,
rpc,
summary,
topargs: args,
commandpath,
command,
collname: collection,
metadata,
response: {
content: response,
type: responsetype,
} = {},
modelscount,
uniquecount,
error,
}) {
const responsedata = MODEL_TYPES.includes(responsetype)
? response.data
: response;
const errorReason = error && getReason({ error });
const compress = normalizeCompress({ compressResponse, compressRequest });
return {
requestid,
timestamp,
duration,
ip,
protocol,
origin,
path,
method,
status,
queryvars,
headers,
format,
charset,
compress,
payload,
rpc,
summary,
args,
commandpath,
command,
collection,
responsedata,
responsetype,
metadata,
modelscount,
uniquecount,
error: errorReason,
};
};
module.exports = {
buildRequestinfo,
};
| 'use strict';
const { getReason } = require('../../error');
const { MODEL_TYPES } = require('../../constants');
const { DEFAULT_FORMAT } = require('../../formats');
const { normalizeCompress } = require('../../compress');
// Builds requestinfo from request mInput
const buildRequestinfo = function ({
requestid,
timestamp,
duration,
ip,
protocol,
origin,
path,
method,
status = 'SERVER_ERROR',
queryvars,
headers,
format: { name: format = 'raw' } = DEFAULT_FORMAT,
compressResponse,
compressRequest,
charset,
payload,
rpc,
summary,
topargs: args,
commandpath,
command,
clientCollname: collection,
metadata,
response: {
content: response,
type: responsetype,
} = {},
modelscount,
uniquecount,
error,
}) {
const responsedata = MODEL_TYPES.includes(responsetype)
? response.data
: response;
const errorReason = error && getReason({ error });
const compress = normalizeCompress({ compressResponse, compressRequest });
return {
requestid,
timestamp,
duration,
ip,
protocol,
origin,
path,
method,
status,
queryvars,
headers,
format,
charset,
compress,
payload,
rpc,
summary,
args,
commandpath,
command,
collection,
responsedata,
responsetype,
metadata,
modelscount,
uniquecount,
error: errorReason,
};
};
module.exports = {
buildRequestinfo,
};
|
Use local variable for clipboard created by ClipboardJS instead of ref | import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.copyBtnRef = React.createRef();
}
static defaultProps = {
content: '',
};
state = {
tooltipAttrs: {},
};
componentDidMount() {
const clipboard = new ClipboardJS(this.copyBtnRef.current, {
text: () => this.props.content,
});
clipboard.on('success', () => {
const self = this;
this.setState({
tooltipAttrs: {
'data-balloon': '複製成功!',
'data-balloon-visible': '',
'data-balloon-pos': 'up',
},
});
setTimeout(function() {
self.setState({ tooltipAttrs: {} });
}, 1000);
});
}
render() {
const { tooltipAttrs } = this.state;
return (
<button ref={this.copyBtnRef} className="btn-copy" {...tooltipAttrs}>
複製到剪貼簿
<style jsx>{`
.btn-copy {
margin-left: 10px;
}
`}</style>
</button>
);
}
}
| import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.copyBtnRef = React.createRef();
this.clipboardRef = React.createRef();
}
static defaultProps = {
content: '',
};
state = {
tooltipAttrs: {},
};
componentDidMount() {
this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
text: () => this.props.content,
});
this.clipboardRef.current.on('success', () => {
const self = this;
this.setState({
tooltipAttrs: {
'data-balloon': '複製成功!',
'data-balloon-visible': '',
'data-balloon-pos': 'up',
},
});
setTimeout(function() {
self.setState({ tooltipAttrs: {} });
}, 1000);
});
}
render() {
const { tooltipAttrs } = this.state;
return (
<button ref={this.copyBtnRef} className="btn-copy" {...tooltipAttrs}>
複製到剪貼簿
<style jsx>{`
.btn-copy {
margin-left: 10px;
}
`}</style>
</button>
);
}
}
|
Fix double include of jQuery on chart pages | <?php
namespace DrupalReleaseDate\Controllers;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
class Charts
{
public function samples(Application $app, Request $request)
{
return $app['twig']->render(
'charts/samples.twig',
array(
'scripts' => array(
'https://www.google.com/jsapi',
),
)
);
}
public function estimates(Application $app, Request $request)
{
return $app['twig']->render(
'charts/estimates.twig',
array(
'scripts' => array(
'https://www.google.com/jsapi',
),
)
);
}
public function distribution(Application $app, Request $request)
{
return $app['twig']->render(
'charts/distribution.twig',
array(
'scripts' => array(
'https://www.google.com/jsapi',
),
)
);
}
}
| <?php
namespace DrupalReleaseDate\Controllers;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
class Charts
{
public function samples(Application $app, Request $request)
{
return $app['twig']->render(
'charts/samples.twig',
array(
'scripts' => array(
'//code.jquery.com/jquery-2.0.2.min.js',
'https://www.google.com/jsapi',
),
)
);
}
public function estimates(Application $app, Request $request)
{
return $app['twig']->render(
'charts/estimates.twig',
array(
'scripts' => array(
'//code.jquery.com/jquery-2.0.2.min.js',
'https://www.google.com/jsapi',
),
)
);
}
public function distribution(Application $app, Request $request)
{
return $app['twig']->render(
'charts/distribution.twig',
array(
'scripts' => array(
'//code.jquery.com/jquery-2.0.2.min.js',
'https://www.google.com/jsapi',
),
)
);
}
}
|
Add pgp to notification channels | /* @flow */
import engine from '../engine'
import {notifyCtlSetNotificationsRpc} from '../constants/types/flow-types'
type NotificationChannels = {
chat?: true,
favorites?: true,
kbfs?: true,
keyfamily?: true,
paperkeys?: true,
pgp?: true,
service?: true,
session?: true,
tracking?: true,
users?: true,
}
let channelsSet = {}
export default function (channels: NotificationChannels): Promise<void> {
return new Promise((resolve, reject) => {
channelsSet = {...channelsSet, ...channels}
const toSend = {
app: !!channelsSet.app,
chat: !!channelsSet.chat,
favorites: !!channelsSet.favorites,
kbfs: !!channelsSet.kbfs,
keyfamily: !!channelsSet.keyfamily,
paperkeys: !!channelsSet.paperkeys,
pgp: !!channelsSet.pgp,
service: !!channelsSet.service,
session: !!channelsSet.session,
tracking: !!channelsSet.tracking,
users: !!channelsSet.users,
}
engine.listenOnConnect('setNotifications', () => {
notifyCtlSetNotificationsRpc({
param: {channels: toSend},
callback: (error, response) => {
if (error != null) {
console.warn('error in toggling notifications: ', error)
reject(error)
} else {
resolve()
}
},
})
})
})
}
| /* @flow */
import engine from '../engine'
import {notifyCtlSetNotificationsRpc} from '../constants/types/flow-types'
type NotificationChannels = {
session?: true,
users?: true,
kbfs?: true,
tracking?: true,
favorites?: true,
paperkeys?: true,
keyfamily?: true,
service?: true,
chat?: true,
}
let channelsSet = {}
export default function (channels: NotificationChannels): Promise<void> {
return new Promise((resolve, reject) => {
channelsSet = {...channelsSet, ...channels}
const toSend = {
session: !!channelsSet.session,
users: !!channelsSet.users,
kbfs: !!channelsSet.kbfs,
tracking: !!channelsSet.tracking,
favorites: !!channelsSet.favorites,
paperkeys: !!channelsSet.paperkeys,
keyfamily: !!channelsSet.keyfamily,
service: !!channelsSet.service,
app: !!channelsSet.app,
chat: !!channelsSet.chat,
}
engine.listenOnConnect('setNotifications', () => {
notifyCtlSetNotificationsRpc({
param: {channels: toSend},
callback: (error, response) => {
if (error != null) {
console.warn('error in toggling notifications: ', error)
reject(error)
} else {
resolve()
}
},
})
})
})
}
|
Change trove classifier to show project is now stable | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_f:
README = readme_f.read()
with open('tests/requirements.txt') as test_requirements_f:
TEST_REQUIREMENTS = test_requirements_f.readlines()
setup(
name='srt',
version='1.0.0',
description='A tiny library for parsing, modifying, and composing SRT '
'files.',
long_description=README,
author='Chris Down',
author_email='[email protected]',
url='https://github.com/cdown/srt',
py_modules=['srt'],
license='ISC',
zip_safe=False,
keywords='srt',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: Public Domain',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Multimedia :: Video',
'Topic :: Software Development :: Libraries',
'Topic :: Text Processing',
],
test_suite='nose.collector',
tests_require=TEST_REQUIREMENTS
)
| #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_f:
README = readme_f.read()
with open('tests/requirements.txt') as test_requirements_f:
TEST_REQUIREMENTS = test_requirements_f.readlines()
setup(
name='srt',
version='1.0.0',
description='A tiny library for parsing, modifying, and composing SRT '
'files.',
long_description=README,
author='Chris Down',
author_email='[email protected]',
url='https://github.com/cdown/srt',
py_modules=['srt'],
license='ISC',
zip_safe=False,
keywords='srt',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: Public Domain',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Multimedia :: Video',
'Topic :: Software Development :: Libraries',
'Topic :: Text Processing',
],
test_suite='nose.collector',
tests_require=TEST_REQUIREMENTS
)
|
Use padding instead of margin for x-axis.
The overflow: hidden; property on the wrapper isn't taking margin into
account for the x-axis. By using padding instead, the x-axis overflow
is correctly hidden. | import React from 'react'
import PropTypes from 'prop-types'
import Component from 'hyper/component'
import decorate from 'hyper/decorate'
class HyperLine extends Component {
static propTypes() {
return {
plugins: PropTypes.array.isRequired
}
}
styles() {
return {
line: {
display: 'flex',
alignItems: 'center',
position: 'absolute',
overflow: 'hidden',
bottom: '-1px',
width: '100%',
height: '18px',
font: 'bold 10px Monospace',
pointerEvents: 'none',
background: 'rgba(0, 0, 0, 0.08)',
margin: '10px 0',
padding: '0 10px',
},
wrapper: {
display: 'flex',
flexShrink: '0',
alignItems: 'center',
paddingLeft: '10px',
paddingRight: '10px'
}
}
}
template(css) {
const { plugins } = this.props
return (
<div className={css('line')} {...this.props}>
{plugins.map((Component, index) => (
<div key={index} className={css('wrapper')}>
<Component />
</div>
))}
</div>
)
}
}
export default decorate(HyperLine, 'HyperLine')
| import React from 'react'
import PropTypes from 'prop-types'
import Component from 'hyper/component'
import decorate from 'hyper/decorate'
class HyperLine extends Component {
static propTypes() {
return {
plugins: PropTypes.array.isRequired
}
}
styles() {
return {
line: {
display: 'flex',
alignItems: 'center',
position: 'absolute',
overflow: 'hidden',
bottom: '-1px',
width: '100%',
height: '18px',
font: 'bold 10px Monospace',
pointerEvents: 'none',
background: 'rgba(0, 0, 0, 0.08)',
margin: '10px 10px 0 10px'
},
wrapper: {
display: 'flex',
flexShrink: '0',
alignItems: 'center',
paddingLeft: '10px',
paddingRight: '10px'
}
}
}
template(css) {
const { plugins } = this.props
return (
<div className={css('line')} {...this.props}>
{plugins.map((Component, index) => (
<div key={index} className={css('wrapper')}>
<Component />
</div>
))}
</div>
)
}
}
export default decorate(HyperLine, 'HyperLine')
|
Replace upsert=True with conflict='replace' in tests
Review 1804 by @gchpaco
Related to #2733 | # This is a (hopefully temporary) shim that uses the rdb protocol to
# implement part of the memcache API
import contextlib
import rdb_workload_common
@contextlib.contextmanager
def make_memcache_connection(opts):
with rdb_workload_common.make_table_and_connection(opts) as (table, conn):
yield MemcacheRdbShim(table, conn)
class MemcacheRdbShim(object):
def __init__(self, table, conn):
self.table = table
self.conn = conn
def get(self, key):
response = self.table.get(key).run(self.conn)
if response:
return response['val']
def set(self, key, val):
response = self.table.insert({
'id': key,
'val': val
},
conflict='replace'
).run(self.conn)
error = response.get('first_error')
if error:
raise Exception(error)
return response['inserted'] | response['replaced'] | response['unchanged']
def delete(self, key):
response = self.table.get(key).delete().run(self.conn)
error = response.get('first_error')
if error:
raise Exception(error)
return response['deleted']
def option_parser_for_memcache():
return rdb_workload_common.option_parser_for_connect()
| # This is a (hopefully temporary) shim that uses the rdb protocol to
# implement part of the memcache API
import contextlib
import rdb_workload_common
@contextlib.contextmanager
def make_memcache_connection(opts):
with rdb_workload_common.make_table_and_connection(opts) as (table, conn):
yield MemcacheRdbShim(table, conn)
class MemcacheRdbShim(object):
def __init__(self, table, conn):
self.table = table
self.conn = conn
def get(self, key):
response = self.table.get(key).run(self.conn)
if response:
return response['val']
def set(self, key, val):
response = self.table.insert({
'id': key,
'val': val
},
upsert=True
).run(self.conn)
error = response.get('first_error')
if error:
raise Exception(error)
return response['inserted'] | response['replaced'] | response['unchanged']
def delete(self, key):
response = self.table.get(key).delete().run(self.conn)
error = response.get('first_error')
if error:
raise Exception(error)
return response['deleted']
def option_parser_for_memcache():
return rdb_workload_common.option_parser_for_connect()
|
Fix race condition in test
@bug W-3269340@
@rev tbliss@ | ({
setStatus: function(cmp, status) {
cmp.set("v.status", status);
this.log(cmp, "\nStatus update: " + status);
},
log: function(cmp, log) {
var l = cmp.get("v.log");
l += log + "\n";
cmp.set("v.log", l);
},
clearActionAndDefStorage: function(cmp) {
// def store is not created until a dynamic def is received. if it doesn't exist
// in aura storage service then create it, clear it (to clear the underlying persistent
// store), then remove it.
var defs = $A.storageService.getStorage("ComponentDefStorage");
var defsCreated = false;
if (!defs) {
defsCreated = true;
defs = $A.storageService.initStorage({
name: "ComponentDefStorage",
persistent: true,
secure: false,
maxSize: 442368,
expiration: 10886400,
debugLogging: true,
clearOnInit: false
});
}
return Promise.all([$A.storageService.getStorage("actions").clear(), defs.clear()])
.then(
function() {
if (defsCreated) {
return $A.storageService.deleteStorage("ComponentDefStorage");
}
}
)
.then(
function() {
cmp.helper.log(cmp, "Action and def storage cleared");
},
function(e) {
cmp.helper.log(cmp, "Error clearing action and def storage: " + e);
}
);
}
}) | ({
setStatus: function(cmp, status) {
cmp.set("v.status", status);
this.log(cmp, "\nStatus update: " + status);
},
log: function(cmp, log) {
var l = cmp.get("v.log");
l += log + "\n";
cmp.set("v.log", l);
},
clearActionAndDefStorage: function(cmp) {
// def store is not created until a dynamic def is received. if it doesn't exist
// in aura storage service then create it, clear it (to clear the underlying persistent
// store), then remove it.
var defs = $A.storageService.getStorage("ComponentDefStorage");
var defsCreated = false;
if (!defs) {
defsCreated = true;
defs = $A.storageService.initStorage({
name: "ComponentDefStorage",
persistent: true,
secure: false,
maxSize: 442368,
expiration: 10886400,
debugLogging: true,
clearOnInit: false
});
}
return Promise.all([$A.storageService.getStorage("actions").clear(), defs.clear()])
.then(
function() {
if (defsCreated) {
$A.storageService.deleteStorage("ComponentDefStorage");
}
}
)
.then(
function() {
cmp.helper.log(cmp, "Action and def storage cleared");
},
function(e) {
cmp.helper.log(cmp, "Error clearing action and def storage: " + e);
}
);
}
}) |
Fix detect Git-LFS in tests | import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='[email protected]')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open('git-lfs.github.com', 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
| import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='[email protected]')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open('git-lfs.github.com', 'r'):
if 'git-lfs' in line:
raise new Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
|
Add pln to box edit form, make username and password optional. | <?php
namespace LOCKSSOMatic\CrudBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class BoxType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('hostname', 'text', array('attr' => array('class' => 'hostname')))
->add('protocol')
->add('ipAddress', 'text', array(
'required' => false,
'attr' => array(
'class' => 'ipAddress ',
'help' => 'LOCKSSOMatic will look up the IP address if it is blank.',
)
))
->add('port')
->add('pln')
->add('username', 'text', array(
'required' => false,
))
->add('password', 'password', array(
'required' => false,
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'LOCKSSOMatic\CrudBundle\Entity\Box'
));
}
/**
* @return string
*/
public function getName()
{
return 'lockssomatic_crudbundle_box';
}
}
| <?php
namespace LOCKSSOMatic\CrudBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class BoxType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('hostname', 'text', array('attr' => array('class' => 'hostname')))
->add('protocol')
->add('ipAddress', 'text', array(
'required' => false,
'attr' => array(
'class' => 'ipAddress ',
'help' => 'LOCKSSOMatic will look up the IP address if it is blank.',
)
))
->add('port')
->add('username')
->add('password', 'password')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'LOCKSSOMatic\CrudBundle\Entity\Box'
));
}
/**
* @return string
*/
public function getName()
{
return 'lockssomatic_crudbundle_box';
}
}
|
Update target count to consider users who subded to `all` | from django.shortcuts import render, redirect
from django.views.generic import View
from django.core.urlresolvers import reverse
from django.contrib import messages
from .models import Email
from .forms import EmailAdminForm
from nightreads.user_manager.models import Subscription
class SendEmailAdminView(View):
template = 'admin/emails/email/send_email.html'
form_class = EmailAdminForm
def get(self, request, pk):
email_obj = Email.objects.get(pk=pk)
return render(request, self.template, {'email_obj': email_obj})
def post(self, request, pk):
email_type = request.POST.get('type', '').lower()
email_obj = Email.objects.get(pk=pk)
if email_type == 'preview':
# send preview email
m = 'Preview email has been sent!'
else:
# send email
m = 'Email has been sent!'
email_obj.is_sent = True
messages.add_message(request, messages.INFO, m)
return redirect(reverse(
'admin:emails_email_change', args=(email_obj.id,)))
class UpdateTargetCountView(View):
def get(self, request, pk):
email_obj = Email.objects.get(pk=pk)
email_obj.targetted_users = Subscription.objects.filter(
Q(tags__in=email_obj.tags.all()) | Q(tags__name='all')).count()
email_obj.save()
return redirect(reverse(
'admin:emails_email_change', args=(email_obj.id,)))
| from django.shortcuts import render, redirect
from django.views.generic import View
from django.core.urlresolvers import reverse
from django.contrib import messages
from .models import Email
from .forms import EmailAdminForm
from nightreads.user_manager.models import Subscription
class SendEmailAdminView(View):
template = 'admin/emails/email/send_email.html'
form_class = EmailAdminForm
def get(self, request, pk):
email_obj = Email.objects.get(pk=pk)
return render(request, self.template, {'email_obj': email_obj})
def post(self, request, pk):
email_type = request.POST.get('type', '').lower()
email_obj = Email.objects.get(pk=pk)
if email_type == 'preview':
# send preview email
m = 'Preview email has been sent!'
else:
# send email
m = 'Email has been sent!'
email_obj.is_sent = True
messages.add_message(request, messages.INFO, m)
return redirect(reverse(
'admin:emails_email_change', args=(email_obj.id,)))
class UpdateTargetCountView(View):
def get(self, request, pk):
email_obj = Email.objects.get(pk=pk)
email_obj.targetted_users = Subscription.objects.filter(
tags__in=email_obj.tags.all()).count()
email_obj.save()
return redirect(reverse(
'admin:emails_email_change', args=(email_obj.id,)))
|
Fix test fails by loading Chart.js on runtime | import React, { PropTypes } from "react";
import { getLabelDisplay } from "./stat";
export default class StatsChart extends React.Component {
componentDidMount() {
const Chart = require("chart.js");
const ctx = this.canvasElement.getContext("2d");
this.chart = new Chart(ctx, {
type: "line",
data: this.buildChartData(),
options: {
title: { display: false },
legend: { display: false },
},
});
}
componentWillReceiveProps() {
this.chart.data = this.buildChartData();
this.chart.update();
}
componentWillUnmount() {
this.chart.destroy();
this.chart = null;
}
buildChartData() {
const { label, xValues, yValues } = this.props;
return {
labels: xValues,
datasets: [{
label: getLabelDisplay(label),
fill: true,
borderColor: "rgb(24, 143, 201)",
backgroundColor: "rgba(24, 143, 201, 0.2)",
data: yValues,
}],
};
}
render() {
return (
<div className="stats-chart">
<canvas
ref={(c) => { this.canvasElement = c; }}
className="starts-chart__canvas"
height="100"
/>
</div>
);
}
}
StatsChart.propTypes = {
label: PropTypes.string.isRequired,
xValues: PropTypes.arrayOf(PropTypes.string).isRequired,
yValues: PropTypes.arrayOf(PropTypes.number).isRequired,
};
| import React, { PropTypes } from "react";
import Chart from "chart.js";
import { getLabelDisplay } from "./stat";
export default class StatsChart extends React.Component {
componentDidMount() {
const ctx = this.canvasElement.getContext("2d");
this.chart = new Chart(ctx, {
type: "line",
data: this.buildChartData(),
options: {
title: { display: false },
legend: { display: false },
},
});
}
componentWillReceiveProps() {
this.chart.data = this.buildChartData();
this.chart.update();
}
componentWillUnmount() {
this.chart.destroy();
this.chart = null;
}
buildChartData() {
const { label, xValues, yValues } = this.props;
return {
labels: xValues,
datasets: [{
label: getLabelDisplay(label),
fill: true,
borderColor: "rgb(24, 143, 201)",
backgroundColor: "rgba(24, 143, 201, 0.2)",
data: yValues,
}],
};
}
render() {
return (
<div className="stats-chart">
<canvas
ref={(c) => { this.canvasElement = c; }}
className="starts-chart__canvas"
height="100"
/>
</div>
);
}
}
StatsChart.propTypes = {
label: PropTypes.string.isRequired,
xValues: PropTypes.arrayOf(PropTypes.string).isRequired,
yValues: PropTypes.arrayOf(PropTypes.number).isRequired,
};
|
Add custom validation to ScoreGroup schema | import _ from 'lodash';
import * as schema from '../../../lib/schema/schema';
export const textQuestion = {
question: schema.string({isRequired: true}),
isRequired: schema.bool(),
text: schema.shape({
isMultiline: schema.bool(),
maxChars: schema.integer({max: 100}),
maxWords: schema.integer({
validate: function validateMaxWords() {
let errors = [];
if (!this.question.text.isMultiline.get() && this.get()) {
errors.push("Can't specify max words if question is not multiline");
}
return errors;
}
})
})
};
export const choiceQuestion = {
question: schema.string({isRequired: true}),
isRequired: schema.bool(),
choice: schema.shape({
options: schema.array(
schema.string({isRequired: true}),
{
unique: true
}
),
isMultiple: schema.bool(),
hasOther: schema.bool(),
otherText: schema.string()
})
};
export const scoreGroupQuestion = {
question: schema.string({isRequired: true}),
isRequired: schema.bool(),
scoregroup: schema.shape({
labels: schema.array(
schema.string({isRequired: true})
),
items: schema.array(
schema.shape({
text: schema.string({isRequired: true}),
scores: schema.array(
schema.integer({isRequired: true}),
{unique: true}
)
}),
{
validate: function() {
let texts = [for (i of this.get()) i.text];
if (!_.isEqual(texts, _.unique(texts))) {
this.addError('Must be unique');
}
return [];
}
}
//{unique: ['text']} ??
)
})
};
| import * as schema from '../../../lib/schema/schema';
export const textQuestion = {
question: schema.string({isRequired: true}),
isRequired: schema.bool(),
text: schema.shape({
isMultiline: schema.bool(),
maxChars: schema.integer({max: 100}),
maxWords: schema.integer({
validate: function validateMaxWords() {
let errors = [];
if (!this.question.text.isMultiline.get() && this.get()) {
errors.push("Can't specify max words if question is not multiline");
}
return errors;
}
})
})
};
export const choiceQuestion = {
question: schema.string({isRequired: true}),
isRequired: schema.bool(),
choice: schema.shape({
options: schema.array(
schema.string({isRequired: true}),
{
unique: true
}
),
isMultiple: schema.bool(),
hasOther: schema.bool(),
otherText: schema.string()
})
};
export const scoreGroupQuestion = {
question: schema.string({isRequired: true}),
isRequired: schema.bool(),
scoregroup: schema.shape({
labels: schema.array(
schema.string({isRequired: true})
),
items: schema.array(
schema.shape({
text: schema.string({isRequired: true}),
scores: schema.array(
schema.integer({isRequired: true}),
{unique: true}
)
})
//{unique: ['text']} ??
)
})
};
|
Update AceQLManager form to new L&L | /*
* This file is part of AceQL HTTP.
* AceQL HTTP: SQL Over HTTP
* Copyright (C) 2021, KawanSoft SAS
* (http://www.kawansoft.com). All rights reserved.
*
* AceQL HTTP is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* AceQL HTTP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Any modifications to this file must keep this entire header
* intact.
*/
package com.kawansoft.app.util;
/**
*
* @author Nicolas de Pomereu
*/
public class WindowSettingMgrDebugConstants {
/** The DEBUG flag */
public static boolean DEBUG = false;
}
| /*
* This file is part of AceQL HTTP.
* AceQL HTTP: SQL Over HTTP
* Copyright (C) 2021, KawanSoft SAS
* (http://www.kawansoft.com). All rights reserved.
*
* AceQL HTTP is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* AceQL HTTP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Any modifications to this file must keep this entire header
* intact.
*/
package com.kawansoft.app.util;
/**
*
* @author Nicolas de Pomereu
*/
public class WindowSettingMgrDebugConstants {
/** The DEBUG flag */
public static boolean DEBUG = true;
}
|
Make `samples/04_markdown_parse` Python 2+3 compatible | #!/usr/bin/env python
import os.path
import subprocess
import sys
from ebooklib import epub
# This is just a basic example which can easily break in real world.
if __name__ == '__main__':
# read epub
book = epub.read_epub(sys.argv[1])
# get base filename from the epub
base_name = os.path.basename(os.path.splitext(sys.argv[1])[0])
for item in book.items:
# convert into markdown if this is html
if isinstance(item, epub.EpubHtml):
proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
content, error = proc.communicate(item.content)
file_name = os.path.splitext(item.file_name)[0] + '.md'
else:
file_name = item.file_name
content = item.content
# create needed directories
dir_name = '{0}/{1}'.format(base_name, os.path.dirname(file_name))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
print('>> {0}'.format(file_name))
# write content to file
with open('{0}/{1}'.format(base_name, file_name), 'w') as f:
f.write(content)
| #!/usr/bin/env python
import sys
import subprocess
import os
import os.path
from ebooklib import epub
# This is just a basic example which can easily break in real world.
if __name__ == '__main__':
# read epub
book = epub.read_epub(sys.argv[1])
# get base filename from the epub
base_name = os.path.basename(os.path.splitext(sys.argv[1])[0])
for item in book.items:
# convert into markdown if this is html
if isinstance(item, epub.EpubHtml):
proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
content, error = proc.communicate(item.content)
file_name = os.path.splitext(item.file_name)[0]+'.md'
else:
file_name = item.file_name
content = item.content
# create needed directories
dir_name = '%s/%s' % (base_name, os.path.dirname(file_name))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
print '>> ', file_name
# write content to file
f = open('%s/%s' % (base_name, file_name), 'w')
f.write(content)
f.close()
|
Convert punctuation to pure ASCII
Curly quotes, en-dashes etc. can be produced by pandoc's --smart
option. | function trim(value) {
return value.replace(/^\s+|\s+$/g, "");
}
function asciify(str) {
return str.replace(/[\u2018\u2019]/g, "'")
.replace(/[\u201c\u201d]/g, '"')
.replace(/\u2013/g, "--")
.replace(/\u2014/g, "---")
.replace(/\u2026/g, "...");
}
(function () {
'use strict';
document.addEventListener('DOMContentLoaded', function () {
var instructions = document.querySelector('#instructions');
var paste_bin = document.querySelector('#paste-bin');
var output = document.querySelector('#output');
var output_wrapper = document.querySelector('#output-wrapper');
var clear = document.querySelector('#clear');
document.addEventListener('keydown', function (event) {
if (event.ctrlKey || event.metaKey) {
if (String.fromCharCode(event.which).toLowerCase() === 'v') {
paste_bin.innerHTML = '';
paste_bin.focus();
instructions.classList.add('hidden');
output_wrapper.classList.add('hidden');
}
}
});
paste_bin.addEventListener('paste', function () {
setTimeout(read_paste_bin, 200);
});
var read_paste_bin = function () {
var text_html = paste_bin.innerHTML;
var text_markdown = trim(asciify(html2markdown(text_html, {
inlineStyle: true
})));
output.value = text_markdown;
output_wrapper.classList.remove('hidden');
};
clear.addEventListener('click', function () {
output.value = '';
output_wrapper.classList.add('hidden');
});
});
})();
| (function () {
'use strict';
document.addEventListener('DOMContentLoaded', function () {
var instructions = document.querySelector('#instructions');
var paste_bin = document.querySelector('#paste-bin');
var output = document.querySelector('#output');
var output_wrapper = document.querySelector('#output-wrapper');
var clear = document.querySelector('#clear');
document.addEventListener('keydown', function (event) {
if (event.ctrlKey || event.metaKey) {
if (String.fromCharCode(event.which).toLowerCase() === 'v') {
paste_bin.innerHTML = '';
paste_bin.focus();
instructions.classList.add('hidden');
output_wrapper.classList.add('hidden');
}
}
});
paste_bin.addEventListener('paste', function () {
setTimeout(read_paste_bin, 200);
});
var read_paste_bin = function () {
var text_html = paste_bin.innerHTML;
var text_markdown = html2markdown(text_html, {
inlineStyle: true
});
output.value = text_markdown;
output_wrapper.classList.remove('hidden');
};
clear.addEventListener('click', function () {
output.value = '';
output_wrapper.classList.add('hidden');
});
});
})();
|
:wrench: Check for isFetching with .some | import React, { Component, PropTypes } from 'react';
import fetchData from '../../actions/fetchData';
import Toast from '../../components/Toast';
import Modals from '../Modals';
import types from '../../utils/types';
import SocketEvents from '../../utils/socketEvents';
import './Main.scss';
import MainNav from '../MainNav';
export default class Main extends Component {
static propTypes = {
...types.entries,
...types.sections,
site: PropTypes.object.isRequired,
socket: PropTypes.object.isRequired,
ui: PropTypes.object.isRequired,
user: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
children: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
};
componentDidMount() {
const { dispatch, socket } = this.props;
fetchData();
const events = new SocketEvents(socket, dispatch);
events.listen();
}
render() {
const { ui, dispatch, site } = this.props;
if (Object.keys(this.props).some(key => this.props[key].isFetching)) return null;
return (
<main className="main">
<MainNav siteName={site.siteName} />
{React.cloneElement(this.props.children, {
...this.props,
key: this.props.location.pathname,
})}
<div className="toasts">
{ui.toasts.map(t => <Toast dispatch={dispatch} key={t.dateCreated} {...t} />)}
</div>
<Modals {...this.props} />
</main>
);
}
}
| import React, { Component, PropTypes } from 'react';
import fetchData from '../../actions/fetchData';
import Toast from '../../components/Toast';
import Modals from '../Modals';
import types from '../../utils/types';
import SocketEvents from '../../utils/socketEvents';
import './Main.scss';
import MainNav from '../MainNav';
export default class Main extends Component {
static propTypes = {
...types.entries,
...types.sections,
site: PropTypes.object.isRequired,
socket: PropTypes.object.isRequired,
ui: PropTypes.object.isRequired,
user: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
children: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
};
componentDidMount() {
const { dispatch, socket } = this.props;
fetchData();
const events = new SocketEvents(socket, dispatch);
events.listen();
}
render() {
const { user, entries, sections, fields, assets, ui, dispatch, site } = this.props;
if (user.isFetching
|| entries.isFetching
|| sections.isFetching
|| assets.isFetching
|| fields.isFetching) return null;
return (
<main className="main">
<MainNav siteName={site.siteName} />
{React.cloneElement(this.props.children, {
...this.props,
key: this.props.location.pathname,
})}
<div className="toasts">
{ui.toasts.map(t => <Toast dispatch={dispatch} key={t.dateCreated} {...t} />)}
</div>
<Modals {...this.props} />
</main>
);
}
}
|
9623: Apply search when dismissing any popover | import React from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/Button';
import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
import { getButtonHintString } from '../utils';
import FilterPopover from '../FilterPopover/component';
class FilterOverlayTrigger extends React.Component {
static propTypes = {
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
popoverContent: PropTypes.node.isRequired,
popoverClass: PropTypes.string,
buttonsContainerClass: PropTypes.string,
onSubmit: PropTypes.func.isRequired,
hints: PropTypes.arrayOf(PropTypes.string),
buttonClass: PropTypes.string,
};
handleExit = () => {
const { onSubmit } = this.props;
// TODO: Don't search if nothing was modified.
onSubmit();
}
renderPopover = () => {
const { id, popoverContent, popoverClass, buttonsContainerClass, onSubmit } = this.props;
return (
<FilterPopover
id={id}
onSubmit={onSubmit}
className={popoverClass}
buttonsContainerClass={buttonsContainerClass}
>
{popoverContent}
</FilterPopover>
);
}
render() {
const { id, title, hints, buttonClass } = this.props;
return (
<OverlayTrigger
id={id}
containerPadding={25}
overlay={this.renderPopover()}
placement="bottom"
rootClose
onExit={this.handleExit}
trigger="click"
>
<Button id={id} variant="secondary" className={buttonClass}>
{title + getButtonHintString(hints)}
</Button>
</OverlayTrigger>
);
}
}
export default FilterOverlayTrigger;
| import React from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/Button';
import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
import { getButtonHintString } from '../utils';
import FilterPopover from '../FilterPopover/component';
class FilterOverlayTrigger extends React.Component {
static propTypes = {
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
popoverContent: PropTypes.node.isRequired,
popoverClass: PropTypes.string,
buttonsContainerClass: PropTypes.string,
onSubmit: PropTypes.func.isRequired,
hints: PropTypes.arrayOf(PropTypes.string),
buttonClass: PropTypes.string,
};
renderPopover = () => {
const { id, popoverContent, popoverClass, buttonsContainerClass, onSubmit } = this.props;
return (
<FilterPopover
id={id}
onSubmit={onSubmit}
className={popoverClass}
buttonsContainerClass={buttonsContainerClass}
>
{popoverContent}
</FilterPopover>
);
}
render() {
const { id, title, hints, buttonClass } = this.props;
return (
<OverlayTrigger
id={id}
containerPadding={25}
overlay={this.renderPopover()}
placement="bottom"
rootClose
trigger="click"
>
<Button id={id} variant="secondary" className={buttonClass}>
{title + getButtonHintString(hints)}
</Button>
</OverlayTrigger>
);
}
}
export default FilterOverlayTrigger;
|
Replace 'basestring' by 'str' for Python 3 compatibility | import time
import functools
import redis
class Redis(redis.Redis):
class RedisSession(object):
def __init__(self, redis, prefix=''):
self.prefix = prefix
self.redis = redis
def start(self, prefix):
self.prefix = prefix + ':' if prefix else ''
def __getattr__(self, name):
try:
return self._wrap(getattr(self.redis, name))
except AttributeError:
return super(Redis.RedisSession, self).__getattr__(name)
def _wrap(self, method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
if len(args) and isinstance(args[0], str):
args = (self.prefix + args[0],) + args[1:]
return method(*args, **kwargs)
return wrapper
def __init__(self, *args, **kwargs):
super(Redis, self).__init__(*args, **kwargs)
self.session = self.RedisSession(self)
def connect_to_redis(*args, **kwargs):
client = Redis(
*args,
unix_socket_path='redis/redis.sock',
decode_responses=True,
**kwargs
)
while True:
try:
assert client.ping()
except (redis.exceptions.ConnectionError, AssertionError):
time.sleep(0.05)
else:
client.session.start(client.get('session'))
return client
| import time
import functools
import redis
class Redis(redis.Redis):
class RedisSession(object):
def __init__(self, redis, prefix=''):
self.prefix = prefix
self.redis = redis
def start(self, prefix):
self.prefix = prefix + ':' if prefix else ''
def __getattr__(self, name):
try:
return self._wrap(getattr(self.redis, name))
except AttributeError:
return super(Redis.RedisSession, self).__getattr__(name)
def _wrap(self, method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
if len(args) and isinstance(args[0], basestring):
args = (self.prefix + args[0],) + args[1:]
return method(*args, **kwargs)
return wrapper
def __init__(self, *args, **kwargs):
super(Redis, self).__init__(*args, **kwargs)
self.session = self.RedisSession(self)
def connect_to_redis(*args, **kwargs):
client = Redis(
*args,
unix_socket_path='redis/redis.sock',
decode_responses=True,
**kwargs
)
while True:
try:
assert client.ping()
except (redis.exceptions.ConnectionError, AssertionError):
time.sleep(0.05)
else:
client.session.start(client.get('session'))
return client
|
Fix bug: Show Opbeat response code if error is returned | var util = require('util');
var http = require('http');
function HTTPTransport() {
// Opbeat currently doesn't support HTTP
this.defaultPort = 80;
this.transport = http;
}
HTTPTransport.prototype.send = function(client, message, headers) {
var options = {
hostname: client.dsn.host,
path: client.dsn.path,
headers: headers,
method: 'POST',
port: client.dsn.port || this.defaultPort
}, req = this.transport.request(options, function(res){
res.setEncoding('utf8');
var body = [];
res.on('data', function(data) {
body.push(data);
});
res.on('end', function(){
if(res.statusCode >= 200 && res.statusCode < 300) {
client.emit('logged', res.headers.location);
} else {
var msg = '';
body = body.join('');
try {
body = JSON.parse(body);
msg = body.error_message;
} catch (e) {}
client.emit('error', new Error('Opbeat error (' + res.statusCode + '): ' + msg));
}
});
});
req.on('error', function(e){
client.emit('connectionError', e);
});
req.end(message);
}
var https = require('https');
function HTTPSTransport() {
this.defaultPort = 443;
this.transport = https;
}
util.inherits(HTTPSTransport, HTTPTransport);
module.exports.https = new HTTPSTransport();
| var util = require('util');
var http = require('http');
function HTTPTransport() {
// Opbeat currently doesn't support HTTP
this.defaultPort = 80;
this.transport = http;
}
HTTPTransport.prototype.send = function(client, message, headers) {
var options = {
hostname: client.dsn.host,
path: client.dsn.path,
headers: headers,
method: 'POST',
port: client.dsn.port || this.defaultPort
}, req = this.transport.request(options, function(res){
res.setEncoding('utf8');
var body = [];
res.on('data', function(data) {
body.push(data);
});
res.on('end', function(){
if(res.statusCode >= 200 && res.statusCode < 300) {
client.emit('logged', res.headers.location);
} else {
var msg = '';
body = body.join('');
try {
body = JSON.parse(body);
msg = body.error_message;
} catch (e) {}
client.emit('error', new Error('Opbeat error (' + res.responseCode + '): ' + msg));
}
});
});
req.on('error', function(e){
client.emit('connectionError', e);
});
req.end(message);
}
var https = require('https');
function HTTPSTransport() {
this.defaultPort = 443;
this.transport = https;
}
util.inherits(HTTPSTransport, HTTPTransport);
module.exports.https = new HTTPSTransport();
|
Upgrade method getController to accept params additional from route | <?php
namespace JS\Test;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\Http\TreeRouteStack;
use Zend\Mvc\Router\Console\RouteMatch;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
abstract class JSTestControllerCase extends AbstractHttpControllerTestCase {
use JSZendFunctionsTrait;
public static function setUpBeforeClass() {
JSDatabaseTest::createDataBase();
}
public static function tearDownAfterClass() {
JSDatabaseTest::dropDatabase();
}
protected function setUp() {
$this->setApplicationConfig(JSBootstrap::getConfig());
parent::setUp();
$this->setApplicationInstance($this->getApplication());
JSDatabaseTest::createTables($this->getEntityManager());
}
protected function tearDown() {
parent::tearDown();
}
public function getController($controllerClass, $controllerName, $action, $params = []) {
$config = $this->getConfig();
$controller = $this->getServiceManager()->get('ControllerLoader')->get($controllerClass);
$event = new MvcEvent();
$routerConfig = isset($config['router']) ? $config['router'] : [];
$router = TreeRouteStack::factory($routerConfig);
$event->setRouter($router);
$event->setRouteMatch(new RouteMatch(['controller' => $controllerName, 'action' => $action] + $params));
$controller->setEvent($event);
return $controller;
}
}
| <?php
namespace JS\Test;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\Http\TreeRouteStack;
use Zend\Mvc\Router\Console\RouteMatch;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
abstract class JSTestControllerCase extends AbstractHttpControllerTestCase {
use JSZendFunctionsTrait;
public static function setUpBeforeClass() {
JSDatabaseTest::createDataBase();
}
public static function tearDownAfterClass() {
JSDatabaseTest::dropDatabase();
}
protected function setUp() {
$this->setApplicationConfig(JSBootstrap::getConfig());
parent::setUp();
$this->setApplicationInstance($this->getApplication());
JSDatabaseTest::createTables($this->getEntityManager());
}
protected function tearDown() {
parent::tearDown();
}
public function getController($controllerClass, $controllerName, $action) {
$config = $this->getConfig();
$controller = $this->getServiceManager()->get('ControllerLoader')->get($controllerClass);
$event = new MvcEvent();
$routerConfig = isset($config['router']) ? $config['router'] : [];
$router = TreeRouteStack::factory($routerConfig);
$event->setRouter($router);
$event->setRouteMatch(new RouteMatch(['controller' => $controllerName, 'action' => $action]));
$controller->setEvent($event);
return $controller;
}
}
|
Fix for logging incorrect region information when using instance role for authentication. | """ Handles connections to AWS """
import logging
import sys
from boto import ec2
from boto.utils import get_instance_metadata
logger = logging.getLogger(__name__)
def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None):
""" Connect to AWS ec2
:type region: str
:param region: AWS region to connect to
:type access_key: str
:param access_key: AWS access key id
:type secret_key: str
:param secret_key: AWS secret access key
:returns: boto.ec2.connection.EC2Connection -- EC2 connection
"""
if access_key:
# Connect using supplied credentials
logger.info('Connecting to AWS EC2 in {}'.format(region))
connection = ec2.connect_to_region(
region,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key)
else:
# Fetch instance metadata
metadata = get_instance_metadata(timeout=1, num_retries=1)
if metadata:
try:
region = metadata['placement']['availability-zone'][:-1]
except KeyError:
pass
# Connect using env vars or boto credentials
logger.info('Connecting to AWS EC2 in {}'.format(region))
connection = ec2.connect_to_region(region)
if not connection:
logger.error('An error occurred when connecting to EC2')
sys.exit(1)
return connection
| """ Handles connections to AWS """
import logging
import sys
from boto import ec2
from boto.utils import get_instance_metadata
logger = logging.getLogger(__name__)
def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None):
""" Connect to AWS ec2
:type region: str
:param region: AWS region to connect to
:type access_key: str
:param access_key: AWS access key id
:type secret_key: str
:param secret_key: AWS secret access key
:returns: boto.ec2.connection.EC2Connection -- EC2 connection
"""
logger.info('Connecting to AWS EC2 in {}'.format(region))
if access_key:
# Connect using supplied credentials
connection = ec2.connect_to_region(
region,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key)
else:
# Fetch instance metadata
metadata = get_instance_metadata(timeout=1, num_retries=1)
if metadata:
try:
region = metadata['placement']['availability-zone'][:-1]
except KeyError:
pass
# Connect using env vars or boto credentials
connection = ec2.connect_to_region(region)
if not connection:
logger.error('An error occurred when connecting to EC2')
sys.exit(1)
return connection
|
Set icon before calling show() to avoid warning. | import trayjenkins
from PySide import QtGui
from pyjenkins.Event import Event
from trayjenkins.status.interfaces import IView
class TrayIconView(IView):
def __init__(self, parentWidget, delayInSecons):
"""
@type parentWidget: QtGui.QWidget
"""
self._statusRefreshEvent= Event()
self._delayInSeconds= delayInSecons
self._trayIcon= QtGui.QSystemTrayIcon(parentWidget)
self._icons= {}
self._icons[trayjenkins.status.FAILING]= QtGui.QIcon('images/status/failing.png')
self._icons[trayjenkins.status.OK]= QtGui.QIcon('images/status/ok.png')
self._icons[trayjenkins.status.UNKNOWN]= QtGui.QIcon('images/status/unknown.png')
self.setStatus(trayjenkins.status.UNKNOWN)
self._trayIcon.show()
def statusRefreshEvent(self):
"""
Event arguments: <none>
@rtype: pyjenkins.interfaces.IEvent
"""
return self._statusRefreshEvent
def setStatus(self, status):
"""
@type status: str
"""
self._trayIcon.setIcon(self._icons[status])
self._trayIcon.setToolTip(status.capitalize())
self._trayIcon.showMessage(unicode("Jenkins status change"),
unicode("Status: %s" % status.capitalize()),
QtGui.QSystemTrayIcon.Information,# icon,
self._delayInSeconds * 1000)
| import trayjenkins
from PySide import QtGui
from pyjenkins.Event import Event
from trayjenkins.status.interfaces import IView
class TrayIconView(IView):
def __init__(self, parentWidget, delayInSecons):
"""
@type parentWidget: QtGui.QWidget
"""
self._statusRefreshEvent= Event()
self._delayInSeconds= delayInSecons
self._trayIcon= QtGui.QSystemTrayIcon(parentWidget)
self._trayIcon.show()
self._icons= {}
self._icons[trayjenkins.status.FAILING]= QtGui.QIcon('images/status/failing.png')
self._icons[trayjenkins.status.OK]= QtGui.QIcon('images/status/ok.png')
self._icons[trayjenkins.status.UNKNOWN]= QtGui.QIcon('images/status/unknown.png')
self.setStatus(trayjenkins.status.UNKNOWN)
def statusRefreshEvent(self):
"""
Event arguments: <none>
@rtype: pyjenkins.interfaces.IEvent
"""
return self._statusRefreshEvent
def setStatus(self, status):
"""
@type status: str
"""
self._trayIcon.setIcon(self._icons[status])
self._trayIcon.setToolTip(status.capitalize())
self._trayIcon.showMessage(unicode("Jenkins status change"),
unicode("Status: %s" % status.capitalize()),
QtGui.QSystemTrayIcon.Information,# icon,
self._delayInSeconds * 1000)
|
Fix bugs occuring when no response is given. | import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
response = ''
if data:
response += handle_data(data)
cur_thread = threading.current_thread()
response += "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_data(data):
data = json.loads(data)
if data['type'] == 'ask':
handle_ask(data)
elif data['type'] == 'bid':
handle_bid(data)
elif data['type'] == 'greeting':
handle_greeting(data)
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
def handle_greeting(greeting):
pass
| import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
response = handle_data(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_data(data):
data = json.loads(data)
if data['type'] == 'ask':
handle_ask(data)
elif data['type'] == 'bid':
handle_bid(data)
elif data['type'] == 'greeting':
handle_greeting(data)
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
def handle_greeting(greeting):
pass
|
Use string constant from metrics-proxy to avoid duplication. | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;
import ai.vespa.metricsproxy.core.VespaMetrics;
import com.google.common.collect.ImmutableList;
import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet;
import static java.util.Collections.emptyList;
/**
* This class sets up the default 'Vespa' metrics consumer.
*
* @author trygve
* @author gjoranv
*/
public class DefaultMetricsConsumer {
public static final String VESPA_CONSUMER_ID = VespaMetrics.VESPA_CONSUMER_ID.id;
private static final MetricSet defaultConsumerMetrics = new MetricSet("default-consumer",
emptyList(),
ImmutableList.of(vespaMetricSet,
systemMetricSet,
networkMetricSet));
@SuppressWarnings("UnusedDeclaration")
public static MetricsConsumer getDefaultMetricsConsumer() {
return new MetricsConsumer(VESPA_CONSUMER_ID, defaultConsumerMetrics);
}
}
| // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;
import com.google.common.collect.ImmutableList;
import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet;
import static java.util.Collections.emptyList;
/**
* This class sets up the default 'Vespa' metrics consumer.
*
* @author trygve
* @author gjoranv
*/
public class DefaultMetricsConsumer {
public static final String VESPA_CONSUMER_ID = "Vespa";
private static final MetricSet defaultConsumerMetrics = new MetricSet("default-consumer",
emptyList(),
ImmutableList.of(vespaMetricSet,
systemMetricSet,
networkMetricSet));
@SuppressWarnings("UnusedDeclaration")
public static MetricsConsumer getDefaultMetricsConsumer() {
return new MetricsConsumer(VESPA_CONSUMER_ID, defaultConsumerMetrics);
}
}
|
Remove round of multiplication result for get_geometric_mean and bug fix get edge weight | from itertools import combinations
class ClusterUtility(object):
@staticmethod
def get_geometric_mean(weights):
multiplication = 1
for weight in weights:
multiplication = multiplication * weight
gmean = 0.0
if multiplication > 0.0:
k = float(len(weights))
gmean = multiplication ** (1 / k)
return round(gmean, 5)
@staticmethod
def get_weighted_cliques(graph, cliques, threshold):
weighted_kcliques = []
for clique in cliques:
weights = []
for u, v in combinations(clique, 2):
reduced_precision = round(graph[u][v][0]['weight'], 5)
weights.append(reduced_precision)
gmean = ClusterUtility.get_geometric_mean(weights)
if gmean > threshold:
weighted_kcliques.append(frozenset(clique))
return weighted_kcliques
@staticmethod
def set_cluster_id(graph, clusters):
cluster_id = 0
for cluster in clusters:
for node in cluster:
graph.node[node]['cluster'] = cluster_id
cluster_id += 1 | from itertools import combinations
class ClusterUtility(object):
@staticmethod
def get_geometric_mean(weights):
multiplication = 1
for weight in weights:
multiplication = multiplication * weight
gmean = 0.0
multiplication = round(multiplication, 5)
if multiplication > 0.0:
k = float(len(weights))
gmean = multiplication ** (1 / k)
return round(gmean, 5)
@staticmethod
def get_weighted_cliques(graph, cliques, threshold):
weighted_kcliques = []
for clique in cliques:
weights = []
for u, v in combinations(clique, 2):
reduced_precision = round(graph[u][v]['weight'], 5)
weights.append(reduced_precision)
gmean = ClusterUtility.get_geometric_mean(weights)
if gmean > threshold:
weighted_kcliques.append(frozenset(clique))
return weighted_kcliques
@staticmethod
def set_cluster_id(graph, clusters):
cluster_id = 0
for cluster in clusters:
for node in cluster:
graph.node[node]['cluster'] = cluster_id
cluster_id += 1 |
Check if the 2nd param is process.argv and work well | (function() {
var HashArg = {};
HashArg.get = function(argdefs, argv) {
var args = {};
if(!argv || argv === process.argv) {
argv = [];
for(var i = 2; i < process.argv.length; i++) {
argv.push(process.argv[i]);
}
}
if(typeof(argdefs) === 'string') {
argdefs = argdefs.split(/\s+/);
}
for(var i = 0; i < argdefs.length; i++) {
var argdef = argdefs[i];
var name = "#" + i;
var value = null;
if(typeof(argdef) === 'string') {
name = argdef;
if(i < argv.length) {
value = argv[i];
}
} else if("name" in argdef) {
name = argdef.name;
if(i < argv.length) {
value = argv[i];
} else if("default" in argdef) {
value = argdef["default"];
}
}
args[name] = value;
}
return args;
};
module.exports = HashArg;
}());
| (function() {
var HashArg = {};
HashArg.get = function(argdefs, argv) {
var args = {};
if(!argv) {
argv = [];
for(var i = 2; i < process.argv.length; i++) {
argv.push(process.argv[i]);
}
}
if(typeof(argdefs) === 'string') {
argdefs = argdefs.split(/\s+/);
}
for(var i = 0; i < argdefs.length; i++) {
var argdef = argdefs[i];
var name = "#" + i;
var value = null;
if(typeof(argdef) === 'string') {
name = argdef;
if(i < argv.length) {
value = argv[i];
}
} else if("name" in argdef) {
name = argdef.name;
if(i < argv.length) {
value = argv[i];
} else if("default" in argdef) {
value = argdef["default"];
}
}
args[name] = value;
}
return args;
};
module.exports = HashArg;
}());
|
Fix Missing Extension from package | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
requirements = {
"package": [
"PyYAML",
],
"test": [
"nose",
"mock",
"pytest",
"pytest-mock",
"pytest-pudb",
],
"setup": [
"pytest-runner",
],
}
requirements.update(all=sorted(set().union(*requirements.values())))
setup(
name='yamlsettings',
version='1.0.1',
description='Yaml Settings Configuration Module',
long_description=readme,
author='Kyle James Walker',
author_email='[email protected]',
url='https://github.com/KyleJamesWalker/yamlsettings',
packages=['yamlsettings', 'yamlsettings.extensions'],
package_dir={'yamlsettings':
'yamlsettings'},
include_package_data=True,
install_requires=requirements['package'],
extras_require=requirements,
setup_requires=requirements['setup'],
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
test_suite='tests',
tests_require=requirements['test'],
)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
requirements = {
"package": [
"PyYAML",
],
"test": [
"nose",
"mock",
"pytest",
"pytest-mock",
"pytest-pudb",
],
"setup": [
"pytest-runner",
],
}
requirements.update(all=sorted(set().union(*requirements.values())))
setup(
name='yamlsettings',
version='1.0.0',
description='Yaml Settings Configuration Module',
long_description=readme,
author='Kyle James Walker',
author_email='[email protected]',
url='https://github.com/KyleJamesWalker/yamlsettings',
packages=['yamlsettings'],
package_dir={'yamlsettings':
'yamlsettings'},
include_package_data=True,
install_requires=requirements['package'],
extras_require=requirements,
setup_requires=requirements['setup'],
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
test_suite='tests',
tests_require=requirements['test'],
)
|
Add more field to search | module.exports = function (models) {
const {
Photo,
User
} = models;
return {
searchPhotos(pattern) {
var regex = new RegExp(pattern, 'i');
return new Promise((resolve, reject) => {
Photo.find({
$or: [{
'title': regex
}, {
'description': regex
}]
},
(err, photos) => {
if (err) {
reject(err);
}
resolve(photos);
})
});
},
searchUsers(pattern) {
var regex = new RegExp(pattern, 'i');
return new Promise((resolve, reject) => {
User.find({
$or: [{
'username': regex
}, {
'description': regex
}, {
'name': regex
}]
},
(err, users) => {
if (err) {
reject(err);
}
resolve(users);
})
});
}
};
}; | module.exports = function (models) {
const {
Photo,
User
} = models;
return {
searchPhotos(pattern) {
return new Promise((resolve, reject) => {
Photo.find({
'title': new RegExp(pattern, 'i')
},
(err, photos) => {
if (err) {
reject(err);
}
resolve(photos);
})
});
},
searchUsers(pattern) {
return new Promise((resolve, reject) => {
User.find({
'username': new RegExp(pattern, 'i')
},
(err, users) => {
if (err) {
reject(err);
}
resolve(users);
})
});
}
};
}; |
Remove optional options from api call | import React, { Component } from "react";
import { injectGlobal } from "styled-components";
import Api from "./api";
import StoryList from "./containers/StoryList";
// eslint-disable-next-line no-unused-expressions
injectGlobal`
@font-face {
font-family: 'Verdana, Geneva, sans-serif'
}
body {
margin: 0;
}
`;
class App extends Component {
state = {
newStories: []
};
fetchNewStories(storyIds) {
let actions = storyIds.slice(0, 30).map(this.fetchSingleStory);
let results = Promise.all(actions);
results.then(data =>
this.setState(
Object.assign({}, this.state, {
newStories: data
})
)
);
}
fetchSingleStory(id, index) {
const rank = index + 1;
return new Promise(resolve => {
Api.fetch(`/item/${id}`, {
then(data) {
let item = data;
// add the rank since it does not exist yet
item.rank = rank;
resolve(item);
}
});
});
}
componentDidMount() {
Api.fetch(`/newstories`, {
context: this,
then(storyIds) {
this.fetchNewStories(storyIds);
}
});
}
render() {
return <StoryList items={this.state.newStories} />;
}
}
export default App;
| import React, { Component } from "react";
import { injectGlobal } from "styled-components";
import Api from "./api";
import StoryList from "./containers/StoryList";
// eslint-disable-next-line no-unused-expressions
injectGlobal`
@font-face {
font-family: 'Verdana, Geneva, sans-serif'
}
body {
margin: 0;
}
`;
class App extends Component {
state = {
newStories: []
};
fetchNewStories(storyIds) {
let actions = storyIds.slice(0, 30).map(this.fetchSingleStory);
let results = Promise.all(actions);
results.then(data =>
this.setState(
Object.assign({}, this.state, {
newStories: data
})
)
);
}
fetchSingleStory(id, index) {
const rank = index + 1;
return new Promise(resolve => {
Api.fetch(`/item/${id}`, {
context: this,
then(data) {
let item = data;
// add the rank since it does not exist yet
item.rank = rank;
resolve(item);
}
});
});
}
componentDidMount() {
Api.fetch(`/newstories`, {
context: this,
asArray: true,
then(storyIds) {
this.fetchNewStories(storyIds);
}
});
}
render() {
return <StoryList items={this.state.newStories} />;
}
}
export default App;
|
Update renamed method (irrep -> decompose) | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Handles the "Unicode" unit format.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from . import console
class Unicode(console.Console):
"""
Output-only format for to display pretty formatting at the console
using Unicode characters.
For example::
>>> print u.Ry.decompose().to_string('unicode')
m² kg
2.18×10-¹⁸ ─────
s²
"""
def __init__(self):
pass
_times = "×"
_line = "─"
def _get_unit_name(self, unit):
return unit.get_format_name('unicode')
@staticmethod
def _format_superscript(number):
mapping = {
'0': '⁰',
'1': '¹',
'2': '²',
'3': '³',
'4': '⁴',
'5': '⁵',
'6': '⁶',
'7': '⁷',
'8': '⁸',
'9': '⁹',
'-': '⁻'}
output = []
for c in number:
output.append(mapping[c])
return ''.join(output)
| # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Handles the "Unicode" unit format.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from . import console
class Unicode(console.Console):
"""
Output-only format for to display pretty formatting at the console
using Unicode characters.
For example::
>>> print u.Ry.irrep().to_string('unicode')
m² kg
2.18×10-¹⁸ ─────
s²
"""
def __init__(self):
pass
_times = "×"
_line = "─"
def _get_unit_name(self, unit):
return unit.get_format_name('unicode')
@staticmethod
def _format_superscript(number):
mapping = {
'0': '⁰',
'1': '¹',
'2': '²',
'3': '³',
'4': '⁴',
'5': '⁵',
'6': '⁶',
'7': '⁷',
'8': '⁸',
'9': '⁹',
'-': '⁻'}
output = []
for c in number:
output.append(mapping[c])
return ''.join(output)
|
:green_heart: Fix tests relying on fs spies | 'use strict';
const fs = require('fs');
const GetEmail = require('../../lib/install/get-email');
describe('GetEmail', () => {
let step;
beforeEach(() => {
step = new GetEmail();
});
describe('.start()', () => {
afterEach(() => {
fs.readFileSync.andCallThrough();
});
describe('when the user has a .gitconfig file', () => {
beforeEach(() => {
spyOn(fs, 'readFileSync').andReturn(`[user]
email = [email protected]`);
});
it('returns a promise that is resolved with the user email', () => {
waitsForPromise(() => step.start().then(data => {
expect(data.email).toEqual('[email protected]');
}));
});
});
describe('when the user has a .gitconfig file without an email', () => {
beforeEach(() => {
spyOn(fs, 'readFileSync').andReturn('');
});
it('returns a promise that is resolved with null', () => {
waitsForPromise(() => step.start().then(data => {
expect(data).toEqual({email: undefined});
}));
});
});
describe('when the user has no .gitconfig file', () => {
beforeEach(() => {
spyOn(fs, 'readFileSync').andCallFake(() => { throw new Error(); });
});
it('returns a promise that is resolved with null', () => {
waitsForPromise(() => step.start().then(data => {
expect(data).toEqual({email: undefined});
}));
});
});
});
});
| 'use strict';
const fs = require('fs');
const GetEmail = require('../../lib/install/get-email');
describe('GetEmail', () => {
let step;
beforeEach(() => {
step = new GetEmail();
});
describe('.start()', () => {
describe('when the user has a .gitconfig file', () => {
beforeEach(() => {
spyOn(fs, 'readFileSync').andReturn(`[user]
email = [email protected]`);
});
it('returns a promise that is resolved with the user email', () => {
waitsForPromise(() => step.start().then(data => {
expect(data.email).toEqual('[email protected]');
}));
});
});
describe('when the user has a .gitconfig file without an email', () => {
beforeEach(() => {
spyOn(fs, 'readFileSync').andReturn('');
});
it('returns a promise that is resolved with null', () => {
waitsForPromise(() => step.start().then(data => {
expect(data).toEqual({email: undefined});
}));
});
});
describe('when the user has no .gitconfig file', () => {
beforeEach(() => {
spyOn(fs, 'readFileSync').andCallFake(() => { throw new Error(); });
});
it('returns a promise that is resolved with null', () => {
waitsForPromise(() => step.start().then(data => {
expect(data).toEqual({email: undefined});
}));
});
});
});
});
|
Clear pasted URL textbox after submitting. | function(context) {
var app = $$(this).app;
var url = $("#pasted_url").val();
if (url.length > 0) {
idPos = url.indexOf("id=");
if (idPos > -1) {
url = url.substr(idPos + 3);
}
lastSlash = url.lastIndexOf("/");
if (lastSlash > -1) {
url = url.substr(lastSlash + 1);
}
ampPos = url.indexOf("&");
if (ampPos > -1) {
url = url.substr(0, ampPos);
}
guid = url.replace(/^\s+|\s+$/g,"");
if (guid.length == 32) {
app.db.openDoc(guid, {
success: function(doc) {
if (doc.type) {
if (doc.type == 'Veteran') {
window.open("vet_edit.html?vetid=" + doc._id, '_blank')
} else if (doc.type == 'Guardian') {
window.open("grd_edit.html?grdid=" + doc._id, '_blank')
} else if (doc.type == 'Volunteer') {
window.open("vol_edit.html?volid=" + doc._id, '_blank')
}
$("#pasted_url").val("");
}
}
});
} else {
alert('Invalid URL');
}
}
return false;
};
//@ sourceURL=/finder/submit_pasted_url.js
| function(context) {
var app = $$(this).app;
var url = $("#pasted_url").val();
if (url.length > 0) {
idPos = url.indexOf("id=");
if (idPos > -1) {
url = url.substr(idPos + 3);
}
lastSlash = url.lastIndexOf("/");
if (lastSlash > -1) {
url = url.substr(lastSlash + 1);
}
ampPos = url.indexOf("&");
if (ampPos > -1) {
url = url.substr(0, ampPos);
}
guid = url.replace(/^\s+|\s+$/g,"");
if (guid.length == 32) {
app.db.openDoc(guid, {
success: function(doc) {
if (doc.type) {
if (doc.type == 'Veteran') {
window.open("vet_edit.html?vetid=" + doc._id, '_blank')
} else if (doc.type == 'Guardian') {
window.open("grd_edit.html?grdid=" + doc._id, '_blank')
} else if (doc.type == 'Volunteer') {
window.open("vol_edit.html?volid=" + doc._id, '_blank')
}
}
}
});
} else {
alert('Invalid URL');
}
}
return false;
};
//@ sourceURL=/finder/submit_pasted_url.js
|
Simplify how we draw the world: operations are not additive operations anymore | (function () {
"use strict";
angular
.module("PLMApp")
.factory("World", World);
function World() {
var World = function (world) {
this.type = world.type;
this.operations = [];
this.currentState = -1;
this.steps = [];
this.width = world.width;
this.height = world.height;
};
World.prototype.clone = function () {
return new World(this);
};
World.prototype.addOperations = function (operations) {
var step = [];
var length = operations.length;
for (var i = 0; i < length; i += 1) {
var operation = operations[i];
step.push(operation);
}
this.operations.push(step);
};
World.prototype.setState = function (state) {
if (state < this.operations.length && state >= -1) {
this.drawSVG(this.operations[state][0]);
this.currentState = state;
}
};
World.prototype.drawSVG = function (svg) {
(function () {
document.getElementById("drawingArea").innerHTML = svg.operation;
var svgElm = document.getElementsByTagName("svg");
svgElm[0].setAttribute("width", "400px");
svgElm[0].setAttribute("height", "400px");
})();
};
return World;
}
}());
| (function () {
"use strict";
angular
.module("PLMApp")
.factory("World", World);
function World() {
var World = function (world) {
this.type = world.type;
this.operations = [];
this.currentState = -1;
this.steps = [];
this.width = world.width;
this.height = world.height;
};
World.prototype.clone = function () {
return new World(this);
};
World.prototype.addOperations = function (operations) {
var step = [];
var length = operations.length;
for (var i = 0; i < length; i += 1) {
var operation = operations[i];
step.push(operation);
}
this.operations.push(step);
};
World.prototype.setState = function (state) {
var i, j, length, step;
if (state < this.operations.length && state >= -1) {
if (this.currentState < state) {
for (i = this.currentState + 1; i <= state; i += 1) {
step= this.operations;
length = step.length;
this.drawSVG(step[i][0]);
}
} else {
for (i = this.currentState; i > state; i -= 1) {
step= this.operations;
length = step.length;
this.drawSVG(step[i][0]);
}
}
this.currentState = state;
}
};
World.prototype.drawSVG = function (svg) {
(function () {
document.getElementById("drawingArea").innerHTML = svg.operation;
var svgElm = document.getElementsByTagName("svg");
svgElm[0].setAttribute("width", "400px");
svgElm[0].setAttribute("height", "400px");
})();
};
return World;
}
}());
|
Add a --target argument and make trailling arguments context dependant | #!/usr/bin/env python2
# -*- coding: UTF-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import argparse
DEFAULT_CONFIG_FILE = '~/.config/xmrc'
def _new_argument_parser():
parser = argparse.ArgumentParser(
description='Build the appropriate make command'
)
parser.add_argument(
'-u', '--unittest', help='run unittest',
action='store_const', const=True, default=False,
)
parser.add_argument(
'-s', '--sync', help='sync local copy on the server',
action='store_const', const=True, default=False,
)
parser.add_argument(
'-f', '--file', help='specify the configuration file',
default=DEFAULT_CONFIG_FILE,
)
parser.add_argument(
'--setup', help='run commands that should be run before sync',
action='store_const', const=True, default=False,
)
parser.add_argument(
'-d', '--dep', help='install missing dependencies on the server',
action='store_const', const=True, default=False,
)
parser.add_argument(
'-t', '--target', help='the target on which to run'
)
parser.add_argument(
'extra', metavar='extra', type=str, nargs='*',
help='Extra variables, usage vary depending on the context',
)
return parser
def main():
parsed_args = _new_argument_parser().parse_args()
print(parsed_args)
if __name__ == '__main__':
main()
| #!/usr/bin/env python2
# -*- coding: UTF-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import argparse
DEFAULT_CONFIG_FILE = '~/.config/xmrc'
def _new_argument_parser():
parser = argparse.ArgumentParser(
description='Build the appropriate make command'
)
parser.add_argument(
'-u', '--unittest', help='run unittest',
action='store_const', const=True, default=False,
)
parser.add_argument(
'-s', '--sync', help='sync local copy on the server',
action='store_const', const=True, default=False,
)
parser.add_argument(
'-f', '--file', help='specify the configuration file',
default=DEFAULT_CONFIG_FILE,
)
parser.add_argument(
'--setup', help='run commands that should be run before sync',
action='store_const', const=True, default=False,
)
parser.add_argument(
'-d', '--dep', help='install missing dependencies on the server',
action='store_const', const=True, default=False,
)
parser.add_argument(
'project', metavar='project', type=str, nargs='+',
help='The selected project',
)
return parser
def main():
parsed_args = _new_argument_parser().parse_args()
print(parsed_args)
if __name__ == '__main__':
main()
|
Comment out failing check. See GH-199. | import attr
import pytest
from eli5.base_utils import attrs
def test_attrs_with_default():
@attrs
class WithDefault(object):
def __init__(self, x, y=1):
self.x = x
self.y = y
x_attr, y_attr = attr.fields(WithDefault)
assert x_attr.name == 'x'
assert y_attr.name == 'y'
assert x_attr.default is attr.NOTHING
assert y_attr.default == 1
assert WithDefault(1) == WithDefault(1)
assert WithDefault(1, 1) != WithDefault(1, 2)
def test_attrs_without_default():
@attrs
class WithoutDefault(object):
def __init__(self, x):
self.x = x
x_attr, = attr.fields(WithoutDefault)
assert x_attr.name == 'x'
assert x_attr.default is attr.NOTHING
assert WithoutDefault(1) == WithoutDefault(1)
assert WithoutDefault(1) != WithoutDefault(2)
def test_attrs_with_repr():
@attrs
class WithRepr(object):
def __init__(self, x):
self.x = x
def __repr__(self):
return 'foo'
# assert hash(WithRepr(1)) == hash(WithRepr(1))
assert repr(WithRepr(2)) == 'foo'
def test_bad_init():
@attrs
class BadInit(object):
def __init__(self, x):
self._x = x
with pytest.raises(AttributeError):
BadInit(1)
| import attr
import pytest
from eli5.base_utils import attrs
def test_attrs_with_default():
@attrs
class WithDefault(object):
def __init__(self, x, y=1):
self.x = x
self.y = y
x_attr, y_attr = attr.fields(WithDefault)
assert x_attr.name == 'x'
assert y_attr.name == 'y'
assert x_attr.default is attr.NOTHING
assert y_attr.default == 1
assert WithDefault(1) == WithDefault(1)
assert WithDefault(1, 1) != WithDefault(1, 2)
def test_attrs_without_default():
@attrs
class WithoutDefault(object):
def __init__(self, x):
self.x = x
x_attr, = attr.fields(WithoutDefault)
assert x_attr.name == 'x'
assert x_attr.default is attr.NOTHING
assert WithoutDefault(1) == WithoutDefault(1)
assert WithoutDefault(1) != WithoutDefault(2)
def test_attrs_with_repr():
@attrs
class WithRepr(object):
def __init__(self, x):
self.x = x
def __repr__(self):
return 'foo'
assert hash(WithRepr(1)) == hash(WithRepr(1))
assert repr(WithRepr(2)) == 'foo'
def test_bad_init():
@attrs
class BadInit(object):
def __init__(self, x):
self._x = x
with pytest.raises(AttributeError):
BadInit(1)
|
Use the configured storage/ path | <?php
/**
* Brings Twig to Laravel.
*
* @author Rob Crowe <[email protected]>
* @license MIT
*/
namespace TwigBridge\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
/**
* Remove compiled Twig templates.
*/
class CleanCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'twig:clean';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Empty the Twig cache';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
// Get the path to where Twig cache lives
$cache_path = $this->laravel['config']->get('twigbridge::twig.cache');
if ($cache_path === null OR !file_exists($cache_path)) {
$cache_path = $this->laravel['path.storage'].'/views/twig';
}
if (file_exists($cache_path)) {
$file = new Filesystem;
$file->deleteDirectory($cache_path);
if (!file_exists($cache_path)) {
$this->info('Twig cache cleaned');
} else {
$this->error('Twig cache failed to be cleaned');
}
return;
}
$this->info('Twig cache cleaned');
}
}
| <?php
/**
* Brings Twig to Laravel.
*
* @author Rob Crowe <[email protected]>
* @license MIT
*/
namespace TwigBridge\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
/**
* Remove compiled Twig templates.
*/
class CleanCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'twig:clean';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Empty the Twig cache';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
// Get the path to where Twig cache lives
$cache_path = $this->laravel['config']->get('twigbridge::twig.cache');
if ($cache_path === null OR !file_exists($cache_path)) {
$cache_path = $this->laravel['path'].'/storage/views/twig';
}
if (file_exists($cache_path)) {
$file = new Filesystem;
$file->deleteDirectory($cache_path);
if (!file_exists($cache_path)) {
$this->info('Twig cache cleaned');
} else {
$this->error('Twig cache failed to be cleaned');
}
return;
}
$this->info('Twig cache cleaned');
}
}
|
Debug statement used the wrong variable. | '''
Return data to a Cassandra ColumFamily
Here's an example Keyspace/ColumnFamily setup that works with this
returner::
create keyspace salt;
use salt;
create column family returns
with key_validation_class='UTF8Type'
and comparator='UTF8Type'
and default_validation_class='UTF8Type';
'''
import logging
import pycassa
log = logging.getLogger(__name__)
__opts__ = {'cassandra.servers': ['localhost:9160'],
'cassandra.keyspace': 'salt',
'cassandra.column_family': 'returns',
'cassandra.consistency_level': 'ONE'}
def returner(ret):
'''
Return data to a Cassandra ColumnFamily
'''
consistency_level = getattr(pycassa.ConsistencyLevel,
__opts__['cassandra.consistency_level'])
pool = pycassa.ConnectionPool(__opts__['cassandra.keyspace'],
__opts__['cassandra.servers'])
cf = pycassa.ColumnFamily(pool, __opts__['cassandra.column_family'],
write_consistency_level=consistency_level)
columns = {'fun': ret['fun'],
'id': ret['id']}
if isinstance(ret['return'], dict):
for key, value in ret['return'].iteritems():
columns['return.%s' % (key,)] = str(value)
else:
columns['return'] = str(ret['return'])
log.debug(columns)
cf.insert(ret['jid'], columns)
| '''
Return data to a Cassandra ColumFamily
Here's an example Keyspace/ColumnFamily setup that works with this
returner::
create keyspace salt;
use salt;
create column family returns
with key_validation_class='UTF8Type'
and comparator='UTF8Type'
and default_validation_class='UTF8Type';
'''
import logging
import pycassa
log = logging.getLogger(__name__)
__opts__ = {'cassandra.servers': ['localhost:9160'],
'cassandra.keyspace': 'salt',
'cassandra.column_family': 'returns',
'cassandra.consistency_level': 'ONE'}
def returner(ret):
'''
Return data to a Cassandra ColumnFamily
'''
consistency_level = getattr(pycassa.ConsistencyLevel,
__opts__['cassandra.consistency_level'])
pool = pycassa.ConnectionPool(__opts__['cassandra.keyspace'],
__opts__['cassandra.servers'])
cf = pycassa.ColumnFamily(pool, __opts__['cassandra.column_family'],
write_consistency_level=consistency_level)
columns = {'fun': ret['fun'],
'id': ret['id']}
if isinstance(ret['return'], dict):
for key, value in ret['return'].iteritems():
columns['return.%s' % (key,)] = str(value)
else:
columns['return'] = str(ret['return'])
log.debug(back)
cf.insert(ret['jid'], columns)
|
Fix a bug when you try to add a geo tag to an object that does not have already one | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=None, form_class=None):
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
try:
geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
except ObjectDoesNotExist:
geotag = None
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid():
new_object = form.save(commit=False)
new_object.object = object
new_object.save()
return HttpResponseRedirect("/admin/%s/%s/%s/"
%(object_content_type.app_label,
object_content_type.model,
object.id))
form = form_class(instance=geotag)
#import ipdb; ipdb.set_trace()
context = RequestContext(request, {
'form': form,
'object' : object,
'object_content_type' : object_content_type,
'geotag' : geotag,
})
return render_to_response(template, context_instance=context )
| from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=None, form_class=None):
model_class = ContentType.objects.get(id=content_type_id).model_class()
object = model_class.objects.get(id=object_id)
object_content_type = ContentType.objects.get_for_model(object)
geotag = Point.objects.get(content_type__pk=object_content_type.id,
object_id=object.id)
if request.method == "POST":
form = form_class(request.POST, instance=geotag)
if form.is_valid():
new_object = form.save(commit=False)
new_object.object = object
new_object.save()
return HttpResponseRedirect("/admin/%s/%s/%s/"
%(object_content_type.app_label,
object_content_type.model,
object.id))
form = form_class(instance=geotag)
#import ipdb; ipdb.set_trace()
context = RequestContext(request, {
'form': form,
'object' : object,
'object_content_type' : object_content_type,
'geotag' : geotag,
})
return render_to_response(template, context_instance=context )
|
Correct game.tick() implementation and pass failing test | package net.gpdev.gameoflife;
public class GameOfLife {
private final int xDim;
private final int yDim;
private Grid current;
private Grid next;
public GameOfLife(int xDim, int yDim) {
this.xDim = xDim;
this.yDim = yDim;
current = new Grid(xDim, yDim);
next = new Grid(xDim, yDim);
}
public void populateCell(int x, int y) {
current.set(x, y);
}
public boolean isCellPopulated(int x, int y) {
return !current.isEmpty(x, y);
}
public void tick() {
for (int i = 0; i < xDim; i++) {
for (int j = 0; j < yDim; j++) {
if (current.isEmpty(i, j)) {
if (current.numNeighbors(i, j) == 3) {
next.set(i, j);
} else {
next.unset(i, j);
}
} else {
final int numNeighbors = current.numNeighbors(i, j);
if (numNeighbors == 2 || numNeighbors == 3) {
next.set(i, j);
} else {
next.unset(i, j);
}
}
}
}
final Grid prev = current;
current = next;
next = prev;
}
@Override
public String toString() {
return current.toString();
}
}
| package net.gpdev.gameoflife;
public class GameOfLife {
private final int xDim;
private final int yDim;
private Grid current;
private Grid next;
public GameOfLife(int xDim, int yDim) {
this.xDim = xDim;
this.yDim = yDim;
current = new Grid(xDim, yDim);
next = new Grid(xDim, yDim);
}
public void populateCell(int x, int y) {
current.set(x, y);
}
public boolean isCellPopulated(int x, int y) {
return !current.isEmpty(x, y);
}
public void tick() {
for (int i = 0; i < xDim; i++) {
for (int j = 0; j < yDim; j++) {
if (current.isEmpty(i, j)) {
if (current.numNeighbors(i, j) == 3) {
next.set(i, j);
}
}
else {
final int numNeighbors = current.numNeighbors(i, j);
if (numNeighbors == 2 || numNeighbors == 3) {
next.set(i, j);
}
}
}
}
current = next;
}
@Override
public String toString() {
return current.toString();
}
}
|
Add fields `archived` and `description`
See #9 | /**
* Show model
* @module models/Show
*/
/**
* Show model - create and export the database model for shows
* including all assosiations and classmethods assiciated with this model.
* @memberof module:models/Post
* @param {Object} sequelize description
* @param {Object} DataTypes description
*/
export default function (sequelize, DataTypes) {
const Show = sequelize.define('show', {
title: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
description: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
rssFeed: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
logoImage: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
lead: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
explicitContent: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
archived: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
language: {
type: DataTypes.STRING(5),
allowNull: false,
defaultValue: 'no'
}
}, {
classMethods: {
associate(models) {
Show.hasMany(models.Post, {
onDelete: 'cascade'
});
Show.hasMany(models.Episode, {
onDelete: 'cascade'
});
}
}
}
);
return Show;
}
| /**
* Show model
* @module models/Show
*/
/**
* Show model - create and export the database model for shows
* including all assosiations and classmethods assiciated with this model.
* @memberof module:models/Post
* @param {Object} sequelize description
* @param {Object} DataTypes description
*/
export default function (sequelize, DataTypes) {
const Show = sequelize.define('show', {
title: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
rssFeed: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
logoImage: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
lead: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ''
},
explicitContent: {
type: DataTypes.BOOL,
allowNull: false,
defaultValue: false
},
language: {
type: DataTypes.STRING(5),
allowNull: false,
defaultValue: 'no'
}
}, {
classMethods: {
associate(models) {
Show.hasMany(models.Post, {
onDelete: 'cascade'
});
Show.hasMany(models.Episode, {
onDelete: 'cascade'
});
}
}
}
);
return Show;
}
|
Make sure to return null for anonymous users | package io.quarkus.resteasy.runtime.standalone;
import java.security.Principal;
import javax.ws.rs.core.SecurityContext;
import io.quarkus.security.identity.CurrentIdentityAssociation;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.vertx.http.runtime.security.QuarkusHttpUser;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
public class QuarkusResteasySecurityContext implements SecurityContext {
private final HttpServerRequest request;
private final RoutingContext routingContext;
public QuarkusResteasySecurityContext(HttpServerRequest request, RoutingContext routingContext) {
this.request = request;
this.routingContext = routingContext;
}
@Override
public Principal getUserPrincipal() {
QuarkusHttpUser user = (QuarkusHttpUser) routingContext.user();
if (user == null || user.getSecurityIdentity().isAnonymous()) {
return null;
}
return user.getSecurityIdentity().getPrincipal();
}
@Override
public boolean isUserInRole(String role) {
SecurityIdentity user = CurrentIdentityAssociation.current();
if (role.equals("**")) {
return !user.isAnonymous();
}
return user.hasRole(role);
}
@Override
public boolean isSecure() {
return request.isSSL();
}
@Override
public String getAuthenticationScheme() {
String authorizationValue = request.getHeader("Authorization");
if (authorizationValue == null) {
return null;
} else {
return authorizationValue.split(" ")[0].trim();
}
}
}
| package io.quarkus.resteasy.runtime.standalone;
import java.security.Principal;
import javax.ws.rs.core.SecurityContext;
import io.quarkus.security.identity.CurrentIdentityAssociation;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.vertx.http.runtime.security.QuarkusHttpUser;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
public class QuarkusResteasySecurityContext implements SecurityContext {
private final HttpServerRequest request;
private final RoutingContext routingContext;
public QuarkusResteasySecurityContext(HttpServerRequest request, RoutingContext routingContext) {
this.request = request;
this.routingContext = routingContext;
}
@Override
public Principal getUserPrincipal() {
QuarkusHttpUser user = (QuarkusHttpUser) routingContext.user();
if (user == null) {
return null;
}
return user.getSecurityIdentity().getPrincipal();
}
@Override
public boolean isUserInRole(String role) {
SecurityIdentity user = CurrentIdentityAssociation.current();
if (role.equals("**")) {
return !user.isAnonymous();
}
return user.hasRole(role);
}
@Override
public boolean isSecure() {
return request.isSSL();
}
@Override
public String getAuthenticationScheme() {
String authorizationValue = request.getHeader("Authorization");
if (authorizationValue == null) {
return null;
} else {
return authorizationValue.split(" ")[0].trim();
}
}
}
|
Add check to ensure second argument is an integer | <?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Date;
/**
* Adds support for Padding a String in Twig
*/
class PadStringExtension extends \Twig_Extension
{
/**
* Name of Extension
*
* @return string
*/
public function getName()
{
return 'PadStringExtension';
}
/**
* Available filters
*
* @return array
*/
public function getFilters()
{
return array(
'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
);
}
/**
* Pads string on right or left with given padCharacter until string
* reaches maxLength
*
* @param $value
* @param $padCharacter
* @param $maxLength
* @param bool $padLeft
* @return string
*/
public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
{
if ( ! is_int($maxLength) ) {
throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer');
}
if (function_exists('mb_strlen')) {
$padLength = $maxLength - mb_strlen($value);
} else {
$padLength = $maxLength - strlen($value);
}
if ($padLength <= 0) {
return $value;
}
$padString = str_repeat($padCharacter, $padLength);
if ($padLeft) {
return $padString . $value;
}
return $value . $padString;
}
}
| <?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Date;
/**
* Adds support for Padding a String in Twig
*/
class PadStringExtension extends \Twig_Extension
{
/**
* Name of Extension
*
* @return string
*/
public function getName()
{
return 'PadStringExtension';
}
/**
* Available filters
*
* @return array
*/
public function getFilters()
{
return array(
'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
);
}
/**
* Pads string on right or left with given padCharacter until string
* reaches maxLength
*
* @param $value
* @param $padCharacter
* @param $maxLength
* @param bool $padLeft
* @return string
*/
public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
{
if (function_exists('mb_strlen')) {
$padLength = $maxLength - mb_strlen($value);
} else {
$padLength = $maxLength - strlen($value);
}
if ($padLength <= 0) {
return $value;
}
$padString = str_repeat($padCharacter, $padLength);
if ($padLeft) {
return $padString . $value;
}
return $value . $padString;
}
}
|
Fix user image disaplay on navbar | <div class="f collapse" id="navbar-collapse-main">
<ul class="nav navbar-nav st">
<li>
<a href="#">Profile</a>
</li>
<li>
<a data-toggle="modal" href="index.html#msgModal">Messages</a>
</li>
</ul>
<ul class="nav navbar-nav oh ald st">
<li>
<a class="g" href="#">
<i class="glyphicon glyphicon-bell"></i>
</a>
</li>
<li>
<button class="cg fm oy ank" data-toggle="popover">
<img class="cu" src="{{ Auth::user()->image_uri }}">
</button>
</li>
</ul>
<form class="ox oh i" role="search">
<div class="et">
<input type="text" class="form-control" data-action="grow" placeholder="Search">
</div>
</form>
<ul class="nav navbar-nav su sv sw">
<li><a href="#">Profile</a></li>
<li><a href="#">Notifications</a></li>
<li><a data-toggle="modal" href="index.html#msgModal">Messages</a></li>
<li><a href="{{ url('/logout') }}">Logout</a></li>
</ul>
<ul class="nav navbar-nav hidden">
<li><a href="{{ url('/logout') }}">Logout</a></li>
</ul>
</div> | <div class="f collapse" id="navbar-collapse-main">
<ul class="nav navbar-nav st">
<li>
<a href="#">Profile</a>
</li>
<li>
<a data-toggle="modal" href="index.html#msgModal">Messages</a>
</li>
</ul>
<ul class="nav navbar-nav oh ald st">
<li>
<a class="g" href="#">
<i class="glyphicon glyphicon-bell"></i>
</a>
</li>
<li>
<button class="cg fm oy ank" data-toggle="popover">
<img class="cu" src="{{ $user->image_uri }}">
</button>
</li>
</ul>
<form class="ox oh i" role="search">
<div class="et">
<input type="text" class="form-control" data-action="grow" placeholder="Search">
</div>
</form>
<ul class="nav navbar-nav su sv sw">
<li><a href="#">Profile</a></li>
<li><a href="#">Notifications</a></li>
<li><a data-toggle="modal" href="index.html#msgModal">Messages</a></li>
<li><a href="{{ url('/logout') }}">Logout</a></li>
</ul>
<ul class="nav navbar-nav hidden">
<li><a href="{{ url('/logout') }}">Logout</a></li>
</ul>
</div> |
Bring back the post button. | Hummingbird.PostCommentComponent = Ember.Component.extend({
classNames: ["status-update-panel"],
didInsertElement: function() {
var self = this;
this.$(".status-form").focus(function() {
self.$(".status-form").autosize({append: "\n"});
self.$(".panel-footer").slideDown(200);
});
this.$(".status-form").blur(function() {
if (self.$(".status-form").val().replace(/\s/g, '').length === 0) {
self.$(".status-form").val('');
self.$(".panel-footer").slideUp(200, function() {
self.$(".status-form").trigger("autosize.destroy");
});
}
});
},
willClearRender: function() {
this.$(".status-form").trigger("autosize.destroy");
},
actions: {
submitPost: function() {
var _this = this
, newPost = this.get('newPost');
if (newPost.length > 0) {
this.set('inFlight', true);
return Ember.$.ajax({
url: "/users/" + _this.get('username') + "/comment.json",
data: { comment: newPost },
type: "POST",
success: function (payload) {
_this.setProperties({
newPost: "",
inFlight: false
});
window.location.href = window.location.href;
},
error: function () {
alert("Failed to save comment");
}
});
}
}
}
});
| Hummingbird.PostCommentComponent = Ember.Component.extend({
classNames: ["status-update-panel"],
didInsertElement: function() {
this.$(".status-form").focus(function() {
self.$(".status-form").autosize({append: "\n"});
self.$(".panel-footer").slideDown(200);
});
this.$(".status-form").blur(function() {
if (self.$(".status-form").val().replace(/\s/g, '').length === 0) {
self.$(".status-form").val('');
self.$(".panel-footer").slideUp(200, function() {
self.$(".status-form").trigger("autosize.destroy");
});
}
});
},
willClearRender: function() {
this.$(".status-form").trigger("autosize.destroy");
},
actions: {
submitPost: function() {
var _this = this
, newPost = this.get('newPost');
if (newPost.length > 0) {
this.set('inFlight', true);
return Ember.$.ajax({
url: "/users/" + _this.get('username') + "/comment.json",
data: { comment: newPost },
type: "POST",
success: function (payload) {
_this.setProperties({
newPost: "",
inFlight: false
});
window.location.href = window.location.href;
},
error: function () {
alert("Failed to save comment");
}
});
}
}
}
});
|
Add debug to handle date case (need to test). | angular.module('materialscommons').directive('processSettings', processSettingsDirective);
function processSettingsDirective() {
return {
restrict: 'E',
scope: {
settings: '=',
taskId: '=',
templateId: '=',
attribute: '='
},
controller: ProcessSettingsDirectiveController,
controllerAs: 'ctrl',
bindToController: true,
templateUrl: 'app/project/processes/process/create/components/process-settings.html'
}
}
/*@ngInject*/
function ProcessSettingsDirectiveController(experimentsService, toast, $stateParams) {
var ctrl = this;
ctrl.datePickerOptions = {
formatYear: 'yy',
startingDay: 1
};
ctrl.openDatePicker = openDatePicker;
ctrl.updateSettingProperty = (property) => {
if (!property.value) {
return;
}
if (property._type === "date") {
console.dir(property);
return;
}
property.setup_attribute = ctrl.attribute;
let propertyArgs = {
template_id: ctrl.templateId,
properties: [property]
};
experimentsService.updateTaskTemplateProperties($stateParams.project_id, $stateParams.experiment_id, ctrl.taskId, propertyArgs)
.then(
() => null,
() => toast.error('Unable to update property')
);
};
///////////////////////////////////////
function openDatePicker($event, prop) {
$event.preventDefault();
$event.stopPropagation();
prop.opened = true;
}
} | angular.module('materialscommons').directive('processSettings', processSettingsDirective);
function processSettingsDirective() {
return {
restrict: 'E',
scope: {
settings: '=',
taskId: '=',
templateId: '=',
attribute: '='
},
controller: ProcessSettingsDirectiveController,
controllerAs: 'ctrl',
bindToController: true,
templateUrl: 'app/project/processes/process/create/components/process-settings.html'
}
}
/*@ngInject*/
function ProcessSettingsDirectiveController(experimentsService, toast, $stateParams) {
var ctrl = this;
ctrl.datePickerOptions = {
formatYear: 'yy',
startingDay: 1
};
ctrl.openDatePicker = openDatePicker;
ctrl.updateSettingProperty = (property) => {
if (!property.value) {
return;
}
property.setup_attribute = ctrl.attribute;
let propertyArgs = {
template_id: ctrl.templateId,
properties: [property]
};
experimentsService.updateTaskTemplateProperties($stateParams.project_id, $stateParams.experiment_id, ctrl.taskId, propertyArgs)
.then(
() => null,
() => toast.error('Unable to update property')
);
};
///////////////////////////////////////
function openDatePicker($event, prop) {
$event.preventDefault();
$event.stopPropagation();
prop.opened = true;
}
} |
Update TreeTime dep link now that the py3 branch is merged | import os
from setuptools import setup
setup(
name = "augur",
version = "0.1.0",
author = "nextstrain developers",
author_email = "[email protected], [email protected]",
description = ("Pipelines for real-time phylogenetic analysis"),
license = "MIT",
keywords = "nextstrain, molecular epidemiology",
url = "https://github.com/nextstrain/augur",
packages=['augur'],
install_requires = [
"biopython >=1.69, ==1.*",
"boto >=2.38, ==2.*",
"cvxopt >=1.1.8, ==1.1.*",
"ipdb >=0.10.1, ==0.10.*",
"matplotlib >=2.0, ==2.*",
"pandas >=0.16.2, <0.18.0",
"pytest >=3.2.1, ==3.*",
"seaborn >=0.6.0, ==0.6.*",
"tox >=2.8.2, ==2.*",
"treetime ==0.4.0"
],
dependency_links = [
"https://api.github.com/repos/neherlab/treetime/tarball/v0.4.0#egg=treetime-0.4.0"
],
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Science",
"License :: OSI Approved :: MIT License",
],
scripts=['bin/augur']
)
| import os
from setuptools import setup
setup(
name = "augur",
version = "0.1.0",
author = "nextstrain developers",
author_email = "[email protected], [email protected]",
description = ("Pipelines for real-time phylogenetic analysis"),
license = "MIT",
keywords = "nextstrain, molecular epidemiology",
url = "https://github.com/nextstrain/augur",
packages=['augur'],
install_requires = [
"biopython >=1.69, ==1.*",
"boto >=2.38, ==2.*",
"cvxopt >=1.1.8, ==1.1.*",
"ipdb >=0.10.1, ==0.10.*",
"matplotlib >=2.0, ==2.*",
"pandas >=0.16.2, <0.18.0",
"pytest >=3.2.1, ==3.*",
"seaborn >=0.6.0, ==0.6.*",
"tox >=2.8.2, ==2.*",
"treetime ==0.4.0"
],
dependency_links = [
"https://api.github.com/repos/neherlab/treetime/tarball/py3#egg=treetime-0.4.0"
],
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Science",
"License :: OSI Approved :: MIT License",
],
scripts=['bin/augur']
)
|
Check if it is None before continuing | from discord.ext import commands
from .utils import checks
import asyncio
import discord
import web.wsgi
from django.utils import timezone
from django.db import models
from django.utils import timezone
from gaming.models import DiscordUser, Game, GameUser, Server, Role, GameSearch, Channel
class GamingTasks:
def __init__(self, bot, task):
self.bot = bot
self.task = task
def __unload(self):
self.task.cancel()
@asyncio.coroutine
def run_tasks(bot):
while True:
yield from asyncio.sleep(15)
channels = Channel.objects.filter(private=False, expire_date__lte=timezone.now(), deleted=False)
if channels.count() >= 1:
for channel in channels:
if channel is None:
continue
try:
c = bot.get_channel(channel.channel_id)
if c is not None:
yield from bot.delete_channel(c)
except Exception as e:
# Channel no longer exists on server
print(e)
finally:
channel.deleted = True
channel.save()
yield from asyncio.sleep(1)
else:
# No channels found to be deleted
pass
def setup(bot):
loop = asyncio.get_event_loop()
task = loop.create_task(GamingTasks.run_tasks(bot))
bot.add_cog(GamingTasks(bot, task))
| from discord.ext import commands
from .utils import checks
import asyncio
import discord
import web.wsgi
from django.utils import timezone
from django.db import models
from django.utils import timezone
from gaming.models import DiscordUser, Game, GameUser, Server, Role, GameSearch, Channel
class GamingTasks:
def __init__(self, bot, task):
self.bot = bot
self.task = task
def __unload(self):
self.task.cancel()
@asyncio.coroutine
def run_tasks(bot):
while True:
yield from asyncio.sleep(15)
channels = Channel.objects.filter(private=False, expire_date__lte=timezone.now(), deleted=False)
if channels.count() >= 1:
for channel in channels:
try:
c = bot.get_channel(channel.channel_id)
yield from bot.delete_channel(c)
except Exception as e:
# Channel no longer exists on server
print(e)
finally:
channel.deleted = True
channel.save()
yield from asyncio.sleep(1)
else:
# No channels found to be deleted
pass
def setup(bot):
loop = asyncio.get_event_loop()
task = loop.create_task(GamingTasks.run_tasks(bot))
bot.add_cog(GamingTasks(bot, task))
|
Use proper index in indexer. | <?php
namespace Gielfeldt\TransactionalPHP;
/**
* Class Indexer
*
* @package Gielfeldt\TransactionalPHP
*/
class Indexer
{
/**
* @var int[]
*/
protected $index = [];
/**
* @var Connection
*/
protected $connection;
/**
* Indexer constructor.
*
* @param Connection $connection
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
/**
* Get connection.
*
* @return Connection
*/
public function getConnection() {
return $this->connection;
}
/**
* Index operation.
*
* @param string $key
* The key to index undeer.
* @param Operation|null $operation
* The operation to index.
*/
public function index($key, Operation $operation = null)
{
if ($operation) {
$this->index[$key][$operation->idx($this->connection)] = $operation;
}
}
/**
* Lookup operation.
*
* @param string $key
* The key to look up.
*
* @return array
* Operations.
*/
public function lookup($key)
{
return isset($this->index[$key]) ? $this->index[$key] : [];
}
}
| <?php
namespace Gielfeldt\TransactionalPHP;
/**
* Class Indexer
*
* @package Gielfeldt\TransactionalPHP
*/
class Indexer
{
/**
* @var int[]
*/
protected $index = [];
/**
* @var Connection
*/
protected $connection;
/**
* Indexer constructor.
*
* @param Connection $connection
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
/**
* Get connection.
*
* @return Connection
*/
public function getConnection() {
return $this->connection;
}
/**
* Index operation.
*
* @param string $key
* The key to index undeer.
* @param Operation|null $operation
* The operation to index.
*/
public function index($key, Operation $operation = null)
{
if ($operation) {
$this->index[$key][] = $operation;
}
}
/**
* Lookup operation.
*
* @param string $key
* The key to look up.
*
* @return array
* Operations.
*/
public function lookup($key)
{
return isset($this->index[$key]) ? $this->index[$key] : [];
}
}
|
Fix the bug people unable to recommend an article. | 'use strict';
// TODO(mkhatib): Write tests.
angular.module('webClientApp')
.directive('recommendButton', ['$rootScope', 'ArticleRecommendation', function ($rootScope, ArticleRecommendation) {
var getUserRecommendation = function(article, recommendations) {
if ($rootScope.currentUser) {
for (var i=0; i < recommendations.length ; i++) {
if ($rootScope.isOwner($rootScope.currentUser, recommendations[i])) {
return recommendations[i];
}
}
}
return null;
};
return {
templateUrl: '/views/directives/recommendButton.html',
restrict: 'A',
scope: {
article: '='
},
link: function (scope, element) {
scope.$watch('article', function (newValue) {
if (!newValue) {
return;
}
var userRecommendation = null;
ArticleRecommendation.query({
'articleId': scope.article.id
}, function (recommendations) {
userRecommendation = getUserRecommendation(scope.article, recommendations);
scope.isRecommended = !!userRecommendation;
});
element.on('click', function () {
if (scope.isRecommended) {
ArticleRecommendation.delete({
'articleId': scope.article.id,
'recommendationId': userRecommendation.id
});
/* jshint camelcase: false */
scope.article.recommendations_count--;
scope.isRecommended = false;
} else {
ArticleRecommendation.save({'articleId': scope.article.id},
function (recommendation) {
userRecommendation = recommendation;
});
/* jshint camelcase: false */
scope.article.recommendations_count++;
scope.isRecommended = true;
}
});
});
}
};
}]);
| 'use strict';
// TODO(mkhatib): Write tests.
angular.module('webClientApp')
.directive('recommendButton', ['ArticleRecommendation', function (ArticleRecommendation) {
var getUserRecommendation = function(article, recommendations) {
for (var i=0; i < recommendations.length ; i++) {
if (article.id === recommendations[i].article.id) {
return recommendations[i];
}
}
return null;
};
return {
templateUrl: '/views/directives/recommendButton.html',
restrict: 'A',
scope: {
article: '='
},
link: function (scope, element) {
scope.$watch('article', function (newValue) {
if (!newValue) {
return;
}
var userRecommendation = null;
ArticleRecommendation.query({
'articleId': scope.article.id
}, function (recommendations) {
userRecommendation = getUserRecommendation(scope.article, recommendations);
scope.isRecommended = !!userRecommendation;
});
element.on('click', function () {
if (scope.isRecommended) {
ArticleRecommendation.delete({
'articleId': scope.article.id,
'recommendationId': userRecommendation.id
});
/* jshint camelcase: false */
scope.article.recommendations_count--;
scope.isRecommended = false;
} else {
ArticleRecommendation.save({'articleId': scope.article.id},
function (recommendation) {
userRecommendation = recommendation;
});
/* jshint camelcase: false */
scope.article.recommendations_count++;
scope.isRecommended = true;
}
});
});
}
};
}]);
|
Move cursor left on function completion. | 'use babel';
import {filter} from 'fuzzaldrin';
import commands from './commands';
import variables from './variables';
export const selector = '.source.cmake';
export const disableForSelector = '.source.cmake .comment';
export const inclusionPriority = 1;
function existy(value) {
return value != null;
}
function dispatch() {
var funs = arguments;
return function() {
for (var f of funs) {
var ret = f.apply(null, arguments);
if (existy(ret)) {
return ret;
}
}
};
}
function variables_suggestions(prefix) {
return filter(variables, prefix.toUpperCase()).map((variable) => ({
text: variable,
displayText: variable,
type: 'variable'
}));
}
function commands_suggestions(prefix) {
return filter(commands, prefix.toLowerCase()).map((command) => ({
text: `${command}()`,
displayText: command,
type: 'function'
}));
}
const suggest = dispatch(
(prefix, scope_descriptor) => {
if (scope_descriptor.scopes.length > 1) {
return variables_suggestions(prefix);
}
},
(prefix) => commands_suggestions(prefix)
)
export function getSuggestions({prefix, scopeDescriptor: scope_descriptor}) {
return suggest(prefix, scope_descriptor);
}
export function onDidInsertSuggestion({editor, suggestion}) {
if (suggestion && suggestion.type === 'function') {
editor.moveLeft(1);
}
}
| 'use babel';
import {filter} from 'fuzzaldrin';
import commands from './commands';
import variables from './variables';
export const selector = '.source.cmake';
export const disableForSelector = '.source.cmake .comment';
export const inclusionPriority = 1;
function existy(value) {
return value != null;
}
function dispatch() {
var funs = arguments;
return function() {
for (var f of funs) {
var ret = f.apply(null, arguments);
if (existy(ret)) {
return ret;
}
}
};
}
function variables_suggestions(prefix) {
return filter(variables, prefix.toUpperCase()).map((variable) => ({
text: variable,
displayText: variable,
type: 'variable'
}));
}
function commands_suggestions(prefix) {
return filter(commands, prefix.toLowerCase()).map((command) => ({
text: `${command}()`,
displayText: command,
type: 'function'
}));
}
const suggest = dispatch(
(prefix, scope_descriptor) => {
if (scope_descriptor.scopes.length > 1) {
return variables_suggestions(prefix);
}
},
(prefix) => commands_suggestions(prefix)
)
export function getSuggestions({prefix, scopeDescriptor: scope_descriptor}) {
return suggest(prefix, scope_descriptor);
}
|
Allow only one simultaneous command. | $(document).ready(function () {
$.each($(".lightcontrol-btn"), function() {
$(this).data("original-color", $(this).css("background-color"));
$(this).data("original-classes", $(this).children().attr("class"));
$(this).on("click", function () {
var main_elem = $(this);
if (main_elem.data("running")) {
return;
}
main_elem.data("running", true);
var command = main_elem.data("command");
var group = main_elem.data("group") || "0";
main_elem.animate({backgroundColor: "#ffffff"}, 250);
main_elem.children().removeClass().addClass("fa fa-spinner fa-spin")
function animate_success(icon) {
main_elem.data("running", false);
main_elem.children().removeClass().addClass("fa fa-"+icon);
var restore_classes = function () {
main_elem.children().removeClass().addClass(main_elem.data("original-classes"));
main_elem.stop().animate({backgroundColor: main_elem.data("original-color")}, 1000);
}
setTimeout(restore_classes, 2000);
}
$.ajax({
url: "/homecontroller/lightcontrol/control/"+command+"/"+group,
success: function () {
animate_success("check");
},
error: function () {
animate_success("times");
}
});
});
});
});
| $(document).ready(function () {
$.each($(".lightcontrol-btn"), function() {
$(this).data("original-color", $(this).css("background-color"));
$(this).on("click", function () {
var main_elem = $(this);
var original_classes = main_elem.children().attr("class");
var command = main_elem.data("command");
var group = main_elem.data("group") || "0";
main_elem.animate({backgroundColor: "#ffffff"}, 250);
main_elem.children().removeClass().addClass("fa fa-spinner fa-spin")
function animate_success(icon) {
main_elem.children().removeClass().addClass("fa fa-"+icon);
var restore_classes = function () {
main_elem.children().removeClass().addClass(original_classes);
main_elem.stop().animate({backgroundColor: main_elem.data("original-color")}, 1000);
}
setTimeout(restore_classes, 2000);
}
$.ajax({
url: "/homecontroller/lightcontrol/control/"+command+"/"+group,
success: function () {
animate_success("check");
},
error: function () {
animate_success("times");
}
});
});
});
});
|
Convert Non-strict to strict equality checking
Convert non-strict equality checking, using `==`, to the strict version, using `===`. | var command = {
command: "console",
description:
"Run a console with contract abstractions and commands available",
builder: {},
help: {
usage: "truffle console [--network <name>] [--verbose-rpc]",
options: [
{
option: "--network <name>",
description:
"Specify the network to use. Network name must exist in the configuration."
},
{
option: "--verbose-rpc",
description:
"Log communication between Truffle and the Ethereum client."
}
]
},
run: function(options, done) {
var Config = require("truffle-config");
var Console = require("../console");
var Environment = require("../environment");
var config = Config.detect(options);
// This require a smell?
var commands = require("./index");
var excluded = ["console", "init", "watch", "develop"];
var available_commands = Object.keys(commands).filter(function(name) {
return excluded.indexOf(name) === -1;
});
var console_commands = {};
available_commands.forEach(function(name) {
console_commands[name] = commands[name];
});
Environment.detect(config, function(err) {
if (err) return done(err);
var c = new Console(
console_commands,
config.with({
noAliases: true
})
);
c.start(done);
});
}
};
module.exports = command;
| var command = {
command: "console",
description:
"Run a console with contract abstractions and commands available",
builder: {},
help: {
usage: "truffle console [--network <name>] [--verbose-rpc]",
options: [
{
option: "--network <name>",
description:
"Specify the network to use. Network name must exist in the configuration."
},
{
option: "--verbose-rpc",
description:
"Log communication between Truffle and the Ethereum client."
}
]
},
run: function(options, done) {
var Config = require("truffle-config");
var Console = require("../console");
var Environment = require("../environment");
var config = Config.detect(options);
// This require a smell?
var commands = require("./index");
var excluded = ["console", "init", "watch", "develop"];
var available_commands = Object.keys(commands).filter(function(name) {
return excluded.indexOf(name) == -1;
});
var console_commands = {};
available_commands.forEach(function(name) {
console_commands[name] = commands[name];
});
Environment.detect(config, function(err) {
if (err) return done(err);
var c = new Console(
console_commands,
config.with({
noAliases: true
})
);
c.start(done);
});
}
};
module.exports = command;
|
Make server respond with the list of dishes | var db = require('./db');
var bluebird = require('bluebird'); //promise library, will have to think more about it
var helpers = require('./helpers.js')
module.exports = {
'/': {
get: function (req, res) {
res.redirect('/explore');
},
post: function (req, res) {
}
},
explore: {
get: function (req, res) { //This means the user wants to get a new picture;
// have to send an api request to Yummly;
// if Yummly responds with an error, send a request to our database
// when receive the response (from Yummly/database):
// 1) parse the response
// 2) serve the picture to the user as the response;
// 3) save the dish to the dishes table in the database;
helpers.getRecipes(res);
//res.json("Hello from Thunder");
},
post: function (req, res) { //This means the user decided whether he likes the dish or not;
// if he likes it, add the dish to the longlist object.
// save the information to the "join" table of the database;
// do the same thing that you did with the get request;
// alternatively, create the "longlist object" at the client side;
}
},
list: {
get: function (req, res) { // This means the user wants to see the longlist;
// serve the longlist object for this session;
},
post: function (req, res) {
// never happens, not applicable;
}
}
};
| var db = require('./db');
var bluebird = require('bluebird'); //promise library, will have to think more about it
var helpers = require('./helpers.js')
module.exports = {
'/': {
get: function (req, res) {
res.redirect('/pictures');
},
post: function (req, res) {
}
},
pictures: {
get: function (req, res) { //This means the user wants to get a new picture;
// have to send an api request to Yummly;
// if Yummly responds with an error, send a request to our database
// when receive the response (from Yummly/database):
// 1) parse the response
// 2) serve the picture to the user as the response;
// 3) save the dish to the dishes table in the database;
helpers.getRecipes(res);
//res.json("Hello from Thunder");
},
post: function (req, res) { //This means the user decided whether he likes the dish or not;
// if he likes it, add the dish to the longlist object.
// save the information to the "join" table of the database;
// do the same thing that you did with the get request;
// alternatively, create the "longlist object" at the client side;
}
},
longlist: {
get: function (req, res) { // This means the user wants to see the longlist;
// serve the longlist object for this session;
},
post: function (req, res) {
// never happens, not applicable;
}
}
};
|
Add on_delete args to CMS plugin migration for Django 2 support | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import cms
from django.db import migrations, models
from pkg_resources import parse_version as V
# Django CMS 3.3.1 is oldest release where the change affects.
# Refs https://github.com/divio/django-cms/commit/871a164
if V(cms.__version__) >= V('3.3.1'):
field_kwargs = {'related_name': 'form_designer_form_cmsformdefinition'}
else:
field_kwargs = {}
class Migration(migrations.Migration):
dependencies = [
('cms', '0001_initial'),
('form_designer', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CMSFormDefinition',
fields=[
('cmsplugin_ptr',
models.OneToOneField(
serialize=False,
auto_created=True,
primary_key=True,
to='cms.CMSPlugin',
parent_link=True,
on_delete=models.CASCADE,
**field_kwargs)),
('form_definition',
models.ForeignKey(
verbose_name='form',
to='form_designer.FormDefinition',
on_delete=models.CASCADE)),
],
options={
'abstract': False,
},
bases=(
'cms.cmsplugin',
),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import cms
from django.db import migrations, models
from pkg_resources import parse_version as V
# Django CMS 3.3.1 is oldest release where the change affects.
# Refs https://github.com/divio/django-cms/commit/871a164
if V(cms.__version__) >= V('3.3.1'):
field_kwargs = {'related_name': 'form_designer_form_cmsformdefinition'}
else:
field_kwargs = {}
class Migration(migrations.Migration):
dependencies = [
('cms', '0001_initial'),
('form_designer', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CMSFormDefinition',
fields=[
('cmsplugin_ptr',
models.OneToOneField(
serialize=False,
auto_created=True,
primary_key=True,
to='cms.CMSPlugin',
parent_link=True,
**field_kwargs)),
('form_definition',
models.ForeignKey(
verbose_name='form',
to='form_designer.FormDefinition')),
],
options={
'abstract': False,
},
bases=(
'cms.cmsplugin',
),
),
]
|
Make color easier to read | import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(self, obj):
object_class = obj.__class__.__name__
method_name = self.draw_methods.get(object_class, None)
if method_name:
method = getattr(self, method_name)
method(obj)
def draw_car(self, car):
coord = car.coordinates
acceleration_rate = car.acceleration_rate
rect = pygame.Rect(coord.x, coord.y,
self.car_width, self.car_width)
# Change car color depending on acceleration
if acceleration_rate > 0:
color = (0, 0, 255)
else:
color = (255, 0, 0)
pygame.draw.rect(self.surface, color, rect, 0)
def draw_road(self, road):
pointlist = road.pointlist()
closed = False
pygame.draw.lines(self.surface, self.road_color, closed, pointlist,
self.road_width)
| import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(self, obj):
object_class = obj.__class__.__name__
method_name = self.draw_methods.get(object_class, None)
if method_name:
method = getattr(self, method_name)
method(obj)
def draw_car(self, car):
coord = car.coordinates
acceleration_rate = car.acceleration_rate
rect = pygame.Rect(coord.x, coord.y,
self.car_width, self.car_width)
# Change car color depending on acceleration
if acceleration_rate > 0:
rate = min(1, acceleration_rate)
color = (0, 0, int(rate * 255))
else:
rate = max(-1, acceleration_rate)
color = (int(-rate * 255), 0, 0)
pygame.draw.rect(self.surface, color, rect, 0)
def draw_road(self, road):
pointlist = road.pointlist()
closed = False
pygame.draw.lines(self.surface, self.road_color, closed, pointlist,
self.road_width)
|
Add ability to convert JS interpolater to an array
This is used when writing interpolator values to the python server | class Interpolator {
constructor() {
this.data = [];
}
addIndexValue(index, value) {
this.data.push({index: index, value: value});
// make sure items are in ascdending order by index
//this.data.sort((a, b) => a.index - b.index);
}
valueAtIndex(target_index) {
if (target_index < this.data[0].index || this.data[this.data.length - 1].index < target_index) {
return null;
}
else {
var start = null
var end = null;
for (var i = 0; i < this.data.length; i++) {
let current = this.data[i];
if (current.index === target_index) {
return current.value;
}
else {
if (current.index <= target_index) {
start = current;
}
else if (target_index < current.index) {
end = current;
break;
}
}
}
let index_delta = end.index - start.index;
let percent = (target_index - start.index) / index_delta;
let value_delta = end.value - start.value;
return start.value + value_delta * percent;
}
}
to_array() {
return this.data.reduce((accum, item) => {
accum.push(item.index);
accum.push(item.value);
return accum;
}, []);
}
}
| class Interpolator {
constructor() {
this.data = [];
}
addIndexValue(index, value) {
this.data.push({index: index, value: value});
// make sure items are in ascdending order by index
//this.data.sort((a, b) => a.index - b.index);
}
valueAtIndex(target_index) {
if (target_index < this.data[0].index || this.data[this.data.length - 1].index < target_index) {
return null;
}
else {
var start = null
var end = null;
for (var i = 0; i < this.data.length; i++) {
let current = this.data[i];
if (current.index === target_index) {
return current.value;
}
else {
if (current.index <= target_index) {
start = current;
}
else if (target_index < current.index) {
end = current;
break;
}
}
}
let index_delta = end.index - start.index;
let percent = (target_index - start.index) / index_delta;
let value_delta = end.value - start.value;
return start.value + value_delta * percent;
}
}
}
|
Add requests to the requirements | #!/usr/bin/env python
import os
import sys
from setuptools import setup
if "publish" in sys.argv[-1]:
os.system("python setup.py sdist upload -r pypi")
sys.exit()
elif "testpublish" in sys.argv[-1]:
os.system("python setup.py sdist upload -r pypitest")
sys.exit()
# Load the __version__ variable without importing the package
exec(open('k2mosaic/version.py').read())
entry_points = {'console_scripts': ['k2mosaic = k2mosaic.k2mosaic:k2mosaic_main']}
setup(name='k2mosaic',
version=__version__,
description='Creates a mosaic of all K2 target pixel files '
'in a given channel during a single cadence.',
author='Geert Barentsen',
author_email='[email protected]',
url='https://github.com/barentsen/k2mosaic',
packages=['k2mosaic'],
package_data={'k2mosaic': ['data/*.csv']},
install_requires=['astropy', 'numpy', 'pandas', 'tqdm', 'requests'],
entry_points=entry_points,
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Astronomy",
],
)
| #!/usr/bin/env python
import os
import sys
from setuptools import setup
if "publish" in sys.argv[-1]:
os.system("python setup.py sdist upload -r pypi")
sys.exit()
elif "testpublish" in sys.argv[-1]:
os.system("python setup.py sdist upload -r pypitest")
sys.exit()
# Load the __version__ variable without importing the package
exec(open('k2mosaic/version.py').read())
entry_points = {'console_scripts': ['k2mosaic = k2mosaic.k2mosaic:k2mosaic_main']}
setup(name='k2mosaic',
version=__version__,
description='Creates a mosaic of all K2 target pixel files '
'in a given channel during a single cadence.',
author='Geert Barentsen',
author_email='[email protected]',
url='https://github.com/barentsen/k2mosaic',
packages=['k2mosaic'],
package_data={'k2mosaic': ['data/*.csv']},
install_requires=['astropy', 'numpy', 'pandas', 'tqdm'],
entry_points=entry_points,
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Astronomy",
],
)
|
Remove unused module namespace from require config. | (function () {
'use strict';
// Initialise RequireJS module loader
require.config({
urlArgs: 'm=' + (new Date()).getTime(),
baseUrl: '/app/',
paths: {
// RequireJS extensions
text: '../lib/text/text',
// Vendor libraries
knockout: '../lib/knockout/dist/knockout.debug',
lodash: '../lib/lodash/lodash',
jquery: '../lib/jquery/dist/jquery',
bootstrap: '../lib/bootstrap/dist/js/bootstrap',
typeahead: '../lib/typeahead.js/dist/typeahead.jquery',
bloodhound: '../lib/typeahead.js/dist/bloodhound',
page: '../lib/page/page',
// Application modules
config: 'config/',
services: 'services/',
ui: 'ui/',
util: 'util/'
},
shim: {
bloodhound: {
exports: 'Bloodhound'
},
typeahead: {
deps: [ 'jquery' ]
}
}
});
// Boot the application
require([ 'jquery' ], function () {
require([ 'bootstrap' ], function () {
var environment = 'development';
if (environment !== 'production' && console && typeof console.log === 'function') {
console.log('Running in "' + environment + '" environment');
}
require([ 'config/env/' + environment, 'util/router' ], function (configure, router) {
configure();
router();
});
});
});
}());
| (function () {
'use strict';
// Initialise RequireJS module loader
require.config({
urlArgs: 'm=' + (new Date()).getTime(),
baseUrl: '/app/',
paths: {
// RequireJS extensions
text: '../lib/text/text',
// Vendor libraries
knockout: '../lib/knockout/dist/knockout.debug',
lodash: '../lib/lodash/lodash',
jquery: '../lib/jquery/dist/jquery',
bootstrap: '../lib/bootstrap/dist/js/bootstrap',
typeahead: '../lib/typeahead.js/dist/typeahead.jquery',
bloodhound: '../lib/typeahead.js/dist/bloodhound',
page: '../lib/page/page',
// Application modules
config: 'config/',
models: 'models/',
services: 'services/',
ui: 'ui/',
util: 'util/'
},
shim: {
bloodhound: {
exports: 'Bloodhound'
},
typeahead: {
deps: [ 'jquery' ]
}
}
});
// Boot the application
require([ 'jquery' ], function () {
require([ 'bootstrap' ], function () {
var environment = 'development';
if (environment !== 'production' && console && typeof console.log === 'function') {
console.log('Running in "' + environment + '" environment');
}
require([ 'config/env/' + environment, 'util/router' ], function (configure, router) {
configure();
router();
});
});
});
}());
|
Allow clicking anywhere in row to toggle checkbox | <table class="table table-striped">
<tbody>
@foreach($lanGames as $lanGame)
@can('view', $lanGame)
@php
if (Auth::user()) {
$voted = $lanGame->votes->where('user_id',Auth::user()->id)->count();
} else {
$voted = false;
}
@endphp
<tr class="{{ $voted ? 'bg-primary' : '' }}" onclick="document.getElementById('lan_game_{{ $lanGame->id }}').checked = ! document.getElementById('lan_game_{{ $lanGame->id }}').checked">
<td>
<form>
<div class="custom-control custom-checkbox">
<input type="checkbox"
class="custom-control-input"
id="lan_game_{{ $lanGame->id }}"
{{ $voted ? 'checked' : '' }}
>
<label class="custom-control-label" for="lan_game_{{ $lanGame->id }}">{{ $lanGame->game_name }}</label>
</div>
</form>
</td>
<td>
@foreach($lanGame->votes as $vote)
@include('pages.users.partials.avatar', ['user' => $vote->user])
@endforeach
</td>
<td class="text-right pr-0">
@canany(['update', 'delete'], $lanGame)
@include('pages.lan-games.partials.actions-dropdown', ['lanGame' => $lanGame])
@endcanany
</td>
</tr>
@endcan
@endforeach
</tbody>
</table>
| <table class="table table-striped">
<tbody>
@foreach($lanGames as $lanGame)
@can('view', $lanGame)
@php
if (Auth::user()) {
$voted = $lanGame->votes->where('user_id',Auth::user()->id)->count();
} else {
$voted = false;
}
@endphp
<tr class="{{ $voted ? 'bg-primary' : '' }}">
<td>
<form>
<div class="custom-control custom-checkbox">
<input type="checkbox"
class="custom-control-input"
id="lan_game_{{ $lanGame->id }}"
{{ $voted ? 'checked' : '' }}
>
<label class="custom-control-label" for="lan_game_{{ $lanGame->id }}">{{ $lanGame->game_name }}</label>
</div>
</form>
</td>
<td>
@foreach($lanGame->votes as $vote)
@include('pages.users.partials.avatar', ['user' => $vote->user])
@endforeach
</td>
<td class="text-right pr-0">
@canany(['update', 'delete'], $lanGame)
@include('pages.lan-games.partials.actions-dropdown', ['lanGame' => $lanGame])
@endcanany
</td>
</tr>
@endcan
@endforeach
</tbody>
</table>
|
Add redirect_uri as config parameter | VK = {};
VK.requestCredential = function (options, credentialRequestCompleteCallback) {
if (!credentialRequestCompleteCallback && typeof options === 'function') {
credentialRequestCompleteCallback = options;
options = {};
}
var config = ServiceConfiguration.configurations.findOne({service: 'vk'});
if (!config) {
credentialRequestCompleteCallback && credentialRequestCompleteCallback(new ServiceConfiguration.ConfigError("Service not configured"));
return;
}
var credentialToken = Random.id();
var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent);
var display = mobile ? 'touch' : 'popup';
var scope = '';
if (config.scope) {
scope = config.scope;
if (options && options.requestPermissions) {
scope = scope + ',';
}
}
if (options && options.requestPermissions) {
scope = scope + options.requestPermissions.join(',');
}
var loginUrl =
'https://oauth.vk.com/authorize' +
'?client_id=' + config.appId +
'&scope=' + scope +
'&redirect_uri=' + config.redirectUri || Meteor.absoluteUrl('_oauth/vk?close=close', {replaceLocalhost: false}) +
'&response_type=code' +
'&display=' + display +
'&state=' + credentialToken;
Oauth.initiateLogin(credentialToken, loginUrl, credentialRequestCompleteCallback);
};
| VK = {};
VK.requestCredential = function (options, credentialRequestCompleteCallback) {
if (!credentialRequestCompleteCallback && typeof options === 'function') {
credentialRequestCompleteCallback = options;
options = {};
}
var config = ServiceConfiguration.configurations.findOne({service: 'vk'});
if (!config) {
credentialRequestCompleteCallback && credentialRequestCompleteCallback(new ServiceConfiguration.ConfigError("Service not configured"));
return;
}
var credentialToken = Random.id();
var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent);
var display = mobile ? 'touch' : 'popup';
var scope = '';
if (config.scope) {
scope = config.scope;
if (options && options.requestPermissions) {
scope = scope + ',';
}
}
if (options && options.requestPermissions) {
scope = scope + options.requestPermissions.join(',');
}
var loginUrl =
'https://oauth.vk.com/authorize' +
'?client_id=' + config.appId +
'&scope=' + scope +
'&redirect_uri=' + Meteor.absoluteUrl('_oauth/vk?close=close', {replaceLocalhost: false}) +
'&response_type=code' +
'&display=' + display +
'&state=' + credentialToken;
Oauth.initiateLogin(credentialToken, loginUrl, credentialRequestCompleteCallback);
};
|
Revert "Fix merging engine/template vars"
This reverts commit 5e734479094e270bc3abb7d6ebf752fad95576b0. | <?php
namespace Colorium\Templating;
class Templater implements Contract\TemplaterInterface
{
/** @var string */
public $directory;
/** @var string */
public $suffix = '.php';
/** @var array */
public $vars = [];
/** @var array */
public $helpers = [];
/**
* Create new engine
*
* @param string $directory
* @param string $suffix
*/
public function __construct($directory = null, $suffix = '.php')
{
$this->directory = $directory;
$this->suffix = $suffix;
$this->helpers['render'] = [$this, 'render'];
$this->helpers['e'] = function($value)
{
return htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
};
}
/**
* Generate content from template compilation
*
* @param string $template
* @param array $vars
* @param array $blocks
* @return string
*/
public function render($template, array $vars = [], array $blocks = [])
{
$directory = rtrim($this->directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$file = $directory . trim($template, DIRECTORY_SEPARATOR) . $this->suffix;
$sandbox = new Template($this, $file, $blocks, $this->helpers);
return $sandbox->compile();
}
} | <?php
namespace Colorium\Templating;
class Templater implements Contract\TemplaterInterface
{
/** @var string */
public $directory;
/** @var string */
public $suffix = '.php';
/** @var array */
public $vars = [];
/** @var array */
public $helpers = [];
/**
* Create new engine
*
* @param string $directory
* @param string $suffix
*/
public function __construct($directory = null, $suffix = '.php')
{
$this->directory = $directory;
$this->suffix = $suffix;
$this->helpers['render'] = [$this, 'render'];
$this->helpers['e'] = function($value)
{
return htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
};
}
/**
* Generate content from template compilation
*
* @param string $template
* @param array $vars
* @param array $blocks
* @return string
*/
public function render($template, array $vars = [], array $blocks = [])
{
$directory = rtrim($this->directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$file = $directory . trim($template, DIRECTORY_SEPARATOR) . $this->suffix;
$vars += $this->vars;
$sandbox = new Template($this, $file, $blocks, $this->helpers);
return $sandbox->compile($vars);
}
} |
Use correct keys for measurement & label | import React, { Component } from 'react';
import Chart from 'chart.js';
class ChartComponent extends Component {
componentDidMount() {
this.renderChart(this.props.measurement.measurements);
}
componentWillUpdate(nextProps) {
if (nextProps.measurement.createdAt !== this.props.measurement.createdAt) {
this.updateChart(nextProps.measurement.measurements);
}
}
updateChart(measurements) {
this.chart.destroy();
this.renderChart(measurements);
}
renderChart(measurements) {
const data = measurements.map(measurement => measurement.inclusiveRenderDuration);
const labels = measurements.map(measurement => measuremen.key);
this.chart = new Chart(document.getElementById('perf-tool-chart-ctx'), {
type: 'bar',
data: {
labels,
datasets: [{
data,
label: this.props.label,
backgroundColor: 'rgba(75,192,192,0.4)',
}],
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
}],
},
},
});
}
render() {
return (<div className="chart-container" style={{ maxWidth: '900px' }}>
<canvas id="perf-tool-chart-ctx" style={{ width: `${this.props.width}px`, height: `${this.props.height}px` }} />
</div>);
}
}
export default ChartComponent;
| import React, { Component } from 'react';
import Chart from 'chart.js';
class ChartComponent extends Component {
componentDidMount() {
this.renderChart(this.props.measurement.measurements);
}
componentWillUpdate(nextProps) {
if (nextProps.measurement.createdAt !== this.props.measurement.createdAt) {
this.updateChart(nextProps.measurement.measurements);
}
}
updateChart(measurements) {
this.chart.destroy();
this.renderChart(measurements);
}
renderChart(measurements) {
const data = measurements.map(measurement => measurement['Wasted time (ms)']);
const labels = measurements.map(measurement => measurement['Owner > component']);
this.chart = new Chart(document.getElementById('perf-tool-chart-ctx'), {
type: 'bar',
data: {
labels,
datasets: [{
data,
label: this.props.label,
backgroundColor: 'rgba(75,192,192,0.4)',
}],
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
}],
},
},
});
}
render() {
return (<div className="chart-container" style={{ maxWidth: '900px' }}>
<canvas id="perf-tool-chart-ctx" style={{ width: `${this.props.width}px`, height: `${this.props.height}px` }} />
</div>);
}
}
export default ChartComponent;
|
Remove extension conflict between Twig and Smarty | <?php
namespace Brendt\Stitcher\Template\Smarty;
use \Smarty;
use Brendt\Stitcher\Template\TemplateEngine;
use Symfony\Component\Finder\SplFileInfo;
/**
* The Smarty template engine.
*/
class SmartyEngine extends Smarty implements TemplateEngine
{
public function __construct($templateDir = './src', $cacheDir = './.cache') {
parent::__construct();
$this->addTemplateDir($templateDir);
$this->setCompileDir($cacheDir);
$this->addPluginsDir([__DIR__]);
$this->caching = false;
}
public function renderTemplate(SplFileInfo $template) {
return $this->fetch($template->getRealPath());
}
public function addTemplateVariables(array $variables) {
foreach ($variables as $name => $variable) {
$this->assign($name, $variable);
}
return $this;
}
public function clearTemplateVariables() {
$this->clearAllAssign();
return $this;
}
public function addTemplateVariable($name, $value) {
$this->assign($name, $value);
return $this;
}
public function hasTemplateVariable(string $name) : bool {
return $this->getTemplateVars($name) != null;
}
public function clearTemplateVariable($variable) {
$this->clearAssign($variable);
return $this;
}
public function getTemplateExtensions(): array {
return ['tpl'];
}
}
| <?php
namespace Brendt\Stitcher\Template\Smarty;
use \Smarty;
use Brendt\Stitcher\Template\TemplateEngine;
use Symfony\Component\Finder\SplFileInfo;
/**
* The Smarty template engine.
*/
class SmartyEngine extends Smarty implements TemplateEngine
{
public function __construct($templateDir = './src', $cacheDir = './.cache') {
parent::__construct();
$this->addTemplateDir($templateDir);
$this->setCompileDir($cacheDir);
$this->addPluginsDir([__DIR__]);
$this->caching = false;
}
public function renderTemplate(SplFileInfo $template) {
return $this->fetch($template->getRealPath());
}
public function addTemplateVariables(array $variables) {
foreach ($variables as $name => $variable) {
$this->assign($name, $variable);
}
return $this;
}
public function clearTemplateVariables() {
$this->clearAllAssign();
return $this;
}
public function addTemplateVariable($name, $value) {
$this->assign($name, $value);
return $this;
}
public function hasTemplateVariable(string $name) : bool {
return $this->getTemplateVars($name) != null;
}
public function clearTemplateVariable($variable) {
$this->clearAssign($variable);
return $this;
}
public function getTemplateExtensions(): array {
return ['html', 'tpl'];
}
}
|
Include channel list in connection | from sockjs.tornado import SockJSConnection
from ..pubsub_providers.redis_pubsub_provider import RedisPubSubProvider
from .. import route_handler
import json
pub_sub = RedisPubSubProvider()
class ConnectionMixin(object):
def to_json(self, data):
if isinstance(data, dict):
return data
try:
data = json.loads(data.replace("'", '"'))
return data
except:
return json.dumps({'message': data})
def to_string(self, data):
if isinstance(data, dict):
return json.dumps(data).replace("'", '"')
return data
class SubscriberConnection(ConnectionMixin, SockJSConnection):
channels = []
def __init__(self, session):
super(SubscriberConnection, self).__init__(session)
def on_open(self, request):
self.pub_sub = pub_sub
def on_close(self):
self.pub_sub.close(self)
def on_message(self, data):
try:
data = self.to_json(data)
handler = route_handler.get_route_handler(data['route'])
handler(self).handle(data)
except Exception as e:
self.abort_connection()
raise e
def abort_connection(self):
self.close()
def send(self, message, binary=False):
super(SubscriberConnection, self).send(message, binary)
def broadcast(self, clients, message):
super(SubscriberConnection, self).broadcast(clients, message)
class DjangoSubscriberConnection(SubscriberConnection):
def __init__(self, session):
super(DjangoSubscriberConnection, self).__init__(session)
| from sockjs.tornado import SockJSConnection
from ..pubsub_providers.redis_pubsub_provider import RedisPubSubProvider
from .. import route_handler
import json
pub_sub = RedisPubSubProvider()
class ConnectionMixin(object):
def to_json(self, data):
if isinstance(data, dict):
return data
try:
data = json.loads(data.replace("'", '"'))
return data
except:
return json.dumps({'message': data})
def to_string(self, data):
if isinstance(data, dict):
return json.dumps(data).replace("'", '"')
return data
class SubscriberConnection(ConnectionMixin, SockJSConnection):
def __init__(self, session):
super(SubscriberConnection, self).__init__(session)
def on_open(self, request):
self.pub_sub = pub_sub
def on_close(self):
self.pub_sub.close(self)
def on_message(self, data):
try:
data = self.to_json(data)
handler = route_handler.get_route_handler(data['route'])
handler(self).handle(data)
except Exception as e:
self.abort_connection()
raise e
def abort_connection(self):
self.close()
def send(self, message, binary=False):
super(SubscriberConnection, self).send(message, binary)
def broadcast(self, clients, message):
super(SubscriberConnection, self).broadcast(clients, message)
class DjangoSubscriberConnection(SubscriberConnection):
def __init__(self, session):
super(DjangoSubscriberConnection, self).__init__(session)
|
Exclude addon-test-support from eslint node files
This PR adds `addon-test-support` folder to excluded files from eslint override for node files.
Fixes #7652 | module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module'
},
plugins: [
'ember'
],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true
},
rules: {
},
overrides: [
// node files
{
files: [<% if (blueprint !== 'app') { %>
'index.js',<% } %>
'testem.js',
'ember-cli-build.js',
'config/**/*.js'<% if (blueprint === 'app') { %>,
'lib/*/index.js'<% } %><% if (blueprint !== 'app') { %>,
'tests/dummy/config/**/*.js'<% } %>
],<% if (blueprint !== 'app') { %>
excludedFiles: [
'app/**',
'addon/**',
'tests/dummy/app/**',
'addon-test-support/**'
],<% } %>
parserOptions: {
sourceType: 'script',
ecmaVersion: 2015
},
env: {
browser: false,
node: true
}<% if (blueprint !== 'app') { %>,
plugins: ['node'],
rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, {
// add your custom rules and overrides for node files here
})<% } %>
}
]
};
| module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module'
},
plugins: [
'ember'
],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true
},
rules: {
},
overrides: [
// node files
{
files: [<% if (blueprint !== 'app') { %>
'index.js',<% } %>
'testem.js',
'ember-cli-build.js',
'config/**/*.js'<% if (blueprint === 'app') { %>,
'lib/*/index.js'<% } %><% if (blueprint !== 'app') { %>,
'tests/dummy/config/**/*.js'<% } %>
],<% if (blueprint !== 'app') { %>
excludedFiles: [
'app/**',
'addon/**',
'tests/dummy/app/**'
],<% } %>
parserOptions: {
sourceType: 'script',
ecmaVersion: 2015
},
env: {
browser: false,
node: true
}<% if (blueprint !== 'app') { %>,
plugins: ['node'],
rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, {
// add your custom rules and overrides for node files here
})<% } %>
}
]
};
|
Fix how we check for Windows in platform_libname. | # -*- coding: utf-8 -*-
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
lname = platform_libname(name)
sdirs = platform_libdirs()
# First attempt to utilise the system search path
try:
return ctypes.CDLL(lname)
# Otherwise, if this fails then run our own search
except OSError:
for sd in sdirs:
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
| # -*- coding: utf-8 -*-
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
lname = platform_libname(name)
sdirs = platform_libdirs()
# First attempt to utilise the system search path
try:
return ctypes.CDLL(lname)
# Otherwise, if this fails then run our own search
except OSError:
for sd in sdirs:
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'Windows':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
|
Make cleanup command less verbose | # coding=utf-8
from django.core.management.base import BaseCommand
from registration.models import RegistrationProfile
class Command(BaseCommand):
help = 'Cleanup expired registrations'
OPT_SIMULATE = 'dry-run'
def add_arguments(self, parser):
parser.add_argument(''.join(['--', self.OPT_SIMULATE]),
action='store_true',
dest=self.OPT_SIMULATE,
default=False,
help='Only print registrations that would be deleted')
def handle(self, *args, **options):
dry_run = True if self.OPT_SIMULATE in options and options[
self.OPT_SIMULATE] else False
if dry_run:
user_count, reg_profile_count = 0, 0
for profile in RegistrationProfile.objects.select_related(
'user').exclude(user__is_active=True):
if profile.activation_key_expired():
user_count += 1
reg_profile_count += 1
print "Would delete {} User and {} RegistrationProfile objects".format(
user_count, reg_profile_count)
else:
RegistrationProfile.objects.delete_expired_users()
| # coding=utf-8
from django.core.management.base import BaseCommand
from registration.models import RegistrationProfile
class Command(BaseCommand):
help = 'Cleanup expired registrations'
OPT_SIMULATE = 'dry-run'
def add_arguments(self, parser):
parser.add_argument(''.join(['--', self.OPT_SIMULATE]),
action='store_true',
dest=self.OPT_SIMULATE,
default=False,
help='Only print registrations that would be deleted')
def handle(self, *args, **options):
self.stdout.write('Deleting expired user registrations')
dry_run = True if self.OPT_SIMULATE in options and options[
self.OPT_SIMULATE] else False
if dry_run:
user_count, reg_profile_count = 0, 0
for profile in RegistrationProfile.objects.select_related(
'user').exclude(user__is_active=True):
if profile.activation_key_expired():
user_count += 1
reg_profile_count += 1
print "Would delete {} User and {} RegistrationProfile objects".format(
user_count, reg_profile_count)
else:
RegistrationProfile.objects.delete_expired_users()
|
Add lsst-dd-rtd-theme as explicit dependency
This is needed since lsst-dd-rtd-theme is configured via the ddconfig
module. I'm pinning the theme version to 0.1 so that documenteer's
version effectively controls the version of the theme as well. | from setuptools import setup, find_packages
import os
packagename = 'documenteer'
description = 'Tools for LSST DM documentation projects'
author = 'Jonathan Sick'
author_email = '[email protected]'
license = 'MIT'
url = 'https://github.com/lsst-sqre/documenteer'
version = '0.1.7'
def read(filename):
full_filename = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
filename)
return open(full_filename).read()
long_description = read('README.rst')
setup(
name=packagename,
version=version,
description=description,
long_description=long_description,
url=url,
author=author,
author_email=author_email,
license=license,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='sphinx documentation lsst',
packages=find_packages(exclude=['docs', 'tests*']),
install_requires=['future',
'Sphinx',
'PyYAML',
'sphinx-prompt',
'sphinxcontrib-bibtex',
'GitPython',
'lsst-dd-rtd-theme==0.1.0'],
tests_require=['pytest',
'pytest-cov',
'pytest-flake8',
'pytest-mock'],
# package_data={},
)
| from setuptools import setup, find_packages
import os
packagename = 'documenteer'
description = 'Tools for LSST DM documentation projects'
author = 'Jonathan Sick'
author_email = '[email protected]'
license = 'MIT'
url = 'https://github.com/lsst-sqre/documenteer'
version = '0.1.7'
def read(filename):
full_filename = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
filename)
return open(full_filename).read()
long_description = read('README.rst')
setup(
name=packagename,
version=version,
description=description,
long_description=long_description,
url=url,
author=author,
author_email=author_email,
license=license,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='sphinx documentation lsst',
packages=find_packages(exclude=['docs', 'tests*']),
install_requires=['future',
'Sphinx',
'PyYAML',
'sphinx-prompt',
'sphinxcontrib-bibtex',
'GitPython'],
tests_require=['pytest',
'pytest-cov',
'pytest-flake8',
'pytest-mock'],
# package_data={},
)
|
Make exception message builder a nicer function
It is used by clients in other modules. | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sys
import threading
import time
import traceback
from .singleton import Singleton
def exception_message():
"""Create a message with details on the exception."""
exc_type, exc_value, exc_tb = exc_info = sys.exc_info()
return {'exception': {'type': exc_type,
'value': exc_value,
'traceback': exc_tb},
'traceback': traceback.format_exception(*exc_info)}
class EventLoop(object, metaclass=Singleton):
"""A generic event loop object."""
def __init__(self):
self.queue = queue.Queue()
def schedule(self, event):
"""Schedule an event.
The events have the form::
(event, error)
where `event` is a thunk and `error` is called with an
exception message (output of `exception_message`) if there is
an error when executing `event`.
"""
self.queue.put(event)
def stop(self):
"""Stop the loop."""
pass
def run_step(self, block=True):
"""Process one event."""
ev, error = self.queue.get(block=block)
try:
ev()
except Exception as exc:
error(exception_message())
def run(self):
"""Process all events in the queue."""
try:
while True:
self.run_step(block=False)
except queue.Empty:
return
| """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sys
import threading
import time
import traceback
from .singleton import Singleton
def _format_exception(exc_info):
"""Create a message with details on the exception."""
exc_type, exc_value, exc_tb = exc_info
return {'exception': {'type': exc_type,
'value': exc_value,
'traceback': exc_tb},
'traceback': traceback.format_exception(*exc_info)}
class EventLoop(object, metaclass=Singleton):
"""A generic event loop object."""
def __init__(self):
self.queue = queue.Queue()
def schedule(self, event):
"""Schedule an event.
The events have the form::
(event, error)
where `event` is a thunk and `error` is called with an
exception message (output of `_format_exception`) if there is
an error when executing `event`.
"""
self.queue.put(event)
def stop(self):
"""Stop the loop."""
pass
def run_step(self, block=True):
"""Process one event."""
ev, error = self.queue.get(block=block)
try:
ev()
except Exception as exc:
error(_format_exception(sys.exc_info()))
def run(self):
"""Process all events in the queue."""
try:
while True:
self.run_step(block=False)
except queue.Empty:
return
|