text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix regex for html links parsing. | export class HtmlTools {
static escapeHtml (text) {
return text.replace(/[\"&<>]/g, a => HtmlTools._escapeCharMap[a]);
}
static anchorLinksEscapeHtml (text) {
var linkRegex = /((https?:\/\/|ftps?:\/\/|www\.|[^\s:=]+@www\.).*?[a-zA-Z_\/0-9\-\#=&])(?=(\.|,|;|:|\?|\!)?("|'|«|»|\[|\s|\r|\n|$))/g;
var parts = [];
var match;
var lastEnd = 0;
while (match = linkRegex.exec(text)) {
if (match.index != lastEnd) {
parts.push(HtmlTools.escapeHtml(text.substring(lastEnd, match.index)));
}
parts.push("<a href='" + match[0] + "' target='_blank'>" + match[0] + "</a>");
lastEnd = linkRegex.lastIndex;
}
if (lastEnd < text.length) {
parts.push(HtmlTools.escapeHtml(text.substring(lastEnd)));
}
return parts.join('');
}
}
HtmlTools._escapeCharMap = { '"': '"', '&': '&', '<': '<', '>': '>' };
| export class HtmlTools {
static escapeHtml (text) {
return text.replace(/[\"&<>]/g, a => HtmlTools._escapeCharMap[a]);
}
static anchorLinksEscapeHtml (text) {
var linkRegex = /((https?:\/\/|www\.|[^\s:=]+@www\.).*?[a-z_\/0-9\-\#=&])(?=(\.|,|;|\?|\!)?("|'|«|»|\[|\s|\r|\n|$))/g;
var parts = [];
var match;
var lastEnd = 0;
while (match = linkRegex.exec(text)) {
if (match.index != lastEnd) {
parts.push(HtmlTools.escapeHtml(text.substring(lastEnd, match.index)));
}
parts.push("<a href='" + match[0] + "' target='_blank'>" + match[0] + "</a>");
lastEnd = linkRegex.lastIndex;
}
if (lastEnd < text.length) {
parts.push(HtmlTools.escapeHtml(text.substring(lastEnd)));
}
return parts.join('');
}
}
HtmlTools._escapeCharMap = { '"': '"', '&': '&', '<': '<', '>': '>' };
|
Add absolute URLs to form and question admin | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.db import models
class Form(models.Model):
title = models.CharField(_("Title"), max_length=255)
def __unicode__(self):
return u'%s' % self.title
class Meta:
ordering = ('title', )
def get_absolute_url(self):
return reverse('customforms.views.view_form', args=[str(self.id)])
class Question(models.Model):
form = models.ForeignKey(Form)
title = models.CharField(
_("Title"), max_length=255, default=_("Question Title"))
help_text = models.TextField(blank=True, null=True)
CHOICES = [
('C', _('Checkbox')),
('R', _('Radio')),
('S', _('Select')),
('T', _('Text')),
]
question_type = models.CharField(
max_length=1, choices=CHOICES, default="T")
required = models.BooleanField(default=False)
position = models.PositiveIntegerField(default=0)
def __unicode__(self):
return u'%s' % (self.title, )
class Meta:
ordering = ('form', 'position', )
def get_absolute_url(self):
return reverse('customforms.views.view_form', args=[str(self.form.id)])
class Choice(models.Model):
question = models.ForeignKey(Question)
title = models.CharField(max_length=200,)
position = models.PositiveIntegerField(default=0)
class Meta:
ordering = ('position', )
def __unicode__(self):
return u'%s' % (self.title, )
| #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext as _
from django.db import models
class Form(models.Model):
title = models.CharField(_("Title"), max_length=255)
def __unicode__(self):
return u'%s' % self.title
class Meta:
ordering = ('title', )
class Question(models.Model):
form = models.ForeignKey(Form)
title = models.CharField(
_("Title"), max_length=255, default=_("Question Title"))
help_text = models.TextField(blank=True, null=True)
CHOICES = [
('C', _('Checkbox')),
('R', _('Radio')),
('S', _('Select')),
('T', _('Text')),
]
question_type = models.CharField(
max_length=1, choices=CHOICES, default="T")
required = models.BooleanField(default=False)
position = models.PositiveIntegerField(default=0)
def __unicode__(self):
return u'%s' % (self.title, )
class Meta:
ordering = ('form', 'position', )
class Choice(models.Model):
question = models.ForeignKey(Question)
title = models.CharField(max_length=200,)
position = models.PositiveIntegerField(default=0)
class Meta:
ordering = ('position', )
def __unicode__(self):
return u'%s' % (self.title, )
|
Add a method to noop the make_key in Django | """
django_casscache
~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by Matt Robenolt.
:license: BSD, see LICENSE for more details.
"""
from django.core.cache.backends.memcached import BaseMemcachedCache
class CasscacheCache(BaseMemcachedCache):
"An implementation of a cache binding using casscache"
def __init__(self, server, params):
import casscache
super(CasscacheCache, self).__init__(server, params,
library=casscache,
value_not_found_exception=ValueError)
@property
def _cache(self):
if getattr(self, '_client', None) is None:
keyspace = self._options.pop('keyspace')
columnfamily = self._options.pop('columnfamily')
self._client = self._lib.Client(self._servers,
keyspace=keyspace,
columnfamily=columnfamily,
**self._options)
return self._client
def _get_memcache_timeout(self, timeout):
return timeout or 0
def close(self, **kwargs):
# Lol, Django wants to close the connection after every request.
# This is 100% not needed for Cassandra.
pass
def noop_make_key(key, *args, **kwargs):
"""
For use with KEY_FUNCTION, to not alter the key name at all.
"""
return key
| """
django_casscache
~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by Matt Robenolt.
:license: BSD, see LICENSE for more details.
"""
from django.core.cache.backends.memcached import BaseMemcachedCache
class CasscacheCache(BaseMemcachedCache):
"An implementation of a cache binding using casscache"
def __init__(self, server, params):
import casscache
super(CasscacheCache, self).__init__(server, params,
library=casscache,
value_not_found_exception=ValueError)
@property
def _cache(self):
if getattr(self, '_client', None) is None:
keyspace = self._options.pop('keyspace')
columnfamily = self._options.pop('columnfamily')
self._client = self._lib.Client(self._servers,
keyspace=keyspace,
columnfamily=columnfamily,
**self._options)
return self._client
def _get_memcache_timeout(self, timeout):
return timeout or 0
def close(self, **kwargs):
# Lol, Django wants to close the connection after every request.
# This is 100% not needed for Cassandra.
pass
|
Remove timestamp from the concat task. | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
stripBanners: false, // no comments are stripped
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> */\n',
separator: '\n'
},
dist: {
// Assemble different game objects
src: [
"base/objects/Objects.js",
"base/objects/Sprite.js",
"base/objects/TexturedPlane.js",
"base/objects/DevActor.js",
"base/objects/Axis.js",
"base/objects/Grid.js",
"base/objects/Target.js",
"base/objects/TextTexture.js",
"base/objects/_init.js",
],
dest: 'base/Objects.js',
},
},
jshint: {
options: {
laxbreak: true
},
all: ['base/*.js', 'base/objects/*.js']
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
// Default task(s).
grunt.registerTask('default', ['concat', 'jshint']);
};
| module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
stripBanners: false, // no comments are stripped
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */\n',
separator: '\n'
},
dist: {
// Assemble different game objects
src: [
"base/objects/Objects.js",
"base/objects/Sprite.js",
"base/objects/TexturedPlane.js",
"base/objects/DevActor.js",
"base/objects/Axis.js",
"base/objects/Grid.js",
"base/objects/Target.js",
"base/objects/TextTexture.js",
"base/objects/_init.js",
],
dest: 'base/Objects.js',
},
},
jshint: {
options: {
laxbreak: true
},
all: ['base/*.js', 'base/objects/*.js']
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
// Default task(s).
grunt.registerTask('default', ['concat', 'jshint']);
};
|
Check whether any getter returns an array before returning a non-array type in Data. | <?php
namespace ComplexPie;
class Data extends Extension
{
protected static $static_ext = array();
public static function add_static_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_static_extension($extpoint, $ext, $priority);
}
public function add_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_extension($extpoint, $ext, $priority);
}
public function __get($name)
{
$extensions = $this->get_extensions('get');
if (method_exists($this, "get_$name"))
{
$extensions[] = array($this, "get_$name");
}
$return = array();
$returnarray = false;
foreach ($extensions as $extension)
{
if (($extreturn = call_user_func($extension, $this->dom, $name)) !== null)
{
if (is_array($extreturn))
{
$returnarray = true;
$return = array_merge_recursive($extreturn, $return);
}
else
{
$return[] = $extreturn;
}
}
}
if ($return)
{
if ($returnarray)
return $return;
else
return $return[0];
}
}
}
Data::add_static_extension_point('get');
| <?php
namespace ComplexPie;
class Data extends Extension
{
protected static $static_ext = array();
public static function add_static_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_static_extension($extpoint, $ext, $priority);
}
public function add_extension($extpoint, $ext, $priority)
{
if ($extpoint === 'get' && !is_callable($ext))
{
throw new \InvalidArgumentException("$ext is not callable");
}
parent::add_extension($extpoint, $ext, $priority);
}
public function __get($name)
{
$return = array();
$extensions = $this->get_extensions('get');
if (method_exists($this, "get_$name"))
{
$extensions[] = array($this, "get_$name");
}
foreach ($extensions as $extension)
{
if (($extreturn = call_user_func($extension, $this->dom, $name)) !== null)
{
if (is_array($extreturn))
{
$return = array_merge_recursive($extreturn, $return);
}
elseif (!$return)
{
return $extreturn;
}
}
}
if ($return)
{
return $return;
}
}
}
Data::add_static_extension_point('get');
|
Fix subtle bug in the ReduceReads stash reported by Adam
* The tailSet generated every time we flush the reads stash is still being affected by subsequent clears because it is just a pointer to the parent element in the original TreeSet. This is dangerous, and there is a weird condition where the clear will affects it.
* Fix by creating a new set, given the tailSet instead of trying to do magic with just the pointer. | package org.broadinstitute.sting.utils.sam;
import com.google.java.contract.Ensures;
import com.google.java.contract.Requires;
import net.sf.samtools.SAMRecord;
import java.util.Comparator;
public class AlignmentStartWithNoTiesComparator implements Comparator<SAMRecord> {
@Requires("c1 >= 0 && c2 >= 0")
@Ensures("result == 0 || result == 1 || result == -1")
private int compareContigs(int c1, int c2) {
if (c1 == c2)
return 0;
else if (c1 > c2)
return 1;
return -1;
}
@Requires("r1 != null && r2 != null")
@Ensures("result == 0 || result == 1 || result == -1")
public int compare(SAMRecord r1, SAMRecord r2) {
int result;
if (r1 == r2)
result = 0;
else if (r1.getReadUnmappedFlag())
result = 1;
else if (r2.getReadUnmappedFlag())
result = -1;
else {
final int cmpContig = compareContigs(r1.getReferenceIndex(), r2.getReferenceIndex());
if (cmpContig != 0)
result = cmpContig;
else {
if (r1.getAlignmentStart() < r2.getAlignmentStart())
result = -1;
else
result = 1;
}
}
return result;
}
} | package org.broadinstitute.sting.utils.sam;
import com.google.java.contract.Ensures;
import com.google.java.contract.Requires;
import net.sf.samtools.SAMRecord;
import java.util.Comparator;
public class AlignmentStartWithNoTiesComparator implements Comparator<SAMRecord> {
@Requires("c1 >= 0 && c2 >= 0")
@Ensures("result == 0 || result == 1 || result == -1")
private int compareContigs(int c1, int c2) {
if (c1 == c2)
return 0;
else if (c1 > c2)
return 1;
return -1;
}
@Requires("r1 != null && r2 != null")
@Ensures("result == 0 || result == 1 || result == -1")
public int compare(SAMRecord r1, SAMRecord r2) {
int result;
if (r1 == r2)
result = 0;
else if (r1.getReadUnmappedFlag())
result = 1;
else if (r2.getReadUnmappedFlag())
result = -1;
else {
final int cmpContig = compareContigs(r1.getReferenceIndex(), r2.getReferenceIndex());
if (cmpContig != 0)
result = cmpContig;
else {
if (r1.getAlignmentStart() < r2.getAlignmentStart()) result = -1;
else result = 1;
}
}
return result;
}
} |
Add 3.8 to the list of supported versions | from setuptools import setup
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
] + [
('Programming Language :: Python :: %s' % x) for x in '3 3.3 3.4 3.5 3.6 3.7 3.8'.split()
]
with open('README.rst') as read_me:
long_description = read_me.read()
setup(
name='nimoy-framework',
version='0.0.1b7',
description='A testing and specification framework for Python 3, heavily inspired by the Spock Framework',
long_description=long_description,
url='https://github.com/browncoat-ninjas/nimoy',
license='Apache License',
platforms=['unix', 'linux', 'osx'],
author='Noam Tenne, Yoav Luft',
author_email='[email protected]',
entry_points={'console_scripts': ['nimoy = nimoy.main:main']},
classifiers=classifiers,
keywords="test unittest specification",
packages=['nimoy', 'nimoy.assertions', 'nimoy.ast_tools', 'nimoy.context', 'nimoy.runner', 'nimoy.compare'],
install_requires=['pyhamcrest==1.9.0'],
)
| from setuptools import setup
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
] + [
('Programming Language :: Python :: %s' % x) for x in '3 3.3 3.4 3.5 3.6 3.7'.split()
]
with open('README.rst') as read_me:
long_description = read_me.read()
setup(
name='nimoy-framework',
version='0.0.1b7',
description='A testing and specification framework for Python 3, heavily inspired by the Spock Framework',
long_description=long_description,
url='https://github.com/browncoat-ninjas/nimoy',
license='Apache License',
platforms=['unix', 'linux', 'osx'],
author='Noam Tenne, Yoav Luft',
author_email='[email protected]',
entry_points={'console_scripts': ['nimoy = nimoy.main:main']},
classifiers=classifiers,
keywords="test unittest specification",
packages=['nimoy', 'nimoy.assertions', 'nimoy.ast_tools', 'nimoy.context', 'nimoy.runner', 'nimoy.compare'],
install_requires=['pyhamcrest==1.9.0'],
)
|
Support the app_dev.php front controller | <?php
class ContaoValetDriver extends ValetDriver
{
/**
* Determine if the driver serves the request.
*
* @param string $sitePath
* @param string $siteName
* @param string $uri
* @return bool
*/
public function serves($sitePath, $siteName, $uri)
{
return is_dir($sitePath.'/vendor/contao') && file_exists($sitePath.'/web/app.php');
}
/**
* Determine if the incoming request is for a static file.
*
* @param string $sitePath
* @param string $siteName
* @param string $uri
* @return string|false
*/
public function isStaticFile($sitePath, $siteName, $uri)
{
if ($this->isActualFile($staticFilePath = $sitePath.'/web'.$uri)) {
return $staticFilePath;
}
return false;
}
/**
* Get the fully resolved path to the application's front controller.
*
* @param string $sitePath
* @param string $siteName
* @param string $uri
* @return string
*/
public function frontControllerPath($sitePath, $siteName, $uri)
{
if ($uri === '/install.php') {
return $sitePath.'/web/install.php';
}
if (0 === strncmp($uri, '/app_dev.php', 12)) {
$_SERVER['SCRIPT_NAME'] = '/app_dev.php';
$_SERVER['SCRIPT_FILENAME'] = $sitePath.'/app_dev.php';
return $sitePath.'/web/app_dev.php';
}
return $sitePath.'/web/app.php';
}
}
| <?php
class ContaoValetDriver extends ValetDriver
{
/**
* Determine if the driver serves the request.
*
* @param string $sitePath
* @param string $siteName
* @param string $uri
* @return bool
*/
public function serves($sitePath, $siteName, $uri)
{
return is_dir($sitePath.'/vendor/contao') && file_exists($sitePath.'/web/app.php');
}
/**
* Determine if the incoming request is for a static file.
*
* @param string $sitePath
* @param string $siteName
* @param string $uri
* @return string|false
*/
public function isStaticFile($sitePath, $siteName, $uri)
{
if ($this->isActualFile($staticFilePath = $sitePath.'/web'.$uri)) {
return $staticFilePath;
}
return false;
}
/**
* Get the fully resolved path to the application's front controller.
*
* @param string $sitePath
* @param string $siteName
* @param string $uri
* @return string
*/
public function frontControllerPath($sitePath, $siteName, $uri)
{
if ($uri === '/install.php') {
return $sitePath.'/web/install.php';
}
return $sitePath.'/web/app.php';
}
}
|
Use $timeout to make $apply functions go to the next digest, to prevent "$digest already in progress". | import CartBase from './base/cart-base.js';
class CartBlogListCtrl extends CartBase {
constructor($scope, $timeout, ...args) {
super(...args);
this.logInit('CartBlogListCtrl');
this.$scope = $scope;
this.$timeout = $timeout;
this.postList = [];
this.init();
}
init() {
if (!this.apiService.isDataInitialized()) {
// loading animation
this.apiService.dataInit().then(
() => {
// end loading animation??
this.convertPostDataToViewArr(this.apiService.postMap);
},
(error) => {
// end loading animation??
this.msgService.error(error);
}
);
} else {
this.convertPostDataToViewArr(this.apiService.postMap);
}
}
categoryGetTitleViaUuid(uuid) {
let name = 'N/A';
if (this.apiService.categoryMap.has(uuid)) {
name = this.apiService.categoryMap.get(uuid).title;
}
return name;
}
convertPostDataToViewArr(postMap) { // pagination??
this.$timeout(() => { // fix the issue: $digest already in progress
this.$scope.$apply(() => { // fix the issue: postList updated but data binding not triggered
for (let [, post] of postMap) {
//noinspection JSUnusedAssignment
this.postList.push(post);
}
});
});
}
}
CartBlogListCtrl.$inject = ['$scope', '$timeout', ...CartBase.$inject];
export default CartBlogListCtrl;
| import CartBase from './base/cart-base.js';
class CartBlogListCtrl extends CartBase {
constructor($scope, ...args) {
super(...args);
this.logInit('CartBlogListCtrl');
this.$scope = $scope;
this.postList = [];
this.init();
}
init() {
if (!this.apiService.isDataInitialized()) {
// loading animation
this.apiService.dataInit().then(
() => {
// end loading animation??
this.convertPostDataToViewArr(this.apiService.postMap);
},
(error) => {
// end loading animation??
this.msgService.error(error);
}
);
} else {
this.convertPostDataToViewArr(this.apiService.postMap);
}
}
categoryGetTitleViaUuid(uuid) {
let name = 'N/A';
if (this.apiService.categoryMap.has(uuid)) {
name = this.apiService.categoryMap.get(uuid).title;
}
return name;
}
convertPostDataToViewArr(postMap) { // pagination??
this.$scope.$apply(() => { // fix the issue: postList updated but data binding not triggered
for (let [, post] of postMap) {
//noinspection JSUnusedAssignment
this.postList.push(post);
}
});
}
}
CartBlogListCtrl.$inject = ['$scope', ...CartBase.$inject];
export default CartBlogListCtrl;
|
Fix NullPointerException when the inventory doesn't contain sugar canes | package org.paolo565.drills.utils;
import org.bukkit.Material;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class InventoryUtils {
public static int countItemsInInventory(Inventory inventory, Material material) {
int count = 0;
for(int i = 0; i < inventory.getSize(); i++) {
ItemStack stack = inventory.getItem(i);
if(stack != null && stack.getType() == material) {
count += stack.getAmount();
}
}
return count;
}
public static void removeItemsFromInventory(Inventory inventory, Material material, int amount) {
for(int i = 0; i < inventory.getSize() && amount > 0; i++) {
ItemStack stack = inventory.getItem(i);
if(stack != null && stack.getType() == material) {
int remove = stack.getAmount() > amount ? amount : stack.getAmount();
amount -= remove;
if(stack.getAmount() == remove) {
stack.setType(Material.AIR);
} else {
stack.setAmount(stack.getAmount() - remove);
}
}
}
}
}
| package org.paolo565.drills.utils;
import org.bukkit.Material;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class InventoryUtils {
public static int countItemsInInventory(Inventory inventory, Material material) {
int count = 0;
for(int i = 0; i < inventory.getSize(); i++) {
ItemStack stack = inventory.getItem(i);
if(stack.getType() == material) {
count += stack.getAmount();
}
}
return count;
}
public static void removeItemsFromInventory(Inventory inventory, Material material, int amount) {
for(int i = 0; i < inventory.getSize() && amount > 0; i++) {
ItemStack stack = inventory.getItem(i);
if(stack.getType() == material) {
int remove = stack.getAmount() > amount ? amount : stack.getAmount();
amount -= remove;
if(stack.getAmount() == remove) {
stack.setType(Material.AIR);
} else {
stack.setAmount(stack.getAmount() - remove);
}
}
}
}
}
|
Add test for missing paddable char | import request from 'supertest';
import test from 'tape';
import app from '../server';
test('Should leftpad correctly', t => {
request(app)
.get('?str=paddin%27%20oswalt&len=68&ch=@')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@paddin' oswalt`)
t.end();
});
});
test('Should handle missing paddable string correctly', t => {
request(app)
.get('?len=68&ch=@')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@`)
t.end();
});
});
test('Should handle missing char string', t => {
request(app)
.get('/?str=paddin%27%20oswalt&len=68')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, ` paddin' oswalt`)
t.end();
});
});
test('Should handle no parameters', t => {
request(app)
.get('/')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, '')
t.end();
});
});
| import request from 'supertest';
import test from 'tape';
import app from '../server';
test('Should leftpad correctly', t => {
request(app)
.get('?str=paddin%27%20oswalt&len=68&ch=@')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@paddin' oswalt`)
t.end();
});
});
test('Should handle missing paddable string correctly', t => {
request(app)
.get('?len=68&ch=@')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@`)
t.end();
});
});
test('Should handle no parameters', t => {
request(app)
.get('/')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, '')
t.end();
});
});
|
Add missing config variable name |
var path = require('path');
var yaml_config = require('node-yaml-config');
var _ = require('lodash');
function ymlHerokuConfigModule() {
var HEROKU_VARS_SUPPORT = [
'user', 'password', 'url', 'pipeline', 'jobs', 'key', 'secret', 'account', 'debug', 'dangerzone', 'acceptableTimeFailed', 'timeDiff'
];
var create = function (configKey) {
var config;
var id = configKey;
init();
var get = function () {
return config[id];
};
function init() {
try {
config = yaml_config.load('config.yml');
} catch (err) {
console.log('could not read yml, trying Heroku vars', err);
config = {};
config[id] = {};
_.each(HEROKU_VARS_SUPPORT, function(varName) {
config[id][varName] = process.env[id.toUpperCase() + '_' + varName.toUpperCase()];
});
if(config[id].jobs) {
config[id].jobs = config[id].jobs.split(',');
}
if (!config[id].user || !config[id].password || !config[id].url) {
console.log('ERROR: Not enough values in ' + id + ' config, cannot get data');
}
}
config[id] = config[id] || { sample: true };
}
return {
get: get
};
};
return {
create: create
};
}
exports.create = ymlHerokuConfigModule().create; |
var path = require('path');
var yaml_config = require('node-yaml-config');
var _ = require('lodash');
function ymlHerokuConfigModule() {
var HEROKU_VARS_SUPPORT = [
'user', 'password', 'url', 'pipeline', 'jobs', 'key', 'secret', 'account', 'debug', 'dangerzone', 'acceptableTimeFailed'
];
var create = function (configKey) {
var config;
var id = configKey;
init();
var get = function () {
return config[id];
};
function init() {
try {
config = yaml_config.load('config.yml');
} catch (err) {
console.log('could not read yml, trying Heroku vars', err);
config = {};
config[id] = {};
_.each(HEROKU_VARS_SUPPORT, function(varName) {
config[id][varName] = process.env[id.toUpperCase() + '_' + varName.toUpperCase()];
});
if(config[id].jobs) {
config[id].jobs = config[id].jobs.split(',');
}
if (!config[id].user || !config[id].password || !config[id].url) {
console.log('ERROR: Not enough values in ' + id + ' config, cannot get data');
}
}
config[id] = config[id] || { sample: true };
}
return {
get: get
};
};
return {
create: create
};
}
exports.create = ymlHerokuConfigModule().create; |
Update post view to save username references and save a post id in user entity | from flask import render_template, redirect, url_for
from flask_classy import FlaskView, route
from flask_user import login_required, current_user
from ..models import PostModel
from ..forms import PostForm
class Post(FlaskView):
""" Here will handle post creations, delete and update."""
def get(self, entity_id):
post = PostModel()
post = post.get(entity_id)
return render_template("post/post.html", post=post)
@login_required
@route("/new/", methods=["GET", "POST"])
def new(self):
form = PostForm()
if form.validate_on_submit():
post = PostModel(user=current_user.username, **form.data)
post.put()
current_user.add_post(post.id)
return redirect(url_for("Post:get", entity_id=post.id))
return render_template("post/post_form.html", form=form,
url="Post:new")
@login_required
@route("/edit/<entity_id>", methods=["GET", "POST"])
def edit(self, entity_id):
post = PostModel()
entity = post.get(entity_id)
form = PostForm(**entity)
if form.validate_on_submit():
post.update(entity_id, form.data)
return redirect(url_for("Post:get", entity_id=entity_id))
return render_template("post/post_form.html", form=form,
url="Post:edit", entity_id=entity_id)
| from flask import render_template, redirect, url_for
from flask_classy import FlaskView, route
from flask_user import login_required
from ..models import PostModel
from ..forms import PostForm
class Post(FlaskView):
""" Here will handle post creations, delete and update."""
def get(self, entity_id):
post = PostModel()
post = post.get(entity_id)
return render_template("post/post.html", post=post)
@login_required
@route("/new/", methods=["GET", "POST"])
def new(self):
form = PostForm()
if form.validate_on_submit():
post = PostModel(**form.data)
post.put()
return redirect(url_for("Post:get", entity_id=post.id))
return render_template("post/post_form.html", form=form,
url="Post:new")
@login_required
@route("/edit/<entity_id>", methods=["GET", "POST"])
def edit(self, entity_id):
post = PostModel()
entity = post.get(entity_id)
form = PostForm(**entity)
if form.validate_on_submit():
post.update(entity_id, form.data)
return redirect(url_for("Post:get", entity_id=entity_id))
return render_template("post/post_form.html", form=form,
url="Post:edit", entity_id=entity_id)
|
Update of sorted merge step test case
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@4016 5fb7f6ec-07c1-534a-b4ca-9155e429e800 | package org.pentaho.di.run.sortedmerge;
import junit.framework.TestCase;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.run.AllRunTests;
import org.pentaho.di.run.TimedTransRunner;
public class RunSortedMerge extends TestCase
{
public void test_SORTED_MERGE_00() {
System.out.println();
System.out.println("SORTED MERGE");
System.out.println("==================");
}
public void test_SORTED_MERGE_01_SIMPLE() throws Exception {
TimedTransRunner timedTransRunner = new TimedTransRunner(
"test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr",
LogWriter.LOG_LEVEL_ERROR,
AllRunTests.getOldTargetDatabase(),
AllRunTests.getNewTargetDatabase(),
1000000
);
timedTransRunner.runOldAndNew();
be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult();
assertTrue(oldResult.getNrErrors()==0);
Result newResult = timedTransRunner.getNewResult();
assertTrue(newResult.getNrErrors()==0);
}
}
| package org.pentaho.di.run.sortedmerge;
import junit.framework.TestCase;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.run.AllRunTests;
import org.pentaho.di.run.TimedTransRunner;
public class RunSortedMerge extends TestCase
{
public void test_SORTED_MERGE_00()
{
System.out.println();
System.out.println("SORTED MERGE");
System.out.println("==================");
}
public void test_SORTED_MERGE_01_SIMPLE() throws Exception
{
TimedTransRunner timedTransRunner = new TimedTransRunner(
"test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr",
LogWriter.LOG_LEVEL_ERROR,
AllRunTests.getOldTargetDatabase(),
AllRunTests.getNewTargetDatabase(),
1000000
);
timedTransRunner.runOldAndNew();
be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult();
assertTrue(oldResult.getNrErrors()==0);
Result newResult = timedTransRunner.getNewResult();
assertTrue(newResult.getNrErrors()==0);
}
}
|
fix(components/tab): Switch label prop type to node
Signed-off-by: Sorin Davidoi <[email protected]> | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import Button from './Button';
import CSSClassnames from '../utils/CSSClassnames';
const CLASS_ROOT = CSSClassnames.TAB;
export default class Tab extends Component {
constructor() {
super();
this._onClickTab = this._onClickTab.bind(this);
}
_onClickTab (event) {
const { onRequestForActive } = this.props;
if (event) {
event.preventDefault();
}
onRequestForActive();
}
render () {
const { active, className, id, title, ...props } = this.props;
delete props.onRequestForActive;
const classes = classnames(
CLASS_ROOT, {
[`${CLASS_ROOT}--active`]: active
},
className
);
return (
<li {...props} className={classes} id={id}>
<Button className={`${CLASS_ROOT}__button`} plain={true}
role='tab' aria-selected={active}
onClick={this._onClickTab} aria-expanded={active}>
<label className={`${CLASS_ROOT}__label`} htmlFor={id}>
{title}
</label>
</Button>
</li>
);
}
}
Tab.propTypes = {
title: PropTypes.node.isRequired,
active: PropTypes.bool,
id: PropTypes.string,
onRequestForActive: PropTypes.func // from Tabs
};
| // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import Button from './Button';
import CSSClassnames from '../utils/CSSClassnames';
const CLASS_ROOT = CSSClassnames.TAB;
export default class Tab extends Component {
constructor() {
super();
this._onClickTab = this._onClickTab.bind(this);
}
_onClickTab (event) {
const { onRequestForActive } = this.props;
if (event) {
event.preventDefault();
}
onRequestForActive();
}
render () {
const { active, className, id, title, ...props } = this.props;
delete props.onRequestForActive;
const classes = classnames(
CLASS_ROOT, {
[`${CLASS_ROOT}--active`]: active
},
className
);
return (
<li {...props} className={classes} id={id}>
<Button className={`${CLASS_ROOT}__button`} plain={true}
role='tab' aria-selected={active}
onClick={this._onClickTab} aria-expanded={active}>
<label className={`${CLASS_ROOT}__label`} htmlFor={id}>
{title}
</label>
</Button>
</li>
);
}
}
Tab.propTypes = {
title: PropTypes.string.isRequired,
active: PropTypes.bool,
id: PropTypes.string,
onRequestForActive: PropTypes.func // from Tabs
};
|
Fix "show campaign" button label | @extends('layouts.app')
@section('title', 'Schedule new campaign run')
@section('content')
<div class="c-header">
<h2>SCHEDULES</h2>
</div>
<div class="card">
<div class="card-header">
<h2>Edit scheduled run <small>{{ $schedule->campaign->name }}</small></h2>
<div class="actions">
<a href="{{ route('campaigns.show', ['campaign' => $schedule->campaign]) }}" class="btn palette-Cyan bg waves-effect">
<i class="zmdi zmdi-palette-Cyan zmdi-eye"></i> Show campaign
</a>
<a href="{{ route('campaigns.edit', ['campaign' => $schedule->campaign]) }}" class="btn palette-Cyan bg waves-effect">
<i class="zmdi zmdi-palette-Cyan zmdi-edit"></i> Edit campaign
</a>
</div>
</div>
<div class="card-body card-padding">
@include('flash::message')
{!! Form::model($schedule, ['route' => ['schedule.update', 'schedule' => $schedule], 'method' => 'PATCH']) !!}
@include('schedule._form')
{!! Form::close() !!}
</div>
</div>
@endsection | @extends('layouts.app')
@section('title', 'Schedule new campaign run')
@section('content')
<div class="c-header">
<h2>SCHEDULES</h2>
</div>
<div class="card">
<div class="card-header">
<h2>Edit scheduled run <small>{{ $schedule->campaign->name }}</small></h2>
<div class="actions">
<a href="{{ route('campaigns.show', ['campaign' => $schedule->campaign]) }}" class="btn palette-Cyan bg waves-effect">
<i class="zmdi zmdi-palette-Cyan zmdi-edit"></i> Edit campaign
</a>
<a href="{{ route('campaigns.edit', ['campaign' => $schedule->campaign]) }}" class="btn palette-Cyan bg waves-effect">
<i class="zmdi zmdi-palette-Cyan zmdi-edit"></i> Edit campaign
</a>
</div>
</div>
<div class="card-body card-padding">
@include('flash::message')
{!! Form::model($schedule, ['route' => ['schedule.update', 'schedule' => $schedule], 'method' => 'PATCH']) !!}
@include('schedule._form')
{!! Form::close() !!}
</div>
</div>
@endsection |
Apply consistent tabbing to gruntfile
2 space tabs | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.name %> <%= pkg.version %> | Copyright <%= grunt.template.today("yyyy") %> <%= pkg.author.name %> | <%= pkg.license %> License */\n',
concat: {
options: {
stripBanners: {
block: true
},
banner: '<%= banner %>'
},
dist: {
src: [ 'correctingInterval.js' ],
dest: 'correctingInterval.js'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
dist: {
files: {
'correctingInterval.min.js': [ 'correctingInterval.js' ]
}
}
},
jshint: {
files: [
'correctingInterval.js'
]
},
mocha: {
index: ['test/index.html'],
options: {
run: true
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('test', [ 'jshint', 'mocha' ]);
grunt.registerTask('compile', [ 'test', 'concat', 'uglify' ]);
grunt.registerTask('default', [ 'compile' ]);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.name %> <%= pkg.version %> | Copyright <%= grunt.template.today("yyyy") %> <%= pkg.author.name %> | <%= pkg.license %> License */\n',
concat: {
options: {
stripBanners: { block: true },
banner: '<%= banner %>'
},
dist: {
src: [ 'correctingInterval.js' ],
dest: 'correctingInterval.js'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
dist: {
files: {
'correctingInterval.min.js': [ 'correctingInterval.js' ]
}
}
},
jshint: {
files: [
'correctingInterval.js'
]
},
mocha: {
index: ['test/index.html'],
options: {
run: true
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('test', [ 'jshint', 'mocha' ]);
grunt.registerTask('compile', [ 'test', 'concat', 'uglify' ]);
grunt.registerTask('default', [ 'compile' ]);
};
|
Add a 'use' statement for PHP 5.3 bug. | <?php
namespace PureMachine\Bundle\WebServiceBundle\WebService;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use Symfony\Component\DependencyInjection\ContainerInterface;
use JMS\DiExtraBundle\Annotation\Service;// new Service() // PHP Bug
class SymfonyBaseWebService extends BaseWebService implements ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
protected $container = null;
/**
* @InjectParams({
* "container" = @Inject("service_container")
* })
* @param ContainerInterface $container
* @return void
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* Returns the symfony application container
*
* @return ContainerInteface
*/
protected function getContainer()
{
return $this->container;
}
protected function get($service)
{
return $this->getContainer()->get($service);
}
protected function getManager()
{
return $this->getContainer()->get('doctrine.orm.entity_manager');
}
protected function getEntityManager()
{
return $this->getManager();
}
protected function getRepository($repo)
{
return $this->getContainer()->get('doctrine.orm.entity_manager')->getRepository($repo);
}
}
| <?php
namespace PureMachine\Bundle\WebServiceBundle\WebService;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use Symfony\Component\DependencyInjection\ContainerInterface;
class SymfonyBaseWebService extends BaseWebService implements ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
protected $container = null;
/**
* @InjectParams({
* "container" = @Inject("service_container")
* })
* @param ContainerInterface $container
* @return void
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* Returns the symfony application container
*
* @return ContainerInteface
*/
protected function getContainer()
{
return $this->container;
}
protected function get($service)
{
return $this->getContainer()->get($service);
}
protected function getManager()
{
return $this->getContainer()->get('doctrine.orm.entity_manager');
}
protected function getEntityManager()
{
return $this->getManager();
}
protected function getRepository($repo)
{
return $this->getContainer()->get('doctrine.orm.entity_manager')->getRepository($repo);
}
}
|
Use single quotes for strings | import React, { Component, PropTypes } from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
class Filter extends Component {
constructor(props){
super(props);
this.state = {filterValue : this.props.query};
this.inputChanged = this.inputChanged.bind(this);
}
componentWillUnmount(){
if(this.timeout){
window.clearTimeout(this.timeout);
this.timeout = null;
}
}
inputChanged(event){
this.setState({filterValue: event.target.value});
if (this.timeout){
window.clearTimeout(this.timeout);
this.timeout = null;
}
this.timeout = window.setTimeout(()=>{
this.props.config.eventHandler(
{
type:'filter-change',
id: this.props.config.id,
column: this.props.column,
query: this.state.filterValue
}
);
}, 300);
}
render(){
return(
<FormControl id={'filter_for_'+this.props.column} type='search' key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={"Filter..."} />
);
}
}
Filter.propTypes = {
query: PropTypes.string,
config: PropTypes.object,
column: PropTypes.string.isRequired
};
export default Filter;
| import React, { Component, PropTypes } from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
class Filter extends Component {
constructor(props){
super(props);
this.state = {filterValue : this.props.query};
this.inputChanged = this.inputChanged.bind(this);
}
componentWillUnmount(){
if(this.timeout){
window.clearTimeout(this.timeout);
this.timeout = null;
}
}
inputChanged(event){
this.setState({filterValue: event.target.value});
if (this.timeout){
window.clearTimeout(this.timeout);
this.timeout = null;
}
this.timeout = window.setTimeout(()=>{
this.props.config.eventHandler(
{
type:'filter-change',
id: this.props.config.id,
column: this.props.column,
query: this.state.filterValue
}
);
}, 300);
}
render(){
return(
<FormControl id={'filter_for_'+this.props.column} type="search" key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={"Filter..."} />
);
}
}
Filter.propTypes = {
query: PropTypes.string,
config: PropTypes.object,
column: PropTypes.string.isRequired
};
export default Filter; |
Add must login requirement to user page | <?php
namespace Page;
class User
{
public function index()
{
$this->router->redirect('user/profile');
}
public function profile()
{
$this->auth->requireLogin();
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->library('Image');
$this->load->library('Date');
$cfg = $this->config->loadInfo('Manga');
$mangas = $this->manga->getUserManga(
$this->auth->getUserId(), 0, 36);
$history = $this->manga->getUserHistory(
$this->auth->getUserId(), 0, 31);
$this->load->storeView('User', [
'mangas'=>$mangas,
'history'=>$history,
'mangapath'=>$cfg['path']
]);
$this->load->layout('Fresh', [
'title'=>'My Reading History'
]);
}
public function history()
{
$this->auth->requireLogin();
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->library('Date');
$history = $this->manga->getUserHistory(
$this->auth->getUserId(), 0, 100);
$this->load->storeView('History', [
'history'=>$history,
'single'=>true
]);
$this->load->layout('Fresh', [
'title'=>'My Reading History'
]);
}
}
?>
| <?php
namespace Page;
class User
{
public function index()
{
$this->router->redirect('user/profile');
}
public function profile()
{
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->library('Image');
$this->load->library('Date');
$cfg = $this->config->loadInfo('Manga');
$mangas = $this->manga->getUserManga(
$this->auth->getUserId(), 0, 36);
$history = $this->manga->getUserHistory(
$this->auth->getUserId(), 0, 31);
$this->load->storeView('User', [
'mangas'=>$mangas,
'history'=>$history,
'mangapath'=>$cfg['path']
]);
$this->load->layout('Fresh', [
'title'=>'My Reading History'
]);
}
public function history()
{
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->library('Date');
$history = $this->manga->getUserHistory(
$this->auth->getUserId(), 0, 100);
$this->load->storeView('History', [
'history'=>$history,
'single'=>true
]);
$this->load->layout('Fresh', [
'title'=>'My Reading History'
]);
}
}
?>
|
Update DictStack implementation from jaraco.collections 3.5.1 | import collections
import itertools
# from jaraco.collections 3.5.1
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
giving preference to the last.
>>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
>>> stack['a']
2
>>> stack['b']
2
>>> stack['c']
2
>>> len(stack)
3
>>> stack.push(dict(a=3))
>>> stack['a']
3
>>> set(stack.keys()) == set(['a', 'b', 'c'])
True
>>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)])
True
>>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2)
True
>>> d = stack.pop()
>>> stack['a']
2
>>> d = stack.pop()
>>> stack['a']
1
>>> stack.get('b', None)
>>> 'c' in stack
True
"""
def __iter__(self):
dicts = list.__iter__(self)
return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts)))
def __getitem__(self, key):
for scope in reversed(tuple(list.__iter__(self))):
if key in scope:
return scope[key]
raise KeyError(key)
push = list.append
def __contains__(self, other):
return collections.abc.Mapping.__contains__(self, other)
def __len__(self):
return len(list(iter(self)))
| import collections
import itertools
# from jaraco.collections 3.5
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
giving preference to the last.
>>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
>>> stack['a']
2
>>> stack['b']
2
>>> stack['c']
2
>>> stack.push(dict(a=3))
>>> stack['a']
3
>>> set(stack.keys()) == set(['a', 'b', 'c'])
True
>>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)])
True
>>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2)
True
>>> d = stack.pop()
>>> stack['a']
2
>>> d = stack.pop()
>>> stack['a']
1
>>> stack.get('b', None)
>>> 'c' in stack
True
"""
def __iter__(self):
dicts = list.__iter__(self)
return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts)))
def __getitem__(self, key):
for scope in reversed(self):
if key in scope:
return scope[key]
raise KeyError(key)
push = list.append
def __contains__(self, other):
return collections.abc.Mapping.__contains__(self, other)
|
Make npm verbose during 'platform build -vv' | <?php
namespace Platformsh\Cli\Local\Toolstack;
use Platformsh\Cli\Exception\DependencyMissingException;
use Symfony\Component\Console\Output\OutputInterface;
class NodeJs extends ToolstackBase
{
public function getKey()
{
return 'nodejs:default';
}
public function detect($appRoot)
{
// Refuse to detect automatically.
return false;
}
public function build()
{
$this->buildInPlace = true;
$buildDir = $this->getBuildDir();
if ($this->copy) {
if (!file_exists($this->appRoot . '/' . $this->documentRoot)) {
$buildDir = $this->getWebRoot();
}
$this->fsHelper->copyAll($this->appRoot, $buildDir);
}
if (file_exists($buildDir . '/package.json')) {
$this->output->writeln("Found a package.json file, installing dependencies");
if (!$this->shellHelper->commandExists('npm')) {
throw new DependencyMissingException('npm is not installed');
}
$npm = $this->shellHelper->resolveCommand('npm');
$npmArgs = [$npm];
if (!empty($this->settings['verbosity']) && $this->settings['verbosity'] >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
$npmArgs[] = '--loglevel=verbose';
}
$pruneArgs = $npmArgs;
$pruneArgs[] = 'prune';
$this->shellHelper->execute($pruneArgs, $buildDir, true, false);
$installArgs = $npmArgs;
$installArgs[] = 'install';
$this->shellHelper->execute($installArgs, $buildDir, true, false);
}
$this->processSpecialDestinations();
}
public function install()
{
$this->copyGitIgnore('gitignore-nodejs');
}
}
| <?php
namespace Platformsh\Cli\Local\Toolstack;
use Platformsh\Cli\Exception\DependencyMissingException;
class NodeJs extends ToolstackBase
{
public function getKey()
{
return 'nodejs:default';
}
public function detect($appRoot)
{
// Refuse to detect automatically.
return false;
}
public function build()
{
$this->buildInPlace = true;
$buildDir = $this->getBuildDir();
if ($this->copy) {
if (!file_exists($this->appRoot . '/' . $this->documentRoot)) {
$buildDir = $this->getWebRoot();
}
$this->fsHelper->copyAll($this->appRoot, $buildDir);
}
if (file_exists($buildDir . '/package.json')) {
$this->output->writeln("Found a package.json file, installing dependencies");
if (!$this->shellHelper->commandExists('npm')) {
throw new DependencyMissingException('npm is not installed');
}
$npm = $this->shellHelper->resolveCommand('npm');
$this->shellHelper->execute([$npm, 'prune'], $buildDir, true, false);
$this->shellHelper->execute([$npm, 'install'], $buildDir, true, false);
}
$this->processSpecialDestinations();
}
public function install()
{
$this->copyGitIgnore('gitignore-nodejs');
}
}
|
Make field filter errors ValidationErrors |
from django.db.models.fields import NOT_PROVIDED
from django.forms import ValidationError
from nap.utils import digattr
class field(property):
'''A base class to compare against.'''
def __get__(self, instance, cls=None):
if instance is None:
return self
return self.fget(instance._obj)
def __set__(self, instance, value):
self.fset(instance._obj, value)
class Field(field):
'''
class V(DataView):
foo = Field('bar', default=1)
'''
def __init__(self, name, default=NOT_PROVIDED, filters=None):
self.name = name
self.default = default
self.filters = filters or []
def __get__(self, instance, cls=None):
if instance is None:
return self
value = getattr(instance._obj, self.name, self.default)
for filt in self.filters:
try:
value = filt.from_python(value)
except (TypeError, ValueError):
raise ValidationError('Invalid value')
return value
def __set__(self, instance, value):
for filt in self.filters[::-1]:
value = filt.to_python(value)
setattr(instance._obj, self.name, value)
class DigField(Field):
def __get__(self, instance, cls=None):
if instance is None:
return self
return digattr(instance._obj, self.name, self.default)
def __set__(self, instance):
raise NotImplementedError
|
from django.db.models.fields import NOT_PROVIDED
from nap.utils import digattr
class field(property):
'''A base class to compare against.'''
def __get__(self, instance, cls=None):
if instance is None:
return self
return self.fget(instance._obj)
def __set__(self, instance, value):
self.fset(instance._obj, value)
class Field(field):
'''
class V(DataView):
foo = Field('bar', default=1)
'''
def __init__(self, name, default=NOT_PROVIDED, filters=None):
self.name = name
self.default = default
self.filters = filters or []
def __get__(self, instance, cls=None):
if instance is None:
return self
value = getattr(instance._obj, self.name, self.default)
for filt in self.filters:
value = filt.from_python(value)
return value
def __set__(self, instance, value):
for filt in self.filters[::-1]:
value = filt.to_python(value)
setattr(instance._obj, self.name, value)
class DigField(Field):
def __get__(self, instance, cls=None):
if instance is None:
return self
return digattr(instance._obj, self.name, self.default)
def __set__(self, instance):
raise NotImplementedError
|
Add test login error case | <?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
class LoginControllerTest extends TestCase
{
/**
*
*/
public function testLogin()
{
$userVerifiedData = [
'email' => '[email protected]',
'password' => Hash::make('password'),
'activated' => true
];
$this->deleteUser($userVerifiedData);
factory(User::class)->create($userVerifiedData);
$response = $this->json('POST', '/api/v1/login',
[
'email' => $userVerifiedData['email'],
'password' => 'password'
]
);
$response->assertStatus(200);
}
/**
*
*/
public function testLoginError()
{
$userVerifiedData = [
'email' => '[email protected]',
'password' => Hash::make('password'),
'activated' => true
];
$this->deleteUser($userVerifiedData);
factory(User::class)->create($userVerifiedData);
$response = $this->json('POST', '/api/v1/login',
[
'email' => $userVerifiedData['email'],
'password' => 'password-wrong'
]
);
$response->assertStatus(401);
}
} | <?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
class LoginControllerTest extends TestCase
{
/**
*
*/
public function testLogin()
{
$userVerifiedData = [
'email' => '[email protected]',
'password' => Hash::make('password'),
'activated' => true
];
$this->deleteUser($userVerifiedData);
factory(User::class)->create($userVerifiedData);
$response = $this->json('POST', '/api/v1/login',
[
'email' => $userVerifiedData['email'],
'password' => 'password'
]
);
$response->assertStatus(200);
}
/**
*
*/
public function testLogout()
{
$userVerifiedData = [
'email' => '[email protected]',
'password' => Hash::make('password'),
'activated' => true
];
$this->deleteUser($userVerifiedData);
$user = factory(User::class)->create($userVerifiedData);
$response = $this->actingAs($user, 'api')->json('GET', '/api/v1/logout',[], $this->headers($user));
$response->assertStatus(200);
}
} |
Add chain capability to a row object | <?php
/*
* This file is part of the DataGridBundle.
*
* (c) Stanislav Turza <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sorien\DataGridBundle\Grid;
class Row
{
private $fields;
private $color;
private $legend;
private $primaryField;
public function __construct()
{
$this->fields = array();
$this->color = '';
}
public function setField($rowId, $value)
{
$this->fields[$rowId] = $value;
return $this;
}
public function getField($rowId)
{
return isset($this->fields[$rowId]) ? $this->fields[$rowId] : '';
}
public function setColor($color)
{
$this->color = $color;
return $this;
}
public function getColor()
{
return $this->color;
}
public function setLegend($legend)
{
$this->legend = $legend
return $this;
}
public function getLegend()
{
return $this->legend;
}
public function setPrimaryField($primaryField)
{
$this->primaryField = $primaryField;
return $this;
}
public function getPrimaryField()
{
return $this->primaryField;
}
public function getPrimaryFieldValue()
{
return $this->fields[$this->primaryField];
}
}
| <?php
/*
* This file is part of the DataGridBundle.
*
* (c) Stanislav Turza <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sorien\DataGridBundle\Grid;
class Row
{
private $fields;
private $color;
private $legend;
private $primaryField;
public function __construct()
{
$this->fields = array();
$this->color = '';
}
public function setField($rowId, $value)
{
$this->fields[$rowId] = $value;
return $this;
}
public function getField($rowId)
{
return isset($this->fields[$rowId]) ? $this->fields[$rowId] : '';
}
public function setColor($color)
{
$this->color = $color;
return $this;
}
public function getColor()
{
return $this->color;
}
public function setLegend($legend)
{
$this->legend = $legend;
return $this;
}
public function getLegend()
{
return $this->legend;
}
public function setPrimaryField($primaryField)
{
$this->primaryField = $primaryField;
return $this;
}
public function getPrimaryField()
{
return $this->primaryField;
}
public function getPrimaryFieldValue()
{
return $this->fields[$this->primaryField];
}
}
|
Make the last function also a generator, so that the explanation flows better | #!/usr/bin/env python
import sys, operator, string
def characters(filename):
for line in open(filename):
for c in line:
yield c
def all_words(filename):
start_char = True
for c in characters(filename):
if start_char == True:
word = ""
if c.isalnum():
# We found the start of a word
word = c.lower()
start_char = False
else: pass
else:
if c.isalnum():
word += c.lower()
else:
# We found end of word, emit it
start_char = True
yield word
def non_stop_words(filename):
stopwords = set(open('../stop_words.txt').read().split(',') + list(string.ascii_lowercase))
for w in all_words(filename):
if not w in stopwords:
yield w
def count_and_sort(filename):
freqs, i = {}, 1
for w in non_stop_words(filename):
freqs[w] = 1 if w not in freqs else freqs[w]+1
if i % 5000 == 0:
yield sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True)
i = i+1
yield sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True)
#
# The main function
#
for word_freqs in count_and_sort(sys.argv[1]):
print "-----------------------------"
for (w, c) in word_freqs[0:25]:
print w, ' - ', c
| #!/usr/bin/env python
import sys, operator, string
def characters(filename):
for line in open(filename):
for c in line:
yield c
def all_words(filename):
start_char = True
for c in characters(filename):
if start_char == True:
word = ""
if c.isalnum():
# We found the start of a word
word = c.lower()
start_char = False
else: pass
else:
if c.isalnum():
word += c.lower()
else:
# We found end of word, emit it
start_char = True
yield word
def non_stop_words(filename):
stopwords = set(open('../stop_words.txt').read().split(',') + list(string.ascii_lowercase))
for w in all_words(filename):
if not w in stopwords:
yield w
def count_and_sort(filename):
freqs = {}
for w in non_stop_words(filename):
freqs[w] = 1 if w not in freqs else freqs[w]+1
return sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True)
#
# The main function
#
word_freqs = count_and_sort(sys.argv[1])
for (w, c) in word_freqs[0:25]:
print w, ' - ', c
|
Use updated_at isntead of created_at | <div class="content-filter-ui" data-url="{!! URL::current() !!}">
{!! Form::label('newscat_id', trans('app.category')) !!}: {!! Form::selectForeign('newscat_id', null, true) !!}
</div>
@foreach ($newsCollection as $news)
<article class="news">
<header>
<h2>{{ $news->title }}</h2>
<span><time>{{ $news->updated_at }}</time> {!! trans('news::written_by') !!} {!! link_to('users/'.$news->creator->id.'/'.$news->creator->slug, $news->creator->username) !!} {!! trans('news::in') !!} {{ $news->newscat->title }}</span>
</header>
<div class="content">
@if ($news->newscat->image)
<div class="image">
<a href="{!! 'news/'.$news->id.'/'.$news->slug !!}">
<img src="{!! $news->newscat->uploadPath().$news->newscat->image !!}" alt="{{ $news->newscat->title }}">
</a>
</div>
@endif
<div class="summary">
{!! $news->summary !!}
</div>
</div>
<div class="meta">
{{ $news->countComments() }} {!! trans('app.comments') !!} - {!! link_to('news/'.$news->id.'/'.$news->slug, trans('app.read_more')) !!}
</div>
</article>
@endforeach | <div class="content-filter-ui" data-url="{!! URL::current() !!}">
{!! Form::label('newscat_id', trans('app.category')) !!}: {!! Form::selectForeign('newscat_id', null, true) !!}
</div>
@foreach ($newsCollection as $news)
<article class="news">
<header>
<h2>{{ $news->title }}</h2>
<span><time>{{ $news->created_at }}</time> {!! trans('news::written_by') !!} {!! link_to('users/'.$news->creator->id.'/'.$news->creator->slug, $news->creator->username) !!} {!! trans('news::in') !!} {{ $news->newscat->title }}</span>
</header>
<div class="content">
@if ($news->newscat->image)
<div class="image">
<a href="{!! 'news/'.$news->id.'/'.$news->slug !!}">
<img src="{!! $news->newscat->uploadPath().$news->newscat->image !!}" alt="{{ $news->newscat->title }}">
</a>
</div>
@endif
<div class="summary">
{!! $news->summary !!}
</div>
</div>
<div class="meta">
{{ $news->countComments() }} {!! trans('app.comments') !!} - {!! link_to('news/'.$news->id.'/'.$news->slug, trans('app.read_more')) !!}
</div>
</article>
@endforeach |
Revert "fix: NpzPckLoader meddle one-element array"
This reverts commit b3bf178ed07d789282a05fa4efac799c9e0c5910.
NpzPckLoader:
* 1 vs array(1)
* 'a' vs array('a', dtype='<U1')
NpzPckSaver np.asanyarray:
* 1 vs np.void(pickle.dumps('1'))
* 'a' vs np.void(pickle.dumps('a'))
Note:
* type(np.asanyarray(np.void(pickle.dumps('a')))[()]) is np.void
* type(np.asanyarray(np.void(pickle.dumps('a'))).item()) is not np.void
* pickle.loads(np.asanyarray(np.void(pickle.dumps('a')))[()].tostring()) is 'a' | # -*- coding: utf-8 -*-
# Copyright (c) 2019 shmilee
'''
Contains Npz pickled file loader class.
'''
import numpy
import zipfile
from ..glogger import getGLogger
from .base import BasePckLoader
__all__ = ['NpzPckLoader']
log = getGLogger('L')
class NpzPckLoader(BasePckLoader):
'''
Load pickled data from ``.npz`` file. Return a dictionary-like object.
Notes
-----
Q: How to read data from .npz file?
A: npzfile[datakey]
>>> npzfile = numpy.load('/tmp/test.npz')
>>> datakey = 'group/key'
>>> npzfile[datakey]
'''
__slots__ = []
loader_type = '.npz'
def _special_check_path(self):
if zipfile.is_zipfile(self.path):
return True
else:
log.error("'%s' is not a ZIP file!" % self.path)
return False
def _special_open(self):
return numpy.load(self.path)
def _special_close(self, tmpobj):
tmpobj.close()
def _special_getkeys(self, tmpobj):
return sorted(dict.fromkeys(tmpobj.files))
def _special_get(self, tmpobj, key):
value = tmpobj[key]
if value.size == 1:
value = value.item()
return value
| # -*- coding: utf-8 -*-
# Copyright (c) 2019 shmilee
'''
Contains Npz pickled file loader class.
'''
import numpy
import zipfile
from ..glogger import getGLogger
from .base import BasePckLoader
__all__ = ['NpzPckLoader']
log = getGLogger('L')
class NpzPckLoader(BasePckLoader):
'''
Load pickled data from ``.npz`` file. Return a dictionary-like object.
Notes
-----
Q: How to read data from .npz file?
A: npzfile[datakey]
>>> npzfile = numpy.load('/tmp/test.npz')
>>> datakey = 'group/key'
>>> npzfile[datakey]
'''
__slots__ = []
loader_type = '.npz'
def _special_check_path(self):
if zipfile.is_zipfile(self.path):
return True
else:
log.error("'%s' is not a ZIP file!" % self.path)
return False
def _special_open(self):
return numpy.load(self.path)
def _special_close(self, tmpobj):
tmpobj.close()
def _special_getkeys(self, tmpobj):
return sorted(dict.fromkeys(tmpobj.files))
def _special_get(self, tmpobj, key):
value = tmpobj[key]
# if value.size == 1:
# value = value.item()
return value
|
Fix failing move forward tests | class Rover:
compass = ['N', 'E', 'S', 'W']
def __init__(self, x=0, y=0, direction='N'):
self.x = x
self.y = y
self.direction = direction
@property
def position(self):
return self.x, self.y, self.direction
@property
def compass_index(self):
return next(i for i in range(0, len(self.compass)) if self.compass[i] == self.direction)
@property
def axis(self):
# 0 if pointing along x axis
# 1 if pointing along y axis
return (self.compass_index + 1) % 2
@property
def multiplier(self):
# 1 if pointing N or E
# -1 if pointing S or W
if self.compass_index <= 1:
return 1
else:
return -1
def set_position(self, x=None, y=None, direction=None):
if x is not None:
self.x = x
if y is not None:
self.y = y
if direction is not None:
self.direction = direction
def move(self, *args):
for command in args:
if command == 'F':
# Move forward command
if self.axis == 0:
# Working on X axis
self.x = self.x + 1 * self.multiplier
else:
# Working on Y axis
self.y = self.y + 1 * self.multiplier
else:
pass
| class Rover:
compass = ['N', 'E', 'S', 'W']
def __init__(self, x=0, y=0, direction='N'):
self.x = x
self.y = y
self.direction = direction
@property
def position(self):
return self.x, self.y, self.direction
@property
def compass_index(self):
return next(i for i in range(0, len(self.compass)) if self.compass[i] == self.direction)
@property
def axis(self):
# 0 if pointing along x axis
# 1 if pointing along y axis
return (self.compass_index + 1) % 2
@property
def multiplier(self):
# 1 if pointing N or E
# -1 if pointing S or W
if self.compass_index <= 1:
return 1
else:
return -1
def set_position(self, x=None, y=None, direction=None):
if x is not None:
self.x = x
if y is not None:
self.y = y
if direction is not None:
self.direction = direction
def move(self, *args):
for command in args:
if command == 'F':
# Move forward command
if self.compass_index < 2:
# Upper right quadrant, increasing x/y
pass
else:
pass
|
Fix exception when access is not specified | package com.github.dump247.jenkins.plugins.dockerjob.slaves;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
public class DirectoryMapping {
private static final Pattern MAPPING_PATTERN = Pattern.compile("^(/[^:]+):(/[^:]+)(?::(ro|rw))?$");
private final String _hostPath;
private final String _containerPath;
private final Access _access;
public DirectoryMapping(String hostPath, String containerPath, Access access) {
_hostPath = checkNotNull(hostPath);
_containerPath = checkNotNull(containerPath);
_access = checkNotNull(access);
}
public String getHostPath() {
return _hostPath;
}
public String getContainerPath() {
return _containerPath;
}
public Access getAccess() {
return _access;
}
public static enum Access {
READ("ro"),
READ_WRITE("rw");
private final String _value;
Access(String value) {
_value = value;
}
public String value() {
return _value;
}
}
public static DirectoryMapping parse(String value) {
checkNotNull(value);
Matcher match = MAPPING_PATTERN.matcher(value);
if (!match.matches()) {
throw new IllegalArgumentException("Invalid directory mapping: " + value);
}
return new DirectoryMapping(
match.group(1),
match.group(2),
"rw".equals(match.group(3)) ? Access.READ_WRITE : Access.READ);
}
}
| package com.github.dump247.jenkins.plugins.dockerjob.slaves;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
public class DirectoryMapping {
private static final Pattern MAPPING_PATTERN = Pattern.compile("^(/[^:]+):(/[^:]+)(?::(ro|rw))?$");
private final String _hostPath;
private final String _containerPath;
private final Access _access;
public DirectoryMapping(String hostPath, String containerPath, Access access) {
_hostPath = checkNotNull(hostPath);
_containerPath = checkNotNull(containerPath);
_access = checkNotNull(access);
}
public String getHostPath() {
return _hostPath;
}
public String getContainerPath() {
return _containerPath;
}
public Access getAccess() {
return _access;
}
public static enum Access {
READ("ro"),
READ_WRITE("rw");
private final String _value;
Access(String value) {
_value = value;
}
public String value() {
return _value;
}
}
public static DirectoryMapping parse(String value) {
checkNotNull(value);
Matcher match = MAPPING_PATTERN.matcher(value);
if (!match.matches()) {
throw new IllegalArgumentException("Invalid directory mapping: " + value);
}
return new DirectoryMapping(
match.group(1),
match.group(2),
match.group(3).equals("rw") ? Access.READ_WRITE : Access.READ);
}
}
|
Switch workbench option to package | <?php namespace Arcanedev\GeoIP\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class InstallCommand extends Command
{
/* ------------------------------------------------------------------------------------------------
| Properties
| ------------------------------------------------------------------------------------------------
*/
/**
* The console command name.
*
* @var string
*/
protected $name = 'geo-ip:install';
/**
* The console command description.
*
* @var string
*/
protected $description = 'GeoIP Install Command [Migration + Seeds].';
/* ------------------------------------------------------------------------------------------------
| Constrcutor
| ------------------------------------------------------------------------------------------------
*/
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/* ------------------------------------------------------------------------------------------------
| Main Functions
| ------------------------------------------------------------------------------------------------
*/
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$this->runMigrations();
$this->runSeeds();
}
/* ------------------------------------------------------------------------------------------------
| Other Functions
| ------------------------------------------------------------------------------------------------
*/
private function runMigrations()
{
$this->call('migrate', [
'--env' => $this->option('env'),
'--package' =>'arcanedev/geo-ip'
]);
}
private function runSeeds()
{
$this->call('db:seed', [
'--class' => 'Arcanedev\\GeoIP\\Seeds\\DatabaseSeeder'
]);
}
}
| <?php namespace Arcanedev\GeoIP\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class InstallCommand extends Command
{
/* ------------------------------------------------------------------------------------------------
| Properties
| ------------------------------------------------------------------------------------------------
*/
/**
* The console command name.
*
* @var string
*/
protected $name = 'geo-ip:install';
/**
* The console command description.
*
* @var string
*/
protected $description = 'GeoIP Install Command [Migration + Seeds].';
/* ------------------------------------------------------------------------------------------------
| Constrcutor
| ------------------------------------------------------------------------------------------------
*/
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/* ------------------------------------------------------------------------------------------------
| Main Functions
| ------------------------------------------------------------------------------------------------
*/
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$this->runMigrations();
$this->runSeeds();
}
/* ------------------------------------------------------------------------------------------------
| Other Functions
| ------------------------------------------------------------------------------------------------
*/
private function runMigrations()
{
$this->call('migrate', [
'--env' => $this->option('env'),
'--bench' =>'arcanedev/geo-ip'
]);
}
private function runSeeds()
{
$this->call('db:seed', [
'--class' => 'Arcanedev\\GeoIP\\Seeds\\DatabaseSeeder'
]);
}
}
|
Create the console script entrypoint. | #!/usr/bin/env python
import os
from setuptools import setup
def readreq(filename):
result = []
with open(filename) as f:
for req in f:
req = req.lstrip()
if req.startswith('-e ') or req.startswith('http:'):
idx = req.find('#egg=')
if idx >= 0:
req = req[idx + 5:].partition('#')[0].strip()
else:
pass
else:
req = req.partition('#')[0].strip()
if not req:
continue
result.append(req)
return result
def readfile(filename):
with open(filename) as f:
return f.read()
setup(
name='train',
version='0.1.0',
author='Kevin L. Mitchell',
author_email='[email protected]',
url='https://github.com/klmitch/train',
description="Turnstile Benchmarking Tool",
long_description=readfile('README.rst'),
license='Apache License (2.0)',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
],
packages=['train'],
install_requires=readreq('.requires'),
tests_require=readreq('.test-requires'),
entry_points={
'console_scripts': [
'train = train.runner:train.console',
],
},
)
| #!/usr/bin/env python
import os
from setuptools import setup
def readreq(filename):
result = []
with open(filename) as f:
for req in f:
req = req.lstrip()
if req.startswith('-e ') or req.startswith('http:'):
idx = req.find('#egg=')
if idx >= 0:
req = req[idx + 5:].partition('#')[0].strip()
else:
pass
else:
req = req.partition('#')[0].strip()
if not req:
continue
result.append(req)
return result
def readfile(filename):
with open(filename) as f:
return f.read()
setup(
name='train',
version='0.1.0',
author='Kevin L. Mitchell',
author_email='[email protected]',
url='https://github.com/klmitch/train',
description="Turnstile Benchmarking Tool",
long_description=readfile('README.rst'),
license='Apache License (2.0)',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
],
packages=['train'],
install_requires=readreq('.requires'),
tests_require=readreq('.test-requires'),
entry_points={
'console_scripts': [
],
},
)
|
Convert column edit to react-modal | import classnames from 'classnames';
import Form from './Item/Form';
import Modal from 'react-modal';
import React, { Component } from 'react';
class EditColumn extends Component {
constructor() {
super();
this.state = { isEditing: false };
this.onDelete = this.onDelete.bind(this);
this.onEdit = this.onEdit.bind(this);
this.toggleEdit = this.toggleEdit.bind(this);
}
onDelete() {
this.props.onDelete(this.props.row.id);
}
toggleEdit() {
this.setState({ isEditing: true });
}
onEdit(item) {
this.setState({ isEditing: false });
this.props.onEdit(item);
}
render() {
return (
<div>
<Modal
contentLabel="Edit Item Modal"
isOpen={this.state.isEditing}
overlayClassName="modal-overlay"
onRequestClose={this.onEdit}
shouldCloseOnOverlayClick={true}
>
<Form
item={this.props.row}
onSubmit={this.onEdit}
isEditing={this.state.isEditing}
/>
</Modal>
<button
className="btn btn-primary"
onClick={this.toggleEdit}
>
Edit
</button>
<button
className="btn btn-primary"
onClick={this.onDelete}
>
Delete
</button>
</div>
);
}
}
export default (EditColumn);
| import classnames from 'classnames';
import Form from './Item/Form';
import React, { Component } from 'react';
class EditColumn extends Component {
constructor() {
super();
this.state = { isEditing: false };
this.onDelete = this.onDelete.bind(this);
this.onEdit = this.onEdit.bind(this);
this.toggleEdit = this.toggleEdit.bind(this);
}
onDelete() {
this.props.onDelete(this.props.row.id);
}
toggleEdit() {
this.setState({ isEditing: true });
}
onEdit(item) {
this.setState({ isEditing: false });
this.props.onEdit(item);
}
render() {
const editName = classnames('btn-group', {
'open': this.state.isEditing,
});
return (
<div>
<div className={editName}>
<button
className="btn btn-primary"
onClick={this.toggleEdit}
type="button"
>
Edit
</button>
<div className="dropdown-menu toggle-description">
<Form
item={this.props.row}
onSubmit={this.onEdit}
isEditing={this.state.isEditing}
/>
</div>
</div>
<button
className="btn btn-primary"
onClick={this.onDelete}
type="button"
>
Delete
</button>
</div>
);
}
}
export default (EditColumn);
|
Use buffer() to try and avoid memory copies | # -*- coding: utf-8 -*-
import errno
import collections
from savate import writev
# FIXME: should this be a method of BufferEvent below ?
# FIXME: handle Python2.x/Python3k compat here
def buffer_slice(buff, offset, size):
return buffer(buff, offset, size)
class BufferOutputHandler(object):
def __init__(self, sock, initial_buffer_queue = ()):
self.sock = sock
self.ready = True
self.buffer_queue = collections.deque(initial_buffer_queue)
def add_buffer(self, buff):
self.buffer_queue.append(buff)
def empty(self):
return len(self.buffer_queue) == 0
def flush(self):
self.ready = True
total_sent_bytes = 0
try:
while self.buffer_queue:
sent_bytes = self.sock.send(self.buffer_queue[0])
total_sent_bytes += sent_bytes
if sent_bytes < len(self.buffer_queue[0]):
# One of the buffers was partially sent
self.buffer_queue[0] = buffer_slice(self.buffer_queue[0], sent_bytes, -1)
else:
self.buffer_queue.popleft()
except IOError, exc:
if exc.errno == errno.EAGAIN:
self.ready = False
else:
raise
return total_sent_bytes
| # -*- coding: utf-8 -*-
import errno
import collections
from savate import writev
# FIXME: should this be a method of BufferEvent below ?
# FIXME: handle Python2.x/Python3k compat here
def buffer_slice(buff, offset, size):
return buffer(buff, offset, size)
class BufferOutputHandler(object):
def __init__(self, sock, initial_buffer_queue = ()):
self.sock = sock
self.ready = True
self.buffer_queue = collections.deque(initial_buffer_queue)
def add_buffer(self, buff):
self.buffer_queue.append(buff)
def empty(self):
return len(self.buffer_queue) == 0
def flush(self):
self.ready = True
total_sent_bytes = 0
try:
while self.buffer_queue:
sent_bytes = self.sock.send(self.buffer_queue[0])
total_sent_bytes += sent_bytes
if sent_bytes < len(self.buffer_queue[0]):
# One of the buffers was partially sent
self.buffer_queue[0] = self.buffer_queue[0][sent_bytes:]
else:
self.buffer_queue.popleft()
except IOError, exc:
if exc.errno == errno.EAGAIN:
self.ready = False
else:
raise
return total_sent_bytes
|
Support hostname argument on hosts defined in inventory.yml | <?php
namespace Droid\Loader;
use Symfony\Component\Yaml\Parser as YamlParser;
use Droid\Model\Inventory;
use Droid\Model\Host;
use Droid\Model\HostGroup;
use RuntimeException;
class YamlInventoryLoader
{
public function load(Inventory $inventory, $filename)
{
if (!file_exists($filename)) {
throw new RuntimeException("File not found: $filename");
}
$parser = new YamlParser();
$data = $parser->parse(file_get_contents($filename));
if (isset($data['hosts'])) {
foreach ($data['hosts'] as $hostName => $hostNode) {
$host = new Host($hostName);
if (isset($hostNode['hostname'])) {
$host->setHostName($hostNode['hostname']);
}
$inventory->addHost($host);
}
}
if (isset($data['groups'])) {
foreach ($data['groups'] as $groupName => $groupNode) {
$group = new HostGroup($groupName);
foreach ($groupNode as $hostName) {
if (!$inventory->hasHost($hostName)) {
throw new RuntimeException("Group $groupName refers to undefined host: $hostName");
}
$host = $inventory->getHost($hostName);
$group->addHost($host);
}
$inventory->addHostGroup($group);
}
}
//print_r($inventory);
}
}
| <?php
namespace Droid\Loader;
use Symfony\Component\Yaml\Parser as YamlParser;
use Droid\Model\Inventory;
use Droid\Model\Host;
use Droid\Model\HostGroup;
use RuntimeException;
class YamlInventoryLoader
{
public function load(Inventory $inventory, $filename)
{
if (!file_exists($filename)) {
throw new RuntimeException("File not found: $filename");
}
$parser = new YamlParser();
$data = $parser->parse(file_get_contents($filename));
if (isset($data['hosts'])) {
foreach ($data['hosts'] as $hostName => $hostNode) {
$host = new Host($hostName);
$inventory->addHost($host);
}
}
if (isset($data['groups'])) {
foreach ($data['groups'] as $groupName => $groupNode) {
$group = new HostGroup($groupName);
foreach ($groupNode as $hostName) {
if (!$inventory->hasHost($hostName)) {
throw new RuntimeException("Group $groupName refers to undefined host: $hostName");
}
$host = $inventory->getHost($hostName);
$group->addHost($host);
}
$inventory->addHostGroup($group);
}
}
//print_r($inventory);
}
}
|
Fix sending Amazon SES email with header by using protected properties in PHPMailer. | <?php
namespace ByJG\Mail\Wrapper;
use Aws\Common\Credentials\Credentials;
use Aws\Ses\SesClient;
use ByJG\Mail\Envelope;
use ByJG\Mail\MailConnection;
class AmazonSesWrapper extends PHPMailerWrapper
{
/**
* ses://accessid:aswsecret@region
*
* @param MailConnection $this->connection
* @param Envelope $envelope
*/
public function send(Envelope $envelope)
{
$mail = $this->prepareMailer($envelope);
// Call the preSend to set all PHPMailer variables and get the correct header and body;
$message = $mail->getFullMessageEnvelope();
// Fix BCC header because PHPMailer does not send to us
foreach ((array) $envelope->getBCC() as $bccEmail) {
$message = 'Bcc: '.$bccEmail."\n".$message;
}
//Send the message (which must be base 64 encoded):
$ses = SesClient::factory([
'credentials' => new Credentials($this->connection->getUsername(), $this->connection->getPassword()),
'region' => $this->connection->getServer()
]);
$ses->sendRawEmail(
[
'RawMessage' => [
'Data' => base64_encode($message),
]
]
);
}
}
| <?php
namespace ByJG\Mail\Wrapper;
use Aws\Common\Credentials\Credentials;
use Aws\Ses\SesClient;
use ByJG\Mail\Envelope;
use ByJG\Mail\MailConnection;
class AmazonSesWrapper extends PHPMailerWrapper
{
/**
* ses://accessid:aswsecret@region
*
* @param MailConnection $this->connection
* @param Envelope $envelope
*/
public function send(Envelope $envelope)
{
$mail = $this->prepareMailer($envelope);
// Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
$message = $mail->createHeader().$mail->createBody();
// Fix BCC header because PHPMailer does not send to us
foreach ((array) $envelope->getBCC() as $bccEmail) {
$message = 'Bcc: '.$bccEmail."\n".$message;
}
//Send the message (which must be base 64 encoded):
$ses = SesClient::factory([
'credentials' => new Credentials($this->connection->getUsername(), $this->connection->getPassword()),
'region' => $this->connection->getServer()
]);
$ses->sendRawEmail(
[
'RawMessage' => [
'Data' => base64_encode($message),
]
]
);
}
}
|
feat(repo): Include module name in AMD definition
RequireJS needs to know which name to register an AMD module under. The name was previously mixing; this PR fixes that. | 'use strict';
var webpack = require('webpack');
var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
var env = process.env.NODE_ENV;
var reactExternal = {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
};
var reactDomExternal = {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
};
var config = {
externals: {
react: reactExternal,
reactDom: reactDomExternal
},
module: {
loaders: [
{ test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ },
{ test: /\.jsx$/, loaders: ['babel-loader'], exclude: /node_modules/ }
]
},
output: {
library: {
root: 'ReactWebAnimation',
amd: 'react-web-animation',
},
libraryTarget: 'umd',
umdNamedDefine: true,
},
plugins: [
new LodashModuleReplacementPlugin(),
new webpack.EnvironmentPlugin([
"NODE_ENV"
])
]
};
if ( env === 'production' ) {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
pure_getters: true,
unsafe: true,
unsafe_comps: true,
screw_ie8: true,
warnings: false
}
})
);
}
module.exports = config;
| 'use strict';
var webpack = require('webpack');
var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
var env = process.env.NODE_ENV;
var reactExternal = {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
};
var reactDomExternal = {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
};
var config = {
externals: {
react: reactExternal,
reactDom: reactDomExternal
},
module: {
loaders: [
{ test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ },
{ test: /\.jsx$/, loaders: ['babel-loader'], exclude: /node_modules/ }
]
},
output: {
library: 'ReactWebAnimation',
libraryTarget: 'umd'
},
plugins: [
new LodashModuleReplacementPlugin(),
new webpack.EnvironmentPlugin([
"NODE_ENV"
])
]
};
if ( env === 'production' ) {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
pure_getters: true,
unsafe: true,
unsafe_comps: true,
screw_ie8: true,
warnings: false
}
})
);
}
module.exports = config;
|
Make AsyncTasks parallel on API 11+
According to the examination of the source code to AsyncTask, on pre-Honeycomb all of the AsyncTasks were executed on a thread pool with a minimum of 5 threads and a maximum of 128. But on API 11+, it won't be executed on a thread pool unless you call executeOnExecutor() with the corresponding argument.
Source: http://developer.android.com/reference/android/os/AsyncTask.html | package inaka.com.tinytask;
public class TinyTask<T> {
private static TinyTask instance = null;
private GenericTask<T> genericTask;
private Something<T> something;
private DoThis<T> callback;
private TinyTask(Something<T> something) {
this.something = something;
}
private TinyTask(DoThis<T> callback) {
this.callback = callback;
}
public static TinyTask perform(Something something) {
if(instance == null) {
instance = new TinyTask(something);
} else {
instance.something = something;
}
return instance;
}
public TinyTask whenDone(DoThis<T> callback) {
if(instance == null) {
instance = new TinyTask<>(callback);
} else {
instance.callback = callback;
}
return instance;
}
public Something<T> getSomething() {
return something;
}
public DoThis<T> getCallback() {
return callback;
}
public void go() {
if(genericTask == null) {
genericTask = new GenericTask<>(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
genericTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
genericTask.execute();
}
}
}
public void cancel() {
if(genericTask != null) {
genericTask.cancel(true);
}
}
public boolean isCancelled() {
return genericTask.isCancelled();
}
}
| package inaka.com.tinytask;
public class TinyTask<T> {
private static TinyTask instance = null;
private GenericTask<T> genericTask;
private Something<T> something;
private DoThis<T> callback;
private TinyTask(Something<T> something) {
this.something = something;
}
private TinyTask(DoThis<T> callback) {
this.callback = callback;
}
public static TinyTask perform(Something something) {
if(instance == null) {
instance = new TinyTask(something);
} else {
instance.something = something;
}
return instance;
}
public TinyTask whenDone(DoThis<T> callback) {
if(instance == null) {
instance = new TinyTask<>(callback);
} else {
instance.callback = callback;
}
return instance;
}
public Something<T> getSomething() {
return something;
}
public DoThis<T> getCallback() {
return callback;
}
public void go() {
if(genericTask == null) {
genericTask = new GenericTask<>(this);
genericTask.execute();
}
}
public void cancel() {
if(genericTask != null) {
genericTask.cancel(true);
}
}
public boolean isCancelled() {
return genericTask.isCancelled();
}
}
|
Fix Webpack entry module path | const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const path = require('path');
// Extract CSS into a separate file
const extractSass = new ExtractTextPlugin({
filename: "../css/main.css",
});
// Minify JavaScript
const UglifyJsPlugin = new webpack.optimize.UglifyJsPlugin();
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: './js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'static/js'),
},
module: {
rules: [
// Process Sass files
{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader",
options: {
minimize: true,
}
}, {
loader: "postcss-loader",
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
},
// Transpile JavaScript files
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
// JavaScript linter
{
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
},
// Process images
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
}
]
}
]
},
plugins: [
extractSass,
UglifyJsPlugin,
]
}
| const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const path = require('path');
// Extract CSS into a separate file
const extractSass = new ExtractTextPlugin({
filename: "../css/main.css",
});
// Minify JavaScript
const UglifyJsPlugin = new webpack.optimize.UglifyJsPlugin();
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: './client/js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'static/js'),
},
module: {
rules: [
// Process Sass files
{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader",
options: {
minimize: true,
}
}, {
loader: "postcss-loader",
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
},
// Transpile JavaScript files
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
// JavaScript linter
{
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
},
// Process images
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
}
]
}
]
},
plugins: [
extractSass,
UglifyJsPlugin,
]
}
|
Return 404 if package was not found instead of raising an exception | """Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
return make_response('Not implemented', 501)
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
if os.path.isdir(package_path):
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
digest_file = os.path.join(package_path, filename)
with open(digest_file, 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
else:
return make_response('404', 404)
| """Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
return make_response('Not implemented', 501)
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
|
Make the string translator return the actual right values!
* zvm/zstring.py:
(ZStringStream._get_block): Remove debug printing.
(ZStringStream.get): Make the offset calculations work on the
correct bits of the data chunk. Remove debug printing. | #
# A ZString-to-ASCII Universal Translator.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
class ZStringEndOfString(Exception):
"""No more data left in string."""
class ZStringStream(object):
"""This class takes an address and a ZMemory, and treats that as
the begginning of a ZString. Subsequent calls to get() will return
one ZChar code at a time, raising ZStringEndOfString when there is
no more data."""
def __init__(self, zmem, addr):
self._mem = zmem
self._addr = addr
self._has_ended = False
self._get_block()
def _get_block(self):
from bitfield import BitField
chunk = self._mem[self._addr:self._addr+2]
self._data = BitField(''.join([chr(x) for x in chunk]))
self._addr += 2
self._char_in_block = 0
def get(self, num=1):
if self._has_ended:
raise ZStringEndOfString
# We must read in sequence bits 14-10, 9-5, 4-0.
offset = (2 - self._char_in_block) * 5
zchar = self._data[offset:offset+5]
if self._char_in_block == 2:
# If end-of-string marker is set...
if self._data[15] == 1:
self._has_ended = True
else:
self._get_block()
else:
self._char_in_block += 1
return zchar
| #
# A ZString-to-ASCII Universal Translator.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
class ZStringEndOfString(Exception):
"""No more data left in string."""
class ZStringStream(object):
"""This class takes an address and a ZMemory, and treats that as
the begginning of a ZString. Subsequent calls to get() will return
one ZChar code at a time, raising ZStringEndOfString when there is
no more data."""
def __init__(self, zmem, addr):
self._mem = zmem
self._addr = addr
self._has_ended = False
self._get_block()
def _get_block(self):
from bitfield import BitField
chunk = self._mem[self._addr:self._addr+2]
print chunk
self._data = BitField(''.join([chr(x) for x in chunk]))
self._addr += 2
self._char_in_block = 0
def get(self, num=1):
if self._has_ended:
raise ZStringEndOfString
offset = self._char_in_block * 5
print offset
zchar = self._data[offset:offset+5]
if self._char_in_block == 2:
# If end-of-string marker is set...
if self._data[15] == 1:
self._has_ended = True
else:
self._get_block()
else:
self._char_in_block += 1
return zchar
|
feat(form): Include maxBikeTime with default general settings | import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import DropdownSelector from './dropdown-selector'
import queryParams from '../../common/query-params'
class GeneralSettingsPanel extends Component {
static propTypes = {
query: PropTypes.object,
paramNames: PropTypes.array
}
static defaultProps = {
paramNames: [ 'maxWalkDistance', 'maxWalkTime', 'walkSpeed', 'maxBikeTime', 'bikeSpeed', 'optimize' ]
}
render () {
const { paramNames, query } = this.props
return (
<div className='general-settings-panel'>
{paramNames.map(param => {
const paramInfo = queryParams.find(qp => qp.name === param)
if (paramInfo.planTypes.indexOf(query.type) === -1) return
switch (paramInfo.selector) {
case 'DROPDOWN':
return <DropdownSelector
key={paramInfo.name}
name={paramInfo.name}
value={query[paramInfo.name]}
label={paramInfo.label}
options={paramInfo.options}
/>
}
})}
</div>
)
}
}
// connect to redux store
const mapStateToProps = (state, ownProps) => {
return {
query: state.otp.currentQuery
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(GeneralSettingsPanel)
| import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import DropdownSelector from './dropdown-selector'
import queryParams from '../../common/query-params'
class GeneralSettingsPanel extends Component {
static propTypes = {
query: PropTypes.object,
paramNames: PropTypes.array
}
static defaultProps = {
paramNames: [ 'maxWalkDistance', 'maxWalkTime', 'walkSpeed', 'bikeSpeed', 'optimize' ]
}
render () {
const { paramNames, query } = this.props
return (
<div className='general-settings-panel'>
{paramNames.map(param => {
const paramInfo = queryParams.find(qp => qp.name === param)
if (paramInfo.planTypes.indexOf(query.type) === -1) return
switch (paramInfo.selector) {
case 'DROPDOWN':
return <DropdownSelector
key={paramInfo.name}
name={paramInfo.name}
value={query[paramInfo.name]}
label={paramInfo.label}
options={paramInfo.options}
/>
}
})}
</div>
)
}
}
// connect to redux store
const mapStateToProps = (state, ownProps) => {
return {
query: state.otp.currentQuery
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(GeneralSettingsPanel)
|
Improve IN clause in WHERE | <?php
namespace BW\BlogBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* PostRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PostRepository extends EntityRepository {
public function findNestedBy($left, $right) {
$request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
$qb = $this->createQueryBuilder('p')
->innerJoin('p.category', 'c')
->innerJoin('p.route', 'r')
->innerJoin('p.lang', 'l')
->where('p.published = 1')
->andWhere('c.published = 1')
->andWhere('c.left >= :left')
->andWhere('c.left <= :right')
->setParameter('left', $left)
->setParameter('right', $right)
->orderBy('p.created', 'DESC')
;
/* Custom Filter */
$form = $request->query->get('form', FALSE);
if ($form) {
if (isset($form['properteis'])) {
$qb = $qb
->innerJoin('p.customFieldProperties', 'cfp')
->andWhere('cfp.id IN (:properties)')
->setParameter('properties', $form['properteis'])
;
}
}
/* /Custom Filter */
return $qb->getQuery()->getResult();
}
}
| <?php
namespace BW\BlogBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* PostRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PostRepository extends EntityRepository {
public function findNestedBy($left, $right) {
$qb = $this->createQueryBuilder('p')
->innerJoin('p.category', 'c')
->innerJoin('p.route', 'r')
->innerJoin('p.lang', 'l')
->where('p.published = 1')
->andWhere('c.published = 1')
->andWhere('c.left >= :left')
->andWhere('c.left <= :right')
->setParameter('left', $left)
->setParameter('right', $right)
->orderBy('p.created', 'DESC')
;
if (isset($_GET['form'])) {
$qb = $qb
->innerJoin('p.customFieldProperties', 'cfp')
->andWhere('cfp.id IN ('. implode(',', $_GET['form']['properteis']) .') ')
//->andWhere('cfp.id IN (:properties)')
//->setParameter('properties', implode(',', $_GET['form']['properteis']))
;
}
return $qb->getQuery()->getResult();
}
}
|
Fix up error handling for flowd | # flowtools_wrapper.py
# Copyright 2014 Bo Bayles ([email protected])
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
ERR_MSG = 'Could not extract data from {}'
FLOWD_READER_ARGS = [
'flowd-reader',
'-v', # Verbose output
'-c', # CSV formatting
'-U', # UTC timestamps
'{file_path:}'
]
def FlowLog(file_path):
args = FLOWD_READER_ARGS[:]
args[-1] = file_path
with io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
# Skip the headers
next(iterator)
next(iterator)
except StopIteration:
raise IOError(ERR_MSG.format(file_path))
line = None
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
else:
if line is None:
raise IOError(ERR_MSG.format(file_path))
| # flowtools_wrapper.py
# Copyright 2014 Bo Bayles ([email protected])
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOWD_READER_ARGS = [
'flowd-reader',
'-v', # Verbose output
'-c', # CSV formatting
'-U', # UTC timestamps
'{file_path:}'
]
def FlowLog(file_path):
args = FLOWD_READER_ARGS[:]
args[-1] = file_path
with io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
# Skip the headers
next(iterator)
next(iterator)
except StopIteration:
msg = 'Could not extract data from {}'.format(file_path)
raise IOError(msg)
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
|
Remove retries limit in read ftm. | import json
import logging
class IOHandler(object):
@classmethod
def is_host_compatible(cls, host):
return False
def __init__(self, host):
raise NotImplementedError
def is_ready(self):
raise NotImplementedError
def read(self, trials=5):
try:
data = self.recv()
return self.loads(data)
except Exception as e:
logging.getLogger(__name__).debug('Msg read failed: {}'.format(str(e)))
if trials == 0:
raise e
return self.read(trials)
def recv(self):
raise NotImplementedError
def send(self, msg):
self.write(self.dumps(msg))
def write(self, data):
raise NotImplementedError
def loads(self, data):
if type(data) == bytes:
data = data.decode()
return json.loads(data)
def dumps(self, msg):
return json.dumps(msg).encode()
from .ws import Ws
from .serial_io import Serial
IOs = [Serial, Ws]
def io_from_host(host, *args, **kwargs):
for cls in IOs:
if cls.is_host_compatible(host):
return cls(host=host, *args, **kwargs)
raise ValueError('No corresponding IO found (among {}).'.format(discover_hosts))
def discover_hosts():
return sum([io.available_hosts() for io in IOs], [])
| import json
import logging
class IOHandler(object):
@classmethod
def is_host_compatible(cls, host):
return False
def __init__(self, host):
raise NotImplementedError
def is_ready(self):
raise NotImplementedError
def read(self, trials=5):
try:
data = self.recv()
return self.loads(data)
except Exception as e:
logging.getLogger(__name__).debug('Msg read failed: {}'.format(str(e)))
if trials > 0:
return self.read(trials - 1)
else:
raise e
def recv(self):
raise NotImplementedError
def send(self, msg):
self.write(self.dumps(msg))
def write(self, data):
raise NotImplementedError
def loads(self, data):
if type(data) == bytes:
data = data.decode()
return json.loads(data)
def dumps(self, msg):
return json.dumps(msg).encode()
from .ws import Ws
from .serial_io import Serial
IOs = [Serial, Ws]
def io_from_host(host, *args, **kwargs):
for cls in IOs:
if cls.is_host_compatible(host):
return cls(host=host, *args, **kwargs)
raise ValueError('No corresponding IO found (among {}).'.format(discover_hosts))
def discover_hosts():
return sum([io.available_hosts() for io in IOs], [])
|
Fix deprecation warning from moment | var _ = require('lodash'),
moment = require('moment');
function RelativeTimeExtension() {
moment.updateLocale('en', {
relativeTime : {
future: "in %s",
past: "%s ago",
s: function (number, withoutSuffix, key, isFuture) {
var plural = (number < 2) ? " second" : " seconds";
return number + plural;
},
m: "%d minute",
mm: "%d minutes",
h: "%d hour",
hh: "%d hours",
d: "%d day",
dd: "%d days",
M: "%d month",
MM: "%d months",
y: "%d year",
yy: "%d years"
}
});
}
RelativeTimeExtension.prototype.getName = function () {
return 'relative_time_extension';
};
RelativeTimeExtension.prototype.timeAgo = function (time_from) {
if (time_from === undefined || time_from === null) {
return false;
}
if (_.isDate(time_from)) {
time_from = time_from.getTime()/1000;
}
var time_now = new Date().getTime();
if ((time_from*1000-time_now) === 0) {
return 'just now';
}
return moment.unix(time_from).fromNow();
};
module.exports = RelativeTimeExtension;
| var _ = require('lodash'),
moment = require('moment');
function RelativeTimeExtension() {
moment.locale('en', {
relativeTime : {
future: "in %s",
past: "%s ago",
s: function (number, withoutSuffix, key, isFuture) {
var plural = (number < 2) ? " second" : " seconds";
return number + plural;
},
m: "%d minute",
mm: "%d minutes",
h: "%d hour",
hh: "%d hours",
d: "%d day",
dd: "%d days",
M: "%d month",
MM: "%d months",
y: "%d year",
yy: "%d years"
}
});
}
RelativeTimeExtension.prototype.getName = function () {
return 'relative_time_extension';
};
RelativeTimeExtension.prototype.timeAgo = function (time_from) {
if (time_from === undefined || time_from === null) {
return false;
}
if (_.isDate(time_from)) {
time_from = time_from.getTime()/1000;
}
var time_now = new Date().getTime();
if ((time_from*1000-time_now) === 0) {
return 'just now';
}
return moment.unix(time_from).fromNow();
};
module.exports = RelativeTimeExtension;
|
Fix crash on delete in private message | const BotModule = require('../BotModule');
module.exports = BotModule.extend({
config: null,
i18n: null,
dependencies: {
'config': 'config',
'i18n': 'i18n',
},
initialize: function (dependencyGraph) {
this._super(dependencyGraph);
this.discordClient.on('messageDelete', message => {
if (message.guild == null) return;
message.guild.channels.find('id', this.config.deletedLogsRoom).send({
embed: {
color: 0xff0000,
title: this.i18n.__mf("Deleted message authored by @{username}#{discriminator}", {username: message.author.username, discriminator: message.author.discriminator}),
description: message.content,
timestamp: new Date(),
footer: {
icon_url: this.discordClient.user.avatarURL,
text: "Shotbow Chat Bot"
}
}
})
.catch(error => console.log("Not enough permissions to send a message to the moderation room."));
});
}
});
| const BotModule = require('../BotModule');
module.exports = BotModule.extend({
config: null,
i18n: null,
dependencies: {
'config': 'config',
'i18n': 'i18n',
},
initialize: function (dependencyGraph) {
this._super(dependencyGraph);
this.discordClient.on('messageDelete', message => {
message.guild.channels.find('id', this.config.deletedLogsRoom).send({
embed: {
color: 0xff0000,
title: this.i18n.__mf("Deleted message authored by @{username}#{discriminator}", {username: message.author.username, discriminator: message.author.discriminator}),
description: message.content,
timestamp: new Date(),
footer: {
icon_url: this.discordClient.user.avatarURL,
text: "Shotbow Chat Bot"
}
}
})
.catch(error => console.log("Not enough permissions to send a message to the moderation room."));
});
}
});
|
Adjust code style, remove constant and exception | package com.sleekbyte.tailor.grammar;
import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
public class GrammarTest {
protected static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";
protected ByteArrayOutputStream errContent;
protected ByteArrayOutputStream outContent;
protected File[] swiftFiles;
@Before
public void setUp() {
File curDir = new File(TEST_INPUT_DIR);
swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
}
@After
public void tearDown() {
System.setOut(null);
}
@Test
public void testRule() {
for (File swiftFile: swiftFiles) {
errContent = new ByteArrayOutputStream();
System.setErr(new PrintStream(errContent));
String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
Tailor.main(command);
assertEquals(errContent.toString(), "");
System.setErr(null);
}
}
}
| package com.sleekbyte.tailor.grammar;
import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import static org.junit.Assert.assertEquals;
public class GrammarTest {
protected static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";
protected static final String NEWLINE_REGEX = "\\r?\\n";
protected ByteArrayOutputStream errContent;
protected ByteArrayOutputStream outContent;
protected File[] swiftFiles;
@Before
public void setUp() {
File curDir = new File(TEST_INPUT_DIR);
swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
}
@After
public void tearDown() {
System.setOut(null);
}
@Test
public void testRule() throws IOException {
for ( File swiftFile: swiftFiles) {
errContent = new ByteArrayOutputStream();
System.setErr(new PrintStream(errContent));
String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
Tailor.main(command);
assertEquals(errContent.toString(), "");
System.setErr(null);
}
}
}
|
Upgrade image base_url to SSL | const _ = require('lodash');
const imageConfig = require('../config/tmdb.json').images;
const formatApiResponse = require('../utils/formatApiResponse');
const { createTransformMany } = require('./utils');
const ORIGINAL_IMAGE_SIZE = 'original';
const BASE_IMAGE_URL = imageConfig.secure_base_url;
const getImageUrl = (baseUrl, size, imagePath) => `${baseUrl}${size}${imagePath}`;
const getAllImageSizes = (imagePath, type) => {
const sizes = imageConfig[`${type}_sizes`];
if (!imagePath) {
return null;
}
if (!sizes) {
throw new Error(`Incorrect image type ${type} provided`);
}
return sizes.filter((size) => size !== ORIGINAL_IMAGE_SIZE)
.map((size) => ({
width: parseInt(size.replace(/[^0-9]/g, '')),
name: imagePath.replace('/', ''),
url: getImageUrl(BASE_IMAGE_URL, size, imagePath),
}));
};
const transformMovie = (movie) => {
return {
...movie,
apiId: movie.tmdbId,
images: {
poster: {
altText: movie.title,
original: getImageUrl(BASE_IMAGE_URL, ORIGINAL_IMAGE_SIZE, movie.poster),
sizes: getAllImageSizes(movie.poster, 'poster'),
},
backdrop: getAllImageSizes(movie.backdrop, 'backdrop'),
},
};
};
module.exports = {
transformOne: transformMovie,
transformMany: _.flow(createTransformMany('movies', transformMovie), formatApiResponse.forMany),
};
| const _ = require('lodash');
const imageConfig = require('../config/tmdb.json').images;
const formatApiResponse = require('../utils/formatApiResponse');
const { createTransformMany } = require('./utils');
const ORIGINAL_IMAGE_SIZE = 'original';
const BASE_IMAGE_URL = imageConfig.base_url;
const getImageUrl = (baseUrl, size, imagePath) => `${baseUrl}${size}${imagePath}`;
const getAllImageSizes = (imagePath, type) => {
const sizes = imageConfig[`${type}_sizes`];
if (!imagePath) {
return null;
}
if (!sizes) {
throw new Error(`Incorrect image type ${type} provided`);
}
return sizes.filter((size) => size !== ORIGINAL_IMAGE_SIZE)
.map((size) => ({
width: parseInt(size.replace(/[^0-9]/g, '')),
name: imagePath.replace('/', ''),
url: getImageUrl(BASE_IMAGE_URL, size, imagePath),
}));
};
const transformMovie = (movie) => {
return {
...movie,
apiId: movie.tmdbId,
images: {
poster: {
altText: movie.title,
original: getImageUrl(BASE_IMAGE_URL, ORIGINAL_IMAGE_SIZE, movie.poster),
sizes: getAllImageSizes(movie.poster, 'poster'),
},
backdrop: getAllImageSizes(movie.backdrop, 'backdrop'),
},
};
};
module.exports = {
transformOne: transformMovie,
transformMany: _.flow(createTransformMany('movies', transformMovie), formatApiResponse.forMany),
};
|
Include options and background files in packaging | #! /usr/bin/env node
var fs = require('fs');
var exec = require('child_process').exec;
var jsonfile = require('jsonfile');
var manifestFile = 'manifest.json';
fs.readFile(manifestFile, 'UTF-8', function (err, data) {
if (err) {
console.log('Error!', err);
}
var manifest = JSON.parse(data);
var fileList = [
'_locales/**/*',
'icons/*'
];
if(process.env.CIRCLE_BUILD_NUM) {
manifest.version = manifest.version + '.' + process.env.CIRCLE_BUILD_NUM;
}
jsonfile.writeFile('dist/' + manifestFile, manifest);
fileList.push(manifest.options_page);
fileList.push('src/options.js');
manifest.content_scripts.forEach(function (scripts) {
(scripts.css.concat(scripts.js)).forEach(function (file) {
fileList.push(file);
});
});
manifest.background.scripts.forEach(function (file) {
fileList.push(file);
});
var zipFile = 'dist/' + manifest.short_name + '-' + manifest.version + '.zip';
fileList.unshift(zipFile);
var cmd = 'zip ' + fileList.join(' ') + ' && zip -j ' + zipFile + ' dist/manifest.json';
exec(cmd, function(error, stdout, stderr) {
if (error) {
console.log('Error!', error, stderr);
} else {
console.log('All good! Chrome extension packaged into\n', zipFile);
}
});
}); | #! /usr/bin/env node
var fs = require('fs');
var exec = require('child_process').exec;
var jsonfile = require('jsonfile');
var manifestFile = 'manifest.json';
fs.readFile(manifestFile, 'UTF-8', function (err, data) {
if (err) {
console.log('Error!', err);
}
var manifest = JSON.parse(data);
var fileList = [
'_locales/**/*',
'icons/*'
];
if(process.env.CIRCLE_BUILD_NUM) {
manifest.version = manifest.version + '.' + process.env.CIRCLE_BUILD_NUM;
}
jsonfile.writeFile('dist/' + manifestFile, manifest);
fileList.push(manifest.options_page);
manifest.content_scripts.forEach(function (scripts) {
(scripts.css.concat(scripts.js)).forEach(function (file) {
fileList.push(file);
});
});
var zipFile = 'dist/' + manifest.short_name + '-' + manifest.version + '.zip';
fileList.unshift(zipFile);
var cmd = 'zip ' + fileList.join(' ') + ' && zip -j ' + zipFile + ' dist/manifest.json';
exec(cmd, function(error, stdout, stderr) {
if (error) {
console.log('Error!', error, stderr);
} else {
console.log('All good! Chrome extension packaged into\n', zipFile);
}
});
}); |
Make title field be full width | import React, { Component } from "react";
import { Form } from "react-form";
import TextField from "material-ui/TextField";
import { Container, Col } from "reactstrap";
import BodyEditor from "./BodyEditor";
import ImageListEditor from "./ImageListEditor";
export default class ItemEditor extends Component {
render() {
let { thing, sidebar, onSubmit } = this.props;
if (!thing) {
return <div />;
}
return (
<Form onSubmit={onSubmit}>
{({ submitForm }) => {
return (
<form onSubmit={submitForm}>
<div className="main-contents">
<Container className="detailed-case-component" fluid={true}>
<Col
md="3"
className="hidden-sm-down sidepanel hidden-sm-down"
>
{sidebar}
</Col>
<Col md="8" xs="12" className="main-area">
<div className="case-box">
<h2 className="category">
Case
</h2>
<h2 className="case-title">
{thing.title}
</h2>
<ImageListEditor thing={thing} />
<div className="title-edit">
<label htmlFor="title">Title</label>
</div>
<TextField
field="title"
placeholder="case title"
fullWidth={true}
/>
<div>
<label htmlFor="body_en">Body</label>
</div>
<BodyEditor value={thing.body} />
</div>
<button type="submit">Submit</button>
</Col>
</Container>
</div>
</form>
);
}}
</Form>
);
}
}
| import React, { Component } from "react";
import { Form, Text } from "react-form";
import { Container, Col } from "reactstrap";
import BodyEditor from "./BodyEditor";
import ImageListEditor from "./ImageListEditor";
export default class ItemEditor extends Component {
render() {
let { thing, sidebar, onSubmit } = this.props;
if (!thing) {
return <div />;
}
return (
<Form onSubmit={onSubmit}>
{({ submitForm }) => {
return (
<form onSubmit={submitForm}>
<div className="main-contents">
<Container className="detailed-case-component" fluid={true}>
<Col
md="3"
className="hidden-sm-down sidepanel hidden-sm-down"
>
{sidebar}
</Col>
<Col md="8" xs="12" className="main-area">
<div className="case-box">
<h2 className="category">
Case
</h2>
<h2 className="case-title">
{thing.title}
</h2>
<ImageListEditor thing={thing} />
<div className="title-edit">
<label htmlFor="title">Title</label>
</div>
<Text field="title" placeholder="case title" />
<div>
<label htmlFor="body_en">Body</label>
</div>
<BodyEditor value={thing.body} />
</div>
<button type="submit">Submit</button>
</Col>
</Container>
</div>
</form>
);
}}
</Form>
);
}
}
|
Update tests to explicitly account for previous | from spec import Spec, skip, ok_, eq_, raises
from invoke.parser import Parser, Context, Argument
from invoke.collection import Collection
class Parser_(Spec):
def can_take_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
def can_take_initial_and_other_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
def can_take_just_other_contexts(self):
c = Context('foo')
p = Parser(contexts=[c])
eq_(p.contexts['foo'], c)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
Parser(initial=Context(), contexts=[Context()])
class parse_argv:
def parses_sys_argv_style_list_of_strings(self):
"parses sys.argv-style list of strings"
# Doesn't-blow-up tests FTL
mytask = Context(name='mytask')
mytask.add_arg('--arg')
p = Parser(contexts=[mytask])
p.parse_argv(['mytask', '--arg'])
def returns_ordered_list_of_tasks_and_their_args(self):
skip()
def returns_remainder(self):
"returns -- style remainder string chunk"
skip()
| from spec import Spec, skip, ok_, eq_, raises
from invoke.parser import Parser, Context, Argument
from invoke.collection import Collection
class Parser_(Spec):
def has_and_requires_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
def may_also_take_additional_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
Parser(initial=Context(), contexts=[Context()])
class parse_argv:
def parses_sys_argv_style_list_of_strings(self):
"parses sys.argv-style list of strings"
# Doesn't-blow-up tests FTL
mytask = Context(name='mytask')
mytask.add_arg('--arg')
p = Parser(contexts=[mytask])
p.parse_argv(['mytask', '--arg'])
def returns_ordered_list_of_tasks_and_their_args(self):
skip()
def returns_remainder(self):
"returns -- style remainder string chunk"
skip()
|
Bump version: 0.0.2 -> 0.0.3
[ci skip] | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.3"
class SanitizeTargetCMakeConan(ConanFile):
name = "sanitize-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"cmake-multi-targets/master@smspillaz/cmake-multi-targets",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit",
"sanitizers-cmake/0.0.1@smspillaz/sanitizers-cmake")
url = "http://github.com/polysquare/sanitize-target-cmake"
license = "MIT"
def source(self):
zip_name = "sanitize-target-cmake.zip"
download("https://github.com/polysquare/"
"sanitize-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/sanitize-target-cmake",
src="sanitize-target-cmake-" + VERSION,
keep_path=True)
| from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class SanitizeTargetCMakeConan(ConanFile):
name = "sanitize-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"cmake-multi-targets/master@smspillaz/cmake-multi-targets",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit",
"sanitizers-cmake/0.0.1@smspillaz/sanitizers-cmake")
url = "http://github.com/polysquare/sanitize-target-cmake"
license = "MIT"
def source(self):
zip_name = "sanitize-target-cmake.zip"
download("https://github.com/polysquare/"
"sanitize-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/sanitize-target-cmake",
src="sanitize-target-cmake-" + VERSION,
keep_path=True)
|
Use a smaller timeout value | "use strict";
var global = require("./global.js");
var ASSERT = require("./assert.js");
var schedule;
if (typeof process !== "undefined" && process !== null &&
typeof process.cwd === "function" &&
typeof process.nextTick === "function" &&
typeof process.version === "string") {
schedule = function Promise$_Scheduler(fn) {
process.nextTick(fn);
};
}
else if ((typeof global.MutationObserver === "function" ||
typeof global.WebkitMutationObserver === "function" ||
typeof global.WebKitMutationObserver === "function") &&
typeof document !== "undefined" &&
typeof document.createElement === "function") {
schedule = (function(){
var MutationObserver = global.MutationObserver ||
global.WebKitMutationObserver;
var div = document.createElement("div");
var queuedFn = void 0;
var observer = new MutationObserver(
function Promise$_Scheduler() {
ASSERT(queuedFn !== void 0);
var fn = queuedFn;
queuedFn = void 0;
fn();
}
);
observer.observe(div, {
attributes: true
});
return function Promise$_Scheduler(fn) {
ASSERT(queuedFn === void 0);
queuedFn = fn;
div.setAttribute("class", "foo");
};
})();
}
else if (global.setTimeout) {
schedule = function Promise$_Scheduler(fn) {
setTimeout(fn, 0);
};
}
else throw new Error("no async scheduler available");
module.exports = schedule;
| "use strict";
var global = require("./global.js");
var ASSERT = require("./assert.js");
var schedule;
if (typeof process !== "undefined" && process !== null &&
typeof process.cwd === "function" &&
typeof process.nextTick === "function" &&
typeof process.version === "string") {
schedule = function Promise$_Scheduler(fn) {
process.nextTick(fn);
};
}
else if ((typeof global.MutationObserver === "function" ||
typeof global.WebkitMutationObserver === "function" ||
typeof global.WebKitMutationObserver === "function") &&
typeof document !== "undefined" &&
typeof document.createElement === "function") {
schedule = (function(){
var MutationObserver = global.MutationObserver ||
global.WebKitMutationObserver;
var div = document.createElement("div");
var queuedFn = void 0;
var observer = new MutationObserver(
function Promise$_Scheduler() {
ASSERT(queuedFn !== void 0);
var fn = queuedFn;
queuedFn = void 0;
fn();
}
);
observer.observe(div, {
attributes: true
});
return function Promise$_Scheduler(fn) {
ASSERT(queuedFn === void 0);
queuedFn = fn;
div.setAttribute("class", "foo");
};
})();
}
else if (global.setTimeout) {
schedule = function Promise$_Scheduler(fn) {
setTimeout(fn, 4);
};
}
else throw new Error("no async scheduler available");
module.exports = schedule;
|
Allow request type specification in ajax requests
Also include csrf token in POST requests, and actually pass
data in the request | function AjaxNetwork() {
function sendRequest(url, onComplete, data, method) {
var requestMethod = method == null ? "GET" : method;
var headers = {};
if (requestMethod == "POST") {
headers["X-CSRFToken"] = $.cookie("csrftoken");
}
$.ajax({
url: url,
type: requestMethod,
headers: headers,
dataType: 'json',
complete: onComplete,
data: data,
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error sending request to url(" + url + "): ",
errorThrown);
}
});
}
function sendGetAllCells(callback) {
sendRequest("/info/cell/", callback);
}
function handleGetAllCells(response) {
terrainTable = new Array(response.responseJSON.length);
for (var i = response.responseJSON.length - 1; i >= 0; i--) {
var cell = response.responseJSON[i].fields;
terrainTable[cell.cType] = function(x, y) {
return new Cell(x, y, cell.spriteName, cell.cType);
}
terrainTypes[cell.spriteName] = cell.cType;
};
}
function sendGetViewWorldTemplate(callback) {
sendRequest("/info/responses/viewWorld/", callback)
}
function handleGetViewWorldTemplate(response) {
responseTemplates["viewWorld"] = response.responseJSON;
}
this.sendGetAllCells = sendGetAllCells;
this.handleGetAllCells = handleGetAllCells;
this.sendGetViewWorldTemplate = sendGetViewWorldTemplate;
this.handleGetViewWorldTemplate = handleGetViewWorldTemplate;
} | function AjaxNetwork() {
function sendRequest(url, onComplete, data) {
$.ajax({
url: url,
dataType: 'json',
complete: onComplete,
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error sending request to url(" + url + "): ",
errorThrown);
}
});
}
function sendGetAllCells(callback) {
sendRequest("/info/cell/", callback);
}
function handleGetAllCells(response) {
terrainTable = new Array(response.responseJSON.length);
for (var i = response.responseJSON.length - 1; i >= 0; i--) {
var cell = response.responseJSON[i].fields;
terrainTable[cell.cType] = function(x, y) {
return new Cell(x, y, cell.spriteName, cell.cType);
}
terrainTypes[cell.spriteName] = cell.cType;
};
}
function sendGetViewWorldTemplate(callback) {
sendRequest("/info/responses/viewWorld/", callback)
}
function handleGetViewWorldTemplate(response) {
responseTemplates["viewWorld"] = response.responseJSON;
}
this.sendGetAllCells = sendGetAllCells;
this.handleGetAllCells = handleGetAllCells;
this.sendGetViewWorldTemplate = sendGetViewWorldTemplate;
this.handleGetViewWorldTemplate = handleGetViewWorldTemplate;
} |
Update test, fix test size | "use strict";
var assert = require('chai').assert;
var xdTesting = require('../../lib/index')
var templates = require('../../lib/templates');
var q = require('q');
describe('MultiDevice - selectAny', function () {
var test = this;
test.baseUrl = "http://localhost:8090/";
it('should select a single device @medium', function () {
var options = {
A: templates.devices.chrome(),
B: templates.devices.chrome()
};
return xdTesting.multiremote(options)
.getCount().then(count => assert.equal(count, 2))
.selectAny(device => device
.getCount().then(count => assert.equal(count, 1))
)
.end()
});
it('should execute promises callback @medium', function () {
var options = {
A: templates.devices.chrome(),
B: templates.devices.chrome()
};
var queue = '';
return xdTesting.multiremote(options)
.then(() => queue += '0')
.selectAny(device => {
queue += '1';
return device.then(() => {
queue += '2';
});
})
.then(() => queue += '3')
.then(() => assert.equal(queue, '0123'))
.end();
});
});
| "use strict";
var assert = require('chai').assert;
var xdTesting = require('../../lib/index')
var templates = require('../../lib/templates');
var q = require('q');
describe('MultiDevice - selectAny', function () {
var test = this;
test.baseUrl = "http://localhost:8090/";
it('should select a single device @large', function () {
var options = {
A: templates.devices.chrome(),
B: templates.devices.chrome()
};
return xdTesting.multiremote(options)
.selectAny(device => device
.getCount().then(count => assert.equal(count, 1))
)
.end()
});
it('should execute promises callback @large', function () {
var options = {
A: templates.devices.chrome(),
B: templates.devices.chrome()
};
var queue = '';
return xdTesting.multiremote(options)
.then(() => queue += '0')
.selectAny(device => {
queue += '1';
return device.then(() => {
queue += '2';
});
})
.then(() => queue += '3')
.then(() => assert.equal(queue, '0123'))
.end();
});
});
|
Remove @author tag for GeLo. | <?php
/*
* This file is part of the Http Discovery package.
*
* (c) PHP HTTP Team <[email protected]>
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code.
*/
namespace Http\Discovery\StreamFactory;
use Http\Message\StreamFactory;
use Psr\Http\Message\StreamInterface;
use Zend\Diactoros\Request;
use Zend\Diactoros\Response;
use Zend\Diactoros\Stream;
/**
* Zend Diactoros StreamFactory
*
* @author Михаил Красильников <[email protected]>
*/
class DiactorosStreamFactory implements StreamFactory
{
/**
* Creates a stream
*
* @param string|resource|StreamInterface|null $body
*
* @return StreamInterface
*
* @throws \InvalidArgumentException If the stream body is invalid
* @throws \RuntimeException If cannot write into stream
*/
public function createStream($body = null)
{
if (!$body instanceof StreamInterface) {
if (is_resource($body)) {
$body = new Stream($body);
} else {
$stream = new Stream('php://memory', 'rw');
if (null !== $body) {
$stream->write((string) $body);
}
$body = $stream;
}
}
$body->rewind();
return $body;
}
}
| <?php
/*
* This file is part of the Http Discovery package.
*
* (c) PHP HTTP Team <[email protected]>
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code.
*/
namespace Http\Discovery\StreamFactory;
use Http\Message\StreamFactory;
use Psr\Http\Message\StreamInterface;
use Zend\Diactoros\Request;
use Zend\Diactoros\Response;
use Zend\Diactoros\Stream;
/**
* Zend Diactoros StreamFactory
*
* @author GeLo <[email protected]>
* @author Михаил Красильников <[email protected]>
*/
class DiactorosStreamFactory implements StreamFactory
{
/**
* Creates a stream
*
* @param string|resource|StreamInterface|null $body
*
* @return StreamInterface
*
* @throws \InvalidArgumentException If the stream body is invalid
* @throws \RuntimeException If cannot write into stream
*/
public function createStream($body = null)
{
if (!$body instanceof StreamInterface) {
if (is_resource($body)) {
$body = new Stream($body);
} else {
$stream = new Stream('php://memory', 'rw');
if (null !== $body) {
$stream->write((string) $body);
}
$body = $stream;
}
}
$body->rewind();
return $body;
}
}
|
Use correct m2m join table name in LatestCommentsFeed
git-svn-id: 554f83ef17aa7291f84efa897c1acfc5d0035373@9089 bcc190cf-cafb-0310-a4f2-bffc1f526a37 | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
| from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
|
Fix publish for first installation | <?php namespace Pingpong\Twitter;
use Codebird\Codebird;
use Illuminate\Support\ServiceProvider;
class TwitterServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Boot the package.
*
* @return void
*/
public function boot()
{
$configPath = config_path('twitter.php');
$this->publishes([
__DIR__ . '/../../config/config.php' => $configPath
]);
if (is_file($configPath)) {
$this->mergeConfigFrom($configPath, 'twitter');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['twitter'] = $this->app->share(function($app)
{
$api = new Api;
$config = $app['config']->get('twitter');
return new Twitter(
$api,
$app['session.store'],
$app['config'],
$app['request'],
$app['redirect'],
$config['consumer_key'],
$config['consumer_secret'],
$config['oauth_token'],
$config['oauth_token_secret'],
$config['bearer_token'],
$config['callback_url'],
$config['fallback_url']
);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['twitter'];
}
}
| <?php namespace Pingpong\Twitter;
use Codebird\Codebird;
use Illuminate\Support\ServiceProvider;
class TwitterServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Boot the package.
*
* @return void
*/
public function boot()
{
$configPath = config_path('twitter.php');
$this->publishes([
__DIR__ . '/../../config/config.php' => $configPath
]);
$this->mergeConfigFrom($configPath, 'twitter');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['twitter'] = $this->app->share(function($app)
{
$api = new Api;
$config = $app['config']->get('twitter');
return new Twitter(
$api,
$app['session.store'],
$app['config'],
$app['request'],
$app['redirect'],
$config['consumer_key'],
$config['consumer_secret'],
$config['oauth_token'],
$config['oauth_token_secret'],
$config['bearer_token'],
$config['callback_url'],
$config['fallback_url']
);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['twitter'];
}
}
|
Fix react 16 key warning bug. | // @flow
import React from 'react';
import Box from 'grommet/components/Box';
import Heading from 'grommet/components/Heading';
type BlockProps = {
title: string,
onClick: () => void,
wireframe: React$Element<any>,
key: string,
}
const Block = ({ title, onClick, wireframe, key }: BlockProps) =>
<Box onClick={onClick} key={key}>
<Box align="center" pad={{ vertical: 'small', horizontal: 'small' }}>
<Box
size={{ height: 'small', width: 'small' }} colorIndex="grey-4"
pad={{
horizontal: 'medium',
vertical: 'small',
}} justify="center"
>
{React.cloneElement(wireframe)}
</Box>
<Heading tag="h3">
{title}
</Heading>
</Box>
</Box>;
type BlockSelectorProps = {
onClick: Function,
blockMap: {},
};
export default function BlockSelector({ onClick, blockMap }: BlockSelectorProps) {
const blocks = Object.keys(blockMap).map((block, index) =>
<Block
title={blockMap[block].name}
onClick={onClick.bind(this, block)}
wireframe={blockMap[block].wireframe}
key={`block-${index}`}
/>,
);
return (
<Box full="horizontal">
<Box pad={{ vertical: 'small' }} colorIndex="light-2">
<Box direction="row" wrap justify="center">
{blocks}
</Box>
</Box>
</Box>
);
}
| // @flow
import React from 'react';
import Box from 'grommet/components/Box';
import Button from 'grommet/components/Button';
import Heading from 'grommet/components/Heading';
type BlockProps = {
title: string,
onClick: () => void,
wireframe: HTMLElement,
}
const Block = ({ title, onClick, wireframe }: BlockProps) =>
<Button onClick={onClick}>
<Box align="center" pad={{ vertical: 'small', horizontal: 'small' }}>
<Box
size={{ height: 'small', width: 'small' }} colorIndex="grey-4"
pad={{
horizontal: 'medium',
vertical: 'small',
}} justify="center"
>
{wireframe}
</Box>
<Heading tag="h3">
{title}
</Heading>
</Box>
</Button>;
type BlockSelectorProps = {
onClick: Function,
blockMap: {},
};
export default function BlockSelector({ onClick, blockMap }: BlockSelectorProps) {
const blocks = Object.keys(blockMap).map((block, index) =>
<Block
title={blockMap[block].name} onClick={onClick.bind(this, block)}
wireframe={blockMap[block].wireframe}
key={`block-${index}`}
/>,
);
return (
<Box full="horizontal">
<Box pad={{ vertical: 'small' }} colorIndex="light-2">
<Box direction="row" wrap justify="center">
{blocks}
</Box>
</Box>
</Box>
);
}
|
Fix compilation with new SDK | package org.jetbrains.jps.cabal;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
public class CabalJspInterface{
private final String myCabalPath;
@NotNull
private File myCabalFile;
CabalJspInterface(String cabalPath, @NotNull File cabalFile) {
myCabalPath = cabalPath;
myCabalFile = cabalFile;
}
private Process runCommand(String ... command) throws IOException {
final String path = myCabalPath != null ? myCabalPath : "cabal";
ArrayList<String> arguments = new ArrayList<String>();
arguments.add(path);
arguments.addAll(Arrays.asList(command));
return new ProcessWrapper(myCabalFile.getParentFile().getCanonicalPath()).
getProcess(arguments);
}
public Process configure(String ghcPath) throws IOException {
if (ghcPath != null) {
return runCommand("configure", "-w", ghcPath);
} else {
return runCommand("configure");
}
}
public Process build() throws IOException {
return runCommand("build");
}
public Process clean() throws IOException {
return runCommand("clean");
}
}
| package org.jetbrains.jps.cabal;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
public class CabalJspInterface{
private final String myCabalPath;
@NotNull
private File myCabalFile;
CabalJspInterface(String cabalPath, @NotNull File cabalFile) {
myCabalPath = cabalPath;
myCabalFile = cabalFile;
}
private Process runCommand(String ... command) throws IOException {
final String path = myCabalPath != null ? myCabalPath : "cabal";
ArrayList<String> arguments = new ArrayList<String>();
arguments.add(path);
arguments.addAll(Arrays.asList(command));
return new ProcessWrapper(myCabalFile.getParentFile().getCanonicalPath()).
getProcess(arguments);
}
public Process configure(String ghcPath) throws IOException {
if (ghcPath != null) {
return runCommand("configure", "-w", ghcPath + File.separator + "bin" + File.separator + "ghc");
} else {
return runCommand("configure");
}
}
public Process build() throws IOException {
return runCommand("build");
}
public Process clean() throws IOException {
return runCommand("clean");
}
}
|
Change the background, and default style | require('script!3Dmol/release/3Dmol.js');
require('style/3dmol.styl');
angular.module('chemPhyWebApp')
.directive('chemPhyWeb3dmol', ['$http', '$log', function($http, $log) {
return {
scope: {},
link: function($scope, $element) {
// Viewer config - properties 'defaultcolors' and 'callback'
var config = {defaultcolors: $3Dmol.rasmolElementColors };
// Create GLViewer within 'gldiv'
$scope.viewer = $3Dmol.createViewer($($element), config);
$scope.viewer.setBackgroundColor(0xeeeeee);
$scope.viewer.resize();
$http.get('/data/2POR.pdb')
.success(function(data) {
$scope.viewer.addModel(data, 'pdb');
$scope.viewer.setStyle({}, {stick:{}});
$scope.viewer.zoomTo();
$scope.viewer.render();
})
.error(function(data) {
$log.error(data);
});
}
};
}]); | require('script!3Dmol/release/3Dmol.js');
require('style/3dmol.styl');
angular.module('chemPhyWebApp')
.directive('chemPhyWeb3dmol', ['$http', '$log', function($http, $log) {
return {
scope: {},
link: function($scope, $element) {
// Viewer config - properties 'defaultcolors' and 'callback'
var config = {defaultcolors: $3Dmol.rasmolElementColors };
// Create GLViewer within 'gldiv'
$scope.viewer = $3Dmol.createViewer($($element), config);
$scope.viewer.resize();
$http.get('/data/2POR.pdb')
.success(function(data) {
$scope.viewer.addModel(data, 'pdb');
$scope.viewer.zoomTo();
$scope.viewer.render();
})
.error(function(data) {
$log.error(data);
});
}
};
}]); |
Add support for Python 3.7 and Django 2.2 | #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='django-latest-tweets',
version='0.4.5',
description='Latest Tweets for Django',
long_description=readme,
url='https://github.com/developersociety/django-latest-tweets',
maintainer='The Developer Society',
maintainer_email='[email protected]',
platforms=['any'],
install_requires=[
'twitter>=1.9.1',
'requests>=2.0',
],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.2',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
license='BSD',
)
| #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='django-latest-tweets',
version='0.4.5',
description='Latest Tweets for Django',
long_description=readme,
url='https://github.com/developersociety/django-latest-tweets',
maintainer='The Developer Society',
maintainer_email='[email protected]',
platforms=['any'],
install_requires=[
'twitter>=1.9.1',
'requests>=2.0',
],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.11',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
license='BSD',
)
|
Comment out sorting function for now | import request from 'request';
import { parseString } from 'xml2js';
export default function loadFromBGG(req) {
return new Promise((resolve, reject) => {
request({
url: `http://www.boardgamegeek.com/xmlapi2/search?query=${req.query.q}&type=boardgame`,
timeout: 10000
}, (error, response, body) => {
if (error) reject(error);
parseString(body, (err, res) => {
if (err) reject(err);
if (Array.isArray(res.items.item)) {
resolve(res.items.item
.map((el) => {
return {
bggid: el.$.id,
type: el.$.type,
name: el.name[0].$.value,
year: el.yearpublished ? Number(el.yearpublished[0].$.value) : 0
};
})
.filter((el) => {
return el.type === 'boardgame';
})
.sort((prev, current) => {
// TODO: Should the items be sorted by year?
// return current.year - prev.year;
}));
} else {
resolve([]);
}
});
});
});
}
| import request from 'request';
import { parseString } from 'xml2js';
export default function loadFromBGG(req) {
return new Promise((resolve, reject) => {
request({
url: `http://www.boardgamegeek.com/xmlapi2/search?query=${req.query.q}&type=boardgame`,
timeout: 10000
}, (error, response, body) => {
if (error) reject(error);
parseString(body, (err, res) => {
if (err) reject(err);
if (Array.isArray(res.items.item)) {
resolve(res.items.item
.map((el) => {
return {
bggid: el.$.id,
type: el.$.type,
name: el.name[0].$.value,
year: el.yearpublished ? Number(el.yearpublished[0].$.value) : 0
};
})
.filter((el) => {
return el.type === 'boardgame';
})
.sort((prev, current) => {
return current.year - prev.year;
}));
} else {
resolve([]);
}
});
});
});
}
|
Define StyleLintPlugin in webpack base config. | import path from 'path';
import webpack from 'webpack';
import StyleLintPlugin from 'stylelint-webpack-plugin';
const paths = {
ASSETS: path.resolve(__dirname, './assets'),
SRC: path.resolve(__dirname),
COMPONENTS: path.resolve(__dirname, '../src'),
DIST: path.resolve(__dirname, './build')
};
module.exports = {
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /de|fr|en/),
new StyleLintPlugin({
files: '**/*.s?(a|c)ss',
failOnError: false,
syntax: 'scss'
})
],
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: [ paths.ASSETS, /src\/.+\/examples/, paths.DIST ],
include: [
paths.COMPONENTS,
paths.SRC,
/rc-datepicker/,
/react-input-children/,
/react-autosize-textarea/,
/react-cookie-banner/,
/react-flexview/
]
},
{
test: /\.png$|\.gif$/,
loader: 'file?name=[path][name].[ext]'
}
],
preLoaders: [
{
test: /\.jsx?$/,
loader: 'eslint',
include: [ paths.SRC, paths.COMPONENTS ],
exclude: paths.ASSETS
}
]
}
};
| import path from 'path';
import webpack from 'webpack';
const paths = {
ASSETS: path.resolve(__dirname, './assets'),
SRC: path.resolve(__dirname),
COMPONENTS: path.resolve(__dirname, '../src'),
DIST: path.resolve(__dirname, './build')
};
module.exports = {
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /de|fr|en/)
],
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: [ paths.ASSETS, /src\/.+\/examples/, paths.DIST ],
include: [
paths.COMPONENTS,
paths.SRC,
/rc-datepicker/,
/react-input-children/,
/react-autosize-textarea/,
/react-cookie-banner/,
/react-flexview/
]
},
{
test: /\.png$|\.gif$/,
loader: 'file?name=[path][name].[ext]'
}
],
preLoaders: [
{
test: /\.jsx?$/,
loader: 'eslint',
include: [ paths.SRC, paths.COMPONENTS ],
exclude: paths.ASSETS
}
]
}
};
|
Change instance declaration of defaultProps to static | import Component from '../PureRenderComponent.react';
import Radium from 'radium';
import React from 'react';
import RPT from 'prop-types';
import * as colors from '../styles/Colors';
@Radium
export default class Select extends Component {
static propTypes = {
onChange: RPT.func,
options: RPT.array.isRequired,
value: RPT.any
}
static defaultProps = {
options: []
}
render() {
const {options, onChange, value} = this.props
return (
<div style={styles.selectWrapper}>
<select onChange={onChange} style={styles.select} value={value}>
{options}
</select>
<div style={styles.selectArrow} />
</div>
);
}
};
const styles = {
selectWrapper: {
position: 'relative'
},
select: {
width: '100%',
height: '30px',
WebkitAppearance: 'none',
MozAppearance: 'none',
appearance: 'none',
borderRadius: '0',
background: 'white',
padding: '3px 5px',
outline: 'none',
borderWidth: '1px',
borderStyle: 'solid',
borderColor: colors.GRAY_DARKER,
},
selectArrow: {
width: 0,
height: 0,
borderLeft: '5px solid transparent',
borderRight: '5px solid transparent',
borderTop: `5px solid ${colors.BLUE}`,
position: 'absolute',
top: '50%',
right: '6px',
transform: 'translateY(-50%)'
}
};
| import Component from '../PureRenderComponent.react';
import Radium from 'radium';
import React from 'react';
import RPT from 'prop-types';
import * as colors from '../styles/Colors';
@Radium
export default class Select extends Component {
static propTypes = {
onChange: RPT.func,
options: RPT.array.isRequired,
value: RPT.any
}
defaultProps = {
options: []
}
render() {
const {options, onChange, value} = this.props
return (
<div style={styles.selectWrapper}>
<select onChange={onChange} style={styles.select} value={value}>
{options}
</select>
<div style={styles.selectArrow} />
</div>
);
}
};
const styles = {
selectWrapper: {
position: 'relative'
},
select: {
width: '100%',
height: '30px',
WebkitAppearance: 'none',
MozAppearance: 'none',
appearance: 'none',
borderRadius: '0',
background: 'white',
padding: '3px 5px',
outline: 'none',
borderWidth: '1px',
borderStyle: 'solid',
borderColor: colors.GRAY_DARKER,
},
selectArrow: {
width: 0,
height: 0,
borderLeft: '5px solid transparent',
borderRight: '5px solid transparent',
borderTop: `5px solid ${colors.BLUE}`,
position: 'absolute',
top: '50%',
right: '6px',
transform: 'translateY(-50%)'
}
};
|
DELETE requests should now work | var express = require('express');
var router = express.Router();
var errands = require('../modules/errands');
router.get('/', function(req, res, next) {
errands.getAll(function (err, result) {
if (err) {
return res.status(500).json(err);
}
res.json(result);
});
});
router.post('/', function(req, res, next) {
var recording = req.body.recording;
var description = req.body.description;
var tags = req.body.tags;
var phone_number = req.body.phone_number;
var timestamp = req.body.timestamp;
var params = {
recording: recording,
description: description,
tags: tags,
phone_number: phone_number,
timestamp: timestamp
};
errands.add(params, function (err, result) {
if (err) {
return res.status(500).json(err);
}
res.json(result);
});
});
router.delete('/:id', function (req, res, next) {
var id = req.params.id;
errands.get(id, function (err, result) {
if (err) {
return res.status(500).json(err);
}
var rev = result._rev;
errands.destroy(id, rev, function (err, result) {
if (err) {
return res.status(500).json(err);
}
res.json(result);
});
});
});
module.exports = router;
| var express = require('express');
var router = express.Router();
var errands = require('../modules/errands');
router.get('/', function(req, res, next) {
errands.getAll(function (err, result) {
if (err) {
return res.status(500).json(err);
}
res.json(result);
});
});
router.post('/', function(req, res, next) {
var recording = req.body.recording;
var description = req.body.description;
var tags = req.body.tags;
var phone_number = req.body.phone_number;
var timestamp = req.body.timestamp;
var params = {
recording: recording,
description: description,
tags: tags,
phone_number: phone_number,
timestamp: timestamp
};
errands.add(params, function (err, result) {
if (err) {
return res.status(500).json(err);
}
res.json(result);
});
});
router.delete('/:id', function (req, res, next) {
var id = req.params.id;
errands.get(id, function (err, result) {
if (err) {
return res.status(500).json(err);
}
var rev = result._rev;
res.json(rev);
});
});
module.exports = router;
|
Allow searching for HPO term ID's and match only entries that contain all of the query words (instead of one of the query words). | var elasticsearch = require('elasticsearch');
if (sails.config.useElastic === true) {
var CLIENT = new elasticsearch.Client({
host: sails.config.elasticHost,
log: sails.config.elasticLogLevel
})
}
module.exports = function(req, res) {
if (!CLIENT) {
return res.notFound()
}
if (!req.body || !req.body.q || !req.socket) {
return res.badRequest()
}
var query = req.body.q;
CLIENT.search({
index: 'search',
from: 0,
size: 100,
body: {
query: {
query_string : {
fields : ["name", "id"],
query: query.replace(/\:/g, '\\\:') + '*',
analyze_wildcard: true,
default_operator: 'AND'
}
}
}
}, function(err, result) {
if (err) {
sails.log.warn(err);
return res.serverError()
} else {
console.log(result[0])
sails.log.debug('Suggest options for %s: %d', query, result.hits.total);
if (result.hits.total > 0) {
return res.json(result.hits.hits)
} else {
return res.notFound()
}
}
})
};
| var elasticsearch = require('elasticsearch');
if (sails.config.useElastic === true) {
var CLIENT = new elasticsearch.Client({
host: sails.config.elasticHost,
log: sails.config.elasticLogLevel
})
}
module.exports = function(req, res) {
if (!CLIENT) {
return res.notFound()
}
if (!req.body || !req.body.q || !req.socket) {
return res.badRequest()
}
var query = req.body.q;
CLIENT.search({
index: 'search',
from: 0,
size: 100,
body: {
query: {
query_string : {
fields : ["name", "id"],
query: query.replace(/\:/g, '\\:') + '*',
analyze_wildcard: true
}
}
}
}, function(err, result) {
if (err) {
sails.log.warn(err);
return res.serverError()
} else {
console.log(result[0])
sails.log.debug('Suggest options for %s: %d', query, result.hits.total);
if (result.hits.total > 0) {
return res.json(result.hits.hits)
} else {
return res.notFound()
}
}
})
};
|
Make compass pointer consistent with LineChart | import React from 'react';
class Compass extends React.Component {
static defaultProps = {
width: 100,
height: 100,
color: "rgb(255, 128, 0)",
pointer_color: "rgb(255, 255, 255)"
};
render() {
let padding = 25,
width = this.props.width,
height = this.props.height,
half_width = width * 0.5,
half_height = height * 0.5,
origin = `translate(${half_width}, ${half_height})`,
radius = (Math.min(width, height) - padding) * 0.5 - 1,
color = this.props.color,
offset = `translate(${radius - 6 - 1}, 0)`;
return (
<svg className="compass" width={width} height={height}>
<g transform={origin}>
<circle r={radius} stroke={color} strokeWidth={1} fill="none"/>
<g transform={this.props.direction}>
<g transform={offset}>
<polygon points="6,0 0,4 0,-4" fill={this.props.pointer_color} fillOpacity="0.5"/>
</g>
</g>
</g>
</svg>
)
}
}
export default Compass;
| import React from 'react';
class Compass extends React.Component {
static defaultProps = {
width: 100,
height: 100,
color: "rgb(255, 128, 0)"
};
render() {
let padding = 25,
width = this.props.width,
height = this.props.height,
half_width = width * 0.5,
half_height = height * 0.5,
origin = `translate(${half_width}, ${half_height})`,
radius = (Math.min(width, height) - padding) * 0.5 - 1,
color = this.props.color,
offset = `translate(${radius - 6 - 1}, 0)`;
return (
<svg className="compass" width={width} height={height}>
<g transform={origin}>
<circle r={radius} stroke={color} strokeWidth={1} fill="none"/>
<g transform={this.props.direction}>
<g transform={offset}>
<polygon points="6,0 0,4 0,-4" fill={color}/>
</g>
</g>
</g>
</svg>
)
}
}
export default Compass;
|
Update to reflect new example data | from __future__ import division
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
__all__ = ["palplot", "dogplot"]
def palplot(pal, size=1):
"""Plot the values in a color palette as a horizontal array.
Parameters
----------
pal : sequence of matplotlib colors
colors, i.e. as returned by seaborn.color_palette()
size :
scaling factor for size of plot
"""
n = len(pal)
f, ax = plt.subplots(1, 1, figsize=(n * size, size))
ax.imshow(np.arange(n).reshape(1, n),
cmap=mpl.colors.ListedColormap(list(pal)),
interpolation="nearest", aspect="auto")
ax.set_xticks(np.arange(n) - .5)
ax.set_yticks([-.5, .5])
ax.set_xticklabels([])
ax.set_yticklabels([])
def dogplot():
"""Who's a good boy?"""
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from io import BytesIO
url = "https://github.com/mwaskom/seaborn-data/raw/master/png/img{}.png"
pic = np.random.randint(2, 7)
data = BytesIO(urlopen(url.format(pic)).read())
img = plt.imread(data)
f, ax = plt.subplots(figsize=(5, 5), dpi=100)
f.subplots_adjust(0, 0, 1, 1)
ax.imshow(img)
ax.set_axis_off()
| from __future__ import division
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
__all__ = ["palplot", "dogplot"]
def palplot(pal, size=1):
"""Plot the values in a color palette as a horizontal array.
Parameters
----------
pal : sequence of matplotlib colors
colors, i.e. as returned by seaborn.color_palette()
size :
scaling factor for size of plot
"""
n = len(pal)
f, ax = plt.subplots(1, 1, figsize=(n * size, size))
ax.imshow(np.arange(n).reshape(1, n),
cmap=mpl.colors.ListedColormap(list(pal)),
interpolation="nearest", aspect="auto")
ax.set_xticks(np.arange(n) - .5)
ax.set_yticks([-.5, .5])
ax.set_xticklabels([])
ax.set_yticklabels([])
def dogplot():
"""Who's a good boy?"""
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from io import BytesIO
url = "https://github.com/mwaskom/seaborn-data/raw/master/png/img1.png"
data = BytesIO(urlopen(url).read())
img = plt.imread(data)
f, ax = plt.subplots(figsize=(5, 5), dpi=100)
f.subplots_adjust(0, 0, 1, 1)
ax.imshow(img)
ax.set_axis_off()
|
Use theme colors in notifications
Closes #177 | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Snackbar from 'material-ui/Snackbar';
import { hideNotification as hideNotificationAction } from '../../actions/notificationActions' ;
function getStyles(context) {
if (!context) return { primary1Color: '#00bcd4', accent1Color: '#ff4081' };
const {
muiTheme: {
baseTheme: {
palette: {
primary1Color,
accent1Color,
},
},
},
} = context;
return { primary1Color, accent1Color };
}
class Notification extends React.Component {
handleRequestClose = () => {
this.props.hideNotification();
};
render() {
const style = {};
const { primary1Color, accent1Color } = getStyles(this.context);
if (this.props.type === 'warning') {
style.backgroundColor = accent1Color;
}
if (this.props.type === 'confirm') {
style.backgroundColor = primary1Color;
}
return (<Snackbar
open={!!this.props.message}
message={this.props.message}
autoHideDuration={4000}
onRequestClose={this.handleRequestClose}
bodyStyle={style}
/>);
}
}
Notification.propTypes = {
message: PropTypes.string,
type: PropTypes.string.isRequired,
hideNotification: PropTypes.func.isRequired,
};
Notification.defaultProps = {
type: 'info',
};
Notification.contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
message: state.admin.notification.text,
type: state.admin.notification.type,
});
export default connect(
mapStateToProps,
{ hideNotification: hideNotificationAction },
)(Notification);
| import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Snackbar from 'material-ui/Snackbar';
import { hideNotification as hideNotificationAction } from '../../actions/notificationActions' ;
class Notification extends React.Component {
handleRequestClose = () => {
this.props.hideNotification();
};
render() {
const style = {};
if (this.props.type === 'warning') {
style.backgroundColor = '#ff4081';
}
if (this.props.type === 'confirm') {
style.backgroundColor = '#00bcd4';
}
return (<Snackbar
open={!!this.props.message}
message={this.props.message}
autoHideDuration={4000}
onRequestClose={this.handleRequestClose}
bodyStyle={style}
/>);
}
}
Notification.propTypes = {
message: PropTypes.string,
type: PropTypes.string.isRequired,
hideNotification: PropTypes.func.isRequired,
};
Notification.defaultProps = {
type: 'info',
};
const mapStateToProps = (state) => ({
message: state.admin.notification.text,
type: state.admin.notification.type,
});
export default connect(
mapStateToProps,
{ hideNotification: hideNotificationAction },
)(Notification);
|
Update ContactBook Middleware to obey contract | import logging
from django.http import Http404
from gargoyle import gargoyle
from contacts.models import Book
sentry = logging.getLogger('sentry')
class ContactBookMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
# CONTRACT: At the end of this, if the user is authenticate,
# request.current_book _must_ be populated with a valid book, and
# request.books _must_ be a list of Books with length greater than 1.
if hasattr(request, 'user'):
if request.user.is_authenticated():
request.books = Book.objects.filter_for_user(request.user)
request.current_book = None
if request.books:
if 'book' in view_kwargs:
current_book = request.books.filter(id=view_kwargs['book'])
if current_book:
request.current_book = current_book
else:
return Http404
else:
request.current_book = request.books[0]
else:
sentry.error("No book found for user", exc_info=True,
extra={"user": user}
)
request.current_book = Book.objects.create_for_user(request.user)
request.books = Book.objects.filter_for_user(request.user)
if (
gargoyle.is_active('enable_payments', request) and
request.current_book
):
request.can_invite = (
request.current_book.plan and not
request.current_book.plan.startswith('basic')
)
else:
request.can_invite = True
| import logging
from django.http import Http404
from gargoyle import gargoyle
from contacts.models import Book
sentry = logging.getLogger('sentry')
class ContactBookMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if hasattr(request, 'user'):
if request.user.is_authenticated():
books = Book.objects.filter_for_user(request.user)
request.current_book = None
if gargoyle.is_active('multi_book', request):
request.books = books
request.current_book = books[0]
if 'book' in view_kwargs:
current_book = request.books.filter(id=view_kwargs['book'])
if current_book:
request.current_book = current_book
else:
return Http404
else:
if books:
request.current_book = books[0]
else:
request.current_book = None
sentry.error("No book found for user", exc_info=True,
extra={"user": user}
)
if (
gargoyle.is_active('enable_payments', request) and
request.current_book
):
request.can_invite = (
request.current_book.plan and not
request.current_book.plan.startswith('basic')
)
else:
request.can_invite = True
|
Refresh the embed block onload in PublishBrief | var Publish = {
enableSend: function() {
MovimUtils.removeClass('#button_send', 'disabled');
},
disableSend: function() {
MovimUtils.addClass('#button_send', 'disabled');
}
}
var PublishBrief = {
togglePrivacy: function() {
var checked = document.querySelector('#publishbrief form #open');
var button = document.querySelector('#publishbrief span.privacy i');
MovimUtils.removeClass(button, 'zmdi-lock-outline');
MovimUtils.removeClass(button, 'zmdi-lock-globe');
// Public
if(checked.checked) {
checked.checked = false;
MovimUtils.addClass(button, 'zmdi-lock-outline');
} else {
checked.checked = true;
MovimUtils.addClass(button, 'zmdi-globe');
}
PublishBrief_ajaxDisplayPrivacy(checked.checked);
},
addUrl: function() {
var url = document.querySelector('#url');
var embed = document.querySelector('#embed');
embed.value = url.value;
embed.onchange();
},
clearEmbed: function() {
document.querySelector('input[name=embed]').value = '';
PublishBrief_ajaxClearEmbed();
}
}
MovimWebsocket.attach(function() {
PublishBrief_ajaxClearEmbed();
});
Upload.attach(function() {
var embed = document.querySelector('input[name=embed]');
embed.value = Upload.get;
embed.onchange();
});
| var Publish = {
enableSend: function() {
MovimUtils.removeClass('#button_send', 'disabled');
},
disableSend: function() {
MovimUtils.addClass('#button_send', 'disabled');
}
}
var PublishBrief = {
togglePrivacy: function() {
var checked = document.querySelector('#publishbrief form #open');
var button = document.querySelector('#publishbrief span.privacy i');
MovimUtils.removeClass(button, 'zmdi-lock-outline');
MovimUtils.removeClass(button, 'zmdi-lock-globe');
// Public
if(checked.checked) {
checked.checked = false;
MovimUtils.addClass(button, 'zmdi-lock-outline');
} else {
checked.checked = true;
MovimUtils.addClass(button, 'zmdi-globe');
}
PublishBrief_ajaxDisplayPrivacy(checked.checked);
},
addUrl: function() {
var url = document.querySelector('#url');
var embed = document.querySelector('#embed');
embed.value = url.value;
embed.onchange();
},
clearEmbed: function() {
document.querySelector('input[name=embed]').value = '';
PublishBrief_ajaxClearEmbed();
}
}
Upload.attach(function() {
var embed = document.querySelector('input[name=embed]');
embed.value = Upload.get;
embed.onchange();
});
|
Fix install dependencies and bump to 1.0.3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
def get_description():
try:
with open("README.md") as f:
return f.read()
except IOError:
return ""
setup(name='ulp',
version='1.0.3',
author='Guilherme Victal',
author_email='guilherme at victal.eti.br',
url='https://github.com/victal/ulp',
description='ULP is a Locator Picker - a PathPicker clone for URLs',
long_description=get_description(),
license='MIT',
packages=['ulp', 'ulp.widgets'],
install_requires=['pyperclip', 'urwid'],
scripts=['scripts/ulp'],
entry_points={
'console_scripts': [
'ulp_extract=ulp.urlextract:main',
'ulp_tui=ulp.tui:main'
]
},
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
def get_description():
try:
with open("README.md") as f:
return f.read()
except IOError:
return ""
setup(name='ulp',
version='1.0.2',
author='Guilherme Victal',
author_email='guilherme at victal.eti.br',
url='https://github.com/victal/ulp',
description='ULP is a Locator Picker - a PathPicker clone for URLs',
long_description=get_description(),
license='MIT',
packages=['ulp', 'ulp.widgets'],
requires=['pyperclip', 'urwid'],
scripts=['scripts/ulp'],
entry_points={
'console_scripts': [
'ulp_extract=ulp.urlextract:main',
'ulp_tui=ulp.tui:main'
]
},
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
]
)
|
Change data provider name for add email test | <?php
class AddMailTest extends PHPUnit_Extensions_Selenium2TestCase
{
protected function setUp()
{
$this->setHost('127.0.0.1');
$this->setBrowser('firefox');
$this->setBrowserUrl('http://mail-sender.dev');
}
public function setUpPage()
{
$this->url('/mail_sender.php?page=add_mail');
$passwordField = $this->byId('pass');
$passwordField->value('admin');
$this->byId('OK')->click();
}
/**
* @dataProvider emailScenarios
*/
public function testAddMail($mail, $expectedMessage)
{
$this->url('/mail_sender.php?page=add_mail');
$emailField = $this->byName('n_mail');
$emailField->value($mail);
$button = $this->byName('add_mail');
$button->click();
$this->assertContains($expectedMessage, $this->source());
}
public function emailScenarios()
{
return array(
array('', 'Niepoprawne mail!'),
array('some@', 'Niepoprawne mail!'),
array('some@email', 'Niepoprawne mail!'),
array('[email protected]', 'Maila dodano do bazy!'),
array('[email protected]', 'Zapytanie ofertowe wysłano ponownie!'),
);
}
}
| <?php
class AddMailTest extends PHPUnit_Extensions_Selenium2TestCase
{
protected function setUp()
{
$this->setHost('127.0.0.1');
$this->setBrowser('firefox');
$this->setBrowserUrl('http://mail-sender.dev');
}
public function setUpPage()
{
$this->url('/mail_sender.php?page=add_mail');
$passwordField = $this->byId('pass');
$passwordField->value('admin');
$this->byId('OK')->click();
}
/**
* @dataProvider emailProvider
*/
public function testAddMail($mail, $expectedMessage)
{
$this->url('/mail_sender.php?page=add_mail');
$emailField = $this->byName('n_mail');
$emailField->value($mail);
$button = $this->byName('add_mail');
$button->click();
$this->assertContains($expectedMessage, $this->source());
}
public function emailProvider()
{
return array(
array('', 'Niepoprawne mail!'),
array('some@', 'Niepoprawne mail!'),
array('some@email', 'Niepoprawne mail!'),
array('[email protected]', 'Maila dodano do bazy!'),
array('[email protected]', 'Zapytanie ofertowe wysłano ponownie!'),
);
}
}
|
Return the appended node to match the DOM api | var mocks = {
getFakeView: function(width, height) {
return {
handler: false,
clientWidth: width,
clientHeight: height,
addEventListener: function(handler) { this.handler = handler; },
removeEventListener: function() {this.handler = false; },
children: [
{
children: [],
id: 0,
style: {},
appendChild: function(child) {
child.__mockId = ++this.id;
this.children.push(child);
return child;
},
removeChild: function(child) {
for(var i = 0; i < this.children.length; i++) {
if(this.children[i].__mockId === child.__mockId) {
this.children.splice(i,1);
return child;
}
}
}
}
]
};
}
};
module.exports = mocks; | var mocks = {
getFakeView: function(width, height) {
return {
handler: false,
clientWidth: width,
clientHeight: height,
addEventListener: function(handler) { this.handler = handler; },
removeEventListener: function() {this.handler = false; },
children: [
{
children: [],
id: 0,
style: {},
appendChild: function(child) {
child.__mockId = ++this.id;
this.children.push(child);
},
removeChild: function(child) {
for(var i = 0; i < this.children.length; i++) {
if(this.children[i].__mockId === child.__mockId) {
this.children.splice(i,1);
return;
}
}
}
}
]
};
}
};
module.exports = mocks; |
Add a subcommand for listing packages | """WebShack: Sensible web components.
Usage:
webshack list
webshack get <package>...
webshack -h | --help
webshack --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
from docopt import docopt
from termcolor import colored
from webshack.install_package import install_package_hierarchy
import webshack.package_db as pdb
from pathlib import Path
VERSION="0.0.1"
class CLIOutput:
def __init__(self):
self.shift_width = 0
def log(self, package):
if package is None:
self.end_package()
else:
self.begin_package(package)
def begin_package(self, package):
self.shift_width = 50 - len(package)
sys.stdout.write("Installing {pkg}...".format(pkg=colored(package, 'blue')))
sys.stdout.flush()
def end_package(self):
sys.stdout.write(' '*self.shift_width)
sys.stdout.write('[{}]\n'.format(colored('DONE', 'green', attrs=['bold'])))
sys.stdout.flush()
def main():
options = docopt(__doc__, version=VERSION)
db = pdb.standard_package_db()
components = Path('components')
if options['get']:
output = CLIOutput()
for package in options['<package>']:
install_package_hierarchy(package, db, components,
log_output=output.log)
elif options['list']:
for package in sorted(db):
print(package)
| """WebShack: Sensible web components.
Usage:
webshack get <package>...
webshack -h | --help
webshack --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
from docopt import docopt
from termcolor import colored
from webshack.install_package import install_package_hierarchy
import webshack.package_db as pdb
from pathlib import Path
VERSION="0.0.1"
class CLIOutput:
def __init__(self):
self.shift_width = 0
def log(self, package):
if package is None:
self.end_package()
else:
self.begin_package(package)
def begin_package(self, package):
self.shift_width = 50 - len(package)
sys.stdout.write("Installing {pkg}...".format(pkg=colored(package, 'blue')))
sys.stdout.flush()
def end_package(self):
sys.stdout.write(' '*self.shift_width)
sys.stdout.write('[{}]\n'.format(colored('DONE', 'green', attrs=['bold'])))
sys.stdout.flush()
def main():
options = docopt(__doc__, version=VERSION)
db = pdb.standard_package_db()
components = Path('components')
if options['get']:
output = CLIOutput()
for package in options['<package>']:
install_package_hierarchy(package, db, components,
log_output=output.log)
|
Remove subtree push from grunt push-master task. | module.exports = function() {
return {
_defaults: {
bg: false
},
/**
* Clean the app distribution folder.
*/
app_clean: {
execOpts: {
cwd: '.'
},
cmd: 'rm -Rf <%= distScriptsPath %>/*'
},
/**
* Copy app HTML template to distribution folder.
*/
copy_app_template: {
execOpts: {
cwd: '.'
},
cmd: 'cp <%= appMainTemplate %> <%= distPath %>'
},
/*
* Push local (master) branch to remote master. Push to subtree remotes also.
*/
push_2_master: {
execOpts: {
cwd: '../../../'
},
cmd: [
'git push origin master',
'git push bitbucket master',
].join(';')
}
};
};
| module.exports = function() {
return {
_defaults: {
bg: false
},
/**
* Clean the app distribution folder.
*/
app_clean: {
execOpts: {
cwd: '.'
},
cmd: 'rm -Rf <%= distScriptsPath %>/*'
},
/**
* Copy app HTML template to distribution folder.
*/
copy_app_template: {
execOpts: {
cwd: '.'
},
cmd: 'cp <%= appMainTemplate %> <%= distPath %>'
},
/*
* Push local (master) branch to remote master. Push to subtree remotes also.
*/
push_2_master: {
execOpts: {
cwd: '../../../'
},
cmd: [
'git push origin master',
'git subtree push -P www/angular angular master',
'git push bitbucket master',
'git subtree push -P www/angular bitbucket_angular master;'
].join(';')
}
};
};
|
Add key to list to optimise rendering | import React from "react"
import classes from "./HeaderBar.module.css"
import Logo from "../../assets/sGonksLogo.png"
import { Link, NavLink } from "react-router-dom"
import LinkButton from "../UI/LinkButton/LinkButton"
import LoginButtonSet from "../UI/LoginButtonSet/LoginButtonSet";
const HeaderBar = (props) => {
let innerNavLinks = [
{ linkTo: "/", display: "My sGonks", key: "mysgonks"},
{ linkTo: "/", display: "Competition", key: "competition" },
{ linkTo: "/", display: "Marketplace", key: "marketplace" },
]
let innerNav = props.innerNav ? (
<nav className={classes.Navigation}>
<ul>
{innerNavLinks.map((link) => {
return (
<li key={link.key}>
<NavLink to={link.linkTo} activeClassName={classes.active}>
{link.display}
</NavLink>
</li>
)
})}
</ul>
</nav>
) : null
return (
<header className={classes.HeaderBar}>
<Link to="/">
<img src={Logo} className={classes.Logo} />
</Link>
<div className={classes.NavigationContainer}>
{innerNav}
</div>
<div className={classes.ButtonsContainer}>
<LoginButtonSet></LoginButtonSet>
</div>
</header>
)
}
export default HeaderBar
| import React from "react"
import classes from "./HeaderBar.module.css"
import Logo from "../../assets/sGonksLogo.png"
import { Link, NavLink } from "react-router-dom"
import LinkButton from "../UI/LinkButton/LinkButton"
import LoginButtonSet from "../UI/LoginButtonSet/LoginButtonSet";
const HeaderBar = (props) => {
let innerNavLinks = [
{ linkTo: "/", display: "My sGonks" },
{ linkTo: "/", display: "Competition" },
{ linkTo: "/", display: "Marketplace" },
]
let innerNav = props.innerNav ? (
<nav className={classes.Navigation}>
<ul>
{innerNavLinks.map((link) => {
return (
<li>
<NavLink to={link.linkTo} activeClassName={classes.active}>
{link.display}
</NavLink>
</li>
)
})}
</ul>
</nav>
) : null
return (
<header className={classes.HeaderBar}>
<Link to="/">
<img src={Logo} className={classes.Logo} />
</Link>
<div className={classes.NavigationContainer}>
{innerNav}
</div>
<div className={classes.ButtonsContainer}>
<LoginButtonSet></LoginButtonSet>
</div>
</header>
)
}
export default HeaderBar
|
Update class name to camelcase pattern. | class UploadFile():
def __init__(self, name, type=None, size=None, not_allowed_msg=''):
self.name = name
self.type = type
self.size = size
self.not_allowed_msg = not_allowed_msg
self.url = "data/%s" % name
self.delete_url = "delete/%s" % name
self.delete_type = "DELETE"
def get_file(self):
if self.type is not None:
# POST an image
if self.not_allowed_msg == '':
return {"name": self.name,
"type": self.type,
"size": self.size,
"url": self.url,
"deleteUrl": self.delete_url,
"deleteType": self.delete_type, }
# File type is not allowed
else:
return {"error": self.not_allowed_msg,
"name": self.name,
"type": self.type,
"size": self.size, }
# GET normal file from disk
else:
return {"name": self.name,
"size": self.size,
"url": self.url,
"deleteUrl": self.delete_url,
"deleteType": self.delete_type, }
| class uploadfile():
def __init__(self, name, type=None, size=None, not_allowed_msg=''):
self.name = name
self.type = type
self.size = size
self.not_allowed_msg = not_allowed_msg
self.url = "data/%s" % name
self.delete_url = "delete/%s" % name
self.delete_type = "DELETE"
def get_file(self):
if self.type is not None:
# POST an image
if self.not_allowed_msg == '':
return {"name": self.name,
"type": self.type,
"size": self.size,
"url": self.url,
"deleteUrl": self.delete_url,
"deleteType": self.delete_type, }
# File type is not allowed
else:
return {"error": self.not_allowed_msg,
"name": self.name,
"type": self.type,
"size": self.size, }
# GET normal file from disk
else:
return {"name": self.name,
"size": self.size,
"url": self.url,
"deleteUrl": self.delete_url,
"deleteType": self.delete_type, }
|
Raise an exception when the API response is not successful | BASE_URL = 'https://api.box.com/2.0'
FOLDERS_URL = '{}/folders/{{}}/items'.format(BASE_URL)
MAX_FOLDERS = 1000
class Client(object):
def __init__(self, provider_logic):
"""
Box client constructor
:param provider_logic: oauthclient ProviderLogic instance
:return:
"""
self.provider_logic = provider_logic
def folders(self, parent=None, limit=100, offset=0):
if parent:
folder_id = parent['id']
else:
folder_id = 0
url = FOLDERS_URL.format(folder_id)
count = 0
while count < limit:
params = {
# this is the request limit, not the number of folders we actually want
'limit': 100,
'offset': offset+count,
}
response = self.provider_logic.get(url, params=params)
response.raise_for_status()
json_data = response.json()
# if we hit the total number of entries, we have to be done
total_count = json_data['total_count']
if count >= total_count:
break
# determine how many more entries to get from the result set
entry_count = limit - count
entries = json_data['entries'][:entry_count]
for entry in entries:
yield entry
# increment the count by the number of entries
count += len(entries)
| BASE_URL = 'https://api.box.com/2.0'
FOLDERS_URL = '{}/folders/{{}}/items'.format(BASE_URL)
MAX_FOLDERS = 1000
class Client(object):
def __init__(self, provider_logic):
"""
Box client constructor
:param provider_logic: oauthclient ProviderLogic instance
:return:
"""
self.provider_logic = provider_logic
def folders(self, parent=None, limit=100, offset=0):
if parent:
folder_id = parent['id']
else:
folder_id = 0
url = FOLDERS_URL.format(folder_id)
count = 0
while count < limit:
params = {
# this is the request limit, not the number of folders we actually want
'limit': 100,
'offset': offset+count,
}
response = self.provider_logic.get(url, params=params)
json_data = response.json()
# if we hit the total number of entries, we have to be done
total_count = json_data['total_count']
if count >= total_count:
break
# determine how many more entries to get from the result set
entry_count = limit - count
entries = json_data['entries'][:entry_count]
for entry in entries:
yield entry
# increment the count by the number of entries
count += len(entries)
|
Fix webpack module resolving rule | var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: __dirname,
entry: 'client',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
chunkFilename: '[id].js'
},
resolve: {
root: path.join(__dirname, 'client-test'),
extensions: ['', '.js'],
modulesDirectories: ['node_modules', 'src']
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
title: 'WebGLue'
})
],
module: {
loaders: [
{
test: /\.js$/i,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.json$/i,
loader: 'json'
},
{
test: /\.html?$/i,
loader: 'html'
},
{
test: /(\.vert|\.frag|\.obj|\.mtl)$/i,
loader: 'raw'
},
{
test: /\.(otf|eot|svg|ttf|woff|woff2)(\?.+)?$/,
loader: 'url-loader?limit=10240'
},
{
test: /\.(png|jpe?g|gif|tiff)?$/,
loader: 'file-loader'
}
]
}
};
| var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: __dirname,
entry: './client-test/client.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
chunkFilename: '[id].js'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
title: 'WebGLue'
}),
new webpack.DefinePlugin({
__CLIENT__: true,
__SERVER__: false
})
],
module: {
loaders: [
{
test: /\.jsx?$/i,
exclude: /(node_modules|bower_components)/,
loader: 'babel'
},
{
test: /\.json$/i,
loader: 'json'
},
{
test: /\.html?$/i,
loader: 'html'
},
{
test: /(\.vert|\.frag|\.obj|\.mtl)$/i,
loader: 'raw'
},
{
test: /\.(otf|eot|svg|ttf|woff|woff2)(\?.+)?$/,
loader: 'url-loader?limit=10240'
},
{
test: /\.(png|jpe?g|gif|tiff)?$/,
loader: 'file-loader'
}
]
}
};
|
Fix releases breaking if there were no notes | <?php
namespace Transformers;
class RecordTransformer extends Transformer
{
/**
* transform record
*
* @param array $record
* @return array
*/
public function transform($record)
{
return [
'release_id' => $record->release_id,
'title' => $record->basic_information->title,
'artist' => $record->basic_information->artists[0]->name,
'year' => $record->basic_information->year,
'thumb' => $record->basic_information->thumb
];
}
/**
* release transformer
*
* @param array $release
* @return array
*/
public function transformRelease($release)
{
$tracklist = [];
foreach ($release['tracklist'] as $key => $track) {
$tracklist[] = $track->title;
}
return [
'title' => $release['title'],
'artist' => $release['artists'][0]->name,
'title' => $release['artists'][0]->name . ' - ' . $release['title'],
'year' => $release['year'],
'label' => $release['labels'][0]->name,
'released' => $release['released'],
'spotify' => $release['spotify'],
'notes' => isset($release['notes']) ? $release['notes'] : false,
'image' => $release['images'][0]->uri,
'tracklist' => $tracklist,
];
}
}
| <?php
namespace Transformers;
class RecordTransformer extends Transformer
{
/**
* transform record
*
* @param array $record
* @return array
*/
public function transform($record)
{
return [
'release_id' => $record->release_id,
'title' => $record->basic_information->title,
'artist' => $record->basic_information->artists[0]->name,
'year' => $record->basic_information->year,
'thumb' => $record->basic_information->thumb
];
}
/**
* release transformer
*
* @param array $release
* @return array
*/
public function transformRelease($release)
{
$tracklist = [];
foreach ($release['tracklist'] as $key => $track) {
$tracklist[] = $track->title;
}
return [
'title' => $release['title'],
'artist' => $release['artists'][0]->name,
'title' => $release['artists'][0]->name . ' - ' . $release['title'],
'year' => $release['year'],
'label' => $release['labels'][0]->name,
'released' => $release['released'],
'spotify' => $release['spotify'],
'notes' => $release['notes'],
'image' => $release['images'][0]->uri,
'tracklist' => $tracklist,
];
}
}
|
Update mock to be a bit closer to generated content | 'use strict';
var extensions = function(){
global.AI = {};
AI.extensions = {
commands: {
test: (function() {
var module = {};
(function() {
function command(flag, parameters) {
console.log("Hello world");
}
module.exports = {
exec: command,
command: "test",
native: null,
help: 'Description:\n- Executes Test\n\nUsage:\n- Test'
};
}());
return module.exports;
}()),
testWithNative: (function() {
var module = {};
(function() {
function command() {
console.log("Hello world");
}
function exec(flag, parameters) {
command();
}
function native() {
command();
}
module.exports = {
exec: exec,
command: "test",
native: native,
help: 'Description:\n- Executes Test\n\nUsage:\n- Test'
};
}());
return module.exports;
}()),
}
};
};
var generated = function() {
extensions();
};
module.exports = generated;
generated(); | 'use strict';
var extensions = function(){
global.AI = {};
AI.extensions = {
commands: {
test: (function() {
var module = {};
(function() {
'use strict';
function command(flag, parameters) {
console.log("Hello world");
}
module.exports = {
exec: command,
command: "test",
native: null,
help: 'Description:\n- Executes Test\n\nUsage:\n- Test'
};
}());
return module.exports;
}()),
testWithNative: (function() {
var module = {};
(function() {
'use strict';
function command() {
console.log("Hello world");
}
function exec(flag, parameters) {
command();
}
function native() {
command();
}
module.exports = {
exec: exec,
command: "test",
native: native,
help: 'Description:\n- Executes Test\n\nUsage:\n- Test'
};
}());
return module.exports;
}()),
}
};
};
var generated = function() {
extensions();
};
generated();
module.exports = generated; |
Add msgpack, dependency used in parallel code. Remove PIL, since it's not pip-installable? | from setuptools import setup, find_packages
version = '0.2.0'
setup(
name='scoville',
version=version,
description="A tool for attributing MVT tile size.",
long_description=open('README.md').read(),
classifiers=[
# strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Utilities',
],
keywords='tile size mvt',
author='Matt Amos, Tilezen',
author_email='[email protected]',
url='https://github.com/tilezen/scoville',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'click',
'requests',
'requests_futures',
'squarify',
'msgpack',
],
entry_points=dict(
console_scripts=[
'scoville = scoville.command:scoville_main',
]
),
test_suite='tests',
)
| from setuptools import setup, find_packages
version = '0.2.0'
setup(
name='scoville',
version=version,
description="A tool for attributing MVT tile size.",
long_description=open('README.md').read(),
classifiers=[
# strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Utilities',
],
keywords='tile size mvt',
author='Matt Amos, Tilezen',
author_email='[email protected]',
url='https://github.com/tilezen/scoville',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'click',
'PIL',
'requests',
'requests_futures',
'squarify',
],
entry_points=dict(
console_scripts=[
'scoville = scoville.command:scoville_main',
]
),
test_suite='tests',
)
|
Make code compatible with PHP <5.4 by removing short array syntax | <?php
class Algolia_Algoliasearch_Model_Resource_Fulltext_Collection extends Mage_CatalogSearch_Model_Resource_Fulltext_Collection
{
/**
* Add search query filter without preparing result since result table causes lots of lock contention.
*
* @param string $query
* @throws Exception
* @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection
*/
public function addSearchFilter($query)
{
if ( ! Mage::helper('algoliasearch')->isEnabled() || Mage::helper('algoliasearch')->useResultCache()) {
return parent::addSearchFilter($query);
}
// This method of filtering the product collection by the search result does not use the catalogsearch_result table
try {
$data = Mage::helper('algoliasearch')->getSearchResult($query, Mage::app()->getStore()->getId());
} catch (Exception $e) {
Mage::getSingleton('catalog/session')->addError(Mage::helper('algoliasearch')->__('Search failed. Please try again.'));
$this->getSelect()->columns(array('relevance' => new Zend_Db_Expr("e.entity_id")));
$this->getSelect()->where('e.entity_id = 0');
return $this;
}
$sortedIds = array_reverse(array_keys($data));
$this->getSelect()->columns(array('relevance' => new Zend_Db_Expr("FIND_IN_SET(e.entity_id, '".implode(',',$sortedIds)."')")));
$this->getSelect()->where('e.entity_id IN (?)', $sortedIds);
return $this;
}
}
| <?php
class Algolia_Algoliasearch_Model_Resource_Fulltext_Collection extends Mage_CatalogSearch_Model_Resource_Fulltext_Collection
{
/**
* Add search query filter without preparing result since result table causes lots of lock contention.
*
* @param string $query
* @throws Exception
* @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection
*/
public function addSearchFilter($query)
{
if ( ! Mage::helper('algoliasearch')->isEnabled() || Mage::helper('algoliasearch')->useResultCache()) {
return parent::addSearchFilter($query);
}
// This method of filtering the product collection by the search result does not use the catalogsearch_result table
try {
$data = Mage::helper('algoliasearch')->getSearchResult($query, Mage::app()->getStore()->getId());
} catch (Exception $e) {
Mage::getSingleton('catalog/session')->addError(Mage::helper('algoliasearch')->__('Search failed. Please try again.'));
$this->getSelect()->columns(['relevance' => new Zend_Db_Expr("e.entity_id")]);
$this->getSelect()->where('e.entity_id = 0');
return $this;
}
$sortedIds = array_reverse(array_keys($data));
$this->getSelect()->columns(['relevance' => new Zend_Db_Expr("FIND_IN_SET(e.entity_id, '".implode(',',$sortedIds)."')")]);
$this->getSelect()->where('e.entity_id IN (?)', $sortedIds);
return $this;
}
}
|
Add missing void pop in uncaptured exception blocks | from thinglang.compiler.buffer import CompilationBuffer
from thinglang.compiler.opcodes import OpcodeJump, OpcodePopLocal, OpcodePop
from thinglang.lexer.blocks.exceptions import LexicalHandle
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
class HandleBlock(BaseNode):
"""
An exception handling block
"""
def __init__(self, exception_type: Identifier, exception_name: Identifier=None):
super(HandleBlock, self).__init__([exception_type, exception_name])
self.exception_type, self.exception_name = exception_type, exception_name
def compile(self, context: CompilationBuffer):
assert self.parent is None, 'Handle blocks may not be part of the AST after finalization'
buffer = context.optional()
if self.exception_name is not None:
buffer.append(OpcodePopLocal.from_reference(context.resolve(self.exception_name)), self.source_ref)
else:
buffer.append(OpcodePop(), self.source_ref)
super(HandleBlock, self).compile(buffer)
buffer.append(OpcodeJump(context.next_index, absolute=True), self.source_ref)
return context.epilogue(buffer)
@staticmethod
@ParserRule.mark
def parse_handle_block_with_value(_: LexicalHandle, exception_type: Identifier, exception_name: Identifier):
return HandleBlock(exception_type, exception_name)
@staticmethod
@ParserRule.mark
def parse_handle_block(_: LexicalHandle, exception_type: Identifier):
return HandleBlock(exception_type)
| from thinglang.compiler.buffer import CompilationBuffer
from thinglang.compiler.opcodes import OpcodeJump, OpcodePopLocal
from thinglang.lexer.blocks.exceptions import LexicalHandle
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
class HandleBlock(BaseNode):
"""
An exception handling block
"""
def __init__(self, exception_type: Identifier, exception_name: Identifier=None):
super(HandleBlock, self).__init__([exception_type, exception_name])
self.exception_type, self.exception_name = exception_type, exception_name
def compile(self, context: CompilationBuffer):
assert self.parent is None, 'Handle blocks may not be part of the AST after finalization'
buffer = context.optional()
if self.exception_name is not None:
buffer.append(OpcodePopLocal.from_reference(context.resolve(self.exception_name)), self.source_ref)
super(HandleBlock, self).compile(buffer)
buffer.append(OpcodeJump(context.next_index, absolute=True), self.source_ref)
return context.epilogue(buffer)
@staticmethod
@ParserRule.mark
def parse_handle_block_with_value(_: LexicalHandle, exception_type: Identifier, exception_name: Identifier):
return HandleBlock(exception_type, exception_name)
@staticmethod
@ParserRule.mark
def parse_handle_block(_: LexicalHandle, exception_type: Identifier):
return HandleBlock(exception_type)
|
Fix bug setting the key='elb', subkey='name' attribute. | from clusto.drivers.devices.appliance.basicappliance import BasicAppliance
import boto.ec2.elb
class AmazonELB(BasicAppliance):
_driver_name = 'amazonelb'
def __init__(self, name, elbname, **kwargs):
BasicAppliance.__init__(self, name, **kwargs)
self.set_attr(key='elb', subkey='name', value=elbname)
def get_boto_connection(self):
region = self.attr_value(key='ec2', subkey='region', merge_container_attrs=True)
return boto.ec2.elb.connect_to_region(region)
def enable_zone(self, name_or_entity):
conn = self.get_boto_connection()
if isinstance(name_or_entity, str):
name = name_or_entity
else:
name = name_or_entity.name
conn.enable_availability_zones(self.attr_value(key='elb', subkey='name'), [name])
def disable_zone(self, name_or_entity):
conn = self.get_boto_connection()
if isinstance(name_or_entity, str):
name = name_or_entity
else:
name = name_or_entity.name
conn.disable_availability_zones(self.attr_value(key='elb', subkey='name'), [name])
def get_state(self):
conn = self.get_boto_connection()
return conn.describe_instance_health(self.attr_value(key='elb', subkey='name'))
| from clusto.drivers.devices.appliance.basicappliance import BasicAppliance
import boto.ec2.elb
class AmazonELB(BasicAppliance):
_driver_name = 'amazonelb'
def __init__(self, name, elbname, **kwargs):
BasicAppliance.__init__(self, name, **kwargs)
self.set_attr(key='elb', subkey='name', value='elbname')
def get_boto_connection(self):
region = self.attr_value(key='ec2', subkey='region', merge_container_attrs=True)
return boto.ec2.elb.connect_to_region(region)
def enable_zone(self, name_or_entity):
conn = self.get_boto_connection()
if isinstance(name_or_entity, str):
name = name_or_entity
else:
name = name_or_entity.name
conn.enable_availability_zones(self.attr_value(key='elb', subkey='name'), [name])
def disable_zone(self, name_or_entity):
conn = self.get_boto_connection()
if isinstance(name_or_entity, str):
name = name_or_entity
else:
name = name_or_entity.name
conn.disable_availability_zones(self.attr_value(key='elb', subkey='name'), [name])
def get_state(self):
conn = self.get_boto_connection()
return conn.describe_instance_health(self.attr_value(key='elb', subkey='name'))
|
Handle mounting and unmounting via ref callback | import React, { Component, PropTypes } from 'react'
import ReactDOMServer from 'react-dom/server'
import SVGInjector from 'svg-injector'
export default class ReactSVG extends Component {
static defaultProps = {
callback: () => {},
className: '',
evalScripts: 'once',
style: {}
}
static propTypes = {
callback: PropTypes.func,
className: PropTypes.string,
evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]),
path: PropTypes.string.isRequired,
style: PropTypes.object
}
refCallback = (container) => {
if (!container) {
this.removeSVG()
return
}
this.container = container
this.renderSVG()
}
renderSVG(props = this.props) {
const {
callback: each,
className,
evalScripts,
path,
style
} = props
const div = document.createElement('div')
div.innerHTML = ReactDOMServer.renderToStaticMarkup(
<img
className={className}
data-src={path}
style={style}
/>
)
const img = this.container.appendChild(div.firstChild)
SVGInjector(img, {
evalScripts,
each
})
}
removeSVG() {
this.container.removeChild(this.container.firstChild)
}
componentWillReceiveProps(nextProps) {
this.removeSVG()
this.renderSVG(nextProps)
}
shouldComponentUpdate() {
return false
}
render() {
return <div ref={this.refCallback} />
}
}
| import React, { Component, PropTypes } from 'react'
import ReactDOM from 'react-dom'
import ReactDOMServer from 'react-dom/server'
import SVGInjector from 'svg-injector'
export default class ReactSVG extends Component {
static defaultProps = {
callback: () => {},
className: '',
evalScripts: 'once',
style: {}
}
static propTypes = {
callback: PropTypes.func,
className: PropTypes.string,
evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]),
path: PropTypes.string.isRequired,
style: PropTypes.object
}
renderSVG(props = this.props) {
const {
callback: each,
className,
evalScripts,
path,
style
} = props
this.container = this.container || ReactDOM.findDOMNode(this)
const div = document.createElement('div')
div.innerHTML = ReactDOMServer.renderToStaticMarkup(
<img
className={className}
data-src={path}
style={style}
/>
)
const img = this.container.appendChild(div.firstChild)
SVGInjector(img, {
evalScripts,
each
})
}
removeSVG() {
this.container.removeChild(this.container.firstChild)
}
componentDidMount() {
this.renderSVG()
}
componentWillReceiveProps(nextProps) {
this.removeSVG()
this.renderSVG(nextProps)
}
shouldComponentUpdate() {
return false
}
componentWillUnmount() {
this.removeSVG()
}
render() {
return <div />
}
}
|
Fix for null values in Voice events | <?php
declare(strict_types=1);
namespace Nexmo\Webhook;
use PDO;
use Zend\Diactoros\ServerRequestFactory;
use Psr\Http\Message\ServerRequestInterface;
abstract class Factory
{
abstract public static function createFromArray(array $data);
public static function createFromJson(string $json)
{
$data = json_decode($json, true);
if (is_null($data)) {
throw new \RuntimeException("Invalid JSON string detected for webhook transformation");
}
return static::createFromArray($data);
}
public static function createFromGlobals()
{
$request = ServerRequestFactory::fromGlobals();
return static::createFromRequest($request);
}
public static function createFromRequest(ServerRequestInterface $request)
{
$params = [];
switch ($request->getMethod()) {
case 'GET':
$params = $request->getQueryParams();
// Fix "null" values coming in from GET requests
foreach ($params as $key => $value) {
if ($value === 'null') {
$params[$key] = null;
}
}
break;
case 'POST':
$type = $request->getHeader('content-type');
if (!isset($type[0]) || $type[0] === 'application/json') {
$params = json_decode($request->getBody()->getContents(), true);
} else {
parse_str($request->getBody()->getContents(), $params);
// Fix "null" values coming in from URL encoded requests
foreach ($params as $key => $value) {
if ($value === 'null') {
$params[$key] = null;
}
}
}
break;
default:
throw new \RuntimeException("Invalid method for incoming webhook");
}
return static::createFromArray($params);
}
}
| <?php
declare(strict_types=1);
namespace Nexmo\Webhook;
use PDO;
use Zend\Diactoros\ServerRequestFactory;
use Psr\Http\Message\ServerRequestInterface;
abstract class Factory
{
abstract public static function createFromArray(array $data);
public static function createFromJson(string $json)
{
$data = json_decode($json, true);
if (is_null($data)) {
throw new \RuntimeException("Invalid JSON string detected for webhook transformation");
}
return static::createFromArray($data);
}
public static function createFromGlobals()
{
$request = ServerRequestFactory::fromGlobals();
return static::createFromRequest($request);
}
public static function createFromRequest(ServerRequestInterface $request)
{
$params = [];
switch ($request->getMethod()) {
case 'GET':
$params = $request->getQueryParams();
break;
case 'POST':
$type = $request->getHeader('content-type');
if (!isset($type[0]) || $type[0] === 'application/json') {
$params = json_decode($request->getBody()->getContents(), true);
} else {
parse_str($request->getBody()->getContents(), $params);
}
break;
default:
throw new \RuntimeException("Invalid method for incoming webhook");
}
return static::createFromArray($params);
}
}
|
Fix bug to make template optional | """
Mixin fragment/html behavior into XBlocks
"""
from __future__ import absolute_import
from django.template.context import Context
from xblock.fragment import Fragment
class XBlockFragmentBuilderMixin(object):
"""
Create a default XBlock fragment builder
"""
def build_fragment(
self,
template='',
context=None,
css=None,
js=None,
js_init=None,
):
"""
Creates a fragment for display.
"""
context = context or {}
css = css or []
js = js or []
rendered_template = ''
if template:
template = 'templates/' + template
rendered_template = self.loader.render_django_template(
template,
context=Context(context),
i18n_service=self.runtime.service(self, 'i18n'),
)
fragment = Fragment(rendered_template)
for item in css:
if item.startswith('/'):
url = item
else:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_css_url(url)
for item in js:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_javascript_url(url)
if js_init:
fragment.initialize_js(js_init)
return fragment
| """
Mixin fragment/html behavior into XBlocks
"""
from __future__ import absolute_import
from django.template.context import Context
from xblock.fragment import Fragment
class XBlockFragmentBuilderMixin(object):
"""
Create a default XBlock fragment builder
"""
def build_fragment(
self,
template='',
context=None,
css=None,
js=None,
js_init=None,
):
"""
Creates a fragment for display.
"""
template = 'templates/' + template
context = context or {}
css = css or []
js = js or []
rendered_template = ''
if template:
rendered_template = self.loader.render_django_template(
template,
context=Context(context),
i18n_service=self.runtime.service(self, 'i18n'),
)
fragment = Fragment(rendered_template)
for item in css:
if item.startswith('/'):
url = item
else:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_css_url(url)
for item in js:
item = 'public/' + item
url = self.runtime.local_resource_url(self, item)
fragment.add_javascript_url(url)
if js_init:
fragment.initialize_js(js_init)
return fragment
|
Revert "Remove IF EXISTS from DROP TABLE when resetting the db."
This reverts commit a7dce25964cd740b0d0db86b255ede60c913e73d. | import sqlite3
DB_FILENAME = 'citationhunt.sqlite3'
def init_db():
return sqlite3.connect(DB_FILENAME)
def reset_db():
db = init_db()
with db:
db.execute('''
DROP TABLE IF EXISTS categories
''')
db.execute('''
DROP TABLE IF EXISTS articles
''')
db.execute('''
DROP TABLE IF EXISTS snippets
''')
db.execute('''
DROP TABLE IF EXISTS articles_categories
''')
db.execute('''
CREATE TABLE categories (id TEXT PRIMARY KEY, title TEXT)
''')
db.execute('''
INSERT INTO categories VALUES ("unassigned", "unassigned")
''')
db.execute('''
CREATE TABLE articles_categories (article_id TEXT, category_id TEXT,
FOREIGN KEY(article_id) REFERENCES articles(page_id)
ON DELETE CASCADE,
FOREIGN KEY(category_id) REFERENCES categories(id)
ON DELETE CASCADE)
''')
db.execute('''
CREATE TABLE articles (page_id TEXT PRIMARY KEY, url TEXT,
title TEXT)
''')
db.execute('''
CREATE TABLE snippets (id TEXT PRIMARY KEY, snippet TEXT,
section TEXT, article_id TEXT, FOREIGN KEY(article_id)
REFERENCES articles(page_id) ON DELETE CASCADE)
''')
return db
def create_indices():
db = init_db()
db.execute('''CREATE INDEX IF NOT EXISTS snippets_articles
ON snippets(article_id);''')
| import sqlite3
DB_FILENAME = 'citationhunt.sqlite3'
def init_db():
return sqlite3.connect(DB_FILENAME)
def reset_db():
db = init_db()
with db:
db.execute('''
DROP TABLE categories
''')
db.execute('''
DROP TABLE articles
''')
db.execute('''
DROP TABLE snippets
''')
db.execute('''
DROP TABLE articles_categories
''')
db.execute('''
CREATE TABLE categories (id TEXT PRIMARY KEY, title TEXT)
''')
db.execute('''
INSERT INTO categories VALUES ("unassigned", "unassigned")
''')
db.execute('''
CREATE TABLE articles_categories (article_id TEXT, category_id TEXT,
FOREIGN KEY(article_id) REFERENCES articles(page_id)
ON DELETE CASCADE,
FOREIGN KEY(category_id) REFERENCES categories(id)
ON DELETE CASCADE)
''')
db.execute('''
CREATE TABLE articles (page_id TEXT PRIMARY KEY, url TEXT,
title TEXT)
''')
db.execute('''
CREATE TABLE snippets (id TEXT PRIMARY KEY, snippet TEXT,
section TEXT, article_id TEXT, FOREIGN KEY(article_id)
REFERENCES articles(page_id) ON DELETE CASCADE)
''')
return db
def create_indices():
db = init_db()
db.execute('''CREATE INDEX IF NOT EXISTS snippets_articles
ON snippets(article_id);''')
|
Fix static files finder errors
Conflicts:
bluebottle/utils/staticfiles_finders.py | from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in the client static directories.
static/assets/greatbarier/images/logo.jpg
will translate to
MULTITENANT_DIR/greatbarier/static/images/logo.jpg
"""
matches = []
tenants = Client.objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
if not tenant_dir:
return matches
for tenant in tenants:
if "{0}/".format(tenant.client_name) in path:
tenant_path = path.replace('{0}/'.format(tenant.client_name),
'{0}/static/'.format(tenant.client_name))
print tenant_path
local_path = safe_join(tenant_dir, tenant_path)
print local_path
if os.path.exists(local_path):
if all:
return [local_path]
return local_path
return matches
| from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in the client static directories.
static/assets/greatbarier/images/logo.jpg
will translate to
MULTITENANT_DIR/greatbarier/static/images/logo.jpg
"""
matches = []
tenants = Client.objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
if not tenant_dir:
return matches
for tenant in tenants:
if "{0}/".format(tenant.client_name) in path:
tenant_path = path.replace('{0}/'.format(tenant.client_name),
'{0}/static/'.format(tenant.client_name))
print tenant_path
local_path = safe_join(tenant_dir, tenant_path)
print local_path
if os.path.exists(local_path):
return local_path
return
|
Add sub fetching on page changeé | import React, { Component } from 'react'
import PostListContainer from '../../containers/PostListContainer'
import Tabs, { Tab } from '../widgets/Tabs'
class Subreddit extends Component {
constructor (props) {
super(props)
}
componentDidMount () {
this.props.actions.requestSubreddit(this.props.r)
}
componentWillReceiveProps (nextProps) {
if (this.props.r !== nextProps.r) {
this.props.actions.requestSubreddit(nextProps.r)
}
}
render () {
if (!this.props.subreddit) {
return null
}
return (
<div className='subreddit'>
<div className="subreddit__header">
<div
className='subreddit__cover'
style={{
backgroundImage: `url(${this.props.subreddit.header_img})`
}}
/>
<h1>{this.props.subreddit.title}</h1>
</div>
<Tabs>
<Tab title='Hot'>
<div className='subreddit__post-list'>
<PostListContainer
r={this.props.r}
from={'hot'}
/>
</div>
</Tab>
<Tab title='New'>
<div className='subreddit__post-list'>
<PostListContainer
r={this.props.r}
from={'new'}
/>
</div>
</Tab>
<Tab title='Rising'>
<div className='subreddit__post-list'>
<PostListContainer
r={this.props.r}
from={'rising'}
/>
</div>
</Tab>
</Tabs>
</div>
)
}
}
export default Subreddit | import React, { Component } from 'react'
import PostListContainer from '../../containers/PostListContainer'
import Tabs, { Tab } from '../widgets/Tabs'
class Subreddit extends Component {
constructor (props) {
super(props)
}
componentDidMount () {
this.props.actions.requestSubreddit(this.props.r)
}
render () {
if (!this.props.subreddit) {
return null
}
return (
<div className='subreddit'>
<div className="subreddit__header">
<div
className='subreddit__cover'
style={{
backgroundImage: `url(${this.props.subreddit.header_img})`
}}
/>
<h1>{this.props.subreddit.title}</h1>
</div>
<Tabs>
<Tab title='Hot'>
<div className='subreddit__post-list'>
<PostListContainer
r={this.props.r}
from={'hot'}
/>
</div>
</Tab>
<Tab title='New'>
<div className='subreddit__post-list'>
<PostListContainer
r={this.props.r}
from={'new'}
/>
</div>
</Tab>
<Tab title='Rising'>
<div className='subreddit__post-list'>
<PostListContainer
r={this.props.r}
from={'rising'}
/>
</div>
</Tab>
</Tabs>
</div>
)
}
}
export default Subreddit |
Set default install to be not-verbose | module.exports = {
verbose: false,
styleLoader: "style-loader!css-loader!sass-loader",
scripts: {
'transition': true,
'alert': true,
'button': true,
'carousel': true,
'collapse': true,
'dropdown': true,
'modal': true,
'tooltip': true,
'popover': true,
'scrollspy': true,
'tab': true,
'affix': true
},
styles: {
"mixins": true,
"normalize": true,
"print": true,
"scaffolding": true,
"type": true,
"code": true,
"grid": true,
"tables": true,
"forms": true,
"buttons": true,
"component-animations": true,
"glyphicons": true,
"dropdowns": true,
"button-groups": true,
"input-groups": true,
"navs": true,
"navbar": true,
"breadcrumbs": true,
"pagination": true,
"pager": true,
"labels": true,
"badges": true,
"jumbotron": true,
"thumbnails": true,
"alerts": true,
"progress-bars": true,
"media": true,
"list-group": true,
"panels": true,
"wells": true,
"close": true,
"modals": true,
"tooltip": true,
"popovers": true,
"carousel": true,
"utilities": true,
"responsive-utilities": true
}
};
| module.exports = {
verbose: true,
styleLoader: "style-loader!css-loader!sass-loader",
scripts: {
'transition': true,
'alert': true,
'button': true,
'carousel': true,
'collapse': true,
'dropdown': true,
'modal': true,
'tooltip': true,
'popover': true,
'scrollspy': true,
'tab': true,
'affix': true
},
styles: {
"mixins": true,
"normalize": true,
"print": true,
"scaffolding": true,
"type": true,
"code": true,
"grid": true,
"tables": true,
"forms": true,
"buttons": true,
"component-animations": true,
"glyphicons": true,
"dropdowns": true,
"button-groups": true,
"input-groups": true,
"navs": true,
"navbar": true,
"breadcrumbs": true,
"pagination": true,
"pager": true,
"labels": true,
"badges": true,
"jumbotron": true,
"thumbnails": true,
"alerts": true,
"progress-bars": true,
"media": true,
"list-group": true,
"panels": true,
"wells": true,
"close": true,
"modals": true,
"tooltip": true,
"popovers": true,
"carousel": true,
"utilities": true,
"responsive-utilities": true
}
};
|
Add exception handling when call json parse | var smash = require("../smash.js");
var requestFactory = require('../core/request.js');
//TODO
//maybe group this with response
//no possibility to define JSON encoder/decoder
function lambdaProxyRequest() {
var that = this;
var next = null;
var fail = null;
var buildRequest = function (event) {
if (!event.httpMethod || !event.path) {
return null;
}
var request = requestFactory.createRequest();
if (event.requestContext && event.requestContext.authorizer && event.requestContext.authorizer.username) {
request.user = {username: event.requestContext.authorizer.username, roles: null};
}
request.method = event.httpMethod;
request.queryParamters = event.queryStringParameters;
request.headers = event.headers;
request.path = event.path;
if (event.body) {
request.body = JSON.parse(event.body);
}
return request;
};
that.setNext = function (extNext, extFail) {
next = extNext;
fail = extFail;
return that;
};
that.handleRequest = function (inputRequest, response) {
try {
request = buildRequest(inputRequest);
} catch (error) {
fail(response);
return false;
}
if (request !== null) {
next(request, response);
return true;
} else {
fail(response);
return false;
}
};
}
smash.registerRequestMiddleware(new lambdaProxyRequest());
module.exports = smash.getRequestMiddleware();
| var smash = require("../smash.js");
var requestFactory = require('../core/request.js');
//TODO
//maybe group this with response
//no possibility to define JSON encoder/decoder
function lambdaProxyRequest() {
var that = this;
var next = null;
var fail = null;
var buildRequest = function (event) {
if (!event.httpMethod || !event.path) {
return null;
}
var request = requestFactory.createRequest();
if (event.requestContext && event.requestContext.authorizer && event.requestContext.authorizer.username) {
request.user = {username: event.requestContext.authorizer.username, roles: null};
}
request.method = event.httpMethod;
request.queryParamters = event.queryStringParameters;
request.headers = event.headers;
request.path = event.path;
if (event.body) {
request.body = JSON.parse(event.body);
}
return request;
};
that.setNext = function (extNext, extFail) {
next = extNext;
fail = extFail;
return that;
};
that.handleRequest = function (inputRequest, response) {
request = buildRequest(inputRequest);
if (request !== null) {
next(request, response);
return true;
} else {
fail(response);
return false;
}
};
}
smash.registerRequestMiddleware(new lambdaProxyRequest());
module.exports = smash.getRequestMiddleware();
|
Fix indefinite loading state for fresh start without network | const {
ADD_ITEM,
REMOVE_ITEM,
OFFLINE_ITEMS_LOADED,
CONNECTION_CHECKING,
CONNECTION_CHECKED,
CONNECTION_ONLINE,
CONNECTION_OFFLINE
} = require('../actions/items')
const initialState = {
onlineList: [],
offlineList: [],
connectionChecked: false
}
module.exports = function items(state = initialState, action) {
let list
switch (action.type) {
case ADD_ITEM:
list = state.onlineList.concat([action.itemData]).sort((a, b) => b.time - a.time)
return {
...state,
onlineList: list,
offlineList: list
}
case REMOVE_ITEM:
list = state.onlineList.slice(0)
const index = list.map(i => i.id).indexOf(action.id)
list.splice(index, 1)
return {
...state,
onlineList: list,
offlineList: list
}
case OFFLINE_ITEMS_LOADED:
return {
...state,
offlineList: action.items,
offlineLoaded: true
}
case CONNECTION_CHECKING:
return {
...state,
connectionChecked: false
}
case CONNECTION_CHECKED:
return {
...state,
connectionChecked: true
}
case CONNECTION_ONLINE:
return {
...state,
connectionChecked: true,
connected: true
}
case CONNECTION_OFFLINE:
return {
...state,
connectionChecked: true,
connected: false
}
default:
return state
}
}
| const {
ADD_ITEM,
REMOVE_ITEM,
OFFLINE_ITEMS_LOADED,
CONNECTION_CHECKING,
CONNECTION_CHECKED,
CONNECTION_ONLINE,
CONNECTION_OFFLINE
} = require('../actions/items')
const initialState = {
onlineList: [],
offlineList: [],
connectionChecked: false
}
module.exports = function items(state = initialState, action) {
let list
switch (action.type) {
case ADD_ITEM:
list = state.onlineList.concat([action.itemData]).sort((a, b) => b.time - a.time)
return {
...state,
onlineList: list,
offlineList: list
}
case REMOVE_ITEM:
list = state.onlineList.slice(0)
const index = list.map(i => i.id).indexOf(action.id)
list.splice(index, 1)
return {
...state,
onlineList: list,
offlineList: list
}
case OFFLINE_ITEMS_LOADED:
return {
...state,
offlineList: action.items,
offlineLoaded: true
}
case CONNECTION_CHECKING:
return {
...state,
connectionChecked: false
}
case CONNECTION_CHECKED:
return {
...state,
connectionChecked: true
}
case CONNECTION_ONLINE:
return {
...state,
connectionChecked: true,
connected: true
}
case CONNECTION_OFFLINE:
return {
...state,
connected: false
}
default:
return state
}
}
|
Fix test involving Element object | from evelink import api
from evelink import constants
def parse_assets(api_result):
def handle_rowset(rowset, parent_location):
results = []
for row in rowset.findall('row'):
item = {'id': int(row.attrib['itemID']),
'item_type_id': int(row.attrib['typeID']),
'location_id': int(row.attrib.get('locationID', parent_location)),
'location_flag': int(row.attrib['flag']),
'quantity': int(row.attrib['quantity']),
'packaged': row.attrib['singleton'] == '0',
}
contents = row.find('rowset')
if contents is not None:
item['contents'] = handle_rowset(contents, item['location_id'])
results.append(item)
return results
result_list = handle_rowset(api_result.find('rowset'), None)
# For convenience, key the result by top-level location ID.
result_dict = {}
for item in result_list:
location = item['location_id']
result_dict.setdefault(location, {})
result_dict[location]['location_id'] = location
result_dict[location].setdefault('contents', [])
result_dict[location]['contents'].append(item)
return result_dict
| from evelink import api
from evelink import constants
def parse_assets(api_result):
def handle_rowset(rowset, parent_location):
results = []
for row in rowset.findall('row'):
item = {'id': int(row.attrib['itemID']),
'item_type_id': int(row.attrib['typeID']),
'location_id': int(row.attrib.get('locationID', parent_location)),
'location_flag': int(row.attrib['flag']),
'quantity': int(row.attrib['quantity']),
'packaged': row.attrib['singleton'] == '0',
}
contents = row.find('rowset')
if contents:
item['contents'] = handle_rowset(contents, item['location_id'])
results.append(item)
return results
result_list = handle_rowset(api_result.find('rowset'), None)
# For convenience, key the result by top-level location ID.
result_dict = {}
for item in result_list:
location = item['location_id']
result_dict.setdefault(location, {})
result_dict[location]['location_id'] = location
result_dict[location].setdefault('contents', [])
result_dict[location]['contents'].append(item)
return result_dict
|
Use live endpoint even on dev
It seems kind of okay | const ENDPOINT = "https://api.cojs.co/v0"
// const ENDPOINT = 'http://localhost:3000'
// Maybe "Connection" might be better
class Session {
constructor(id) {
// this.state = 'DISCONNECTED'
this.id = id
this.ready = Promise.resolve(id)
if(!id)
this.ready = this.create()
.then(({session, token}) => {
this.id = session
this.token = token
localStorage.setItem(`auth-${session}`, token)
return this.id
})
else {
this.token = localStorage.getItem(`auth-${id}`)
// todo - handle no token & check token
}
}
create() {
return fetch(`${ENDPOINT}/session`,
{ method: "POST" }
)
.then(res => res.json())
}
set(ref, code) {
return this.ready.then(() => fetch(`${ENDPOINT}/cells/${this.id}/${ref}`,
{
headers: {
'Authorization': `Bearer ${this.token}`
},
method: "POST",
body: code
})
)
.then(res => res.status == 200 ? res : res.json().then(Promise.reject.bind(Promise)))
.then(res => res.json())
}
fetch() {
return this.ready.then(() => fetch(`${ENDPOINT}/cells/${this.id}`,
{
method: "GET"
})
.then(res => res.json())
)
}
}
export default Session
| // const ENDPOINT = "https://api.cojs.co/v0"
const ENDPOINT = 'http://localhost:3000'
// Maybe "Connection" might be better
class Session {
constructor(id) {
// this.state = 'DISCONNECTED'
this.id = id
this.ready = Promise.resolve(id)
if(!id)
this.ready = this.create()
.then(({session, token}) => {
this.id = session
this.token = token
localStorage.setItem(`auth-${session}`, token)
return this.id
})
else {
this.token = localStorage.getItem(`auth-${id}`)
// todo - handle no token & check token
}
}
create() {
return fetch(`${ENDPOINT}/session`,
{ method: "POST" }
)
.then(res => res.json())
}
set(ref, code) {
return this.ready.then(() => fetch(`${ENDPOINT}/cells/${this.id}/${ref}`,
{
headers: {
'Authorization': `Bearer ${this.token}`
},
method: "POST",
body: code
})
)
.then(res => res.status == 200 ? res : res.json().then(Promise.reject.bind(Promise)))
.then(res => res.json())
}
fetch() {
return this.ready.then(() => fetch(`${ENDPOINT}/cells/${this.id}`,
{
method: "GET"
})
.then(res => res.json())
)
}
}
export default Session
|
Correct indentation et replace doublequote | var parse_insee = function(insee){
if ( insee.length !== 5 ) {
return null ;
}
//Cas spécial pour la Corse
if ( (insee.substr(0,2) == '2A') || (insee.substr(0,2) == '2B')) {
return {
code_dep: insee.substr(0,2),
code_com: insee.substr(2,3)
} ;
} else {
//Erreur si nous n'avons pas 5 chiffres
var regExpInsee = new RegExp('[0-9]{5}$');
if((regExpInsee.test(insee))) {
if ( insee.substr(0,2) == '97' ) {
return {
code_dep: insee.substr(0,3),
code_com: insee.substr(3,2)
} ;
} else {
return {
code_dep: insee.substr(0,2),
code_com: insee.substr(2,3)
};
}
} else {
return null;
}
}
};
module.exports = parse_insee;
| var parse_insee = function(insee){
if ( insee.length !== 5 ) {
return null ;
}
//Cas spécial pour la Corse
if ( (insee.substr(0,2) == '2A') || (insee.substr(0,2) == '2B')) {
return {
code_dep: insee.substr(0,2),
code_com: insee.substr(2,3)
} ;
} else {
//Erreur si nous n'avons pas 5 chiffres
var regExpInsee = new RegExp("[0-9]{5}$");
if((regExpInsee.test(insee))) {
if ( insee.substr(0,2) == '97' ) {
return {
code_dep: insee.substr(0,3),
code_com: insee.substr(3,2)
} ;
} else {
return {
code_dep: insee.substr(0,2),
code_com: insee.substr(2,3)
} ;
};
} else {
return null;
}
};
}
module.exports = parse_insee;
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.