text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Change 'Scatter Plot' to 'Scatterplot' | Settings = {
chart: {
padding: { right: 40, bottom: 80 },
margins: { top: 30, bottom: 0, right: 35 },
dots: {
size: 5,
color: '#378E00',
opacity: 0.7
}
},
defaultData: {
title: 'Scatter Plot',
x: {
indicator: 'ipr', // Percentage of individuals using the Internet
log: false,
jitter: 0.0
},
y: {
indicator: 'downloadkbps', // Average download speed (kbps)
log: false,
jitter: 0.0
}
}
};
IMonScatterWidget = function(doc) {
Widget.call(this, doc);
_.defaults(this.data, Settings.defaultData);
};
IMonScatterWidget.prototype = Object.create(Widget.prototype);
IMonScatterWidget.prototype.constructor = IMonScatterWidget;
IMonScatter = {
widget: {
name: 'Scatterplot',
description: 'Shows a scatterplot of two chosen metrics from the Internet Monitor dataset across all countries',
url: 'https://thenetmonitor.org/sources',
dimensions: { width: 3, height: 2 },
resize: { mode: 'cover' },
constructor: IMonScatterWidget,
typeIcon: 'line-chart'
},
org: {
name: 'Internet Monitor',
shortName: 'IM',
url: 'http://thenetmonitor.org'
}
};
| Settings = {
chart: {
padding: { right: 40, bottom: 80 },
margins: { top: 30, bottom: 0, right: 35 },
dots: {
size: 5,
color: '#378E00',
opacity: 0.7
}
},
defaultData: {
title: 'Scatter Plot',
x: {
indicator: 'ipr', // Percentage of individuals using the Internet
log: false,
jitter: 0.0
},
y: {
indicator: 'downloadkbps', // Average download speed (kbps)
log: false,
jitter: 0.0
}
}
};
IMonScatterWidget = function(doc) {
Widget.call(this, doc);
_.defaults(this.data, Settings.defaultData);
};
IMonScatterWidget.prototype = Object.create(Widget.prototype);
IMonScatterWidget.prototype.constructor = IMonScatterWidget;
IMonScatter = {
widget: {
name: 'Scatter Plot',
description: 'Shows a scatterplot of two chosen metrics from the Internet Monitor dataset across all countries',
url: 'https://thenetmonitor.org/sources',
dimensions: { width: 3, height: 2 },
resize: { mode: 'cover' },
constructor: IMonScatterWidget,
typeIcon: 'line-chart'
},
org: {
name: 'Internet Monitor',
shortName: 'IM',
url: 'http://thenetmonitor.org'
}
};
|
Fix wrong gulp task during watch | var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var stylus = require('gulp-stylus');
var rename = require('gulp-rename');
var mainStyl = './styl/main.styl';
gulp.task('build:dev', function() {
gulp.src(mainStyl)
.pipe(sourcemaps.init())
.pipe(stylus())
.pipe(sourcemaps.write())
.pipe(rename('baremetal.css'))
.pipe(gulp.dest('./build/development'));
});
gulp.task('build:prod', function() {
gulp.src(mainStyl)
.pipe(stylus({ compress: true }))
.pipe(rename('baremetal.min.css'))
.pipe(gulp.dest('./build/production'));
gulp.src(mainStyl)
.pipe(stylus())
.pipe(rename('baremetal.css'))
.pipe(gulp.dest('./build/production'));
});
gulp.task('stylus:watch', function() {
gulp.watch('./styl/**/*.styl', ['build:dev']);
});
gulp.task('watch', ['build:dev', 'stylus:watch']);
gulp.task('default', ['build:dev', 'build:prod']); | var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var stylus = require('gulp-stylus');
var rename = require('gulp-rename');
var mainStyl = './styl/main.styl';
gulp.task('build:dev', function() {
gulp.src(mainStyl)
.pipe(sourcemaps.init())
.pipe(stylus())
.pipe(sourcemaps.write())
.pipe(rename('baremetal.css'))
.pipe(gulp.dest('./build/development'));
});
gulp.task('build:prod', function() {
gulp.src(mainStyl)
.pipe(stylus({ compress: true }))
.pipe(rename('baremetal.min.css'))
.pipe(gulp.dest('./build/production'));
gulp.src(mainStyl)
.pipe(stylus())
.pipe(rename('baremetal.css'))
.pipe(gulp.dest('./build/production'));
});
gulp.task('stylus:watch', function() {
gulp.watch('./styl/**/*.styl', ['stylus:main']);
});
gulp.task('watch', ['build:dev', 'stylus:watch']);
gulp.task('default', ['build:dev', 'build:prod']); |
Use find_packages() to ensure the whole regparser gets installed | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages
setup(
name='regulations-parser',
url='https://github.com/cfpb/regulations-parser',
author='CFPB',
author_email='tech@cfpb.gov',
license='CC0',
version='0.1.0',
description='eCFR Parser for eRegulations',
long_description=open('README.md').read()
if os.path.exists('README.md') else '',
packages=find_packages(),
include_package_data=True,
install_requires=[
'lxml',
'pyparsing',
'inflection',
'requests',
'GitPython',
'python-constraint',
],
setup_requires=[
'nose>=1.0'
],
test_suite='xtdiff.tests',
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from distutils.core import setup
setup(
name='regulations-parser',
url='https://github.com/cfpb/regulations-parser',
author='CFPB',
author_email='tech@cfpb.gov',
license='CC0',
version='0.1.0',
description='eCFR Parser for eRegulations',
long_description=open('README.md').read()
if os.path.exists('README.md') else '',
packages=['regparser', ],
include_package_data=True,
install_requires=[
'lxml',
'pyparsing',
'inflection',
'requests',
'GitPython',
'python-constraint',
],
setup_requires=[
'nose>=1.0'
],
test_suite='xtdiff.tests',
)
|
Use flickr's full image for the thumbnail, if available
Flickr's thumbnails are just too small at 75x75. | package com.todoist.mediaparser.mediaparser;
import com.todoist.mediaparser.util.MediaType;
import java.util.regex.Pattern;
public class FlickrParser extends BaseOEmbedMediaParserWithContent {
private static Pattern sMatchingPattern;
FlickrParser(String url) {
super(url);
}
@Override
public MediaType getContentMediaType() {
return MediaType.OTHER;
}
@Override
protected Pattern getMatchingPattern() {
if(sMatchingPattern == null) {
sMatchingPattern = Pattern.compile(
"https?://(?:www\\.)?(?:flic\\.kr/p|flickr.com/photos)/\\w+/?",
Pattern.CASE_INSENSITIVE
);
}
return sMatchingPattern;
}
@Override
protected String createThumbnailUrl(int smallestSide) {
// Flickr thumbnails are tiny. If available, use content url.
String contentUrl = super.getContentUrl();
if(!mUrl.equals(contentUrl))
return contentUrl;
else
return super.createThumbnailUrl(smallestSide);
}
@Override
protected String getOEmbedUrlTemplate() {
return "http://www.flickr.com/services/oembed?url=%s&format=json";
}
@Override
protected String getOEmbedContentUrlName() {
return "url";
}
@Override
protected String getOEmbedThumbnailUrlName() {
return "thumbnail_url";
}
}
| package com.todoist.mediaparser.mediaparser;
import com.todoist.mediaparser.util.MediaType;
import java.util.regex.Pattern;
public class FlickrParser extends BaseOEmbedMediaParserWithContent {
private static Pattern sMatchingPattern;
FlickrParser(String url) {
super(url);
}
@Override
public MediaType getContentMediaType() {
return MediaType.OTHER;
}
@Override
protected Pattern getMatchingPattern() {
if(sMatchingPattern == null) {
sMatchingPattern = Pattern.compile(
"https?://(?:www\\.)?(?:flic\\.kr/p|flickr.com/photos)/\\w+/?",
Pattern.CASE_INSENSITIVE
);
}
return sMatchingPattern;
}
@Override
protected String getOEmbedUrlTemplate() {
return "http://www.flickr.com/services/oembed?url=%s&format=json";
}
@Override
protected String getOEmbedContentUrlName() {
return "url";
}
@Override
protected String getOEmbedThumbnailUrlName() {
return "thumbnail_url";
}
}
|
Make m2sh have the same version number as mongrel2. |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'author_email': 'zedshaw@zedshaw.com',
'version': '1.0beta5',
'scripts': ['bin/m2sh'],
'install_requires': ['nose', 'simplejson', 'pyrepl', 'storm'],
'packages': ['mongrel2', 'mongrel2.config'],
'package_data': {'mongrel2': ['sql/config.sql']},
'name': 'm2py'
}
setup(**config)
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'author_email': 'zedshaw@zedshaw.com',
'version': '0.2',
'scripts': ['bin/m2sh'],
'install_requires': ['nose', 'simplejson', 'pyrepl', 'storm'],
'packages': ['mongrel2', 'mongrel2.config'],
'package_data': {'mongrel2': ['sql/config.sql']},
'name': 'm2py'
}
setup(**config)
|
Add URLs to profile app. | from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
(r'^profile/', include('epiweb.apps.profile.urls')),
)
| from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
)
|
Revert "Specify specific version of feedparser"
This reverts commit e2a6bc54e404538f01a980f1573a507c224d1c31. | #!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name="ShowTransmission",
version="0.1",
packages=find_packages(),
author="Chris Scutcher",
author_email="chris.scutcher@ninebysix.co.uk",
description=("Script that monitors a ShowRSS feed and adds new torrents to transmission via "
"RPC interface"),
install_requires=['feedparser'],
entry_points = {
'console_scripts': [
'showtransmission = showtransmission.showtransmission:run_script',
],
'setuptools.installation': [
'eggsecutable = showtransmission.showtransmission:run_script',
]
}
)
| #!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name="ShowTransmission",
version="0.1",
packages=find_packages(),
author="Chris Scutcher",
author_email="chris.scutcher@ninebysix.co.uk",
description=("Script that monitors a ShowRSS feed and adds new torrents to transmission via "
"RPC interface"),
install_requires=['feedparser>=5.3.1'],
entry_points = {
'console_scripts': [
'showtransmission = showtransmission.showtransmission:run_script',
],
'setuptools.installation': [
'eggsecutable = showtransmission.showtransmission:run_script',
]
}
)
|
Boost priority of the indentation fixer
Many other fixers have the assumption that this has been ran, so it should run early | <?php
/*
* This file is part of the PHP CS utility.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Symfony\CS\Fixer;
use Symfony\CS\FixerInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class IndentationFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{
// [Structure] Indentation is done by steps of four spaces (tabs are never allowed)
return preg_replace_callback('/^([ \t]+)/m', function ($matches) use ($content) {
return str_replace("\t", ' ', $matches[0]);
}, $content);
}
public function getLevel()
{
// defined in PSR2 ¶2.4
return FixerInterface::PSR2_LEVEL;
}
public function getPriority()
{
return 50;
}
public function supports(\SplFileInfo $file)
{
return 'php' == $file->getExtension();
}
public function getName()
{
return 'indentation';
}
public function getDescription()
{
return 'Code must use 4 spaces for indenting, not tabs.';
}
}
| <?php
/*
* This file is part of the PHP CS utility.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Symfony\CS\Fixer;
use Symfony\CS\FixerInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class IndentationFixer implements FixerInterface
{
public function fix(\SplFileInfo $file, $content)
{
// [Structure] Indentation is done by steps of four spaces (tabs are never allowed)
return preg_replace_callback('/^([ \t]+)/m', function ($matches) use ($content) {
return str_replace("\t", ' ', $matches[0]);
}, $content);
}
public function getLevel()
{
// defined in PSR2 ¶2.4
return FixerInterface::PSR2_LEVEL;
}
public function getPriority()
{
return 0;
}
public function supports(\SplFileInfo $file)
{
return 'php' == $file->getExtension();
}
public function getName()
{
return 'indentation';
}
public function getDescription()
{
return 'Code must use 4 spaces for indenting, not tabs.';
}
}
|
Include pcbmode_config.json file in package | from setuptools import setup, find_packages
setup(
name = "pcbmode",
packages = find_packages(),
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires = ['lxml', 'pyparsing'],
package_data = {
'pcbmode': ['stackups/*.json',
'styles/*/*.json',
'fonts/*.svg',
'pcbmode_config.json'],
},
# metadata for upload to PyPI
author = "Saar Drimer",
author_email = "saardrimer@gmail.com",
description = "A printed circuit board design tool with a twist",
license = "MIT",
keywords = "pcb svg eda pcbmode",
url = "https://github.com/boldport/pcbmode",
entry_points={
'console_scripts': ['pcbmode = pcbmode.pcbmode:main']
},
zip_safe = True
)
| from setuptools import setup, find_packages
setup(
name = "pcbmode",
packages = find_packages(),
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires = ['lxml', 'pyparsing'],
package_data = {
'pcbmode': ['stackups/*.json',
'styles/*/*.json',
'fonts/*.svg'],
},
# metadata for upload to PyPI
author = "Saar Drimer",
author_email = "saardrimer@gmail.com",
description = "A printed circuit board design tool with a twist",
license = "MIT",
keywords = "pcb svg eda pcbmode",
url = "https://github.com/boldport/pcbmode",
entry_points={
'console_scripts': ['pcbmode = pcbmode.pcbmode:main']
},
zip_safe = True
)
|
Add argument pid at the command in rails suggestion
By default the rails stores the `pid` file of service within the `tmp` folder of the project, when working with multiple instances it creates conflict. | import { _ } from 'azk';
import { UIProxy } from 'azk/cli/ui';
import { example_system } from 'azk/generator/rules';
export class Suggestion extends UIProxy {
constructor(...args) {
super(...args);
// Readable name for this suggestion
this.name = 'rails';
// Which rules they suggestion is valid
this.ruleNamesList = ['rails41'];
// Initial Azkfile.js suggestion
this.suggestion = _.extend({}, example_system, {
__type : 'rails 4.1',
image : 'rails:4.1',
provision: [
'bundle install --path /azk/bundler',
'bundle exec rake db:create',
'bundle exec rake db:migrate',
],
http : true,
scalable: { default: 2 },
command : 'bundle exec rackup config.ru --pid /tmp/rails.pid --port $HTTP_PORT',
mounts : {
'/azk/#{manifest.dir}': {type: 'path', value: '.'},
'/azk/bundler' : {type: 'persistent', value: 'bundler'},
},
envs : {
RAILS_ENV : 'development',
BUNDLE_APP_CONFIG : '/azk/bundler',
}
});
}
suggest() {
return this.suggestion;
}
}
| import { _ } from 'azk';
import { UIProxy } from 'azk/cli/ui';
import { example_system } from 'azk/generator/rules';
export class Suggestion extends UIProxy {
constructor(...args) {
super(...args);
// Readable name for this suggestion
this.name = 'rails';
// Which rules they suggestion is valid
this.ruleNamesList = ['rails41'];
// Initial Azkfile.js suggestion
this.suggestion = _.extend({}, example_system, {
__type : 'rails 4.1',
image : 'rails:4.1',
provision: [
'bundle install --path /azk/bundler',
'bundle exec rake db:create',
'bundle exec rake db:migrate',
],
http : true,
scalable: { default: 2 },
command : 'bundle exec rackup config.ru --port $HTTP_PORT',
mounts : {
'/azk/#{manifest.dir}': {type: 'path', value: '.'},
'/azk/bundler' : {type: 'persistent', value: 'bundler'},
},
envs : {
RAILS_ENV : 'development',
BUNDLE_APP_CONFIG : '/azk/bundler',
}
});
}
suggest() {
return this.suggestion;
}
}
|
Add cart title class to cart item view. | module.exports = function(Backbone, _, SearchShop) {
return Backbone.View.extend({
tagName: 'div',
className: 'row',
template: '<div class="col-md-12 cart-title"><%= title %></div>',
events: {
'click .name' : 'remove'
},
initialize: function() {
this.render();
// If this models contents change, we re-render
this.model.on('change', function(){
this.render();
}, this);
},
render : function() {
// Render this view and return its context.
this.$el.html( _.template( this.template, this.model.toJSON() ));
return this;
},
remove: function() {
// Fade out item out from the shopping cart list
this.$el.fadeOut(500, function(){
// Remove it from the DOM on completetion
$(this).remove();
});
// Remove the model for this view from the Shopping Cart Items collection
SearchShop.cartItems.remove(this.model);
}
});
}
| module.exports = function(Backbone, _, SearchShop) {
return Backbone.View.extend({
tagName: 'div',
className: 'row',
template: '<div class="col-md-12"><%= title %></div>',
events: {
'click .name' : 'remove'
},
initialize: function() {
this.render();
// If this models contents change, we re-render
this.model.on('change', function(){
this.render();
}, this);
},
render : function() {
// Render this view and return its context.
this.$el.html( _.template( this.template, this.model.toJSON() ));
return this;
},
remove: function() {
// Fade out item out from the shopping cart list
this.$el.fadeOut(500, function(){
// Remove it from the DOM on completetion
$(this).remove();
});
// Remove the model for this view from the Shopping Cart Items collection
SearchShop.cartItems.remove(this.model);
}
});
}
|
[RM-14742] Set default init to systemd for (open)SUSE
(open)SUSE is now using systemd moving forward, this patch corrects behavior
on Tumbleweed and LEAP
openSUSE Tumbleweed distribution is a pure rolling release version of openSUSE
running the latest packages.
openSUSE LEAP is a rolling release version of openSUSE based on SUSE linux
Enterprise.
Signed-off-by: Owen Synge <ea78e0e20fce5319fd66b8fd4f543d9e30ef46a5@suse.com> | import mon # noqa
from install import install, mirror_install, repo_install # noqa
from uninstall import uninstall # noqa
import logging
from ceph_deploy.util import pkg_managers
# Allow to set some information about this distro
#
log = logging.getLogger(__name__)
distro = None
release = None
codename = None
def choose_init(module):
"""
Select a init system
Returns the name of a init system (upstart, sysvinit ...).
"""
init_mapping = { '11' : 'sysvinit', # SLE_11
'12' : 'systemd', # SLE_12
'13.1' : 'systemd', # openSUSE_13.1
}
return init_mapping.get(release, 'systemd')
def get_packager(module):
return pkg_managers.Zypper(module)
| import mon # noqa
from install import install, mirror_install, repo_install # noqa
from uninstall import uninstall # noqa
import logging
from ceph_deploy.util import pkg_managers
# Allow to set some information about this distro
#
log = logging.getLogger(__name__)
distro = None
release = None
codename = None
def choose_init(module):
"""
Select a init system
Returns the name of a init system (upstart, sysvinit ...).
"""
init_mapping = { '11' : 'sysvinit', # SLE_11
'12' : 'systemd', # SLE_12
'13.1' : 'systemd', # openSUSE_13.1
}
return init_mapping.get(release, 'sysvinit')
def get_packager(module):
return pkg_managers.Zypper(module)
|
[Content] Fireplace: Reduce fireplace runtime to 3 hours rather than 6 | var BurningFirePlace = Entity.extend({
HOURS_PER_LIGHTING: 3,
timeStarted: 0,
init: function () {
this._super();
this.width = 96;
this.height = 60;
this.causesCollision = false;
this.spriteHead = new Animation('fireplace_lit', this.width, this.height, 10, 3, true);
this.direction = Direction.UP;
this.timeStarted = Time.timer + (Time.day * Time.SECONDS_PER_DAY);
this.setCoord(10, 11);
this.posY -= 18;
},
update: function () {
this._super();
var curTime = Time.timer + (Time.day * Time.SECONDS_PER_DAY);
var timeSince = curTime - this.timeStarted;
var hoursSince = Math.floor(timeSince / Time.SECONDS_PER_HOUR);
if (hoursSince >= this.HOURS_PER_LIGHTING) {
this.map.remove(this);
this.map.fireplaceLit = false;
this.map = null;
}
}
}); | var BurningFirePlace = Entity.extend({
HOURS_PER_LIGHTING: 6,
timeStarted: 0,
init: function () {
this._super();
this.width = 96;
this.height = 60;
this.causesCollision = false;
this.spriteHead = new Animation('fireplace_lit', this.width, this.height, 10, 3, true);
this.direction = Direction.UP;
this.timeStarted = Time.timer + (Time.day * Time.SECONDS_PER_DAY);
this.setCoord(10, 11);
this.posY -= 18;
},
update: function () {
this._super();
var curTime = Time.timer + (Time.day * Time.SECONDS_PER_DAY);
var timeSince = curTime - this.timeStarted;
var hoursSince = Math.floor(timeSince / Time.SECONDS_PER_HOUR);
if (hoursSince >= this.HOURS_PER_LIGHTING) {
this.map.remove(this);
this.map.fireplaceLit = false;
this.map = null;
}
}
}); |
Set start time after socket client connect event fires | /**
* @module src/websocket-client
*/
'use strict'
const Base = require('./base')
const payload = 'a'.repeat(process.env.PB_PAYLOAD_BYTES) // ~1kb payload
var count = 0
const limit = 5000
var start
class WebsocketClient extends Base {
constructor () {
super()
this._initWebsocketClient()
this._ws.on('connect', () => {
start = new Date()
console.log('connect')
this._sendMessage()
})
}
_sendMessage () {
this._ws.emit('message', {
payload: payload
}, (responseData) => {
console.log('Response from server #', count)
count++
if (count < limit) {
this._sendMessage()
} else {
let totalTime = new Date() - start
console.log('total time', totalTime)
console.log('average RTT', totalTime / limit)
}
})
}
}
new WebsocketClient()
| /**
* @module src/websocket-client
*/
'use strict'
const Base = require('./base')
const payload = 'a'.repeat(process.env.PB_PAYLOAD_BYTES) // ~1kb payload
var count = 0
const limit = 5000
var start
class WebsocketClient extends Base {
constructor () {
super()
this._initWebsocketClient()
start = new Date()
this._sendMessage()
}
_sendMessage () {
this._ws.emit('message', {
payload: payload
}, (responseData) => {
console.log('Response from server #', count)
count++
if (count < limit) {
this._sendMessage()
} else {
let totalTime = new Date() - start
console.log('total time', totalTime)
console.log('average RTT', totalTime / limit)
}
})
}
}
new WebsocketClient()
|
Add support to react 15.4.0 | 'use strict';
exports.__esModule = true;
var _ReactUpdates = require('react-dom/lib/ReactUpdates');
var _ReactUpdates2 = _interopRequireDefault(_ReactUpdates);
var _createUncontrollable = require('./createUncontrollable');
var _createUncontrollable2 = _interopRequireDefault(_createUncontrollable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var mixin = {
componentWillReceiveProps: function componentWillReceiveProps() {
// if the update already happend then don't fire it twice
this._needsUpdate = false;
}
};
function set(component, propName, handler, value, args) {
component._needsUpdate = true;
component._values[propName] = value;
if (handler) handler.call.apply(handler, [component, value].concat(args));
_ReactUpdates2.default.batchedUpdates(function () {
_ReactUpdates2.default.asap(function () {
if (component.isMounted() && component._needsUpdate) {
component._needsUpdate = false;
if (component.isMounted()) component.forceUpdate();
}
});
});
}
exports.default = (0, _createUncontrollable2.default)([mixin], set);
module.exports = exports['default']; | 'use strict';
exports.__esModule = true;
var _ReactUpdates = require('react/lib/ReactUpdates');
var _ReactUpdates2 = _interopRequireDefault(_ReactUpdates);
var _createUncontrollable = require('./createUncontrollable');
var _createUncontrollable2 = _interopRequireDefault(_createUncontrollable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var mixin = {
componentWillReceiveProps: function componentWillReceiveProps() {
// if the update already happend then don't fire it twice
this._needsUpdate = false;
}
};
function set(component, propName, handler, value, args) {
component._needsUpdate = true;
component._values[propName] = value;
if (handler) handler.call.apply(handler, [component, value].concat(args));
_ReactUpdates2.default.batchedUpdates(function () {
_ReactUpdates2.default.asap(function () {
if (component.isMounted() && component._needsUpdate) {
component._needsUpdate = false;
if (component.isMounted()) component.forceUpdate();
}
});
});
}
exports.default = (0, _createUncontrollable2.default)([mixin], set);
module.exports = exports['default']; |
Use page-based pagination instead of cursor-based | <?php
namespace ZfrShopify\Iterator;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Resource\ResourceIterator;
/**
* @author Daniel Gimenes
*/
final class ShopifyResourceIterator extends ResourceIterator
{
/**
* @param CommandInterface $command
* @param array $data
*/
public function __construct(CommandInterface $command, array $data = [])
{
parent::__construct($command, $data);
$this->pageSize = 250; // This is the maximum allowed by Shopify
}
/**
* {@inheritDoc}
*/
protected function sendRequest()
{
$this->command['limit'] = $this->pageSize;
if ($this->nextToken) {
$this->command['page'] = $this->nextToken;
}
// Run request and "unwrap" the result
$result = $this->command->execute();
$rootKey = $this->command->getOperation()->getData('root_key');
$data = $result[$rootKey] ?? $result;
// Check if reached last page
if (count($data) === $this->pageSize) {
$this->nextToken = $this->nextToken ? $this->nextToken + 1 : 2;
} else {
$this->nextToken = false;
}
return $data;
}
}
| <?php
namespace ZfrShopify\Iterator;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Resource\ResourceIterator;
/**
* @author Daniel Gimenes
*/
final class ShopifyResourceIterator extends ResourceIterator
{
/**
* @param CommandInterface $command
* @param array $data
*/
public function __construct(CommandInterface $command, array $data = [])
{
parent::__construct($command, $data);
$this->pageSize = 250; // This is the maximum allowed by Shopify
}
/**
* {@inheritDoc}
*/
protected function sendRequest()
{
$this->command['limit'] = $this->pageSize;
if ($this->nextToken) {
$this->command['since_id'] = $this->nextToken;
}
// Run request and "unwrap" the result
$result = $this->command->execute();
$rootKey = $this->command->getOperation()->getData('root_key');
$data = $result[$rootKey] ?? $result;
// This avoid to do any additional request
$lastItem = end($data);
$this->nextToken = $lastItem['id'] ?? false;
return $data;
}
}
|
Add new subdomain to cert checker | 'use strict';
const tls = require('tls');
const Promise = require('bluebird');
const moment = require('moment');
const SITES = ['porybox.com', 'hq.porygon.co', 'modapps.porygon.co'];
module.exports = {
period: 60 * 60 * 24,
concurrent: true,
task () {
return Promise.reduce(SITES, (messages, host) => {
return getSecureSocket(host).then(socket => {
if (!socket.authorized) {
return messages.concat(`Warning: The site ${host} has an invalid SSL certificate. SSL error: ${socket.authorizationError}`);
}
const expirationTime = moment.utc(socket.getPeerCertificate().valid_to, 'MMM D HH:mm:ss YYYY');
if (expirationTime < moment().add({days: 14})) {
return messages.concat(`Warning: The SSL certificate for ${host} expires ${expirationTime.fromNow()}`);
}
return messages;
});
}, []);
}
};
function getSecureSocket(host) {
return new Promise(resolve => {
const socket = tls.connect({host, port: 443, rejectUnauthorized: false}, () => resolve(socket));
});
}
| 'use strict';
const tls = require('tls');
const Promise = require('bluebird');
const moment = require('moment');
const SITES = ['porybox.com', 'hq.porygon.co'];
module.exports = {
period: 60 * 60 * 24,
concurrent: true,
task () {
return Promise.reduce(SITES, (messages, host) => {
return getSecureSocket(host).then(socket => {
if (!socket.authorized) {
return messages.concat(`Warning: The site ${host} has an invalid SSL certificate. SSL error: ${socket.authorizationError}`);
}
const expirationTime = moment.utc(socket.getPeerCertificate().valid_to, 'MMM D HH:mm:ss YYYY');
if (expirationTime < moment().add({days: 14})) {
return messages.concat(`Warning: The SSL certificate for ${host} expires ${expirationTime.fromNow()}`);
}
return messages;
});
}, []);
}
};
function getSecureSocket(host) {
return new Promise(resolve => {
const socket = tls.connect({host, port: 443, rejectUnauthorized: false}, () => resolve(socket));
});
}
|
Make user field read-only in InstitutionSerializer | from rest_framework import serializers
from .models import Institution
class InstitutionSerializer(serializers.HyperlinkedModelSerializer):
on_site = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Institution
fields = ('on_site',
'url',
'name',
'slug',
'user',
'email',
'region',
'regon',
'krs',
'monitorings')
extra_kwargs = {
'region': {'view_name': 'jednostkaadministracyjna-detail'},
'user': {'read_only': True}
}
| from rest_framework import serializers
from .models import Institution
class InstitutionSerializer(serializers.HyperlinkedModelSerializer):
on_site = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Institution
fields = ('on_site',
'url',
'name',
'slug',
'user',
'email',
'region',
'regon',
'krs',
'monitorings')
extra_kwargs = {
'region': {'view_name': 'jednostkaadministracyjna-detail'}
}
|
Send error in callback, too. | var ds_model = require('./datasource/model');
function resolve (name, callback) {
// TODO check name to be valid (and avoid SQL injection)
if (!name) {
return callback(M.error(M.error.API_DS_INVALID_NAME, name));
}
var appId = M.config.app.id;
ds_model.get(appId, name, function(err, ds) {
if (err) { return callback(err); }
// TODO improve this:
// move db to data
var datasource = {
type: ds.type,
db: ds.db
};
for (var i in ds.data) {
datasource[i] = ds.data[i];
}
callback(null, datasource);
});
}
exports.resolve = resolve;
| var ds_model = require('./datasource/model');
function resolve (name, callback) {
// TODO check name to be valid (and avoid SQL injection)
if (!name) {
return callback(M.error(M.error.API_DS_INVALID_NAME, name));
}
var appId = M.config.app.id;
ds_model.get(appId, name, function(err, ds) {
if (err) { return callback(); }
// TODO improve this:
// move db to data
var datasource = {
type: ds.type,
db: ds.db
};
for (var i in ds.data) {
datasource[i] = ds.data[i];
}
callback(null, datasource);
});
}
exports.resolve = resolve;
|
Add sql stm for selecting trait_entry_ids to a list of organism_ids | <?php
namespace fennecweb\ajax\details;
use \PDO as PDO;
/**
* Web Service.
* Returns trait information to a list of organism ids
*/
class TraitsOfOrganisms extends \fennecweb\WebService
{
private $db;
/**
* @param $querydata['organism_ids' => [13,7,12,5]]
* @returns Array $result
* <code>
* array(trait_entry_id => cvterm);
* </code>
*/
public function execute($querydata)
{
$this->db = $this->openDbConnection($querydata);
$organism_ids = $querydata['organism_ids'];
$placeholders = implode(',', array_fill(0, count($organism_ids), '?'));
var_dump($placeholders);
$query_get_traits_to_organisms = <<<EOF
SELECT *
FROM trait_entry WHERE organism_id IN ($placeholders)
EOF;
$stm_get_traits_to_organisms = $this->db->prepare($query_get_traits_to_organisms);
$stm_get_traits_to_organisms->execute($organism_ids);
$result = array();
return $result;
}
}
| <?php
namespace fennecweb\ajax\details;
use \PDO as PDO;
/**
* Web Service.
* Returns trait information to a list of organism ids
*/
class TraitsOfOrganisms extends \fennecweb\WebService
{
private $db;
/**
* @param $querydata['organism_ids' => [13,7,12,5]]
* @returns Array $result
* <code>
* array(trait_entry_id => cvterm);
* </code>
*/
public function execute($querydata)
{
$this->db = $this->openDbConnection($querydata);
$organism_ids = $querydata['organism_ids'];
var_dump($organism_ids);
$result = array();
return $result;
}
}
|
Use '_' instead of ':' in synthetic delegate task name | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.composite.internal;
import org.gradle.api.tasks.TaskReference;
public class IncludedBuildTaskReference implements TaskReference {
private final String buildName;
private final String taskPath;
public IncludedBuildTaskReference(String buildName, String taskPath) {
this.buildName = buildName;
this.taskPath = taskPath;
}
@Override
public String getName() {
return "_" + buildName + taskPath.replace(':', '_');
}
public String getBuildName() {
return buildName;
}
public String getTaskPath() {
return taskPath;
}
}
| /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.composite.internal;
import org.gradle.api.tasks.TaskReference;
public class IncludedBuildTaskReference implements TaskReference {
private final String buildName;
private final String taskPath;
public IncludedBuildTaskReference(String buildName, String taskPath) {
this.buildName = buildName;
this.taskPath = taskPath;
}
@Override
public String getName() {
return buildName + ":" + taskPath;
}
public String getBuildName() {
return buildName;
}
public String getTaskPath() {
return taskPath;
}
}
|
Remove unintended import of Guava classes | /**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micrometer.core.instrument.simple;
import io.micrometer.core.instrument.AbstractMeter;
import io.micrometer.core.instrument.Counter;
import java.util.concurrent.atomic.DoubleAdder;
public class CumulativeCounter extends AbstractMeter implements Counter {
private final DoubleAdder value;
/** Create a new instance. */
public CumulativeCounter(Id id) {
super(id);
this.value = new DoubleAdder();
}
@Override
public void increment(double amount) {
value.add(amount);
}
@Override
public double count() {
return value.sum();
}
}
| /**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micrometer.core.instrument.simple;
import com.google.common.util.concurrent.AtomicDouble;
import io.micrometer.core.instrument.AbstractMeter;
import io.micrometer.core.instrument.Counter;
public class CumulativeCounter extends AbstractMeter implements Counter {
private final AtomicDouble value;
/** Create a new instance. */
public CumulativeCounter(Id id) {
super(id);
this.value = new AtomicDouble();
}
@Override
public void increment(double amount) {
value.getAndAdd(amount);
}
@Override
public double count() {
return value.get();
}
}
|
Test against old, but not quite too old folks too. | <?php
use Carbon\Carbon;
use Northstar\Models\User;
class RemoveOldBirthdatesTest extends TestCase
{
/** @test */
public function it_should_fix_birthdates()
{
// Create some normal and *really* old users:
$normalUsers = factory(User::class, 5)->create(['birthdate' => $this->faker->dateTimeBetween('1/1/1901', 'now')]);
$ancientOnes = factory(User::class, 3)->create(['birthdate' => new Carbon('0001-01-01 00:00:00')]);
// Run the script!
$this->artisan('northstar:olds');
// Make sure we have 0 borked users
foreach ($normalUsers as $user) {
$attributes = $user->fresh()->getAttributes();
$this->assertArrayHasKey('birthdate', $user->fresh()->getAttributes(), 'Valid birthdates should not be removed.');
}
foreach ($ancientOnes as $user) {
$attributes = $user->fresh()->getAttributes();
$this->assertArrayNotHasKey('birthdate', $attributes, 'Invalid birthdates should be removed.');
}
}
}
| <?php
use Carbon\Carbon;
use Northstar\Models\User;
class RemoveOldBirthdatesTest extends TestCase
{
/** @test */
public function it_should_fix_birthdates()
{
// Create some normal and *really* old users:
$normalUsers = factory(User::class, 5)->create();
$ancientOnes = factory(User::class, 3)->create(['birthdate' => new Carbon('0001-01-01 00:00:00')]);
// Run the script!
$this->artisan('northstar:olds');
// Make sure we have 0 borked users
foreach ($normalUsers as $user) {
$attributes = $user->fresh()->getAttributes();
$this->assertArrayHasKey('birthdate', $user->fresh()->getAttributes(), 'Valid birthdates should not be removed.');
}
foreach ($ancientOnes as $user) {
$attributes = $user->fresh()->getAttributes();
$this->assertArrayNotHasKey('birthdate', $attributes, 'Invalid birthdates should be removed.');
}
}
}
|
Exclude node_modules/react-devtools/node_modules for webpack build | import { join } from 'path';
export default {
output: {
path: join(__dirname, '../dist/js'),
filename: 'bundle.js',
libraryTarget: 'commonjs2',
},
plugins: [
],
resolve: {
extensions: ['', '.js'],
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
include: [
join(__dirname, '../app'),
join(__dirname, '../electron'),
join(__dirname, '../node_modules/react-devtools'),
],
exclude: [
join(__dirname, '../node_modules/react-devtools/node_modules'),
],
}],
},
externals: [
// just avoid warning.
// this is not really used from ws. (it used fallback)
'bufferutil', 'utf-8-validate',
],
};
| import { join } from 'path';
export default {
output: {
path: join(__dirname, '../dist/js'),
filename: 'bundle.js',
libraryTarget: 'commonjs2',
},
plugins: [
],
resolve: {
extensions: ['', '.js'],
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
include: [
join(__dirname, '../app'),
join(__dirname, '../electron'),
join(__dirname, '../node_modules/react-devtools'),
],
}],
},
externals: [
// just avoid warning.
// this is not really used from ws. (it used fallback)
'bufferutil', 'utf-8-validate',
],
};
|
Update tests to be ff compliant. | /**
* Client tests
*/
import React from "react/addons";
import Component from "src/components/boilerplate-component";
// Use `TestUtils` to inject into DOM, simulate events, etc.
// See: https://facebook.github.io/react/docs/test-utils.html
const TestUtils = React.addons.TestUtils;
describe("components/boilerplate-component", function () {
it("has expected content with deep render", function () {
// This is a "deep" render that renders children + all into an actual
// browser DOM node.
//
// https://facebook.github.io/react/docs/test-utils.html#renderintodocument
const rendered = TestUtils.renderIntoDocument(<Component />);
// This is a real DOM node to assert on.
const divNode = TestUtils
.findRenderedDOMComponentWithTag(rendered, "div")
.getDOMNode();
expect(divNode).to.have.property("innerHTML", "Edit me!");
});
it("has expected content with shallow render", function () {
// This is a "shallow" render that renders only the current component
// without using the actual DOM.
//
// https://facebook.github.io/react/docs/test-utils.html#shallow-rendering
const renderer = TestUtils.createRenderer();
renderer.render(<Component />);
const output = renderer.getRenderOutput();
expect(output.type).to.equal("div");
expect(output.props.children).to.contain("Edit me");
});
});
| /**
* Client tests
*/
import React from "react/addons";
import Component from "src/components/boilerplate-component";
// Use `TestUtils` to inject into DOM, simulate events, etc.
// See: https://facebook.github.io/react/docs/test-utils.html
const TestUtils = React.addons.TestUtils;
describe("components/boilerplate-component", function () {
it("has expected content with deep render", function () {
// This is a "deep" render that renders children + all into an actual
// browser DOM node.
//
// https://facebook.github.io/react/docs/test-utils.html#renderintodocument
const rendered = TestUtils.renderIntoDocument(<Component />);
// This is a real DOM node to assert on.
const divNode = TestUtils
.findRenderedDOMComponentWithTag(rendered, "div")
.getDOMNode();
expect(divNode).to.have.property("innerText", "Edit me!");
});
it("has expected content with shallow render", function () {
// This is a "shallow" render that renders only the current component
// without using the actual DOM.
//
// https://facebook.github.io/react/docs/test-utils.html#shallow-rendering
const renderer = TestUtils.createRenderer();
renderer.render(<Component />);
const output = renderer.getRenderOutput();
expect(output.type).to.equal("div");
expect(output.props.children).to.contain("Edit me");
});
});
|
Add test for extend method. | from twisted.trial.unittest import TestCase
import vumi.blinkenlights.message20110818 as message
import time
class TestMessage(TestCase):
def test_to_dict(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msg = message.MetricMessage()
msg.append(datapoint)
self.assertEqual(msg.to_dict(), {
'datapoints': [datapoint],
})
def test_from_dict(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msgdict = {"datapoints": [datapoint]}
msg = message.MetricMessage.from_dict(msgdict)
self.assertEqual(msg._datapoints, [datapoint])
def test_extend(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msg = message.MetricMessage()
msg.extend([datapoint, datapoint, datapoint])
self.assertEqual(msg._datapoints, [
datapoint, datapoint, datapoint])
| from twisted.trial.unittest import TestCase
import vumi.blinkenlights.message20110818 as message
import time
class TestMessage(TestCase):
def test_to_dict(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msg = message.MetricMessage()
msg.append(datapoint)
self.assertEqual(msg.to_dict(), {
'datapoints': [datapoint],
})
def test_from_dict(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5)
msgdict = {"datapoints": [datapoint]}
msg = message.MetricMessage.from_dict(msgdict)
self.assertEqual(msg._datapoints, [datapoint])
|
Add error just to test | 'use strict';
const expect = require('chai').expect;
const Loader = require('../modules/loader');
const config = require('../config');
const image = 'https://www.google.es/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
const noImage = 'https://www.google.es/nope.png';
const loader = new Loader(config.download);
describe('Image Loader', () => {
describe('Download images', () => {
it('Should download an image', () => {
return loader.load(image).then((file) => {
expect(file).to.be.a('string');
});
});
it('Should throw an error trying to download a non existant image', () => {
return loader.load(noImage).catch((error) => {
expect(error).to.be.an.instanceof(Erro);
});
});
});
}); | 'use strict';
const expect = require('chai').expect;
const Loader = require('../modules/loader');
const config = require('../config');
const image = 'https://www.google.es/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
const noImage = 'https://www.google.es/nope.png';
const loader = new Loader(config.download);
describe('Image Loader', () => {
describe('Download images', () => {
it('Should download an image', () => {
return loader.load(image).then((file) => {
expect(file).to.be.a('string');
});
});
it('Should throw an error trying to download a non existant image', () => {
return loader.load(noImage).catch((error) => {
expect(error).to.be.an.instanceof(Error);
});
});
});
}); |
Fix issue with multiple lines | # -*- coding: utf-8 -*-
# © 2004-2009 Tiny SPRL (<http://tiny.be>).
# © 2015 Pedro M. Baeza
# © 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import api, fields, models
import openerp.addons.decimal_precision as dp
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
@api.depends('discount')
def _compute_amount(self):
prices = {}
for line in self:
if line.discount:
prices[line.id] = line.price_unit
line.price_unit *= (1 - line.discount / 100.0)
super(PurchaseOrderLine, self)._compute_amount()
# restore prices
for line in self:
if line.discount:
line.price_unit = prices[line.id]
discount = fields.Float(
string='Discount (%)', digits_compute=dp.get_precision('Discount'))
_sql_constraints = [
('discount_limit', 'CHECK (discount <= 100.0)',
'Discount must be lower than 100%.'),
]
| # -*- coding: utf-8 -*-
# © 2004-2009 Tiny SPRL (<http://tiny.be>).
# © 2015 Pedro M. Baeza
# © 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import api, fields, models
import openerp.addons.decimal_precision as dp
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
@api.depends('discount')
def _compute_amount(self):
prices = {}
for line in self:
if line.discount:
prices[line.id] = line.price_unit
line.price_unit *= (1 - line.discount / 100.0)
super(PurchaseOrderLine, self)._compute_amount()
# restore prices
for line in self:
if self.discount:
line.price_unit = prices[line.id]
discount = fields.Float(
string='Discount (%)', digits_compute=dp.get_precision('Discount'))
_sql_constraints = [
('discount_limit', 'CHECK (discount <= 100.0)',
'Discount must be lower than 100%.'),
]
|
Use resource uri instead so rule will also work in subfolder installations | <?php
/*
* This file is part of Slim JSON Web Token Authentication middleware
*
* Copyright (c) 2015 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-jwt-auth
*
*/
namespace Slim\Middleware\JwtAuthentication;
class RequestPathRule implements RuleInterface
{
protected $options = array(
"path" => "/",
"passthrough" => array()
);
public function __construct($options = array())
{
$this->options = array_merge($this->options, $options);
}
public function __invoke(\Slim\Slim $app)
{
/* If request path is matches passthrough should not authenticate. */
foreach ($this->options["passthrough"] as $passthrough) {
$passthrough = rtrim($passthrough, "/");
if (!!preg_match("@{$passthrough}(/.*)?$@", $app->request->getResourceUri())) {
return false;
}
}
/* Otherwise check if path matches and we should authenticate. */
$path = rtrim($this->options["path"], "/");
return !!preg_match("@{$path}(/.*)?$@", $app->request->getPath());
}
}
| <?php
/*
* This file is part of Slim JSON Web Token Authentication middleware
*
* Copyright (c) 2015 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-jwt-auth
*
*/
namespace Slim\Middleware\JwtAuthentication;
class RequestPathRule implements RuleInterface
{
protected $options = array(
"path" => "/",
"passthrough" => array()
);
public function __construct($options = array())
{
$this->options = array_merge($this->options, $options);
}
public function __invoke(\Slim\Slim $app)
{
/* If request path is matches passthrough should not authenticate. */
foreach ($this->options["passthrough"] as $passthrough) {
$passthrough = rtrim($passthrough, "/");
if (!!preg_match("@{$passthrough}(/.*)?$@", $app->request->getPath())) {
return false;
}
}
/* Otherwise check if path matches and we should authenticate. */
$path = rtrim($this->options["path"], "/");
return !!preg_match("@{$path}(/.*)?$@", $app->request->getPath());
}
}
|
Fix performance.now not being available in node environment | var timerStart = new Date().getTime();
try {
var settings = require('_settings');
var controller = require('stage_controller');
var creeps = require('stage_creeps');
var spawners = require('stage_spawners');
controller.pre();
creeps();
spawners();
controller.post();
} catch (e) {
console.log('Caught exception:');
if (typeof e === "object") {
if (e.stack) {
if (e.name && e.message) {
console.log(e.name + ': ' + e.message);
}
console.log(e.stack);
} else {
console.log(e, JSON.stringify(e));
}
} else {
console.log(e);
}
}
var timerEnd = new Date().getTime();
var timerDiff = Math.round(timerEnd - timerStart);
if (timerDiff > settings.roundTimeLimit) {
console.log('Warning: Round ' + Game.time + ' took ' + timerDiff + ' ms to complete');
}
| var timerStart = performance.now();
try {
var settings = require('_settings');
var controller = require('stage_controller');
var creeps = require('stage_creeps');
var spawners = require('stage_spawners');
controller.pre();
creeps();
spawners();
controller.post();
} catch (e) {
console.log('Caught exception:');
if (typeof e === "object") {
if (e.stack) {
if (e.name && e.message) {
console.log(e.name + ': ' + e.message);
}
console.log(e.stack);
} else {
console.log(e, JSON.stringify(e));
}
} else {
console.log(e);
}
}
var timerEnd = performance.now();
var timerDiff = timerEnd - timerStart;
if (timerDiff > settings.roundTimeLimit) {
console.log('Warning: Round ' + Game.time + ' took ' + timerDiff + ' ms to complete');
}
|
Remove error handler here as well | <?php
/*
* This is just a dummy page pretending to log a user in.
* The idea is to test sessions on the server
*/
require(__DIR__ . '/../vendor/autoload.php');
use \Symfony\Component\HttpFoundation\Session\Session;
use \Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler;
use \Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
try{
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
$handler = new MemcachedSessionHandler($memcached);
$storage = new NativeSessionStorage(array(), $handler);
$session = new Session($storage);
$session->setName('CUSTOM_NAME');
$session->start();
if($session->has('username')){
echo "Already logged in";
}else{
$session->set('username', 'Mister hoba loba loba');
echo "Logged in!";
}
}catch(Exception $e){
echo $e->getMessage();
} | <?php
/*
* This is just a dummy page pretending to log a user in.
* The idea is to test sessions on the server
*/
require(__DIR__ . '/../vendor/autoload.php');
use \Socketty\ErrorHandler;
use \Symfony\Component\HttpFoundation\Session\Session;
use \Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler;
use \Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
ErrorHandler::setErrorHandler();
try{
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
$handler = new MemcachedSessionHandler($memcached);
$storage = new NativeSessionStorage(array(), $handler);
$session = new Session($storage);
$session->setName('CUSTOM_NAME');
$session->start();
if($session->has('username')){
echo "Already logged in";
}else{
$session->set('username', 'Mister hoba loba loba');
echo "Logged in!";
}
}catch(Exception $e){
echo $e->getMessage();
} |
Update to the new uuid project home.
Change-Id: I341722687895f9ab83f41269045d0d52f032b0f9 | package main
import (
"fmt"
"io/ioutil"
"os"
"github.com/jsgoecke/nest"
"github.com/pborman/uuid"
"gopkg.in/yaml.v2"
)
var thermostat *nest.Thermostat
type NestConf struct {
Productid string
Productsecret string
Authorization string
Token string
}
func init() {
f, err := ioutil.ReadFile("./nest.yml")
if err != nil {
panic(err)
}
var c NestConf
err = yaml.Unmarshal(f, &c)
if err != nil {
panic(err)
}
client := nest.New(c.Productid, uuid.NewUUID().String(), c.Productsecret, c.Authorization)
client.Token = c.Token
devices, apierr := client.Devices()
if apierr != nil {
panic(apierr)
}
// FIXME: If there's more than one thermostat to work with this is going to be frustrating.
for _, thermostat = range devices.Thermostats {
}
fmt.Fprintln(os.Stderr, thermostat)
}
| package main
import (
"fmt"
"io/ioutil"
"os"
"code.google.com/p/go-uuid/uuid"
"github.com/jsgoecke/nest"
"gopkg.in/yaml.v2"
)
var thermostat *nest.Thermostat
type NestConf struct {
Productid string
Productsecret string
Authorization string
Token string
}
func init() {
f, err := ioutil.ReadFile("./nest.yml")
if err != nil {
panic(err)
}
var c NestConf
err = yaml.Unmarshal(f, &c)
if err != nil {
panic(err)
}
client := nest.New(c.Productid, uuid.NewUUID().String(), c.Productsecret, c.Authorization)
client.Token = c.Token
devices, apierr := client.Devices()
if apierr != nil {
panic(apierr)
}
// FIXME: If there's more than one thermostat to work with this is going to be frustrating.
for _, thermostat = range devices.Thermostats {
}
fmt.Fprintln(os.Stderr, thermostat)
}
|
Fix missing module on __version__
(develop) | # -*- coding: utf-8 -*-
"""entry point for zazu"""
__author__ = "Nicholas Wiles"
__copyright__ = "Copyright 2016, Lily Robotics"
import click
import git_helper
import subprocess
import zazu.build
import zazu.config
import zazu.dev.commands
import zazu.repo.commands
import zazu.style
import zazu.upgrade
@click.group()
@click.version_option(version=zazu.__version__)
@click.pass_context
def cli(ctx):
try:
ctx.obj = zazu.config.Config(git_helper.get_root_path())
required_zazu_version = ctx.obj.zazu_version_required()
if required_zazu_version and required_zazu_version != zazu.__version__:
click.echo('Warning: this repo has requested zazu {}, which doesn\'t match the installed version ({}). \
Use "zazu upgrade" to fix this'.format(ctx.obj.zazu_version_required(), zazu.__version__))
except subprocess.CalledProcessError:
pass
cli.add_command(zazu.upgrade.upgrade)
cli.add_command(zazu.style.style)
cli.add_command(zazu.build.build)
cli.add_command(zazu.dev.commands.dev)
cli.add_command(zazu.repo.commands.repo)
| # -*- coding: utf-8 -*-
"""entry point for zazu"""
__author__ = "Nicholas Wiles"
__copyright__ = "Copyright 2016, Lily Robotics"
import click
import git_helper
import subprocess
import zazu.build
import zazu.config
import zazu.dev.commands
import zazu.repo.commands
import zazu.style
import zazu.upgrade
@click.group()
@click.version_option(version=zazu.__version__)
@click.pass_context
def cli(ctx):
try:
ctx.obj = zazu.config.Config(git_helper.get_root_path())
required_zazu_version = ctx.obj.zazu_version_required()
if required_zazu_version and required_zazu_version != zazu.__version__:
click.echo('Warning: this repo has requested zazu {}, which doesn\'t match the installed version ({}). \
Use "zazu upgrade" to fix this'.format(ctx.obj.zazu_version_required(), __version__))
except subprocess.CalledProcessError:
pass
cli.add_command(zazu.upgrade.upgrade)
cli.add_command(zazu.style.style)
cli.add_command(zazu.build.build)
cli.add_command(zazu.dev.commands.dev)
cli.add_command(zazu.repo.commands.repo)
|
Rename helper methods for clarity | function filter(arr) {
var filteredArray = [], prev;
arr.sort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== prev) {
filteredArray.push(arr[i]);
}
prev = arr[i];
}
return filteredArray
}
function rarefyXMLTextContent(pattern) {
arr = [];
matches = [];
merged = [];
str = text.doc;
elements = xml.doc.querySelectorAll("[category=" + pattern + "]")
for (var i = 0; i < elements.length; i++) {
arr.push(elements[i].textContent.replace(/(\r\n|\n|\r)/gm,"").trim());
}
filteredArray = filter(arr);
return filteredArray
}
function countMatches(pattern) {
filteredArray = rarefyXMLTextContent(pattern);
for (var i = 0; i < filteredArray.length; i++) {
pattern = filteredArray[i];
regex = new RegExp(pattern, 'gi');
if (str.match(regex)) {
matches.push(str.match(regex));
}
}
merged = merged.concat.apply(merged, matches); // For unnesting nested arrays
return merged.length;
}
| function filter(arr) {
var filteredArray = [], prev;
arr.sort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== prev) {
filteredArray.push(arr[i]);
}
prev = arr[i];
}
return filteredArray
}
function rarefy(pattern) {
arr = [];
matches = [];
merged = [];
str = text.doc;
elements = xml.doc.querySelectorAll("[category=" + pattern + "]")
for (var i = 0; i < elements.length; i++) {
arr.push(elements[i].textContent.replace(/(\r\n|\n|\r)/gm,"").trim());
}
filteredArray = filter(arr);
return filteredArray
}
function countMatches(pattern) {
filteredArray = rarefy(pattern);
for (var i = 0; i < filteredArray.length; i++) {
pattern = filteredArray[i];
regex = new RegExp(pattern, 'gi');
if (str.match(regex)) {
matches.push(str.match(regex));
}
}
merged = merged.concat.apply(merged, matches); // For unnesting nested arrays
return merged.length;
}
|
Add bottle as a requirement for this package. | import os
from setuptools import setup
def long_description():
os.system('pandoc --from=markdown --to=rst --output=README.rst README.md')
readme_fn = os.path.join(os.path.dirname(__file__), 'README.rst')
if os.path.exists(readme_fn):
with open(readme_fn) as f:
return f.read()
else:
return 'not available'
setup(
name='boddle',
version=__import__('boddle').__version__,
description="A unit testing tool for Python's bottle library.",
long_description=long_description(),
author='Derek Anderson',
author_email='public@kered.org',
url='https://github.com/keredson/boddle',
packages=[],
py_modules=['boddle'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
install_requires=['bottle'],
)
| import os
from setuptools import setup
def long_description():
os.system('pandoc --from=markdown --to=rst --output=README.rst README.md')
readme_fn = os.path.join(os.path.dirname(__file__), 'README.rst')
if os.path.exists(readme_fn):
with open(readme_fn) as f:
return f.read()
else:
return 'not available'
setup(
name='boddle',
version=__import__('boddle').__version__,
description="A unit testing tool for Python's bottle library.",
long_description=long_description(),
author='Derek Anderson',
author_email='public@kered.org',
url='https://github.com/keredson/boddle',
packages=[],
py_modules=['boddle'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
install_requires=[],
)
|
Disable for Windows as it doesn't work now. | package org.jetbrains.plugins.terminal;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import icons.TerminalIcons;
import java.nio.charset.Charset;
/**
* @author traff
*/
public class OpenLocalTerminalAction extends AnAction implements DumbAware {
public OpenLocalTerminalAction() {
super("Open Terminal...", null, TerminalIcons.OpenTerminal);
}
@Override
public void update(final AnActionEvent e) {
boolean enabled = SystemInfo.isUnix;
e.getPresentation().setVisible(enabled);
e.getPresentation().setEnabled(enabled);
}
public void actionPerformed(final AnActionEvent e) {
runLocalTerminal(e);
}
public void runLocalTerminal(AnActionEvent event) {
final Project project = event.getData(PlatformDataKeys.PROJECT);
setupRemoteCredentialsAndRunTerminal(project);
}
public static void setupRemoteCredentialsAndRunTerminal(final Project project) {
String terminalCommand = SystemInfo.isMac ? "/bin/tcsh" : "/bin/bash";
new LocalTerminalDirectRunner(project, Charset.defaultCharset(), terminalCommand).run();
}
}
| package org.jetbrains.plugins.terminal;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import icons.TerminalIcons;
import java.nio.charset.Charset;
/**
* @author traff
*/
public class OpenLocalTerminalAction extends AnAction implements DumbAware {
public OpenLocalTerminalAction() {
super("Open Terminal...", null, TerminalIcons.OpenTerminal);
}
@Override
public void update(final AnActionEvent e) {
e.getPresentation().setVisible(true);
e.getPresentation().setEnabled(true);
}
public void actionPerformed(final AnActionEvent e) {
runLocalTerminal(e);
}
public void runLocalTerminal(AnActionEvent event) {
final Project project = event.getData(PlatformDataKeys.PROJECT);
setupRemoteCredentialsAndRunTerminal(project);
}
public static void setupRemoteCredentialsAndRunTerminal(final Project project) {
String terminalCommand = SystemInfo.isMac ? "/bin/tcsh" : "/bin/bash";
new LocalTerminalDirectRunner(project, Charset.defaultCharset(), terminalCommand).run();
}
}
|
Fix split/join and move functions so they can refer to recipient var. | var l10n_file = __dirname + '/../l10n/commands/tell.yml';
var l10n = require('../src/l10n')(l10n_file);
var CommandUtil = require('../src/command_util').CommandUtil;
exports.command = function(rooms, items, players, npcs, Commands) {
return function(args, player) {
var message = args.split(' ');
var recipient = message.shift();
message = message.join(' ');
if (recipient) {
player.sayL10n(l10n, 'YOU_TELL', recipient, message);
players.eachIf(
playerIsOnline,
tellPlayer
);
return;
}
player.sayL10n(l10n, 'NOTHING_TOLD');
return;
function tellPlayer(p) {
if (recipient.getName() !== player.getName())
p.sayL10n(l10n, 'THEY_TELL', player.getName(), message);
}
function playerIsOnline(p) {
if (p)
return (recipient.getName() === p.getName());
};
}
}; | var l10n_file = __dirname + '/../l10n/commands/tell.yml';
var l10n = require('../src/l10n')(l10n_file);
var CommandUtil = require('../src/command_util').CommandUtil;
exports.command = function(rooms, items, players, npcs, Commands) {
return function(args, player) {
var message = args.split('');
var recipient = message.shift();
if (recipient) {
player.sayL10n(l10n, 'YOU_TELL', recipient, message);
players.eachIf(
playerIsOnline,
tellPlayer
);
return;
}
player.sayL10n(l10n, 'NOTHING_TOLD');
return;
}
function tellPlayer (p){
if (recipient.getName() !== player.getName())
p.sayL10n(l10n, 'THEY_TELL', player.getName(), message);
}
function playerIsOnline(p) {
if (p)
return (recipient.getName() === p.getName());
};
}; |
Add debug logs to preview release | 'use strict';
const { waterfall, mapSeries } = require('async');
const logger = require('../../lib/logger');
module.exports = function createPreviewRelease(getConfig, getReleasePreview, notify, repos) {
return ({ verbose = false }, cb) => {
waterfall([
(next) => getConfigForEachRepo(repos, next),
(reposInfo, next) => getReleasePreview(reposInfo, next),
(reposInfo, next) => notifyPreviewInSlack(reposInfo, verbose, next)
], cb);
};
function getConfigForEachRepo(repos, cb) {
logger.debug('getConfigForEachRepo', { repos });
mapSeries(repos, (repo, nextRepo) => {
getConfig(repo, (err, config) => {
if (err) {
logger.error('Error getting repo config', repo, err);
return nextRepo(null, { repo, failReason: 'INVALID_REPO_CONFIG' });
}
nextRepo(null, { repo, config });
});
}, cb);
}
function notifyPreviewInSlack(reposInfo, verbose, cb) {
logger.debug('notifyPreviewInSlack', { reposInfo, verbose });
notify(reposInfo, 'preview', verbose, cb);
}
};
| 'use strict';
const { waterfall, mapSeries } = require('async');
const logger = require('../../lib/logger');
module.exports = function createPreviewRelease(getConfig, getReleasePreview, notify, repos) {
return ({ verbose = false }, cb) => {
waterfall([
(next) => getConfigForEachRepo(repos, next),
(reposInfo, next) => getReleasePreview(reposInfo, next),
(reposInfo, next) => notifyPreviewInSlack(reposInfo, verbose, next)
], cb);
};
function getConfigForEachRepo(repos, cb) {
mapSeries(repos, (repo, nextRepo) => {
getConfig(repo, (err, config) => {
if (err) {
logger.error('Error getting repo config', repo, err);
return nextRepo(null, { repo, failReason: 'INVALID_REPO_CONFIG' });
}
nextRepo(null, { repo, config });
});
}, cb);
}
function notifyPreviewInSlack(reposInfo, verbose, cb) {
notify(reposInfo, 'preview', verbose, cb);
}
};
|
Fix parsing of source with several distached statements. | var parse = require('./grammar/parser').parse,
ast = require('./ast');
exports.parse = function(sexp) {
var result = parse(sexp);
if (!ast.is_list(result) || result.length === 1) {
return result[0];
}
return result;
};
exports.unparse = function(sexp) {
// Turns AST back into list program
if (ast.is_boolean(sexp)) {
return sexp === true ? '#t' : '#f';
} else if (ast.is_list(sexp)) {
if (sexp.length > 0 && sexp[0] === 'quote') {
return "'" + exports.unparse(sexp[1]);
} else {
return '(' + sexp.map(exports.unparse).join(' ') + ')';
}
} else {
return sexp.toString();
}
};
| var parse = require('./grammar/parser').parse,
ast = require('./ast');
exports.parse = function(sexp) {
if (!ast.is_list(sexp) || sexp.length === 1) {
return parse(sexp)[0];
}
return parse(sexp);
};
exports.unparse = function(sexp) {
// Turns AST back into list program
if (ast.is_boolean(sexp)) {
return sexp === true ? '#t' : '#f';
} else if (ast.is_list(sexp)) {
if (sexp.length > 0 && sexp[0] === 'quote') {
return "'" + exports.unparse(sexp[1]);
} else {
return '(' + sexp.map(exports.unparse).join(' ') + ')';
}
} else {
return sexp.toString();
}
};
|
Remove simplejson for Python 3.2.x since there is no support | #!/usr/bin/env python
from setuptools import setup
from distutils.core import Command
from sys import stdout, version_info
import logging
VERSION = '0.9'
DESCRIPTION = "A wrapper for comicvine.com"
with open('README.md', 'r') as f:
LONG_DESCRIPTION = f.read()
extra = {}
if version_info >= (3,):
extra['use_2to3'] = True
extra['convert_2to3_doctests'] = ['README.md']
if version_info >= (3,2,) and version_info < (3,3,):
extra['install_requires'] = ['python-dateutil >= 2.0']
else:
extra['install_requires'] = ['simplejson', 'python-dateutil >= 2.0']
logging.basicConfig(stream=stdout)
logging.getLogger("tests").setLevel(logging.DEBUG)
setup(
name='PyComicVine',
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author='Martin Lenders',
author_email='authmillenon@gmail.com',
url='http://www.github.com/authmillenon/pycomicvine/',
packages=['pycomicvine', 'pycomicvine.tests'],
license="MIT License",
test_suite='pycomicvine.tests',
**extra
)
| #!/usr/bin/env python
from setuptools import setup
from distutils.core import Command
from sys import stdout, version_info
import logging
VERSION = '0.9'
DESCRIPTION = "A wrapper for comicvine.com"
with open('README.md', 'r') as f:
LONG_DESCRIPTION = f.read()
extra = {}
if version_info >= (3,):
extra['use_2to3'] = True
extra['convert_2to3_doctests'] = ['README.md']
logging.basicConfig(stream=stdout)
logging.getLogger("tests").setLevel(logging.DEBUG)
setup(
name='PyComicVine',
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author='Martin Lenders',
author_email='authmillenon@gmail.com',
url='http://www.github.com/authmillenon/pycomicvine/',
packages=['pycomicvine', 'pycomicvine.tests'],
install_requires=['simplejson','python-dateutil >= 2.0'],
license="MIT License",
test_suite='pycomicvine.tests',
**extra
)
|
Increase timeout for mocha tests | 'use strict';
const gulp = require('gulp');
const tools = require('./src');
const unmockedModulePathPatterns = [
'node_modules/.*',
'utils/helper-tests.js'
];
tools.setGlobalConfiguration(defaults => {
defaults.sourceFiles = defaults.sourceFiles.concat(// eslint-disable-line no-param-reassign
'!**/dist/**',
'!**/help/**',
'!**/coverage/**',
'!**/__tests__/**/*-invalid.+(js|jsx)'
);
return defaults;
});
tools.initialize(gulp, {
checkDependencies: true,
checkFileNames: defaults => {
defaults.paramCase.push('!src/tasks/check-file-names/__tests__/**');
return defaults;
},
conventionalChangelog: true,
eslint: {
rules: {
'global-require': 0
}
},
jest: {
unmockedModulePathPatterns,
collectCoverage: false,
testPathIgnorePatterns: [
'/node_modules/',
'/jest/__tests__/.+/',
'/mocha/__tests__/.+/'
]
},
jsdoc: true,
mocha: {
timeout: 5000
},
nsp: true,
retire: true
});
gulp.task('default', ['pre-release']);
| 'use strict';
const gulp = require('gulp');
const tools = require('./src');
const unmockedModulePathPatterns = [
'node_modules/.*',
'utils/helper-tests.js'
];
tools.setGlobalConfiguration(defaults => {
defaults.sourceFiles = defaults.sourceFiles.concat(// eslint-disable-line no-param-reassign
'!**/dist/**',
'!**/help/**',
'!**/coverage/**',
'!**/__tests__/**/*-invalid.+(js|jsx)'
);
return defaults;
});
tools.initialize(gulp, {
checkDependencies: true,
checkFileNames: defaults => {
defaults.paramCase.push('!src/tasks/check-file-names/__tests__/**');
return defaults;
},
conventionalChangelog: true,
eslint: {
rules: {
'global-require': 0
}
},
jest: {
unmockedModulePathPatterns,
collectCoverage: false,
testPathIgnorePatterns: [
'/node_modules/',
'/jest/__tests__/.+/',
'/mocha/__tests__/.+/'
]
},
jsdoc: true,
mocha: true,
nsp: true,
retire: true
});
gulp.task('default', ['pre-release']);
|
Unify and simplify for tests. | # -*- coding: utf-8 -*-
import warnings
from .settings import * # noqa: F403,F401
# Handle system warning as log messages
warnings.simplefilter("once")
for handler in LOGGING.get("handlers", []):
LOGGING["handlers"][handler]["level"] = "CRITICAL"
for logger in LOGGING.get("loggers", []):
LOGGING["loggers"][logger]["level"] = "CRITICAL"
mysql_db = DATABASES["default"]
DEFAULT_DB = {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
"TEST": {"MIGRATE": False},
}
if os.environ.get("DB_TYPE") == "mysql":
print("Using MySQL Backend!")
DEFAULT_DB = mysql_db
DATABASES = {
"default": DEFAULT_DB,
}
| # -*- coding: utf-8 -*-
import warnings
from .settings import * # noqa: F403,F401
# Handle system warning as log messages
warnings.simplefilter("once")
for handler in LOGGING.get("handlers", []):
LOGGING["handlers"][handler]["level"] = "CRITICAL"
for logger in LOGGING.get("loggers", []):
LOGGING["loggers"][logger]["level"] = "CRITICAL"
mysql_db = DATABASES["default"]
DEFAULT_DB = {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
"TEST": {"MIGRATE": False},
}
if os.environ.get("DB_TYPE") == "mysql":
print("Using MySQL Backend!")
DEFAULT_DB = mysql_db
DATABASES = {
"default": DEFAULT_DB,
} |
Add interface to loazy entity manager | <?php
namespace Bolt\Storage;
/**
* Lazy-loading EntityManager.
*
* @author Gawain Lynch <gawain.lynch@gmail.com>
*/
class LazyEntityManager implements EntityManagerInterface
{
/** @var \Closure $factory */
private $factory;
/** @var EntityManager $urlGenerator */
private $em;
/**
* Constructor.
*
* @param \Closure $factory Should return EntityManager when invoked
*/
public function __construct(\Closure $factory)
{
$this->factory = $factory;
}
/**
* @return EntityManager
*/
public function getEntityManager()
{
if (!$this->em) {
$this->em = call_user_func($this->factory);
if (!$this->em instanceof EntityManager) {
throw new \LogicException('Factory supplied to LazyEntityManager must return implementation of EntityManager.');
}
}
return $this->em;
}
/**
* @inheritDoc
*/
public function getRepository($className)
{
return $this->getEntityManager()->getRepository($className);
}
}
| <?php
namespace Bolt\Storage;
/**
* Lazy-loading EntityManager.
*
* @author Gawain Lynch <gawain.lynch@gmail.com>
*/
class LazyEntityManager
{
/** @var \Closure $factory */
private $factory;
/** @var EntityManager $urlGenerator */
private $em;
/**
* Constructor.
*
* @param \Closure $factory Should return EntityManager when invoked
*/
public function __construct(\Closure $factory)
{
$this->factory = $factory;
}
/**
* @return EntityManager
*/
public function getEntityManager()
{
if (!$this->em) {
$this->em = call_user_func($this->factory);
if (!$this->em instanceof EntityManager) {
throw new \LogicException('Factory supplied to LazyEntityManager must return implementation of EntityManager.');
}
}
return $this->em;
}
}
|
Use LinkedList instead of Array | package net.megaroid.math;
import java.util.Scanner;
import java.util.LinkedList;
public class Factors {
private int mNumber;
private LinkedList<Integer> mFactors;
public Factors(int number) {
mNumber = number;
}
public int getNumber() {
return mNumber;
}
public void printAllFactors() {
if (mFactors == null) {
initialize();
}
System.out.print("Factors: ");
for (int i : mFactors) {
System.out.print(i + " ");
}
System.out.println("");
}
private void initialize()
{
int sqrtN = (int)Math.sqrt(mNumber);
mFactors = new LinkedList<Integer>();
for (int i = 1; i <= sqrtN; i++) {
if (mNumber % i == 0) {
mFactors.add(i);
if (i * i != mNumber) {
mFactors.add(mNumber / i);
}
}
}
}
public static void main(String[] args) {
System.out.print("Input a number : ");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.close();
Factors f = new Factors(num);
System.out.println("The number is " + f.getNumber());
f.printAllFactors();
}
}
| package net.megaroid.math;
import java.util.Scanner;
public class Factors {
private int mNumber;
private int[] mFactors;
private int mCount;
public Factors(int number) {
mNumber = number;
}
public int getNumber() {
return mNumber;
}
public void printAllFactors() {
if (mFactors == null) {
initialize();
}
System.out.print("Factors: ");
for (int i = 0; i < mCount; i++) {
System.out.print(mFactors[i] + " ");;
}
System.out.println("");
}
private void initialize()
{
int sqrtN = (int)Math.sqrt(mNumber);
mCount = 0;
mFactors = new int[sqrtN * 2];
for (int i = 1; i <= sqrtN; i++) {
if (mNumber % i == 0) {
mFactors[mCount++] = i;
if (i * i != mNumber) {
mFactors[mCount++] = mNumber / i;
}
}
}
}
public static void main(String[] args) {
System.out.print("Input a number : ");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.close();
Factors f = new Factors(num);
System.out.println("The number is " + f.getNumber());
f.printAllFactors();
}
}
|
Add api-key and authorisation in http header | package com.github.sbugat.samplerest.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
@WebFilter(
urlPatterns = "/*")
public class ApiOriginFilter implements Filter {
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
} | package com.github.sbugat.samplerest.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
@WebFilter(
urlPatterns = "/*")
public class ApiOriginFilter implements Filter {
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
final HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
} |
Fix formatting and a warning for FoursqauredAppTestCase.
committer: Joe LaPenna <16a9a54ddf4259952e3c118c763138e83693d7fd@joelapenna.com> | /**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.Foursquared;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
public FoursquaredAppTestCase() {
super(Foursquared.class);
}
@MediumTest
public void testLocationMethods() {
createApplication();
getApplication().getLastKnownLocation();
getApplication().getLocationListener();
}
@SmallTest
public void testPreferences() {
createApplication();
Foursquared foursquared = getApplication();
foursquared.getFoursquare();
// ... to be continued.
}
}
| /**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.Foursquared;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
public FoursquaredAppTestCase() {
super(Foursquared.class);
}
@MediumTest
public void testLocationMethods() {
createApplication();
getApplication().getLastKnownLocation();
getApplication().getLocationListener();
}
@SmallTest
public void testPreferences() {
createApplication();
Foursquared foursquared = getApplication();
Foursquare foursquare = foursquared.getFoursquare();
// ... to be continued.
}
}
|
Sort events by start and iso format datetimes | import requests
import csv
from datetime import datetime
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicates and sort
events = {e['UID']: e for e in events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events:
for key, value in e.items():
if isinstance(value, datetime): e[key] = value.isoformat()
writer.writerow(e)
| import requests
import csv
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicate events
events = {e['UID']: e for e in events}.values()
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events: writer.writerow(e)
|
Clean up errant import of non-DW class. | package io.ifar.goodies;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.codahale.metrics.MetricRegistry;
import io.dropwizard.Configuration;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.setup.Environment;
import org.slf4j.LoggerFactory;
import javax.validation.Validation;
/**
*
*/
public class CliConveniences {
public static void quietLogging(String... packages) {
for (String pkg : packages) {
((Logger) LoggerFactory.getLogger(pkg)).setLevel(Level.OFF);
}
}
public static Environment fabricateEnvironment(String name, Configuration configuration) {
return new Environment(name, Jackson.newObjectMapper(), Validation.buildDefaultValidatorFactory().getValidator(),
new MetricRegistry(),ClassLoader.getSystemClassLoader());
}
}
| package io.ifar.goodies;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.codahale.metrics.MetricRegistry;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.setup.Environment;
import org.slf4j.LoggerFactory;
import javax.security.auth.login.Configuration;
import javax.validation.Validation;
/**
*
*/
public class CliConveniences {
public static void quietLogging(String... packages) {
for (String pkg : packages) {
((Logger) LoggerFactory.getLogger(pkg)).setLevel(Level.OFF);
}
}
public static Environment fabricateEnvironment(String name, Configuration configuration) {
return new Environment(name, Jackson.newObjectMapper(), Validation.buildDefaultValidatorFactory().getValidator(),
new MetricRegistry(),ClassLoader.getSystemClassLoader());
}
}
|
Fix GZip issue in script. | import compression from 'compression';
import express from 'express';
import path from 'path';
import open from 'open';
// tslint:disable:no-console
const port = 3000;
const app = express();
app.use(compression());
app.use(express.static('dist'));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
app.get('/users', function(req, res) {
// Hard coding for simplicity. Pretend this hits a real database
res.json([
{"id": 1,"firstName":"Bob","lastName":"Smith","email":"bob@gmail.com"},
{"id": 2,"firstName":"Tammy","lastName":"Norton","email":"tnorton@yahoo.com"},
{"id": 3,"firstName":"Tina","lastName":"Lee","email":"lee.tina@hotmail.com"}
]);
});
app.listen(port, function(err) {
if (err) {
console.log(err);
} else {
open(`http://localhost:${port}`);
}
});
| import compression from 'compression';
import express from 'express';
import path from 'path';
import open from 'open';
// tslint:disable:no-console
const port = 3000;
const app = express();
app.use(express.static('dist'));
app.use(compression());
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
app.get('/users', function(req, res) {
// Hard coding for simplicity. Pretend this hits a real database
res.json([
{"id": 1,"firstName":"Bob","lastName":"Smith","email":"bob@gmail.com"},
{"id": 2,"firstName":"Tammy","lastName":"Norton","email":"tnorton@yahoo.com"},
{"id": 3,"firstName":"Tina","lastName":"Lee","email":"lee.tina@hotmail.com"}
]);
});
app.listen(port, function(err) {
if (err) {
console.log(err);
} else {
open(`http://localhost:${port}`);
}
});
|
Use SQLA Session directly in tests | import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy_utils import create_database, database_exists, drop_database
from gold_digger.database.db_model import Base
@pytest.fixture(scope="module")
def db_connection(db_connection_string):
"""
Create one test database for all database tests.
"""
engine = create_engine(db_connection_string)
if not database_exists(engine.url):
create_database(engine.url)
connection = engine.connect()
yield connection
connection.close()
engine.dispose()
drop_database(engine.url)
@pytest.fixture
def db_session(db_connection):
"""
Drop and create all tables for every test, ie. every test starts with empty tables and new session.
"""
db_connection.execute("DROP TABLE IF EXISTS statistics_base CASCADE")
Base.metadata.drop_all(db_connection)
Base.metadata.create_all(db_connection)
session = scoped_session(sessionmaker(db_connection))
yield session()
session.remove()
| import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy_utils import create_database, database_exists, drop_database
from gold_digger.database.db_model import Base
@pytest.fixture(scope="module")
def db_connection(db_connection_string):
"""
Create one test database for all database tests.
"""
engine = create_engine(db_connection_string)
if not database_exists(engine.url):
create_database(engine.url)
connection = engine.connect()
yield connection
connection.close()
engine.dispose()
drop_database(engine.url)
@pytest.fixture
def db_session(db_connection):
"""
Drop and create all tables for every test, ie. every test starts with empty tables and new session.
"""
db_connection.execute("DROP TABLE IF EXISTS statistics_base CASCADE")
Base.metadata.drop_all(db_connection)
Base.metadata.create_all(db_connection)
session = scoped_session(sessionmaker(db_connection))
yield session
session.remove()
|
Use "sublime-session" as file extension
Furthermore fix some bugs in serialize.py | import sublime
import json
import os
from ..json import encoder
from ..json import decoder
from . import settings
_DEFAULT_PATH = os.path.join('User', 'sessions')
_DEFAULT_EXTENSION = '.sublime-session'
def dump(name, session):
session_path = _generate_path(name)
with open(session_path, 'w') as f:
json.dump(session, f, cls=encoder.SessionEncoder)
def load(name):
session_path = _generate_path(name)
with open(session_path, 'r') as f:
return json.load(f, cls=decoder.SessionDecoder)
def _generate_path(name):
return os.path.join(_generate_folder(), _generate_name(name))
def _generate_folder():
folder = settings.get('session_path')
if folder:
folder = os.path.normpath(folder)
else:
folder = os.path.join(sublime.packages_path(), _DEFAULT_PATH)
# Ensure the folder exists
os.makedirs(folder, exist_ok=True)
return folder
def _generate_name(name, extension=_DEFAULT_EXTENSION):
return ''.join([name, extension])
| import sublime
import json
import os
from ..json import encoder
from ..json import decoder
from . import settings
_DEFAULT_PATH = os.path.join('User', 'sessions')
_DEFAULT_EXTENSION = 'json'
def dump(name, session):
session_path = _generate_path(name)
with open(session_path, 'w') as f:
json.dump(session, f, cls=encoder.SessionEncoder)
def load(name):
session_path = _generate_path(name)
with open(session_path, 'r') as f:
return json.load(f, cls=decoder.SessionDecoder)
def _generate_path(name):
path = settings.get('session_path')
if not path:
path = _DEFAULT_PATH
folder = os.path.join(sublime.packages_path(), path)
# Ensure the folder exists
os.makedirs(folder, exist_ok=True)
return os.path.join(folder, _generate_name(name))
def _generate_name(name, extension=_DEFAULT_EXTENSION):
return '.'.join([name, extension])
|
Increment version number for release | import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
files.append(relpath(join(root, fn), package_root))
return files
setup(
name = "smarty",
version = "0.1.5",
author = "John Chodera, David Mobley, and others",
author_email = "john.chodera@choderalab.org",
description = ("Automated Bayesian atomtype sampling"),
license = "GNU Lesser General Public License (LGPL), Version 3",
keywords = "Bayesian atomtype sampling forcefield parameterization",
url = "http://github.com/open-forcefield-group/smarty",
packages=['smarty', 'smarty/tests', 'smarty/data'],
long_description=read('README.md'),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: GNU Lesser General Public License (LGPL), Version 3",
],
entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']},
package_data={'smarty': find_package_data('smarty/data', 'smarty')},
)
| import os
from os.path import relpath, join
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_package_data(data_root, package_root):
files = []
for root, dirnames, filenames in os.walk(data_root):
for fn in filenames:
files.append(relpath(join(root, fn), package_root))
return files
setup(
name = "smarty",
version = "0.1.4",
author = "John Chodera, David Mobley, and others",
author_email = "john.chodera@choderalab.org",
description = ("Automated Bayesian atomtype sampling"),
license = "GNU Lesser General Public License (LGPL), Version 3",
keywords = "Bayesian atomtype sampling forcefield parameterization",
url = "http://github.com/open-forcefield-group/smarty",
packages=['smarty', 'smarty/tests', 'smarty/data'],
long_description=read('README.md'),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: GNU Lesser General Public License (LGPL), Version 3",
],
entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']},
package_data={'smarty': find_package_data('smarty/data', 'smarty')},
)
|
Change the default theme name | <?php namespace Modules\Setting\Database\Seeders;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Modules\Setting\Repositories\SettingRepository;
class SettingDatabaseSeeder extends Seeder
{
/**
* @var SettingRepository
*/
private $setting;
public function __construct(SettingRepository $setting)
{
$this->setting = $setting;
}
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
$data = [
'name' => 'core::template',
'plainValue' => 'Flatly',
'isTranslatable' => false,
];
$this->setting->create($data);
}
}
| <?php namespace Modules\Setting\Database\Seeders;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Modules\Setting\Repositories\SettingRepository;
class SettingDatabaseSeeder extends Seeder
{
/**
* @var SettingRepository
*/
private $setting;
public function __construct(SettingRepository $setting)
{
$this->setting = $setting;
}
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
$data = [
'name' => 'core::template',
'plainValue' => 'Demo',
'isTranslatable' => false,
];
$this->setting->create($data);
}
}
|
Comment out the debug code. | import React from 'react';
import {loadViaAjax, loadViaNode} from './katas.js';
import Page from './components/page.js';
import GithubSearchResult from './github-search-result.js';
function githubJsonToKataGroups(githubJson) {
return GithubSearchResult.toKataGroups(githubJson);
}
const _renderInBrowser = (err, githubJson) => {
if (err) {
console.log(err);
} else {
React.render(<Page kataGroups={githubJsonToKataGroups(githubJson)}/>, document.querySelector('body'));
}
};
const _renderOnServer = (err, githubJson) => {
if (err) {
console.log(err);
} else {
const preRendered = React.renderToStaticMarkup(<Page kataGroups={githubJsonToKataGroups(githubJson)}/>);
console.log(preRendered);
}
};
import data from './for-offline/data.json';
function loadFromFile(onLoaded) {
onLoaded(null, data);
}
export function renderInBrowser() {
loadViaAjax(_renderInBrowser);
//loadFromFile(_renderInBrowser);
}
export function renderOnServer() {
loadViaNode(_renderOnServer);
//loadFromFile(_renderOnServer);
}
| import React from 'react';
import {loadViaAjax, loadViaNode} from './katas.js';
import Page from './components/page.js';
import GithubSearchResult from './github-search-result.js';
function githubJsonToKataGroups(githubJson) {
return GithubSearchResult.toKataGroups(githubJson);
}
const _renderInBrowser = (err, githubJson) => {
if (err) {
console.log(err);
} else {
React.render(<Page kataGroups={githubJsonToKataGroups(githubJson)}/>, document.querySelector('body'));
}
};
const _renderOnServer = (err, githubJson) => {
if (err) {
console.log(err);
} else {
const preRendered = React.renderToStaticMarkup(<Page kataGroups={githubJsonToKataGroups(githubJson)}/>);
console.log(preRendered);
}
};
import data from './for-offline/data.json';
function loadFromFile(onLoaded) {
onLoaded(null, data);
}
export function renderInBrowser() {
loadViaAjax(_renderInBrowser);
}
export function renderOnServer() {
loadViaNode(_renderOnServer);
}
|
Add authentication hook to all methods (except create) | const { authenticate } = require('@feathersjs/authentication').hooks;
const { hashPassword, protect } = require('@feathersjs/authentication-local').hooks;
const gravatar = require('../../hooks/gravatar');
module.exports = {
before: {
all: [],
find: [ authenticate('jwt') ],
get: [ authenticate('jwt') ],
create: [hashPassword(), authenticate('jwt'), gravatar()],
update: [ hashPassword(), authenticate('jwt') ],
patch: [ hashPassword(), authenticate('jwt') ],
remove: [ authenticate('jwt') ]
},
after: {
all: [
// Make sure the password field is never sent to the client
// Always must be the last hook
protect('password')
],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
| const { authenticate } = require('@feathersjs/authentication').hooks;
const { hashPassword, protect } = require('@feathersjs/authentication-local').hooks;
const gravatar = require('../../hooks/gravatar');
module.exports = {
before: {
all: [],
find: [ authenticate('jwt') ],
get: [],
create: [hashPassword(), gravatar()],
update: [ hashPassword() ],
patch: [ hashPassword() ],
remove: []
},
after: {
all: [
// Make sure the password field is never sent to the client
// Always must be the last hook
protect('password')
],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
|
Fix .published() to accept current date as well. | """
The manager class for the CMS models
"""
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
class EntryQuerySet(QuerySet):
def published(self):
"""
Return only published entries
"""
from fluent_blogs.models import Entry # the import can't be globally, that gives a circular dependency
return self \
.filter(status=Entry.PUBLISHED) \
.filter(
Q(publication_date__isnull=True) |
Q(publication_date__lte=datetime.now())
).filter(
Q(publication_end_date__isnull=True) |
Q(publication_end_date__gte=datetime.now())
)
class EntryManager(models.Manager):
"""
Extra methods attached to ``Entry.objects`` .
"""
def get_query_set(self):
return EntryQuerySet(self.model, using=self._db)
def published(self):
"""
Return only published entries
"""
return self.get_query_set().published()
| """
The manager class for the CMS models
"""
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
class EntryQuerySet(QuerySet):
def published(self):
"""
Return only published entries
"""
from fluent_blogs.models import Entry # the import can't be globally, that gives a circular dependency
return self \
.filter(status=Entry.PUBLISHED) \
.filter(
Q(publication_date__isnull=True) |
Q(publication_date__lt=datetime.now())
).filter(
Q(publication_end_date__isnull=True) |
Q(publication_end_date__gte=datetime.now())
)
class EntryManager(models.Manager):
"""
Extra methods attached to ``Entry.objects`` .
"""
def get_query_set(self):
return EntryQuerySet(self.model, using=self._db)
def published(self):
"""
Return only published entries
"""
return self.get_query_set().published()
|
Simplify implementation and achieve full test coverage | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var defineProperties = require( './define_properties.js' );
// MAIN //
/**
* Tests for `Object.defineProperties` support.
*
* @returns {boolean} boolean indicating if an environment has `Object.defineProperties` support
*
* @example
* var bool = hasDefinePropertiesSupport();
* // returns <boolean>
*/
function hasDefinePropertiesSupport() {
// Test basic support...
try {
defineProperties( {}, {
'x': {}
});
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = hasDefinePropertiesSupport;
| /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var defineProperties = require( './define_properties.js' );
// MAIN //
/**
* Tests for `Object.defineProperties` support.
*
* @returns {boolean} boolean indicating if an environment has `Object.defineProperties` support
*
* @example
* var bool = hasDefinePropertiesSupport();
* // returns <boolean>
*/
function hasDefinePropertiesSupport() {
var bool;
if ( typeof defineProperties !== 'function' ) {
return false;
}
// Test basic support...
try {
defineProperties( {}, {
'x': {}
});
bool = true;
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasDefinePropertiesSupport;
|
Fix unit test for JDK 1.3. | package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
static class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.setUp();
xstream.setMode(XStream.NO_REFERENCES);
}
public void testThrowsExceptionWhenDetectingCircularReferences() {
Thing a = new Thing();
Thing b = new Thing();
a.thing = b;
b.thing = a;
try {
xstream.toXML(a);
fail("expected exception");
} catch (TreeMarshaller.CircularReferenceException expected) {
// good
}
}
}
| package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.setUp();
xstream.setMode(XStream.NO_REFERENCES);
}
public void testThrowsExceptionWhenDetectingCircularReferences() {
Thing a = new Thing();
Thing b = new Thing();
a.thing = b;
b.thing = a;
try {
xstream.toXML(a);
fail("expected exception");
} catch (TreeMarshaller.CircularReferenceException expected) {
// good
}
}
}
|
Add session hack for behat | <?php
/**
* URL rules for the CMS module
*
* @package newsletter
*/
if(!(defined('NEWSLETTER_DIR'))){
define('NEWSLETTER_DIR', basename(dirname(__FILE__)));
}
Config::inst()->update('Director', 'rules', array(
'newsletterlinks/$Hash' => "TrackLinkController",
'unsubscribe//$Action/$ValidateHash/$MailingList' => 'UnsubscribeController'
));
if (class_exists('MessageQueue')) {
MessageQueue::add_interface("default", array( "queues" => "/.*/",
"implementation" => "SimpleDBMQ",
"encoding" => "php_serialize",
"send" => array( "onShutdown" => "all" ),
"delivery" => array( "onerror" => array( "log" ) ),
"retrigger" => "yes", // on consume, retrigger if there are more items
"onShutdownMessageLimit" => "1" // one message per async process
));
}
//SS_Log::add_writer(new SS_LogFileWriter(BASE_PATH . '/logN.txt'), SS_Log::NOTICE);
//SS_Log::add_writer(new SS_LogFileWriter(BASE_PATH . '/logW.txt'), SS_Log::WARN);
//SS_Log::add_writer(new SS_LogFileWriter(BASE_PATH . '/logE.txt'), SS_Log::ERR);
Session::start();
| <?php
/**
* URL rules for the CMS module
*
* @package newsletter
*/
if(!(defined('NEWSLETTER_DIR'))){
define('NEWSLETTER_DIR', basename(dirname(__FILE__)));
}
Config::inst()->update('Director', 'rules', array(
'newsletterlinks/$Hash' => "TrackLinkController",
'unsubscribe//$Action/$ValidateHash/$MailingList' => 'UnsubscribeController'
));
if (class_exists('MessageQueue')) {
MessageQueue::add_interface("default", array( "queues" => "/.*/",
"implementation" => "SimpleDBMQ",
"encoding" => "php_serialize",
"send" => array( "onShutdown" => "all" ),
"delivery" => array( "onerror" => array( "log" ) ),
"retrigger" => "yes", // on consume, retrigger if there are more items
"onShutdownMessageLimit" => "1" // one message per async process
));
}
//SS_Log::add_writer(new SS_LogFileWriter(BASE_PATH . '/logN.txt'), SS_Log::NOTICE);
//SS_Log::add_writer(new SS_LogFileWriter(BASE_PATH . '/logW.txt'), SS_Log::WARN);
//SS_Log::add_writer(new SS_LogFileWriter(BASE_PATH . '/logE.txt'), SS_Log::ERR);
|
test: Fix race in redis test
The redis appliance is not always ready when the `resource add` command
returns. Added a check that waits for the discoverd registration before
continuing.
Signed-off-by: Jonathan Rudenberg <3692bfa45759a67d83aedf0045f6cb635a966abf@titanous.com> | package main
import (
"path/filepath"
c "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-check"
)
type RedisSuite struct {
Helper
}
var _ = c.ConcurrentSuite(&RedisSuite{})
func (s *RedisSuite) TestDumpRestore(t *c.C) {
a := s.newCliTestApp(t)
t.Assert(a.flynn("resource", "add", "redis"), Succeeds)
release, err := s.controllerClient(t).GetAppRelease(a.id)
t.Assert(err, c.IsNil)
t.Assert(release.Env["FLYNN_REDIS"], c.Not(c.Equals), "")
a.waitForService(release.Env["FLYNN_REDIS"])
t.Assert(a.flynn("redis", "redis-cli", "set", "foo", "bar"), Succeeds)
file := filepath.Join(t.MkDir(), "dump.rdb")
t.Assert(a.flynn("redis", "dump", "-f", file), Succeeds)
t.Assert(a.flynn("redis", "redis-cli", "del", "foo"), Succeeds)
a.flynn("redis", "restore", "-f", file)
query := a.flynn("redis", "redis-cli", "get", "foo")
t.Assert(query, SuccessfulOutputContains, "bar")
}
| package main
import (
"path/filepath"
c "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-check"
)
type RedisSuite struct {
Helper
}
var _ = c.ConcurrentSuite(&RedisSuite{})
func (s *RedisSuite) TestDumpRestore(t *c.C) {
r := s.newGitRepo(t, "empty")
t.Assert(r.flynn("create"), Succeeds)
t.Assert(r.flynn("resource", "add", "redis"), Succeeds)
t.Assert(r.flynn("redis", "redis-cli", "set", "foo", "bar"), Succeeds)
file := filepath.Join(t.MkDir(), "dump.rdb")
t.Assert(r.flynn("redis", "dump", "-f", file), Succeeds)
t.Assert(r.flynn("redis", "redis-cli", "del", "foo"), Succeeds)
r.flynn("redis", "restore", "-f", file)
query := r.flynn("redis", "redis-cli", "get", "foo")
t.Assert(query, SuccessfulOutputContains, "bar")
}
|
Support python 2 and 3
Add source argument.
Update arguments to use long names from GNU netcat. | #!/usr/bin/python
import argparse
import socket
import sys
parser = argparse.ArgumentParser(description='Simple netcat in pure python.')
parser.add_argument('-s', '--source', metavar='ADDRESS')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-w', '--wait', metavar='SECONDS', type=int)
parser.add_argument('-z', '--zero', action='store_true')
parser.add_argument('host')
parser.add_argument('port')
args = parser.parse_args()
# Set a souce address for socket connection
source = ('', 0)
if args.source:
source = (args.source, 0) # port 0 specifies that the OS will choose a port
# exit successfully if the connection succeeds
if args.zero:
try:
connection = socket.create_connection((args.host, args.port), args.wait, source)
if args.verbose:
print("Connection to {} {} port (tcp) succeeded!".format(args.host, args.port))
sys.exit(0)
except socket.error as msg:
if args.verbose:
print("Connection to {} {} port (tcp) failed. {}".format(args.host, args.port, msg))
sys.exit(1)
else:
print('Not implemented')
| #!/usr/bin/python2
import argparse
import socket
import sys
parser = argparse.ArgumentParser(description='Simple netcat in pure python.')
parser.add_argument('-z', '--scan', action='store_true')
parser.add_argument('-w', '--timeout', metavar='SECONDS', type=int)
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('host')
parser.add_argument('port', type=int)
args = parser.parse_args()
if args.scan:
try:
connection = socket.create_connection((args.host, args.port), args.timeout)
if args.verbose:
print "Connection to {} {} port (tcp) succeeded!".format(args.host, args.port)
sys.exit(0)
except socket.error as msg:
if args.verbose:
print "Connection to {} {} port (tcp) failed. {}".format(args.host, args.port, msg)
sys.exit(1)
else:
print 'Not implemented'
|
Rearrange look & feel of `eslint` configuration | const { join } = require("path");
const { PluginName, PresetName } = require("@manuth/eslint-plugin-typescript");
module.exports = {
extends: [
`plugin:${PluginName}/${PresetName.RecommendedWithTypeChecking}`
],
env: {
node: true,
es6: true
},
parserOptions: {
project: [
join(__dirname, "tsconfig.json"),
join(__dirname, "tsconfig.eslint.json"),
join(__dirname, "tsconfig.webpack.json"),
join(__dirname, "src", "test", "tsconfig.json"),
join(__dirname, "src", "tests", "tsconfig.json")
]
}
};
| const { join } = require("path");
const ESLintPresets = require("@manuth/eslint-plugin-typescript");
module.exports = {
extends: [
`plugin:${ESLintPresets.PluginName}/${ESLintPresets.PresetName.RecommendedWithTypeChecking}`
],
env: {
node: true,
es6: true
},
parserOptions: {
project: [
join(__dirname, "tsconfig.json"),
join(__dirname, "tsconfig.eslint.json"),
join(__dirname, "tsconfig.webpack.json"),
join(__dirname, "src", "test", "tsconfig.json"),
join(__dirname, "src", "tests", "tsconfig.json")
]
}
};
|
Remove columns, only if they already exist | <?php
use Migrations\AbstractMigration;
class ReorganizeTranslationTable extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function change()
{
$table = $this->table('language_translations');
if ($table->hasColumn('is_active')) {
$table->removeColumn('is_active');
}
if ($table->hasColumn('code')) {
$table->removeColumn('code');
}
$table->addColumn('language_id', 'string', [
'limit' => 36,
'null' => false,
]);
$table->save();
}
}
| <?php
use Migrations\AbstractMigration;
class ReorganizeTranslationTable extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function change()
{
$table = $this->table('language_translations');
$table->removeColumn('is_active');
$table->removeColumn('code');
$table->addColumn('language_id', 'string', [
'limit' => 36,
'null' => false,
]);
$table->save();
}
}
|
chore: Tidy up the eslint excludes | const RESPONSE_PUBLIC = 'in_channel';
const RESPONSE_PRIVATE = 'ephemeral';
const baseResponse = {
// Required names for slack
/*eslint-disable camelcase */
parse: 'full',
text: '',
unfurl_media: true
/*eslint-enable camelcase */
};
function getImageAttachment(image) {
// Required names for slack
/*eslint-disable camelcase */
return [{
fallback: 'Image failed to load',
image_url: encodeURI(image)
}];
/*eslint-enable camelcase */
}
module.exports = function create(data) {
let responseObject = Object.assign({}, baseResponse);
responseObject.text = data.text;
if(data.image) {
responseObject.attachments = getImageAttachment(data.image);
}
// Required names for slack
/*eslint-disable camelcase */
responseObject.response_type = (!data.isPrivate ? RESPONSE_PUBLIC : RESPONSE_PRIVATE);
/*eslint-enable camelcase */
return responseObject;
};
| const RESPONSE_PUBLIC = 'in_channel';
const RESPONSE_PRIVATE = 'ephemeral';
// Required names for slack
/*eslint-disable camelcase */
const baseResponse = {
parse: 'full',
text: '',
unfurl_media: true
};
/*eslint-enable camelcase */
function getImageAttachment(image) {
// Required names for slack
/*eslint-disable camelcase */
return [{
fallback: 'Image failed to load',
image_url: encodeURI(image)
}];
/*eslint-enable camelcase */
}
module.exports = function create(data) {
let responseObject = Object.assign({}, baseResponse);
responseObject.text = data.text;
if(data.image) {
responseObject.attachments = getImageAttachment(data.image);
}
// Required names for slack
/*eslint-disable camelcase */
responseObject.response_type = (!data.isPrivate ? RESPONSE_PUBLIC : RESPONSE_PRIVATE);
/*eslint-enable camelcase */
return responseObject;
};
|
Tweak ConfigContext manager to allow for objects with a regionless site | from __future__ import unicode_literals
from django.db.models import Q, QuerySet
class ConfigContextQuerySet(QuerySet):
def get_for_object(self, obj):
"""
Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.
"""
# `device_role` for Device; `role` for VirtualMachine
role = getattr(obj, 'device_role', None) or obj.role
return self.filter(
Q(regions=getattr(obj.site, 'region', None)) | Q(regions=None),
Q(sites=obj.site) | Q(sites=None),
Q(roles=role) | Q(roles=None),
Q(tenants=obj.tenant) | Q(tenants=None),
Q(platforms=obj.platform) | Q(platforms=None),
is_active=True,
).order_by('weight', 'name')
| from __future__ import unicode_literals
from django.db.models import Q, QuerySet
class ConfigContextQuerySet(QuerySet):
def get_for_object(self, obj):
"""
Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.
"""
# `device_role` for Device; `role` for VirtualMachine
role = getattr(obj, 'device_role', None) or obj.role
return self.filter(
Q(regions=obj.site.region) | Q(regions=None),
Q(sites=obj.site) | Q(sites=None),
Q(roles=role) | Q(roles=None),
Q(tenants=obj.tenant) | Q(tenants=None),
Q(platforms=obj.platform) | Q(platforms=None),
is_active=True,
).order_by('weight', 'name')
|
Set the Default Storage_Engine to RocksDB | "use strict";
const aim = require("arangodb-instance-manager");
exports.create = () => {
let pathOrImage;
let runner;
if (process.env.RESILIENCE_ARANGO_BASEPATH) {
pathOrImage = process.env.RESILIENCE_ARANGO_BASEPATH;
runner = "local";
} else if (process.env.RESILIENCE_DOCKER_IMAGE) {
pathOrImage = process.env.RESILIENCE_DOCKER_IMAGE;
runner = "docker";
}
if (!runner) {
throw new Error(
'Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container'
);
}
let storageEngine = process.env.ARANGO_STORAGE_ENGINE === "mmfiles" ? "mmfiles" : "rocksdb";
return new aim.InstanceManager(pathOrImage, runner, storageEngine);
};
exports.endpointToUrl = aim.endpointToUrl;
exports.FailoverError = aim.FailoverError;
exports.waitForInstance = aim.InstanceManager.waitForInstance;
exports.rpAgency = aim.InstanceManager.rpAgency;
| "use strict";
const aim = require("arangodb-instance-manager");
exports.create = () => {
let pathOrImage;
let runner;
if (process.env.RESILIENCE_ARANGO_BASEPATH) {
pathOrImage = process.env.RESILIENCE_ARANGO_BASEPATH;
runner = "local";
} else if (process.env.RESILIENCE_DOCKER_IMAGE) {
pathOrImage = process.env.RESILIENCE_DOCKER_IMAGE;
runner = "docker";
}
if (!runner) {
throw new Error(
'Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container'
);
}
let storageEngine;
if (process.env.ARANGO_STORAGE_ENGINE) {
storageEngine = process.env.ARANGO_STORAGE_ENGINE;
if (storageEngine !== "rocksdb") {
storageEngine = "mmfiles";
}
} else {
storageEngine = "mmfiles";
}
return new aim.InstanceManager(pathOrImage, runner, storageEngine);
};
exports.endpointToUrl = aim.endpointToUrl;
exports.FailoverError = aim.FailoverError;
exports.waitForInstance = aim.InstanceManager.waitForInstance;
exports.rpAgency = aim.InstanceManager.rpAgency;
|
Support arbitary numeric types for creating pygame surfaces | """ SDL errors.def
"""
from pygame._sdl import sdl, ffi
from numbers import Number
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
# This is as liberal as pygame when used for pygame.surface, but
# more liberal for pygame.display. I don't think the inconsistency
# matters
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], Number) or
not isinstance(rect[1], Number)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
# We'll throw a conversion TypeError here if someone is using a
# complex number, but so does pygame.
return int(rect[0]), int(rect[1])
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
| """ SDL errors.def
"""
from pygame._sdl import sdl, ffi
class SDLError(Exception):
"""SDL error."""
@classmethod
def from_sdl_error(cls):
return cls(ffi.string(sdl.SDL_GetError()))
def unpack_rect(rect):
"""Unpack the size and raise a type error if needed."""
if (not hasattr(rect, '__iter__') or
len(rect) != 2 or
not isinstance(rect[0], int) or
not isinstance(rect[1], int)):
raise TypeError("expected tuple of two integers but got %r"
% type(rect))
return rect
def get_error():
err = ffi.string(sdl.SDL_GetError())
if not isinstance(err, str):
return err.decode('utf8')
return err
def set_error(errmsg):
if not isinstance(errmsg, bytes):
errmsg = errmsg.encode('utf8')
sdl.SDL_SetError(errmsg)
|
Remove registerTask actions, they already exist and gives problems when they are specified multiple times | module.exports = function (grunt) {
'use strict';
grunt.initConfig({
autoprefixer: {
single_file: {
src: 'public/style.css',
dest: 'public/style-prefixed.css'
}
},
handlebars: {
options: {
namespace: 'Handlebars.templates',
processName: function (filename) {
var pieces = filename.split('/');
return pieces[pieces.length - 1].replace(/\.handlebars$/, '');
}
},
compile: {
files: {
'public/js/tweet.handlebars.js': 'templates/tweet.handlebars'
}
}
},
reduce: {
root: 'public',
outRoot: 'dist',
less: false
}
});
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-contrib-handlebars');
grunt.loadNpmTasks('grunt-reduce');
grunt.registerTask('default', ['autoprefixer', 'handlebars', 'reduce']);
};
| module.exports = function (grunt) {
'use strict';
grunt.initConfig({
autoprefixer: {
single_file: {
src: 'public/style.css',
dest: 'public/style-prefixed.css'
}
},
handlebars: {
options: {
namespace: 'Handlebars.templates',
processName: function (filename) {
var pieces = filename.split('/');
return pieces[pieces.length - 1].replace(/\.handlebars$/, '');
}
},
compile: {
files: {
'public/js/tweet.handlebars.js': 'templates/tweet.handlebars'
}
}
},
reduce: {
root: 'public',
outRoot: 'dist',
less: false
}
});
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-contrib-handlebars');
grunt.loadNpmTasks('grunt-reduce');
grunt.registerTask('prefix', ['autoprefixer']);
grunt.registerTask('handlebars', ['handlebars']);
grunt.registerTask('reduce', ['reduce']);
grunt.registerTask('default', ['autoprefixer', 'handlebars', 'reduce']);
};
|
AMQ-4010: Use pre compiled pattern when doing string replaceAll as its faster.
git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@1379761 13f79535-47bb-0310-9956-ffa450edef68 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.util;
import java.util.regex.Pattern;
public final class JMXSupport {
private static final Pattern PART_1 = Pattern.compile("[\\:\\,\\'\\\"]");
private static final Pattern PART_2 = Pattern.compile("\\?");
private static final Pattern PART_3 = Pattern.compile("=");
private static final Pattern PART_4 = Pattern.compile("\\*");
private JMXSupport() {
}
public static String encodeObjectNamePart(String part) {
String answer = PART_1.matcher(part).replaceAll("_");
answer = PART_2.matcher(answer).replaceAll("&qe;");
answer = PART_3.matcher(answer).replaceAll("&");
answer = PART_4.matcher(answer).replaceAll("*");
return answer;
}
}
| /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.util;
public final class JMXSupport {
private JMXSupport() {
}
public static String encodeObjectNamePart(String part) {
// return ObjectName.quote(part);
String answer = part.replaceAll("[\\:\\,\\'\\\"]", "_");
answer = answer.replaceAll("\\?", "&qe;");
answer = answer.replaceAll("=", "&");
answer = answer.replaceAll("\\*", "*");
return answer;
}
}
|
Move HTTP server definition to end of module | import express from 'express';
import compression from 'compression';
import expressEnforcesSSL from 'express-enforces-ssl';
import helmet from 'helmet';
import http from 'http';
import path from 'path';
// Express server
let app = express();
// Force HTTPS on production
if (process.env.NODE_ENV === 'production') {
app.enable('trust proxy');
app.use(expressEnforcesSSL());
app.use(helmet());
}
// Serve assets using gzip compression
app.use(compression());
// Routes
app.get('/room/:roomCode', (req, res) => {
res.sendFile(path.join(path.dirname(__dirname), 'index.html'));
});
app.get('/room', (req, res) => {
res.sendFile(path.join(path.dirname(__dirname), 'index.html'));
});
app.use(express.static(path.dirname(__dirname)));
// HTTP server wrapper
let server = http.Server(app);
// Warning: app.listen(8080) will not work here; see
// <https://github.com/socketio/socket.io/issues/2075>
server.listen(process.env.PORT || 8080, () => {
console.log(`Server started. Listening on port ${server.address().port}`);
});
export default server;
| import express from 'express';
import compression from 'compression';
import expressEnforcesSSL from 'express-enforces-ssl';
import helmet from 'helmet';
import http from 'http';
import path from 'path';
// Express server
let app = express();
let server = http.Server(app);
// Force HTTPS on production
if (process.env.NODE_ENV === 'production') {
app.enable('trust proxy');
app.use(expressEnforcesSSL());
app.use(helmet());
}
// Serve assets using gzip compression
app.use(compression());
// Routes
app.get('/room/:roomCode', (req, res) => {
res.sendFile(path.join(path.dirname(__dirname), 'index.html'));
});
app.get('/room', (req, res) => {
res.sendFile(path.join(path.dirname(__dirname), 'index.html'));
});
app.use(express.static(path.dirname(__dirname)));
// Warning: app.listen(8080) will not work here; see
// <https://github.com/socketio/socket.io/issues/2075>
server.listen(process.env.PORT || 8080, () => {
console.log(`Server started. Listening on port ${server.address().port}`);
});
export default server;
|
Add exit with status 1 on caught exception
Refactor | package ru.nsu.ccfit.bogush;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.nsu.ccfit.bogush.view.FactoryView;
public class Main {
private static final String CONFIG_FILE = "config.properties";
private static final String LOG_CONFIG_FILE = "log4j2.xml";
private static final String LOGGER_NAME = "Main";
private static final Logger logger;
static {
System.setProperty("log4j.configurationFile", LOG_CONFIG_FILE);
logger = LogManager.getLogger(LOGGER_NAME);
}
public static void main(String[] args) {
logger.trace("Launching application");
try {
logger.trace("Running prepare");
Config config = new ConfigSerializer().load(CONFIG_FILE);
new FactoryView(new CarFactoryModel(config));
} catch (Exception e) {
logger.fatal(e);
e.printStackTrace();
System.exit(1);
} finally {
logger.trace("Exiting");
}
}
}
| package ru.nsu.ccfit.bogush;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.nsu.ccfit.bogush.view.FactoryView;
public class Main {
private static final String CONFIG_FILE = "config.properties";
private static final String LOG_CONFIG_FILE = "log4j2.xml";
private static final String LOGGER_NAME = "Main";
private static final Logger logger;
static {
System.setProperty("log4j.configurationFile", LOG_CONFIG_FILE);
logger = LogManager.getLogger(LOGGER_NAME);
}
public static void main(String[] args) {
logger.trace("Launching application");
try {
logger.trace("Running prepare");
Config config = new ConfigSerializer().load(CONFIG_FILE);
new FactoryView(new CarFactoryModel(config));
} catch (Exception e) {
logger.fatal(e);
e.printStackTrace();
}
logger.trace("Exiting");
}
}
|
Fix typo accessing q's promise constructor | var q = require('q');
module.exports = {
waitFor: function(condition, timeout, frequency){
timeout = timeout || 1000
frequency = frequency || 10
return new q.promise(function(resolve, reject){
var timedout = false, it = setInterval(function(){
try {
condition()
resolve()
clearInterval(it)
} catch(e){
if(timedout) {
reject(e)
clearInterval(it)
}
}
}, frequency)
setTimeout(function(){
timedout=true
}, timeout)
})
},
justWait: function(timeout){
return new q.promise(function(resolve, reject){
setTimeout(resolve, timeout)
})
}
}
| var q = require('q');
module.exports = {
waitFor: function(condition, timeout, frequency){
timeout = timeout || 1000
frequency = frequency || 10
return new q.Promise(function(resolve, reject){
var timedout = false, it = setInterval(function(){
try {
condition()
resolve()
clearInterval(it)
} catch(e){
if(timedout) {
reject(e)
clearInterval(it)
}
}
}, frequency)
setTimeout(function(){
timedout=true
}, timeout)
})
},
justWait: function(timeout){
return new q.Promise(function(resolve, reject){
setTimeout(resolve, timeout)
})
}
}
|
Add example for 'styles' prop | import React from 'react';
import Notification from 'notification';
var View = React.createClass({
handleShow() {
console.log('Notification hidden:', false);
this.refs.notification.show();
},
handleHide() {
console.log('Notification hidden:', true);
this.refs.notification.hide();
},
handleNotificationActionClick() {
console.log('Notification action clicked:', true);
},
getNotificationStyles() {
var bar = {
background: '#263238'
};
var action = {
color: '#FFCCBC'
};
return { bar, action };
},
getInitialState() {
return {
message: 'Todo added',
action: 'Undo'
};
},
render() {
return (
<div>
<button onClick={this.handleShow}>Show</button>
<button onClick={this.handleHide}>Hide</button>
<Notification
ref="notification"
message={this.state.message}
action={this.state.action}
styles={this.getNotificationStyles()}
onClick={this.handleNotificationActionClick}/>
</div>
);
}
});
React.render(
<View />,
document.querySelector('main')
);
| import React from 'react';
import Notification from 'notification';
var View = React.createClass({
handleShow() {
console.log('Notification hidden:', false);
this.refs.notification.show();
},
handleHide() {
console.log('Notification hidden:', true);
this.refs.notification.hide();
},
handleNotificationActionClick() {
console.log('Notification action clicked:', true);
},
getInitialState() {
return {
message: 'Todo added',
action: 'Undo'
};
},
render() {
return (
<div>
<button onClick={this.handleShow}>Show</button>
<button onClick={this.handleHide}>Hide</button>
<Notification
ref="notification"
message={this.state.message}
action={this.state.action}
onClick={this.handleNotificationActionClick}/>
</div>
);
}
});
React.render(
<View />,
document.querySelector('main')
);
|
Use js instead of moment to parse date to avoid warning | // Generated by CoffeeScript 1.4.0
(function() {
var $;
$ = jQuery;
$(function() {});
if ($('th.default-sort').data()) {
$('table.sortable').tablesort().data('tablesort').sort($("th.default-sort"), "desc");
}
$('thead th.date').data('sortBy', function(th, td, tablesort) {
var tdTime = td.text().replace("-", "");
return moment.utc(new Date(tdTime)).unix();
});
$('input.filter-table').parent('div').removeClass('hide');
$("input.filter-table").on("keyup", function(e) {
var ev, rex;
rex = new RegExp($(this).val(), "i");
$(".searchable tr").hide();
$(".searchable tr").filter(function() {
return rex.test($(this).text());
}).show();
if (e.keyCode === 27) {
$(e.currentTarget).val("");
ev = $.Event("keyup");
ev.keyCode = 13;
$(e.currentTarget).trigger(ev);
return e.currentTarget.blur();
}
});
}).call(this);
| // Generated by CoffeeScript 1.4.0
(function() {
var $;
$ = jQuery;
$(function() {});
if ($('th.default-sort').data()) {
$('table.sortable').tablesort().data('tablesort').sort($("th.default-sort"), "desc");
}
$('thead th.date').data('sortBy', function(th, td, tablesort) {
var tdTime = td.text().replace("-", "");
return moment.utc(tdTime).unix();
});
$('input.filter-table').parent('div').removeClass('hide');
$("input.filter-table").on("keyup", function(e) {
var ev, rex;
rex = new RegExp($(this).val(), "i");
$(".searchable tr").hide();
$(".searchable tr").filter(function() {
return rex.test($(this).text());
}).show();
if (e.keyCode === 27) {
$(e.currentTarget).val("");
ev = $.Event("keyup");
ev.keyCode = 13;
$(e.currentTarget).trigger(ev);
return e.currentTarget.blur();
}
});
}).call(this);
|
Improve image size replacement regex | // Define search and replace terms for image src link
let search = /\/s[0-9]+/g;
let replace = 's512';
function getProfileImageContainer() {
// Get profile image containers
return $('#channel-header-container');
}
function getProfileImage(container) {
// Get profile image tag
return container.find('img');
}
function wrapEnlargeLink() {
// Get profile image link
let imageContainer = getProfileImageContainer();
// No image?
if (!imageContainer.length) {
return;
}
// Get img tag nested within container
let imageTag = getProfileImage(imageContainer);
// No tag?
if (!imageTag.length) {
return;
}
// Get image src URL
let src = imageTag.attr('src');
// Replace image pixel value in URL for a larger 512px image
src = src.replace(search, replace);
// Wrap image tag with a link that points to the larger image
$( imageTag ).wrap( "<a href='" + src + "' target='_blank'></a>" );
}
// One-time injection
wrapEnlargeLink(); | // Define search and replace terms for image src link
let search = /s[0-9]+/g;
let replace = 's512';
function getProfileImageContainer() {
// Get profile image containers
return $('#channel-header-container');
}
function getProfileImage(container) {
// Get profile image tag
return container.find('img');
}
function wrapEnlargeLink() {
// Get profile image link
let imageContainer = getProfileImageContainer();
// No image?
if (!imageContainer.length) {
return;
}
// Get img tag nested within container
let imageTag = getProfileImage(imageContainer);
// No tag?
if (!imageTag.length) {
return;
}
// Get image src URL
let src = imageTag.attr('src');
// Replace image pixel value in URL for a larger 512px image
src = src.replace(search, replace);
// Wrap image tag with a link that points to the larger image
$( imageTag ).wrap( "<a href='" + src + "' target='_blank'></a>" );
}
// One-time injection
wrapEnlargeLink(); |
Simplify js ready function (and make it work…) | function previousElementSibling( elem ) {
do {
elem = elem.previousSibling;
} while ( elem && elem.nodeType !== 1 );
return elem;
}
function pullPullQuotes(){
var pullquotes = document.getElementsByClassName('pullquote');
for (var i = 0; i < pullquotes.length; i++) {
var el = pullquotes[i];
for (var i = 0; i < 10; i++){
if (el.parentNode.nodeName == "P"){
var parentParagraph = el.parentNode;
break;
}
}
if (previousElementSibling(parentParagraph).nodeName == "P"){
parentParagraph = previousElementSibling(parentParagraph);
}
var newEl = el.cloneNode(true);
newEl.classList.add('pullquote--pulled');
newEl.classList.remove('pullquote');
parentParagraph.insertBefore(newEl, parentParagraph.firstChild);
}
}
document.addEventListener('DOMContentLoaded', pullPullQuotes());
| function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
function previousElementSibling( elem ) {
do {
elem = elem.previousSibling;
} while ( elem && elem.nodeType !== 1 );
return elem;
}
function pullPullQuotes(){
var pullquotes = document.getElementsByClassName('pullquote');
for (var i = 0; i < pullquotes.length; i++) {
var el = pullquotes[i];
for (var i = 0; i < 10; i++){
if (el.parentNode.nodeName == "P"){
var parentParagraph = el.parentNode;
break;
}
}
if (previousElementSibling(parentParagraph).nodeName == "P"){
parentParagraph = previousElementSibling(parentParagraph);
}
var newEl = el.cloneNode(true);
newEl.classList.add('pullquote--pulled');
newEl.classList.remove('pullquote');
parentParagraph.insertBefore(newEl, parentParagraph.firstChild);
}
}
ready(pullPullQuotes());
|
Add actionCreators option for window.devToolsExtension()
add counter actions & push action of `react-router-redux` | import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import { hashHistory } from 'react-router';
import { routerMiddleware, push } from 'react-router-redux';
import rootReducer from '../reducers';
import * as counterActions from '../actions/counter';
const actionCreators = {
...counterActions,
push,
};
const logger = createLogger({
level: 'info',
collapsed: true,
});
const router = routerMiddleware(hashHistory);
const enhancer = compose(
applyMiddleware(thunk, router, logger),
window.devToolsExtension ?
window.devToolsExtension({ actionCreators }) :
noop => noop
);
export default function configureStore(initialState) {
const store = createStore(rootReducer, initialState, enhancer);
if (module.hot) {
module.hot.accept('../reducers', () =>
store.replaceReducer(require('../reducers')) // eslint-disable-line global-require
);
}
return store;
}
| import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import { hashHistory } from 'react-router';
import { routerMiddleware } from 'react-router-redux';
import rootReducer from '../reducers';
const logger = createLogger({
level: 'info',
collapsed: true,
});
const router = routerMiddleware(hashHistory);
const enhancer = compose(
applyMiddleware(thunk, router, logger),
window.devToolsExtension ? window.devToolsExtension() : noop => noop
);
export default function configureStore(initialState) {
const store = createStore(rootReducer, initialState, enhancer);
if (module.hot) {
module.hot.accept('../reducers', () =>
store.replaceReducer(require('../reducers')) // eslint-disable-line global-require
);
}
return store;
}
|
Change event parameter name from `e` to `event`. | /**
* CreateAccountField component.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import {
Input,
TextField,
} from '../../../../material-components';
import classnames from 'classnames';
export default function CreateAccountField( {
hasError,
value,
setValue,
name,
label,
} ) {
if ( 'undefined' === typeof value ) {
return null;
}
return (
<TextField
className={ classnames(
'mdc-text-field',
{ 'mdc-text-field--error': hasError }
) }
label={ label }
name={ name }
onChange={ ( event ) => {
setValue( event.target.value, name );
} }
outlined
required
>
<Input
name={ name }
value={ value }
/>
</TextField>
);
}
| /**
* CreateAccountField component.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import {
Input,
TextField,
} from '../../../../material-components';
import classnames from 'classnames';
export default function CreateAccountField( {
hasError,
value,
setValue,
name,
label,
} ) {
if ( 'undefined' === typeof value ) {
return null;
}
return (
<TextField
className={ classnames(
'mdc-text-field',
{ 'mdc-text-field--error': hasError }
) }
label={ label }
name={ name }
onChange={ ( e ) => {
setValue( e.target.value, name );
} }
outlined
required
>
<Input
name={ name }
value={ value }
/>
</TextField>
);
}
|
Add test text finding that fails
This indicates that a different method of specifying how and where
to find text within a document is required. | import pytest
from web_test_base import *
"""
A class to test new features without running all of the tests.
Usage:
py.test tests/test_test.py -rsx
"""
class TestTest(WebTestBase):
urls_to_get = [
"http://iatistandard.org/"
, "http://iatistandard.org/202/namespaces-extensions/"
]
text_to_find = [
("technical publishing framework", '//*[@id="home-strapline"]/h1')
]
def test_locate_text(self, loaded_request, text_to_find):
"""
Tests that each page contains lthe specified text at the required location.
"""
result = self._get_text_from_xpath(loaded_request, text_to_find[1])
assert self._substring_in_list(text_to_find[0], result)
| import pytest
from web_test_base import *
"""
A class to test new features without running all of the tests.
Usage:
py.test tests/test_test.py -rsx
"""
class TestTest(WebTestBase):
urls_to_get = [
"http://aidtransparency.net/"
]
text_to_find = [
("information", '//*[@id="home-strapline"]/h1')
]
def test_locate_text(self, loaded_request, text_to_find):
"""
Tests that each page contains lthe specified text at the required location.
"""
result = self._get_text_from_xpath(loaded_request, text_to_find[1])
assert self._substring_in_list(text_to_find[0], result)
|
Remove spec for method MemberId::any, method was removed. | <?php
/**
* PHP version 5.6
*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
namespace specs\Ewallet\Accounts;
use Assert\InvalidArgumentException;
use Ewallet\Accounts\MemberId;
use PhpSpec\ObjectBehavior;
class MemberIdSpec extends ObjectBehavior
{
function it_should_be_created_from_a_string()
{
$this->beConstructedThrough('with', ['abcd']);
$this->value()->shouldBe('abcd');
}
function it_should_not_be_created_from_an_empty_string()
{
$this->beConstructedThrough('with', ['']);
$this
->shouldThrow(InvalidArgumentException::class)
->duringInstantiation()
;
}
function it_should_know_when_it_is_equal_to_another_id()
{
$this->beConstructedThrough('with', ['abcd']);
$this->equals(MemberId::with('abcd'))->shouldBe(true);
}
function it_should_be_casted_to_string()
{
$this->beConstructedThrough('with', ['abcd']);
$this->__toString()->shouldBe('abcd');
}
}
| <?php
/**
* PHP version 5.6
*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
namespace specs\Ewallet\Accounts;
use Assert\InvalidArgumentException;
use Ewallet\Accounts\MemberId;
use PhpSpec\ObjectBehavior;
class MemberIdSpec extends ObjectBehavior
{
function it_should_be_created_from_a_string()
{
$this->beConstructedThrough('with', ['abcd']);
$this->value()->shouldBe('abcd');
}
function it_should_be_created_randomly_using_any_non_empty_value()
{
$this->beConstructedThrough('any', []);
$this->value()->shouldNotBe('');
}
function it_should_not_be_created_from_an_empty_string()
{
$this->beConstructedThrough('with', ['']);
$this
->shouldThrow(InvalidArgumentException::class)
->duringInstantiation()
;
}
function it_should_know_when_it_is_equal_to_another_id()
{
$this->beConstructedThrough('with', ['abcd']);
$this->equals(MemberId::with('abcd'))->shouldBe(true);
}
function it_should_be_casted_to_string()
{
$this->beConstructedThrough('with', ['abcd']);
$this->__toString()->shouldBe('abcd');
}
}
|
Handle edge case with zero count | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
import copy
def isValid(s):
return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO"
def containsOnlyOneDifferentCharacterCount(string):
characterCounts = Counter(string)
if allOccurencesAreEqual(characterCounts):
return True
else:
# Try to remove one occurence of every character
for character in characterCounts:
characterCountWithOneRemovedCharacter = characterCounts.copy()
characterCountWithOneRemovedCharacter[character] -= 1
characterCountWithOneRemovedCharacter += Counter() # remove zero and negative counts
if allOccurencesAreEqual(characterCountWithOneRemovedCharacter):
return True
return False
def allOccurencesAreEqual(dict):
return len(set(dict.values())) == 1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = isValid(s)
fptr.write(result + '\n')
fptr.close()
| #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
def isValid(s):
return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO"
def containsOnlyOneDifferentCharacterCount(string):
characterCounts = Counter(string)
if allOccurencesAreEqual(characterCounts):
return True
else:
# Try to remove one occurence of every character
for character in characterCounts:
characterCountWithOneRemovedCharacter = dict.copy(characterCounts)
characterCountWithOneRemovedCharacter[character] -= 1
if allOccurencesAreEqual(characterCountWithOneRemovedCharacter):
return True
return False
def allOccurencesAreEqual(dict):
return len(set(dict.values())) == 1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = isValid(s)
fptr.write(result + '\n')
fptr.close()
|
Fix URLs so APPEND_SLASH works | from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3/
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit/
url(r'^(?P<week_id>[0-9]+)/submit/$', views.submit, name='submit'),
# eg: /footballseason/3/vote/
url(r'^(?P<week_id>[0-9]+)/vote/$', views.vote, name='vote'),
# eg: /footballseason/update/
url(r'^update/$', views.update, name='update'),
# eg: /footballseason/records/
url(r'^records/$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015/
url(r'^records/(?P<season>[0-9]+)/$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3/
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)/$', views.records_by_week, name='records_by_week'),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit
url(r'^(?P<week_id>[0-9]+)/submit$', views.submit, name='submit'),
# eg: /footballseason/3/vote
url(r'^(?P<week_id>[0-9]+)/vote$', views.vote, name='vote'),
# eg: /footballseason/update
url(r'^update$', views.update, name='update'),
# eg: /footballseason/records
url(r'^records$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015
url(r'^records/(?P<season>[0-9]+)$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)$', views.records_by_week, name='records_by_week'),
]
|
Fix some errors in stack trace printing.
Return $this for chaining. | <?php
class Metrodi_Proto {
protected $thing;
public function __construct($thing) {
$this->thing = $thing;
}
/**
* Intercept all function calls so there are no stopping errors.
* in DEV mode (_set('env', 'dev')) a trace will be emitted.
*/
public function __call($name, $args) {
//only show proto messages in dev mode
if (_get('env') != 'dev') {
return $this;
}
$bt = debug_backtrace();
if (!isset($bt[0]) ||
!array_key_exists('line', $bt[0])) {
return $this;
}
$line = $bt[0]['line'];
$file = $bt[0]['file'];
$bt = null;
$parts = explode(DIRECTORY_SEPARATOR, $file);
$fname = array_pop($parts);
$file = array_pop($parts).DIRECTORY_SEPARATOR.$fname;
echo("Called [".$name."] against proto object of type: ".$this->thing." from: ".$file." (".$line.").\n");
return $this;
}
public function __toString() {
return "Proto object of type: ".$this->thing.PHP_EOL;
}
}
| <?php
class Metrodi_Proto {
protected $thing;
public function __construct($thing) {
$this->thing = $thing;
}
/**
* Intercept all function calls so there are no stopping errors.
* in DEV mode (_set('env', 'dev')) a trace will be emitted.
*/
public function __call($name, $args) {
//only show proto messages in dev mode
if (_get('env') != 'dev') {
return;
}
$bt = debug_backtrace();
$line = $bt[0]['line'];
$file = $bt[0]['file'];
$bt = null;
$parts = explode(DIRECTORY_SEPARATOR, $file);
$fname = array_pop($parts);
$file = array_pop($parts).DIRECTORY_SEPARATOR.$fname;
var_dump("Called: ".$name." against proto object of type: ".$this->thing." from: ".$file." (".$line.").");
return $this;
}
public function __toString() {
return "Proto object of type: ".$this->thing.PHP_EOL;
}
}
|
Support async tests in the Jasmine helper | /* global jasmine:true, beforeEach:true, jsc:true, Promise:true */
/* eslint strict:[2,"function"] */
beforeEach(function () {
"use strict";
function message(r) {
return "Expected property to hold. Counterexample found: " + r.counterexamplestr;
}
jasmine.addMatchers({
toHold: function () {
return {
compare: function (actual, done) {
var r = jsc.check(actual);
if (done) {
Promise.resolve().then(function () { return r; }).then(function (v) {
if (v === true) {
done();
} else {
done.fail(message(v));
}
});
return {
pass: true,
};
}
return {
pass: r === true,
message: message(r),
};
},
};
},
});
});
| /* global jasmine:true, beforeEach:true, jsc:true */
/* eslint strict:[2,"function"] */
beforeEach(function () {
"use strict";
jasmine.addMatchers({
// Expects that property is synchronous
toHold: function () {
return {
compare: function (actual) {
/* global window */
var quiet = window && !(/verbose=true/).test(window.location.search);
var r = jsc.check(actual, { quiet: quiet });
var pass = r === true;
var message = "";
if (pass) {
message = "Expected property not to hold.";
} else {
message = "Expected property to hold. Counterexample found: " + r.counterexamplestr;
}
return {
pass: pass,
message: message,
};
},
};
},
});
});
|
[desk-tool] Add a note about keeping unused component for later reference | /**
*
*
*
*
*
*
*
* HEADSUP: This is not in use, but keep for later reference
*
*
*
*
*
*
*
*/
import PropTypes from 'prop-types'
import React from 'react'
import {diffJson} from 'diff'
import styles from './styles/Diff.css'
function getDiffStatKey(part) {
if (part.added) {
return 'added'
}
if (part.removed) {
return 'removed'
}
return 'neutral'
}
export default class Diff extends React.PureComponent {
static defaultProps = {
inputA: '',
inputB: ''
}
static propTypes = {
inputA: PropTypes.object,
inputB: PropTypes.object
}
render() {
const diff = diffJson(this.props.inputA, this.props.inputB)
return (
<pre>
{diff.map((part, index) => (
<span key={index} className={styles[getDiffStatKey(part)]}>{part.value}</span>
))}
</pre>
)
}
}
| import PropTypes from 'prop-types'
import React from 'react'
import {diffJson} from 'diff'
import styles from './styles/Diff.css'
function getDiffStatKey(part) {
if (part.added) {
return 'added'
}
if (part.removed) {
return 'removed'
}
return 'neutral'
}
export default class Diff extends React.PureComponent {
static defaultProps = {
inputA: '',
inputB: ''
}
static propTypes = {
inputA: PropTypes.object,
inputB: PropTypes.object
}
render() {
const diff = diffJson(this.props.inputA, this.props.inputB)
return (
<pre>
{diff.map((part, index) => (
<span key={index} className={styles[getDiffStatKey(part)]}>{part.value}</span>
))}
</pre>
)
}
}
|
Update script to show which file it is loading. | #!/usr/bin/env python
import json
import rethinkdb as r
import sys
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
parser.add_option("-f", "--file", dest="filename",
help="json file", type="string")
(options, args) = parser.parse_args()
if options.filename is None:
print "You must specify json file"
sys.exit(1)
conn = r.connect('localhost', int(options.port), db='materialscommons')
json_data = open(options.filename)
print "Loading template file: %s" % (options.filename)
data = json.load(json_data)
existing = r.table('templates').get(data['id']).run(conn)
if existing:
r.table('templates').get(data['id']).delete().run(conn)
r.table('templates').insert(data).run(conn)
print 'template deleted and re-inserted into the database'
else:
r.table('templates').insert(data).run(conn)
print 'template inserted into the database'
| #!/usr/bin/env python
import json
import rethinkdb as r
import sys
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
parser.add_option("-f", "--file", dest="filename",
help="json file", type="string")
(options, args) = parser.parse_args()
if options.filename is None:
print "You must specify json file"
sys.exit(1)
conn = r.connect('localhost', int(options.port), db='materialscommons')
json_data = open(options.filename)
data = json.load(json_data)
existing = r.table('templates').get(data['id']).run(conn)
if existing:
r.table('templates').get(data['id']).delete().run(conn)
r.table('templates').insert(data).run(conn)
print 'template deleted and re-inserted into the database'
else:
r.table('templates').insert(data).run(conn)
print 'template inserted into the database'
|
Change base model string representation | # -*- coding: UTF-8 -*-
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_repr(self):
self.generate_fixture_project_status()
self.generate_fixture_project()
self.assertEqual(str(self.project), "<Project %s>" % self.project.id)
def test_query(self):
pass
def test_get(self):
pass
def test_get_by(self):
pass
def test_get_all_by(self):
pass
def test_create(self):
pass
def test_get_id_map(self):
pass
def save(self):
pass
def delete(self):
pass
def update(self):
pass
| # -*- coding: UTF-8 -*-
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_repr(self):
self.generate_fixture_project_status()
self.generate_fixture_project()
self.assertEqual(str(self.project), "<Project Cosmos Landromat>")
self.project.name = u"Big Buck Bunny"
self.assertEqual(str(self.project), "<Project Big Buck Bunny>")
def test_query(self):
pass
def test_get(self):
pass
def test_get_by(self):
pass
def test_get_all_by(self):
pass
def test_create(self):
pass
def test_get_id_map(self):
pass
def save(self):
pass
def delete(self):
pass
def update(self):
pass
|
Use double quotes instead of single ones. | var gulp = require("gulp");
var tasks = [];
// Browserify
var browserify = require("browserify");
var vinylSourceStream = require("vinyl-source-stream");
var makeBrowserify = function(source, destination, output) {
gulp.task(output+"-browserify", function() {
bundler = browserify(source);
bundler.transform("brfs");
bundle = function() {
bundler.bundle()
.pipe(vinylSourceStream(output+".js"))
.pipe(gulp.dest(destination));
};
bundle();
});
tasks.push(output+"-browserify");
};
makeBrowserify("./api/index.js", "./public", "api");
// Watch
gulp.task("watch", function() {
gulp.watch(["./api/*"], ["api-browserify"]);
});
// All
gulp.task("default", tasks);
| var gulp = require('gulp');
var tasks = [];
// Browserify
var browserify = require('browserify');
var vinylSourceStream = require('vinyl-source-stream');
var makeBrowserify = function(source, destination, output) {
gulp.task(output+"-browserify", function() {
bundler = browserify(source);
bundler.transform('brfs');
bundle = function() {
bundler.bundle()
.pipe(vinylSourceStream(output+".js"))
.pipe(gulp.dest(destination));
};
bundle();
});
tasks.push(output+"-browserify");
};
makeBrowserify("./api/index.js", "./public", "api");
// Watch
gulp.task("watch", function() {
gulp.watch(["./api/*"], ["api-browserify"]);
});
// All
gulp.task('default', tasks);
|
Fix checkstyle issue: parameter constraintAnnotation hides field | package com.github.britter.beanvalidators.file;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ValidationException;
import java.io.File;
import java.lang.annotation.Annotation;
import org.apache.commons.lang3.StringUtils;
abstract class AbstractFileConstraintValidator<A extends Annotation> implements ConstraintValidator<A, Object> {
private Class<? extends Annotation> annotationType;
@Override
public void initialize(A constraintAnnotation) {
this.annotationType = constraintAnnotation.annotationType();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
if (value instanceof File) {
return isValid((File) value, context);
} else if (value instanceof String) {
String str = (String) value;
return StringUtils.isBlank(str) || isValid(new File(str), context);
} else {
throw new ValidationException("@" + annotationType.getSimpleName()
+ " can not be applied to instances of " + value.getClass());
}
}
public abstract boolean isValid(File value, ConstraintValidatorContext context);
}
| package com.github.britter.beanvalidators.file;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ValidationException;
import java.io.File;
import java.lang.annotation.Annotation;
import org.apache.commons.lang3.StringUtils;
abstract class AbstractFileConstraintValidator<A extends Annotation> implements ConstraintValidator<A, Object> {
private Class<? extends Annotation> constraintAnnotation;
@Override
public void initialize(A constraintAnnotation) {
this.constraintAnnotation = constraintAnnotation.annotationType();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
if (value instanceof File) {
return isValid((File) value, context);
} else if (value instanceof String) {
String str = (String) value;
return StringUtils.isBlank(str) || isValid(new File(str), context);
} else {
throw new ValidationException("@" + constraintAnnotation.getSimpleName()
+ " can not be applied to instances of " + value.getClass());
}
}
public abstract boolean isValid(File value, ConstraintValidatorContext context);
}
|
Improve the name of a local variable. Seems like copy/paste error | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package integration.glue;
import dom.simple.SimpleObject;
import org.apache.isis.core.specsupport.scenarios.InMemoryDB;
import org.apache.isis.core.specsupport.scenarios.ScenarioExecution;
public class InMemoryDBForSimpleApp extends InMemoryDB {
public InMemoryDBForSimpleApp(ScenarioExecution scenarioExecution) {
super(scenarioExecution);
}
/**
* Hook to initialize if possible.
*/
@Override
protected void init(Object obj, String str) {
if(obj instanceof SimpleObject) {
SimpleObject simpleObject = (SimpleObject) obj;
simpleObject.setName(str);
}
}
}
| /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package integration.glue;
import dom.simple.SimpleObject;
import org.apache.isis.core.specsupport.scenarios.InMemoryDB;
import org.apache.isis.core.specsupport.scenarios.ScenarioExecution;
public class InMemoryDBForSimpleApp extends InMemoryDB {
public InMemoryDBForSimpleApp(ScenarioExecution scenarioExecution) {
super(scenarioExecution);
}
/**
* Hook to initialize if possible.
*/
@Override
protected void init(Object obj, String str) {
if(obj instanceof SimpleObject) {
SimpleObject toDoItem = (SimpleObject) obj;
toDoItem.setName(str);
}
}
} |
Use 2 solenoids instead of 1. Also have startExpand and startRetract instead of just one. | package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.commands.RunFrisbeeDumperSolenoid;
import edu.wpi.first.wpilibj.templates.variablestores.VstM;
/**
*
* @author daboross
*/
public class FrisbeeDumperSolenoid extends Subsystem {
private Solenoid solenoid1, solenoid2;
public FrisbeeDumperSolenoid() {
System.out.println("SubSystem Created: FrisbeeDumperSolenoid");
solenoid1 = new Solenoid(VstM.SOLENOID.FRISBEE_DUMP_1);
solenoid1.set(false);
solenoid2 = new Solenoid(VstM.SOLENOID.FRISBEE_DUMP_2);
solenoid2.set(false);
}
protected void initDefaultCommand() {
setDefaultCommand(new RunFrisbeeDumperSolenoid());
}
public void startExpand() {
solenoid1.set(true);
solenoid1.set(false);
}
public void startRetract(){
solenoid2.set(true);
solenoid1.set(false);
}
}
| package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.commands.RunFrisbeeDumperSolenoid;
import edu.wpi.first.wpilibj.templates.variablestores.VstM;
/**
*
* @author daboross
*/
public class FrisbeeDumperSolenoid extends Subsystem {
private Solenoid solenoid;
public FrisbeeDumperSolenoid() {
System.out.println("SubSystem Created: FrisbeeDumperSolenoid");
solenoid = new Solenoid(VstM.SOLENOID.FRISBEE_DUMP);
solenoid.set(false);
}
protected void initDefaultCommand() {
setDefaultCommand(new RunFrisbeeDumperSolenoid());
}
public void startExpand() {
solenoid.set(true);
}
}
|
Make static PYISH_OBJECT_WRITER public so it can be used in PyishSerializable overrides | package com.hubspot.jinjava.objects.serialization;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.hubspot.jinjava.util.WhitespaceUtils;
import java.util.Objects;
public class PyishObjectMapper {
public static final ObjectWriter PYISH_OBJECT_WRITER = new ObjectMapper()
.registerModule(
new SimpleModule()
.setSerializerModifier(PyishBeanSerializerModifier.INSTANCE)
.addSerializer(PyishSerializable.class, PyishSerializer.INSTANCE)
)
.writer(PyishPrettyPrinter.INSTANCE)
.with(PyishCharacterEscapes.INSTANCE);
public static String getAsUnquotedPyishString(Object val) {
if (val != null) {
return WhitespaceUtils.unquoteAndUnescape(getAsPyishString(val));
}
return "";
}
public static String getAsPyishString(Object val) {
try {
return PYISH_OBJECT_WRITER
.writeValueAsString(val)
.replace("'", "\\'")
// Replace double-quotes with single quote as they are preferred in Jinja
.replaceAll("(?<!\\\\)(\\\\\\\\)*(?:\")", "$1'");
} catch (JsonProcessingException e) {
return Objects.toString(val, "");
}
}
}
| package com.hubspot.jinjava.objects.serialization;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.hubspot.jinjava.util.WhitespaceUtils;
import java.util.Objects;
public class PyishObjectMapper {
private static final ObjectWriter PYISH_OBJECT_WRITER = new ObjectMapper()
.registerModule(
new SimpleModule()
.setSerializerModifier(PyishBeanSerializerModifier.INSTANCE)
.addSerializer(PyishSerializable.class, PyishSerializer.INSTANCE)
)
.writer(PyishPrettyPrinter.INSTANCE)
.with(PyishCharacterEscapes.INSTANCE);
public static String getAsUnquotedPyishString(Object val) {
if (val != null) {
return WhitespaceUtils.unquoteAndUnescape(getAsPyishString(val));
}
return "";
}
public static String getAsPyishString(Object val) {
try {
return PYISH_OBJECT_WRITER
.writeValueAsString(val)
.replace("'", "\\'")
// Replace double-quotes with single quote as they are preferred in Jinja
.replaceAll("(?<!\\\\)(\\\\\\\\)*(?:\")", "$1'");
} catch (JsonProcessingException e) {
return Objects.toString(val, "");
}
}
}
|
Remove user key from generated databases.json file | 'use strict';
// Node.js core.
const execSync = require('child_process').execSync;
const path = require('path');
// Logger.
const logger = require('strapi-utils').logger;
module.exports = (scope, success, error) => {
const knex = require(path.resolve(`${scope.rootPath}/node_modules/knex`))({
client: scope.client.module,
connection: Object.assign({}, scope.database.settings, {
user: scope.database.settings.username
})
});
knex.raw('select 1+1 as result').then(() => {
logger.info('The app has been connected to the database successfully');
knex.destroy();
execSync(`rm -r ${scope.rootPath}`);
logger.info('Copying the dashboard...');
success();
})
.catch(() => {
logger.warn('Database connection has failed! Make sure your database is running.');
error();
});
};
| 'use strict';
// Node.js core.
const execSync = require('child_process').execSync;
const path = require('path');
// Logger.
const logger = require('strapi-utils').logger;
module.exports = (scope, success, error) => {
const knex = require(path.resolve(`${scope.rootPath}/node_modules/knex`))({
client: scope.client.module,
connection: Object.assign(scope.database.settings, {
user: scope.database.settings.username
})
});
knex.raw('select 1+1 as result').then(() => {
logger.info('The app has been connected to the database successfully');
knex.destroy();
execSync(`rm -r ${scope.rootPath}`);
logger.info('Copying the dashboard...');
success();
})
.catch(() => {
logger.warn('Database connection has failed! Make sure your database is running.');
error();
});
};
|
Remove unexisting $attrs provider + unused itemScope parameter | (function () {
'use strict';
angular.module('ui.nestedSortable')
.controller('NestedSortableController', ['$scope', 'nestedSortableConfig',
function ($scope, nestedSortableConfig) {
$scope.sortableElement = null;
$scope.sortableModelValue = null;
$scope.callbacks = null;
$scope.items = [];
$scope.initSortable = function(element) {
$scope.sortableElement = element;
};
$scope.insertSortableItem = function(index, itemModelData) {
console.log($scope.sortableModelValue);
$scope.sortableModelValue.splice(index, 0, itemModelData);
$scope.$apply();
};
$scope.initSubItemElement = function(subElement) {
subElement.parentScope = $scope;
};
$scope.parentItemScope = function() {
return $scope.sortableElement.parentItemScope;
};
}
]);
})(); | (function () {
'use strict';
angular.module('ui.nestedSortable')
.controller('NestedSortableController', ['$scope', '$attrs', 'nestedSortableConfig',
function ($scope, $attrs, nestedSortableConfig) {
$scope.sortableElement = null;
$scope.sortableModelValue = null;
$scope.callbacks = null;
$scope.items = [];
$scope.initSortable = function(element) {
$scope.sortableElement = element;
};
$scope.insertSortableItem = function(index, itemModelData, itemScope) {
$scope.sortableModelValue.splice(index, 0, itemModelData);
$scope.$apply();
};
$scope.initSubItemElement = function(subElement) {
subElement.parentScope = $scope;
};
$scope.parentItemScope = function() {
return $scope.sortableElement.parentItemScope;
};
}
]);
})(); |
Use the default access value when creating a project | <?php
/**
* @package hubzero-cms
* @copyright Copyright 2005-2019 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
// No direct access
defined('_HZEXEC_') or die();
?>
<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
<input type="hidden" name="alias" value="<?php echo $this->model->get('alias'); ?>" />
<input type="hidden" name="pid" id="pid" value="<?php echo $this->model->get('id'); ?>" />
<input type="hidden" name="controller" value="<?php echo $this->controller; ?>" />
<input type="hidden" name="task" value="save" />
<input type="hidden" name="setup" id="insetup" value="<?php echo $this->model->inSetup() ? 1 : 0; ?>" />
<input type="hidden" name="active" value="<?php echo $this->section; ?>" />
<input type="hidden" name="access" value="<?php echo $this->model->get('access'); ?>" />
<input type="hidden" name="step" id="step" value="<?php echo $this->step; ?>" />
<input type="hidden" name="gid" value="<?php echo $this->model->get('owned_by_group') ? $this->model->get('owned_by_group') : 0; ?>" />
<?php echo Html::input('token'); ?>
<?php echo Html::input('honeypot'); | <?php
/**
* @package hubzero-cms
* @copyright Copyright 2005-2019 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
// No direct access
defined('_HZEXEC_') or die();
?>
<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
<input type="hidden" name="alias" value="<?php echo $this->model->get('alias'); ?>" />
<input type="hidden" name="pid" id="pid" value="<?php echo $this->model->get('id'); ?>" />
<input type="hidden" name="controller" value="<?php echo $this->controller; ?>" />
<input type="hidden" name="task" value="save" />
<input type="hidden" name="setup" id="insetup" value="<?php echo $this->model->inSetup() ? 1 : 0; ?>" />
<input type="hidden" name="active" value="<?php echo $this->section; ?>" />
<input type="hidden" name="step" id="step" value="<?php echo $this->step; ?>" />
<input type="hidden" name="gid" value="<?php echo $this->model->get('owned_by_group') ? $this->model->get('owned_by_group') : 0; ?>" />
<?php echo Html::input('token'); ?>
<?php echo Html::input('honeypot'); |
Switch to courses instead of enrollments - MUWM-457 | from restclients.canvas import Canvas
from myuw_mobile.dao.pws import Person
from myuw_mobile.logger.timer import Timer
from myuw_mobile.logger.logback import log_resp_time, log_exception
import logging
import traceback
class Enrollments:
def get_enrollments(self):
"""
Returns calendar information for the current term.
"""
timer = Timer()
logger = logging.getLogger('myuw_mobile.dao.canvas.Enrollments')
try:
regid = Person().get_regid()
return Canvas().get_courses_for_regid(regid)
except Exception as ex:
log_exception(logger,
'canvas.get_enrollments',
traceback.format_exc())
finally:
log_resp_time(logger,
'canvas.get_enrollments',
timer)
return []
| from restclients.canvas import Canvas
from myuw_mobile.dao.pws import Person
from myuw_mobile.logger.timer import Timer
from myuw_mobile.logger.logback import log_resp_time, log_exception
import logging
import traceback
class Enrollments:
def get_enrollments(self):
"""
Returns calendar information for the current term.
"""
timer = Timer()
logger = logging.getLogger('myuw_mobile.dao.canvas.Enrollments')
try:
regid = Person().get_regid()
return Canvas().get_enrollments_for_regid(regid)
except Exception as ex:
log_exception(logger,
'canvas.get_enrollments',
traceback.format_exc())
finally:
log_resp_time(logger,
'canvas.get_enrollments',
timer)
return []
|
Fix test for PHP 5.4 | <?php
namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;
use Doctrine\MongoDB\GridFSFile;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
class GH832Test extends \Doctrine\ODM\MongoDB\Tests\BaseTest
{
/**
* @expectedException MongoGridFSException
*/
public function testGridFSWithUniqueIndex()
{
$doc = new GH832Document();
$this->dm->getSchemaManager()->ensureDocumentIndexes(get_class($doc));
$docA = new GH832Document();
$docA->unique = 'foo';
$docA->file = new GridFSFile(__FILE__);
$this->dm->persist($docA);
$this->dm->flush();
$this->dm->clear();
$docB = new GH832Document();
$docB->unique = 'foo';
$docB->file = new GridFSFile(__FILE__);
$this->dm->persist($docB);
$this->dm->flush();
$this->dm->clear();
}
}
/** @ODM\Document */
class GH832Document
{
const CLASSNAME = __CLASS__;
/** @ODM\Id */
public $id;
/** @ODM\File */
public $file;
/**
* @ODM\String
* @ODM\UniqueIndex
*/
public $unique;
}
| <?php
namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;
use Doctrine\MongoDB\GridFSFile;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
class GH832Test extends \Doctrine\ODM\MongoDB\Tests\BaseTest
{
/**
* @expectedException MongoGridFSException
*/
public function testGridFSWithUniqueIndex()
{
$this->dm->getSchemaManager()->ensureDocumentIndexes(GH832Document::CLASS);
$docA = new GH832Document();
$docA->unique = 'foo';
$docA->file = new GridFSFile(__FILE__);
$this->dm->persist($docA);
$this->dm->flush();
$this->dm->clear();
$docB = new GH832Document();
$docB->unique = 'foo';
$docB->file = new GridFSFile(__FILE__);
$this->dm->persist($docB);
$this->dm->flush();
$this->dm->clear();
}
}
/** @ODM\Document */
class GH832Document
{
const CLASSNAME = __CLASS__;
/** @ODM\Id */
public $id;
/** @ODM\File */
public $file;
/**
* @ODM\String
* @ODM\UniqueIndex
*/
public $unique;
}
|
Reduce contention during lifecycle tracking | /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.bootstrap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
class LifeCycleMethodsMap
{
private final Map<Class<?>, LifeCycleMethods> map = new ConcurrentHashMap<>();
public LifeCycleMethods get(Class<?> clazz)
{
return map.computeIfAbsent(clazz, LifeCycleMethods::new);
}
}
| /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.bootstrap;
import com.google.common.collect.Maps;
import java.util.Map;
class LifeCycleMethodsMap
{
private final Map<Class<?>, LifeCycleMethods> map = Maps.newHashMap();
synchronized LifeCycleMethods get(Class<?> clazz)
{
LifeCycleMethods methods = map.get(clazz);
if (methods == null) {
methods = new LifeCycleMethods(clazz);
map.put(clazz, methods);
}
return methods;
}
}
|
Switch Django version from 1.0 to 1.1 | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
| """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.0')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
|
Fix the db tag of model.Route | package model
import "regexp"
type Route struct {
Id int64 `json:"-"`
Name string `json:"name"`
Pattern string `json:"pattern"`
Broker string `json:"broker"`
From string `json:"from" db:"fromName"`
IsActive bool `json:"is_active" db:"isActive"`
broker Broker
regex *regexp.Regexp
}
func NewRoute(name, pattern string, broker Broker, isActive bool) *Route {
return &Route{
Name: name,
Pattern: pattern,
Broker: broker.Name(),
IsActive: isActive,
broker: broker,
regex: regexp.MustCompile(pattern),
}
}
func (r *Route) SetBroker(broker Broker) *Route {
r.broker = broker
return r
}
func (r *Route) GetBroker() Broker {
return r.broker
}
func (r *Route) SetFrom(from string) *Route {
r.From = from
return r
}
func (r *Route) Match(recipient string) bool {
return r.IsActive && r.regex.MatchString(recipient)
}
| package model
import "regexp"
type Route struct {
Id int64 `json:"-"`
Name string `json:"name"`
Pattern string `json:"pattern"`
Broker string `json:"broker"`
From string `json:"from" db:"fromName"`
IsActive bool `json:"is_active"`
broker Broker
regex *regexp.Regexp
}
func NewRoute(name, pattern string, broker Broker, isActive bool) *Route {
return &Route{
Name: name,
Pattern: pattern,
Broker: broker.Name(),
IsActive: isActive,
broker: broker,
regex: regexp.MustCompile(pattern),
}
}
func (r *Route) SetBroker(broker Broker) *Route {
r.broker = broker
return r
}
func (r *Route) GetBroker() Broker {
return r.broker
}
func (r *Route) SetFrom(from string) *Route {
r.From = from
return r
}
func (r *Route) Match(recipient string) bool {
return r.IsActive && r.regex.MatchString(recipient)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.