text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Replace host with explicit component name
On browsers where the ShadowRoot class is polyfilled, the :host selector
fails to function and needs to be replaced with the current
webcomponent's name.
Fix #1224 | /**
* BaseComponent
*
* A base webcomponent class.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
class BaseComponent extends HTMLElement {
constructor(template) {
super();
this.attachShadow({mode: 'open'});
const templateClone = template.content.cloneNode(true);
// Detect whether ShadowRoot has been polyfilled on this browser
if (ShadowRoot.name !== 'ShadowRoot') {
const tagName = this.shadowRoot.host.tagName;
templateClone.querySelectorAll('style').forEach((style) => {
style.innerHTML = style.innerHTML.replace(/:host/g, tagName);
});
}
this.shadowRoot.appendChild(templateClone);
}
connectedCallback() {
}
disconnectedCallback() {
}
_upgradeProperty(prop) {
if (this.hasOwnProperty(prop)) {
const value = this[prop];
delete this[prop];
this[prop] = value;
}
if (this.hasAttribute(prop)) {
this[prop] = this.getAttribute(prop);
}
}
}
module.exports = BaseComponent;
| /**
* BaseComponent
*
* A base webcomponent class.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
class BaseComponent extends HTMLElement {
constructor(template) {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
}
disconnectedCallback() {
}
_upgradeProperty(prop) {
if (this.hasOwnProperty(prop)) {
const value = this[prop];
delete this[prop];
this[prop] = value;
}
if (this.hasAttribute(prop)) {
this[prop] = this.getAttribute(prop);
}
}
}
module.exports = BaseComponent;
|
Revert "Fix alert beep on osx" | const React = require('react')
const Search = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
handleQueryChange: React.PropTypes.func.isRequired,
},
getInitialState () {
return {
input: null,
}
},
focus () {
this.state.input && this.state.input.focus()
},
componentDidMount () {
this.focus()
},
componentDidUpdate () {
if (this.props.value === '') {
this.focus()
}
},
handleQueryChange (event) {
const query = event.target.value
this.props.handleQueryChange(query)
},
setReference (input) {
this.setState({
input,
})
},
render () {
const { value } = this.props
return (
<input
title='Search Zazu'
className='mousetrap'
ref={this.setReference}
type='text'
onChange={this.handleQueryChange}
value={value}/>
)
},
})
module.exports = Search
| const React = require('react')
const Search = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
handleQueryChange: React.PropTypes.func.isRequired,
},
getInitialState () {
return {
input: null,
}
},
focus () {
this.state.input && this.state.input.focus()
},
componentDidMount () {
this.focus()
},
componentDidUpdate () {
if (this.props.value === '') {
this.focus()
}
},
handleKeyPress (event) {
if (event.keyCode === 13 && event.keyCode === 27) {
return false
}
},
handleQueryChange (event) {
const query = event.target.value
this.props.handleQueryChange(query)
},
setReference (input) {
this.setState({
input,
})
},
render () {
const { value } = this.props
return (
<input
title='Search Zazu'
className='mousetrap'
ref={this.setReference}
type='text'
onKeyPress={this.handleKeyPress}
onChange={this.handleQueryChange}
value={value}/>
)
},
})
module.exports = Search
|
Change to display username if there is no name | import './style/UserMiniCard.scss';
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import userPlaceholder from '../assets/userPlaceholder.png';
export default class UserMiniCard extends Component {
render() {
const { user, hideUsername, hideName } = this.props;
// Why are we using div tag instead of span?
// Double clicking selects everything including near span tags.
// display: inline-block doesn't.
return (
<div className='user-mini-card'>
<Link to={`/${user.username}`}>
<div className='photo'>
<img src={user.photo || userPlaceholder} />
</div>
{ !hideName ? (
<div className='name'>
{user.name || user.username}
</div>
) : false }
{ !hideUsername ? (
<div className='username'>
{user.username}
</div>
) : false }
</Link>
</div>
);
}
}
UserMiniCard.propTypes = {
user: PropTypes.object.isRequired,
hideUsername: PropTypes.bool,
hideName: PropTypes.bool
};
| import './style/UserMiniCard.scss';
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import userPlaceholder from '../assets/userPlaceholder.png';
export default class UserMiniCard extends Component {
render() {
const { user, hideUsername, hideName } = this.props;
// Why are we using div tag instead of span?
// Double clicking selects everything including near span tags.
// display: inline-block doesn't.
return (
<div className='user-mini-card'>
<Link to={`/${user.username}`}>
<div className='photo'>
<img src={user.photo || userPlaceholder} />
</div>
{ !hideName ? (
<div className='name'>
{user.name}
</div>
) : false }
{ !hideUsername ? (
<div className='username'>
{user.username}
</div>
) : false }
</Link>
</div>
);
}
}
UserMiniCard.propTypes = {
user: PropTypes.object.isRequired,
hideUsername: PropTypes.bool,
hideName: PropTypes.bool
};
|
Add Pygments as installation requirement | from setuptools import setup, find_packages
setup(
name='snippets',
version='0.0.dev',
license='ISC',
description='Code snippets repository generator',
url='https://github.com/trilan/snippets',
author='Mike Yumatov',
author_email='mike@yumatov.org',
packages=find_packages(),
install_requires=[
'Pygments',
],
classifiers=[
'Development Status :: 1 - Planning',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
| from setuptools import setup, find_packages
setup(
name='snippets',
version='0.0.dev',
license='ISC',
description='Code snippets repository generator',
url='https://github.com/trilan/snippets',
author='Mike Yumatov',
author_email='mike@yumatov.org',
packages=find_packages(),
classifiers=[
'Development Status :: 1 - Planning',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
],
)
|
Return a plain object to support Babel 6 | import { AST_Node, Compressor, TreeWalker } from 'uglify-js';
var compressor = Compressor();
class LocationFixer extends TreeWalker {
constructor(path) {
var filename = path.hub.file.opts.filenameRelative;
super(node => {
node.start.file = node.end.file = filename;
});
}
}
export default ({ types: t }) => ({
visitor: {
Program(ast) {
// Convert to UglifyJS AST
var uAST = AST_Node.from_mozilla_ast(ast);
// Fix locations (Babel doesn't insert `loc.source` into nodes for some reason)
uAST.walk(new LocationFixer(this));
// Compress
uAST.figure_out_scope();
uAST = uAST.transform(compressor);
// Mangle names
uAST.figure_out_scope();
uAST.compute_char_frequency();
uAST.mangle_names();
// Convert back to ESTree AST
return uAST.to_mozilla_ast();
}
}
});
| import { AST_Node, Compressor, TreeWalker } from 'uglify-js';
var compressor = Compressor();
class LocationFixer extends TreeWalker {
constructor(path) {
var filename = path.hub.file.opts.filenameRelative;
super(node => {
node.start.file = node.end.file = filename;
});
}
}
export default ({ Plugin, types: t }) => new Plugin('uglify', {
visitor: {
Program(ast) {
// Convert to UglifyJS AST
var uAST = AST_Node.from_mozilla_ast(ast);
// Fix locations (Babel doesn't insert `loc.source` into nodes for some reason)
uAST.walk(new LocationFixer(this));
// Compress
uAST.figure_out_scope();
uAST = uAST.transform(compressor);
// Mangle names
uAST.figure_out_scope();
uAST.compute_char_frequency();
uAST.mangle_names();
// Convert back to ESTree AST
return uAST.to_mozilla_ast();
}
}
});
|
Add configure call to random_agent | #!/usr/bin/env python
import argparse
import logging
import sys
import gym
import universe # register the universe environments
from universe import wrappers
logger = logging.getLogger()
def main():
parser = argparse.ArgumentParser(description=None)
parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help='Set verbosity.')
args = parser.parse_args()
if args.verbosity == 0:
logger.setLevel(logging.INFO)
elif args.verbosity >= 1:
logger.setLevel(logging.DEBUG)
env = gym.make('flashgames.NeonRace-v0')
env.configure(remotes=1) # automatically creates a local docker container
# Restrict the valid random actions. (Try removing this and see
# what happens when the agent is given full control of the
# keyboard/mouse.)
env = wrappers.SafeActionSpace(env)
observation_n = env.reset()
while True:
# your agent here
#
# Try sending this instead of a random action: ('KeyEvent', 'ArrowUp', True)
action_n = [env.action_space.sample() for ob in observation_n]
observation_n, reward_n, done_n, info = env.step(action_n)
env.render()
return 0
if __name__ == '__main__':
sys.exit(main())
| #!/usr/bin/env python
import argparse
import logging
import sys
import gym
import universe # register the universe environments
from universe import wrappers
logger = logging.getLogger()
def main():
parser = argparse.ArgumentParser(description=None)
parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help='Set verbosity.')
args = parser.parse_args()
if args.verbosity == 0:
logger.setLevel(logging.INFO)
elif args.verbosity >= 1:
logger.setLevel(logging.DEBUG)
env = gym.make('flashgames.NeonRace-v0')
# Restrict the valid random actions. (Try removing this and see
# what happens when the agent is given full control of the
# keyboard/mouse.)
env = wrappers.SafeActionSpace(env)
observation_n = env.reset()
while True:
# your agent here
#
# Try sending this instead of a random action: ('KeyEvent', 'ArrowUp', True)
action_n = [env.action_space.sample() for ob in observation_n]
observation_n, reward_n, done_n, info = env.step(action_n)
env.render()
return 0
if __name__ == '__main__':
sys.exit(main())
|
Fix typo @JsonProperty(state) -> @JsonProperty(status) | package com.cisco.trex.stateless.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class L2Configuration {
@JsonProperty("dst")
private String dst;
@JsonProperty("src")
private String src;
@JsonProperty("status")
private String state;
@JsonProperty("dst")
public String getDst() {
return dst;
}
@JsonProperty("dst")
public void setDst(String dst) {
this.dst = dst;
}
@JsonProperty("src")
public String getSrc() {
return src;
}
@JsonProperty("src")
public void setSrc(String src) {
this.src = src;
}
@JsonProperty("status")
public String getStatus() {
return state;
}
@JsonProperty("status")
public void setStatus(String status) {
this.state = status;
}
}
| package com.cisco.trex.stateless.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class L2Configuration {
@JsonProperty("dst")
private String dst;
@JsonProperty("src")
private String src;
@JsonProperty("status")
private String state;
@JsonProperty("dst")
public String getDst() {
return dst;
}
@JsonProperty("dst")
public void setDst(String dst) {
this.dst = dst;
}
@JsonProperty("src")
public String getSrc() {
return src;
}
@JsonProperty("src")
public void setSrc(String src) {
this.src = src;
}
@JsonProperty("status")
public String getStatus() {
return state;
}
@JsonProperty("state")
public void setStatus(String status) {
this.state = status;
}
}
|
Add interface for Datastore items | /*
* 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.
*/
package com.google.vinet.data;
/**
* Any class that can be stored and loaded from Datastore. The implementing class must also provide
* a constructor for loading an object from a Datastore entity.
*/
public interface Datastoreable {
/**
* Store this class instance to Datastore.
<<<<<<< HEAD
*
* @throws IllegalArgumentException If the entity was incomplete.
* @throws java.util.ConcurrentModificationException If the entity group to which the entity belongs was modified concurrently.
* @throws com.google.appengine.api.datastore.DatastoreFailureException If any other datastore error occurs.
=======
>>>>>>> Add interface for Datastore items
*/
void toDatastore();
}
| /*
* 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.
*/
package com.google.vinet.data;
/**
* Any class that can be stored and loaded from Datastore. The implementing class must also provide
* a constructor for loading an object from a Datastore entity.
*/
public interface Datastoreable {
/**
* Store this class instance to Datastore.
*
* @throws IllegalArgumentException If the entity was incomplete.
* @throws java.util.ConcurrentModificationException If the entity group to which the entity belongs was modified concurrently.
* @throws com.google.appengine.api.datastore.DatastoreFailureException If any other datastore error occurs.
*/
void toDatastore();
}
|
Add a sample of erroneous test. | # -*- encoding: utf-8 -*-
"""
"""
import unittest
import time
class Case1(unittest.TestCase):
def test_success(self):
time.sleep(0.5)
self.assertEqual(1, 1)
def test_failure(self):
time.sleep(0.5)
self.assertEqual(1, 2)
@unittest.skip("because")
def test_skip(self):
time.sleep(0.1)
self.assertFalse(True)
@unittest.expectedFailure
def test_expected_failure(self):
time.sleep(0.1)
self.assertEqual(1, 0, "broken")
@unittest.expectedFailure
def test_unexpected_success(self):
time.sleep(0.1)
self.assertEqual(1, 1, "not broken after all")
def test_error(self):
raise RuntimeError("error raised for testing purpose")
class Case2(unittest.TestCase):
def test_success(self):
self.assertTrue(True)
class EmptyCase(unittest.TestCase):
pass
| # -*- encoding: utf-8 -*-
"""
"""
import unittest
import time
class Case1(unittest.TestCase):
def test_success(self):
time.sleep(0.5)
self.assertEqual(1, 1)
def test_failure(self):
time.sleep(0.5)
self.assertEqual(1, 2)
@unittest.skip("because")
def test_skip(self):
time.sleep(0.1)
self.assertFalse(True)
@unittest.expectedFailure
def test_expected_failure(self):
time.sleep(0.1)
self.assertEqual(1, 0, "broken")
@unittest.expectedFailure
def test_unexpected_success(self):
time.sleep(0.1)
self.assertEqual(1, 1, "not broken after all")
class Case2(unittest.TestCase):
def test_success(self):
self.assertTrue(True)
class EmptyCase(unittest.TestCase):
pass
|
Rename version field in Choice to question_id | from django.db import models
from rest_framework import serializers
class Question(models.Model):
version = models.CharField(primary_key=True, max_length=8)
text = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Choice(models.Model):
text = models.TextField()
question_id = models.ForeignKey(Question, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Answer(models.Model):
choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
user_id = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = ('id', 'text', 'version', 'created_on', 'updated_on',)
class QuestionSerializer(serializers.ModelSerializer):
# TODO: create a serializer that returns list of choices for the question
class Meta:
model = Question
fields = ('text', 'version', 'created_on', 'updated_on',)
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('id', 'choice_id', 'user_id', 'created_on',)
| from django.db import models
from rest_framework import serializers
class Question(models.Model):
version = models.CharField(primary_key=True, max_length=8)
text = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Choice(models.Model):
text = models.TextField()
version = models.ForeignKey(Question, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Answer(models.Model):
choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
user_id = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = ('id', 'text', 'version', 'created_on', 'updated_on',)
class QuestionSerializer(serializers.ModelSerializer):
# TODO: create a serializer that returns list of choices for the question
class Meta:
model = Question
fields = ('text', 'version', 'created_on', 'updated_on',)
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('id', 'choice_id', 'user_id', 'created_on',)
|
Put secretballot's Git repository instead of using the release | from setuptools import setup, find_packages
setup(
name='django-likes',
version='0.1',
description='Django app providing view interface to django-secretballot.',
long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekelt.com',
license='BSD',
url='http://github.com/praekelt/django-likes',
packages = find_packages(),
include_package_data=True,
install_requires = [
'git+https://github.com/sunlightlabs/django-secretballot.git',
],
tests_require=[
'django-setuptest>=0.0.6',
],
test_suite="setuptest.setuptest.SetupTestSuite",
classifiers = [
"Programming Language :: Python",
"License :: OSI Approved :: BSD License",
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"Framework :: Django",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
],
zip_safe=False,
)
| from setuptools import setup, find_packages
setup(
name='django-likes',
version='0.1',
description='Django app providing view interface to django-secretballot.',
long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekelt.com',
license='BSD',
url='http://github.com/praekelt/django-likes',
packages = find_packages(),
include_package_data=True,
install_requires = [
'django-secretballot',
],
tests_require=[
'django-setuptest>=0.0.6',
],
test_suite="setuptest.setuptest.SetupTestSuite",
classifiers = [
"Programming Language :: Python",
"License :: OSI Approved :: BSD License",
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"Framework :: Django",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
],
zip_safe=False,
)
|
Change ct default revision name to v1
https://github.com/rancher/rancher/issues/22162 | import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { hash } from 'rsvp';
export default Route.extend({
globalStore: service(),
access: service(),
clusterTemplates: service(),
model() {
return hash({
clusterTemplate: this.globalStore.createRecord({ type: 'clustertemplate', }),
clusterTemplateRevision: this.globalStore.createRecord({
name: 'v1',
type: 'clusterTemplateRevision',
enabled: true,
clusterConfig: this.globalStore.createRecord({
type: 'clusterSpecBase',
rancherKubernetesEngineConfig: this.globalStore.createRecord({ type: 'rancherKubernetesEngineConfig' })
})
}),
psps: this.globalStore.findAll('podSecurityPolicyTemplate'),
users: this.globalStore.findAll('user'),
});
},
afterModel(model, transition) {
if (transition.from && transition.from.name === 'global-admin.clusters.index') {
this.controllerFor(this.routeName).set('parentRoute', transition.from.name);
}
return this.clusterTemplates.fetchQuestionsSchema();
},
});
| import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { hash } from 'rsvp';
export default Route.extend({
globalStore: service(),
access: service(),
clusterTemplates: service(),
model() {
return hash({
clusterTemplate: this.globalStore.createRecord({ type: 'clustertemplate', }),
clusterTemplateRevision: this.globalStore.createRecord({
name: 'first-revision',
type: 'clusterTemplateRevision',
enabled: true,
clusterConfig: this.globalStore.createRecord({
type: 'clusterSpecBase',
rancherKubernetesEngineConfig: this.globalStore.createRecord({ type: 'rancherKubernetesEngineConfig' })
})
}),
psps: this.globalStore.findAll('podSecurityPolicyTemplate'),
users: this.globalStore.findAll('user'),
});
},
afterModel(model, transition) {
if (transition.from && transition.from.name === 'global-admin.clusters.index') {
this.controllerFor(this.routeName).set('parentRoute', transition.from.name);
}
return this.clusterTemplates.fetchQuestionsSchema();
},
});
|
Add originally raised exception value to pytest error message | import re
import py.code
import pytest
def pytest_namespace():
return {'raises_regexp': raises_regexp}
class raises_regexp(object):
def __init__(self, expected_exception, regexp):
self.exception = expected_exception
self.regexp = regexp
self.excinfo = None
def __enter__(self):
self.excinfo = object.__new__(py.code.ExceptionInfo)
return self.excinfo
def __exit__(self, exc_type, exc_val, exc_tb):
__tracebackhide__ = True
if exc_type is None:
pytest.fail('DID NOT RAISE %s' % self.exception)
self.excinfo.__init__((exc_type, exc_val, exc_tb))
if not issubclass(exc_type, self.exception):
pytest.fail('%s RAISED instead of %s\n%s' % (exc_type, self.exception, repr(exc_val)))
if not re.search(self.regexp, str(exc_val)):
pytest.fail('pattern "%s" not found in "%s"' % (self.regexp, str(exc_val)))
return True
| import re
import py.code
import pytest
def pytest_namespace():
return {'raises_regexp': raises_regexp}
class raises_regexp(object):
def __init__(self, expected_exception, regexp):
self.exception = expected_exception
self.regexp = regexp
self.excinfo = None
def __enter__(self):
self.excinfo = object.__new__(py.code.ExceptionInfo)
return self.excinfo
def __exit__(self, exc_type, exc_val, exc_tb):
__tracebackhide__ = True
if exc_type is None:
pytest.fail('DID NOT RAISE %s' % self.exception)
self.excinfo.__init__((exc_type, exc_val, exc_tb))
if not issubclass(exc_type, self.exception):
pytest.fail('%s RAISED instead of %s' % (exc_type, self.exception))
if not re.search(self.regexp, str(exc_val)):
pytest.fail('pattern "%s" not found in "%s"' % (self.regexp, str(exc_val)))
return True
|
Update package imports for module name change. | # Copyright (c) 2013 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''Yet another OpenGL-and-physics simulator framework !'''
from . import physics
from .log import enable_default_logging, get_logger
from .world import Viewer, World
import plac
def call(main):
'''Enable logging and start up a main method.'''
enable_default_logging()
plac.call(main)
args = plac.annotations
| # Copyright (c) 2013 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''Yet another OpenGL-and-physics simulator framework !'''
from . import ode
from .log import enable_default_logging, get_logger
from .ode import make_quaternion
from .world import Viewer, World
import plac
def call(main):
'''Enable logging and start up a main method.'''
enable_default_logging()
plac.call(main)
args = plac.annotations
|
Add method to retrieve unvalidated evaluations | <?php
namespace Project\AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* EvaluationRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class EvaluationRepository extends EntityRepository
{
public function findAllBySpeaker($speakerId)
{
return $this->getEntityManager()
->createQuery(
'SELECT e
FROM ProjectAppBundle:Evaluation e
WHERE e.speaker = :speaker'
)
->setParameter('speaker', $speakerId)
->getResult();
}
public function findAllUnvalidatedByPromotion($promotionId)
{
return $this->getEntityManager()
->createQuery(
'SELECT e
FROM ProjectAppBundle:Evaluation e
LEFT JOIN e.module m
LEFT JOIN m.promotion p
WHERE p.id = :promotion
AND e.validated = 0'
)
->setParameter('promotion', $promotionId)
->getResult();
}
}
| <?php
namespace Project\AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* EvaluationRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class EvaluationRepository extends EntityRepository
{
public function findAllBySpeaker($speakerId)
{
return $this->getEntityManager()
->createQuery(
'SELECT e
FROM ProjectAppBundle:Evaluation e
WHERE e.speaker = :speaker'
)
->setParameter('speaker', $speakerId)
->getResult();
}
}
|
Use the new existing file helper with forge in the generation data now | package info.u_team.u_team_core.data;
import java.util.function.*;
import net.minecraft.data.*;
import net.minecraftforge.common.data.ExistingFileHelper;
import net.minecraftforge.fml.event.lifecycle.GatherDataEvent;
public class GenerationData {
private final String modid;
private final DataGenerator generator;
private final ExistingFileHelper existingFileHelper;
private CommonBlockTagsProvider blockTagsProvider;
public GenerationData(String modid, GatherDataEvent event) {
this(modid, event.getGenerator(), new ExistingFileHelperWithForge(event.getExistingFileHelper()));
}
public GenerationData(String modid, DataGenerator generator, ExistingFileHelper existingFileHelper) {
this.modid = modid;
this.generator = generator;
this.existingFileHelper = existingFileHelper;
}
public String getModid() {
return modid;
}
public DataGenerator getGenerator() {
return generator;
}
public ExistingFileHelper getExistingFileHelper() {
return existingFileHelper;
}
public void addProvider(Function<GenerationData, IDataProvider> function) {
final IDataProvider provider = function.apply(this);
if (provider instanceof CommonBlockTagsProvider) {
blockTagsProvider = (CommonBlockTagsProvider) provider;
}
generator.addProvider(provider);
}
public void addProvider(BiFunction<GenerationData, CommonBlockTagsProvider, IDataProvider> function) {
generator.addProvider(function.apply(this, blockTagsProvider));
}
}
| package info.u_team.u_team_core.data;
import java.util.function.*;
import net.minecraft.data.*;
import net.minecraftforge.common.data.ExistingFileHelper;
import net.minecraftforge.fml.event.lifecycle.GatherDataEvent;
public class GenerationData {
private final String modid;
private final DataGenerator generator;
private final ExistingFileHelper existingFileHelper;
private CommonBlockTagsProvider blockTagsProvider;
public GenerationData(String modid, GatherDataEvent event) {
this(modid, event.getGenerator(), event.getExistingFileHelper());
}
public GenerationData(String modid, DataGenerator generator, ExistingFileHelper existingFileHelper) {
this.modid = modid;
this.generator = generator;
this.existingFileHelper = existingFileHelper;
}
public String getModid() {
return modid;
}
public DataGenerator getGenerator() {
return generator;
}
public ExistingFileHelper getExistingFileHelper() {
return existingFileHelper;
}
public void addProvider(Function<GenerationData, IDataProvider> function) {
final IDataProvider provider = function.apply(this);
if (provider instanceof CommonBlockTagsProvider) {
blockTagsProvider = (CommonBlockTagsProvider) provider;
}
generator.addProvider(provider);
}
public void addProvider(BiFunction<GenerationData, CommonBlockTagsProvider, IDataProvider> function) {
generator.addProvider(function.apply(this, blockTagsProvider));
}
}
|
Make FormUI text fields output their classes properly. As the formcontrol class is always set, we can probably take out the test entirely, which would make the templates much more readable.
git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@3638 653ae4dd-d31e-0410-96ef-6bf7bf53c507 | <div<?php echo isset( $class ) ? " class=\"$class\"" : ''; ?><? echo isset( $id ) ? " id=\"$id\"" : ''; ?>>
<label<?php if ( isset( $label_title ) ) { ?> title="<?php echo $label_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> for="<?php echo $field; ?>"><?php echo $this->caption; ?></label>
<input<?php if ( isset( $control_title ) ) { ?> title="<?php echo $control_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> type="text" id="<?php echo $field; ?>" name="<?php echo $field; ?>" value="<?php echo htmlspecialchars( $value ); ?>">
<?php $control->errors_out( '<li>%s</li>', '<ul class="error">%s</ul>' ); ?>
</div>
| <div<?php echo isset( $class ) ? " class=\"$class\"" : '' . isset( $id ) ? " id=\"$id\"" : ''; ?>>
<label<?php if ( isset( $label_title ) ) { ?> title="<?php echo $label_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> for="<?php echo $field; ?>"><?php echo $this->caption; ?></label>
<input<?php if ( isset( $control_title ) ) { ?> title="<?php echo $control_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> type="text" id="<?php echo $field; ?>" name="<?php echo $field; ?>" value="<?php echo htmlspecialchars( $value ); ?>">
<?php $control->errors_out( '<li>%s</li>', '<ul class="error">%s</ul>' ); ?>
</div>
|
Add prefer-rest-params to Node preset | 'use strict'
module.exports = {
extends: './base.js',
plugins: [
'node'
],
rules: {
'node/no-unsupported-features': 'error',
'template-curly-spacing': ['error', 'always'],
'prefer-arrow-callback': 'error',
'no-dupe-class-members': 'error',
'no-this-before-super': 'error',
'prefer-rest-params': 'error',
'constructor-super': 'error',
'object-shorthand': 'error',
'no-const-assign': 'error',
'no-new-symbol': 'error',
'require-yield': 'error',
'arrow-spacing': 'error',
'arrow-parens': ['error', 'as-needed'],
'prefer-const': 'error',
'strict': ['error', 'global'],
'no-var': 'error'
},
env: {
es6: true
},
parserOptions: {
sourceType: 'script'
}
}
| 'use strict'
module.exports = {
extends: './base.js',
plugins: [
'node'
],
rules: {
'node/no-unsupported-features': 'error',
'template-curly-spacing': ['error', 'always'],
'prefer-arrow-callback': 'error',
'no-dupe-class-members': 'error',
'no-this-before-super': 'error',
'constructor-super': 'error',
'object-shorthand': 'error',
'no-const-assign': 'error',
'no-new-symbol': 'error',
'require-yield': 'error',
'arrow-spacing': 'error',
'arrow-parens': ['error', 'as-needed'],
'prefer-const': 'error',
'strict': ['error', 'global'],
'no-var': 'error'
},
env: {
es6: true
},
parserOptions: {
sourceType: 'script'
}
}
|
Add ability to increase debug level through multiple instances of flag | import argparse
import json
from os import path
import pinder
from twisted.words import service
rooms = {}
irc_users = {}
if path.exists(path.expanduser('~') + '/.luckystrike/config.json'):
with open(path.expanduser('~') + '/.luckystrike/config.json') as config_file:
configuration = dict(json.loads(config_file.read()))
else:
with open('config.json') as config_file:
configuration = dict(json.loads(config_file.read()))
users = configuration['users']
parser = argparse.ArgumentParser(description='Campfire to IRC Proxy')
parser.add_argument(
'-d', '--debug',
action='count',
help='add debug logging, add multiple times to increase level'
)
parser.add_argument(
'-s', '--setup_config',
action='store_true',
help='generate config.json'
)
args = parser.parse_args()
# connect to Campfire
campfire = pinder.Campfire(configuration['domain'], configuration['api_key'])
# Initialize the Cred authentication system used by the IRC server.
irc_realm = service.InMemoryWordsRealm('LuckyStrike')
| import argparse
import json
from os import path
import pinder
from twisted.words import service
rooms = {}
irc_users = {}
if path.exists(path.expanduser('~') + '/.luckystrike/config.json'):
with open(path.expanduser('~') + '/.luckystrike/config.json') as config_file:
configuration = dict(json.loads(config_file.read()))
else:
with open('config.json') as config_file:
configuration = dict(json.loads(config_file.read()))
users = configuration['users']
parser = argparse.ArgumentParser(description='Campfire to IRC Proxy')
parser.add_argument(
'-d', '--debug',
action='store_true',
help='increase debug level'
)
parser.add_argument(
'-s', '--setup_config',
action='store_true',
help='generate config.json'
)
args = parser.parse_args()
# connect to Campfire
campfire = pinder.Campfire(configuration['domain'], configuration['api_key'])
# Initialize the Cred authentication system used by the IRC server.
irc_realm = service.InMemoryWordsRealm('LuckyStrike')
|
Use SelfAttribute instead of explicit lambda | # -*- coding: utf-8 -*-
# Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
import factory
from factory.faker import Faker
from pycroft.model.user import User
from .base import BaseFactory
from .facilities import RoomFactory
from .finance import AccountFactory
class UserFactory(BaseFactory):
class Meta:
model = User
login = Faker('user_name')
name = Faker('name')
registered_at = Faker('date_time')
password = Faker('password')
email = Faker('email')
account = factory.SubFactory(AccountFactory, type="USER_ASSET")
room = factory.SubFactory(RoomFactory)
address = factory.SelfAttribute('room.address')
class UserWithHostFactory(UserFactory):
host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner')
| # -*- coding: utf-8 -*-
# Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
import factory
from factory.faker import Faker
from pycroft.model.user import User
from .base import BaseFactory
from .facilities import RoomFactory
from .finance import AccountFactory
class UserFactory(BaseFactory):
class Meta:
model = User
login = Faker('user_name')
name = Faker('name')
registered_at = Faker('date_time')
password = Faker('password')
email = Faker('email')
account = factory.SubFactory(AccountFactory, type="USER_ASSET")
room = factory.SubFactory(RoomFactory)
address = factory.LazyAttribute(lambda o: o.room.address)
class UserWithHostFactory(UserFactory):
host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner')
|
Fix off-by-1 bug for `mid`
- in SPOJ palin
Signed-off-by: Karel Ha <70f8965fdfb04f1fc0e708a55d9e822c449f57d3@gmail.com> | #!/usr/bin/env python3
def next_palindrome(k):
palin = list(k)
n = len(k)
mid = n // 2
# case 1: forward right
just_copy = False
for i in range(mid, n):
mirrored = n - 1 - i
if k[i] < k[mirrored]:
just_copy = True
if just_copy:
palin[i] = palin[mirrored]
# case 2: backward left
if not just_copy:
i = (n - 1) // 2
while i >= 0 and k[i] == '9':
i -= 1
if i >= 0:
palin[i] = str(int(k[i]) + 1)
for j in range(i + 1, mid):
palin[j] = '0'
for j in range(mid, n):
mirrored = n - 1 - j
palin[j] = palin[mirrored]
else:
# case 3: "99...9" -> "100..01"
palin = ['0'] * (n + 1)
palin[0] = palin[-1] = '1'
return ''.join(palin)
if __name__ == '__main__':
t = int(input())
for _ in range(t):
k = input()
print(next_palindrome(k))
| #!/usr/bin/env python3
def next_palindrome(k):
palin = list(k)
n = len(k)
mid = n // 2
# case 1: forward right
just_copy = False
for i in range(mid, n):
mirrored = n - 1 - i
if k[i] < k[mirrored]:
just_copy = True
if just_copy:
palin[i] = palin[mirrored]
# case 2: backward left
if not just_copy:
i = (n - 1) // 2
while i >= 0 and k[i] == '9':
i -= 1
if i >= 0:
palin[i] = str(int(k[i]) + 1)
for j in range(i + 1, mid + 1):
palin[j] = '0'
for j in range(mid + 1, n):
mirrored = n - 1 - j
palin[j] = palin[mirrored]
else:
# case 3: "99...9" -> "100..01"
palin = ['0'] * (n + 1)
palin[0] = palin[-1] = '1'
return ''.join(palin)
if __name__ == '__main__':
t = int(input())
for _ in range(t):
k = input()
print(next_palindrome(k))
|
Add a details field in the events table. | <?php
namespace Application\Model;
// This class contains all data of an entity of the view referencing all event's properties.
class ViewEvent
{
public $type;
public $fileLogo;
public $id;
public $date;
public $message;
public $details;
public $username;
public $linkedEntityId;
public $isTaskEvent;
public function exchangeArray($data)
{
$this->type = (!empty($data['type'])) ? $data['type'] : null;
$this->fileLogo = (!empty($data['fileLogo'])) ? $data['fileLogo'] : null;
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->date = (!empty($data['date'])) ? $data['date'] : null;
$this->message = (!empty($data['message'])) ? $data['message'] : null;
$this->details = (!empty($data['details'])) ? $data['details'] : null;
$this->username = (!empty($data['username'])) ? $data['username'] : null;
$this->linkedEntityId = (!empty($data['linkedEntityId'])) ? $data['linkedEntityId'] : null;
$this->isTaskEvent = (!empty($data['isTaskEvent'])) ? $data['isTaskEvent'] : null;
}
}
| <?php
namespace Application\Model;
// This class contains all data of an entity of the view referencing all event's properties.
class ViewEvent
{
public $type;
public $fileLogo;
public $id;
public $date;
public $message;
public $username;
public $linkedEntityId;
public $isTaskEvent;
public function exchangeArray($data)
{
$this->type = (!empty($data['type'])) ? $data['type'] : null;
$this->fileLogo = (!empty($data['fileLogo'])) ? $data['fileLogo'] : null;
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->date = (!empty($data['date'])) ? $data['date'] : null;
$this->message = (!empty($data['message'])) ? $data['message'] : null;
$this->username = (!empty($data['username'])) ? $data['username'] : null;
$this->linkedEntityId = (!empty($data['linkedEntityId'])) ? $data['linkedEntityId'] : null;
$this->isTaskEvent = (!empty($data['isTaskEvent'])) ? $data['isTaskEvent'] : null;
}
}
|
Add SECRET_KEY which is required by Django 1.5. | import os
from settings import *
SECRET_KEY = "test_secret"
# This needs to point at the test riak buckets.
VUMI_API_CONFIG['riak_manager'] = {'bucket_prefix': 'test.'}
VUMI_API_CONFIG['redis_manager'] = {
'key_prefix': 'test',
'FAKE_REDIS': 'sure',
}
if os.environ.get('VUMIGO_FAST_TESTS'):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
NOSE_ARGS = ['-evumitools', '-evumi_app', '-ehandlers', '-m^test']
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'
# disable console logging to avoid log messages messing up test output
LOGGING['loggers']['go']['handlers'].remove('console')
| import os
from settings import *
# This needs to point at the test riak buckets.
VUMI_API_CONFIG['riak_manager'] = {'bucket_prefix': 'test.'}
VUMI_API_CONFIG['redis_manager'] = {
'key_prefix': 'test',
'FAKE_REDIS': 'sure',
}
if os.environ.get('VUMIGO_FAST_TESTS'):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
NOSE_ARGS = ['-evumitools', '-evumi_app', '-ehandlers', '-m^test']
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'
# disable console logging to avoid log messages messing up test output
LOGGING['loggers']['go']['handlers'].remove('console')
|
Add numpy.round to model api | # -*- coding: utf-8 -*-
from datetime import date # noqa analysis:ignore
from numpy import ( # noqa analysis:ignore
logical_not as not_,
maximum as max_,
minimum as min_,
round as round_,
select,
where,
)
from .columns import ( # noqa analysis:ignore
AgeCol,
BoolCol,
DateCol,
EnumCol,
FixedStrCol,
FloatCol,
IntCol,
PeriodSizeIndependentIntCol,
StrCol,
)
from .enumerations import Enum # noqa analysis:ignore
from .formulas import ( # noqa analysis:ignore
ADD,
calculate_output_add,
calculate_output_divide,
dated_function,
DIVIDE,
set_input_dispatch_by_period,
set_input_divide_by_period,
missing_value
)
from .base_functions import ( # noqa analysis:ignore
requested_period_added_value,
requested_period_default_value,
requested_period_last_or_next_value,
requested_period_last_value,
)
from .variables import DatedVariable, Variable # noqa analysis:ignore
from .formula_helpers import apply_thresholds, switch # noqa analysis:ignore
from .periods import MONTH, YEAR, ETERNITY # noqa analysis:ignore
from .reforms import Reform # noqa analysis:ignore
| # -*- coding: utf-8 -*-
from datetime import date # noqa analysis:ignore
from numpy import maximum as max_, minimum as min_, logical_not as not_, where, select # noqa analysis:ignore
from .columns import ( # noqa analysis:ignore
AgeCol,
BoolCol,
DateCol,
EnumCol,
FixedStrCol,
FloatCol,
IntCol,
PeriodSizeIndependentIntCol,
StrCol,
)
from .enumerations import Enum # noqa analysis:ignore
from .formulas import ( # noqa analysis:ignore
ADD,
calculate_output_add,
calculate_output_divide,
dated_function,
DIVIDE,
set_input_dispatch_by_period,
set_input_divide_by_period,
missing_value
)
from .base_functions import ( # noqa analysis:ignore
requested_period_added_value,
requested_period_default_value,
requested_period_last_or_next_value,
requested_period_last_value,
)
from .variables import DatedVariable, Variable # noqa analysis:ignore
from .formula_helpers import apply_thresholds, switch # noqa analysis:ignore
from .periods import MONTH, YEAR, ETERNITY # noqa analysis:ignore
from .reforms import Reform # noqa analysis:ignore
|
Add help text for cute | import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@client.command()
async def cute(ctx, user: discord.Member = None):
"""
Tell someone they are cute!
Tells a user that you think they are cute, if you don't give a user, then Yutu will let you know that you are cute.
"""
if user is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = user
post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
if __name__ == "__main__":
with open("cfg.json") as fh:
token = json.load(fh)['token']
client.run(token)
| import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@client.command()
async def cute(ctx, member: discord.Member = None):
if member is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = member
post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first, second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post)
if __name__ == "__main__":
with open("cfg.json") as fh:
token = json.load(fh)['token']
client.run(token)
|
Fix wrong table preferrence for role_user | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(config('auth.table'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
|
Make it a kata, all tests fail. | // 36: Symbol.keyFor - retrieves a shared symbol key from the global symbol registry
// To do: make all tests pass, leave the assert lines unchanged!
describe('`Symbol.keyFor` gets the symbol key for a given symbol', function() {
const sym = Symbol.for('foo');
it('pass the symbol to `keyFor()` and you get it`s key', function() {
const key = Symbol.____(sym);
assert.equal(key, 'foo');
});
it('local symbols are not in the runtime-wide registry', function() {
// hint: `Symbol()` creates a local symbol!
const localSymbol = Symbol.for('foo');
const key = Symbol.keyFor(localSymbol);
assert.equal(key, void 0);
});
it('well-known symbols are not in the runtime-wide registry either', function() {
const key = Symbol.keyFor(Symbol.iteraTor);
assert.equal(key, void 0);
});
it('for non-Symbols throws an error', function() {
function fn() {
Symbol.keyFor(sym);
}
assert.throws(fn);
});
}); | // 36: Symbol.keyFor - retrieves a shared symbol key from the global symbol registry
// To do: make all tests pass, leave the assert lines unchanged!
describe('`Symbol.keyFor` gets the symbol key for a given symbol', function() {
it('pass the symbol to `keyFor()` and you get it`s key', function() {
const sym = Symbol.for('foo');
const key = Symbol.keyFor(sym);
assert.equal(key, 'foo');
});
it('local symbols are not in the runtime-wide registry', function() {
const localSymbol = Symbol('foo');
const key = Symbol.keyFor(localSymbol);
assert.equal(key, void 0);
});
it('well-known symbols are not in the runtime-wide registry either', function() {
const key = Symbol.keyFor(Symbol.iterator);
assert.equal(key, void 0);
});
it('for non-Symbols throws an error', function() {
function fn() {
Symbol.keyFor(null);
}
assert.throws(fn);
});
}); |
Fix non-iobj campaign request connection | from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .consumers import PRESENCE_ROOM
from .models import Campaign
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, ident = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
if not ident:
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
provider = campaign.get_provider()
iobj = provider.connect_request(ident, sender)
broadcast_request_made(provider, iobj)
def broadcast_request_made(provider, iobj):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
PRESENCE_ROOM.format(provider.campaign.id), {
"type": "request_made",
"data": provider.get_detail_data(iobj)
}
)
| from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .consumers import PRESENCE_ROOM
from .models import Campaign
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, ident = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
provider = campaign.get_provider()
iobj = provider.connect_request(ident, sender)
broadcast_request_made(provider, iobj)
def broadcast_request_made(provider, iobj):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
PRESENCE_ROOM.format(provider.campaign.id), {
"type": "request_made",
"data": provider.get_detail_data(iobj)
}
)
|
Clone bounds, don't share them! | package com.opensymphony.workflow.designer;
import java.awt.*;
import javax.swing.*;
import org.jgraph.graph.DefaultGraphCell;
import org.jgraph.graph.GraphConstants;
import org.jgraph.graph.AttributeMap;
/**
* @author Harsh Vijaywargiya Mar 9, 2003 1:04:57 PM
*/
public class WorkflowCell extends DefaultGraphCell
{
public static final Rectangle defaultBounds = new Rectangle(10, 10, 100, 30);
protected int id;
protected String name;
/**
* @param cellName
*/
public WorkflowCell(Object cellName)
{
super(cellName);
GraphConstants.setBounds(attributes, (Rectangle)defaultBounds.clone());
GraphConstants.setOpaque(attributes, true);
GraphConstants.setBackground(attributes, Color.blue.darker());
GraphConstants.setForeground(attributes, Color.white);
GraphConstants.setBorder(attributes, BorderFactory.createRaisedBevelBorder());
GraphConstants.setEditable(attributes, false);
GraphConstants.setVerticalAlignment(attributes, SwingConstants.TOP);
//GraphConstants.setFont(attributes, GraphConstants.defaultFont.deriveFont(Font.BOLD, 12));
}
/**
* Returns the mId.
* @return int
*/
public int getId()
{
return id;
}
/**
* Returns the mName.
* @return String
*/
public String getName()
{
return name;
}
}
| package com.opensymphony.workflow.designer;
import java.awt.*;
import javax.swing.*;
import org.jgraph.graph.DefaultGraphCell;
import org.jgraph.graph.GraphConstants;
/**
* @author Harsh Vijaywargiya Mar 9, 2003 1:04:57 PM
*/
public class WorkflowCell extends DefaultGraphCell
{
public static final Rectangle defaultBounds = new Rectangle(10, 10, 100, 30);
protected int id;
protected String name;
/**
* @param cellName
*/
public WorkflowCell(Object cellName)
{
super(cellName);
GraphConstants.setBounds(attributes, defaultBounds);
GraphConstants.setOpaque(attributes, true);
GraphConstants.setBackground(attributes, Color.blue.darker());
GraphConstants.setForeground(attributes, Color.white);
GraphConstants.setBorder(attributes, BorderFactory.createRaisedBevelBorder());
GraphConstants.setEditable(attributes, false);
GraphConstants.setVerticalAlignment(attributes, SwingConstants.TOP);
//GraphConstants.setFont(attributes, GraphConstants.defaultFont.deriveFont(Font.BOLD, 12));
}
/**
* Returns the mId.
* @return int
*/
public int getId()
{
return id;
}
/**
* Returns the mName.
* @return String
*/
public String getName()
{
return name;
}
}
|
Add caching for get neighbors method | function Cell(row, col, value, board) {
this.row = row,
this.col = col,
this.value = value,
this.board = board
}
Cell.prototype.find = function(word, visited=new Set(), wordIndex=0) {
if(visited.has(this)) return null;
word = word.toUpperCase();
var die = this.value;
var letter = word[wordIndex];
if(wordIndex === word.length - 1) {
if(die !== letter) return null;
visited.add(this);
return visited;
}
if(die === letter) {
visited.add(this);
var neighbors = this.getNeighbors(this.row, this.col);
var pass = neighbors.some(function(cell, index) {
return cell.find(word, visited, wordIndex + 1)
}, this);
if(pass) return visited;
}
visited.delete(this);
return null;
};
Cell.prototype.getNeighbors = function() {
if(this.neighbors) return this.neighbors;
this.neighbors = [];
var i = -1;
while(i <= 1) {
var j = -1;
var row = this.row + i;
while(j <= 1) {
var col = this.col + j++;
var neighbor = this.board.cell(row, col);
if(neighbor) this.neighbors.push(neighbor);
}
i++;
}
return this.neighbors;
};
module.exports = Cell;
| function Cell(row, col, value, board) {
this.row = row,
this.col = col,
this.value = value,
this.board = board
}
Cell.prototype.find = function(word, visited=new Set(), wordIndex=0) {
if(visited.has(this)) return null;
word = word.toUpperCase();
var die = this.value;
var letter = word[wordIndex];
if(wordIndex === word.length - 1) {
if(die !== letter) return null;
visited.add(this);
return visited;
}
if(die === letter) {
visited.add(this);
var neighbors = this.getNeighbors(this.row, this.col);
var pass = neighbors.some(function(cell, index) {
return cell.find(word, visited, wordIndex + 1)
}, this);
if(pass) return visited;
}
visited.delete(this);
return null;
};
Cell.prototype.getNeighbors = function() {
var neighbors = [];
var i = -1;
while(i <= 1) {
var j = -1;
var row = this.row + i;
while(j <= 1) {
var col = this.col + j++;
var neighbor = this.board.cell(row, col);
if(neighbor) neighbors.push(neighbor);
}
i++;
}
return neighbors;
};
module.exports = Cell;
|
Fix file path to check | <?php
/**
* First stage loader
*
* Here we get things started by ensuring the PHP version we're running on
* is supported by the app. We'll display a friendly error page if not.
*
* Next, we'll check if the script is being run with PHP's built in web
* server, and make sure static assets are handled gracefully.
*
* Last but not least, we pass things off to the second stage loader
*/
/**
* Version must be greater than 5.3.3.
* See: https://github.com/bolt/bolt/issues/1531
*/
if (version_compare(PHP_VERSION, '5.3.3', '<')) {
require __DIR__ . '/legacy.php';
return false;
}
/**
* Return false if the requested file is available on the filesystem.
* See: http://silex.sensiolabs.org/doc/web_servers.html#php-5-4
*/
if (php_sapi_name() == 'cli-server') {
$filename = dirname(__DIR__) . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (is_file($filename)) {
return false;
}
}
/**
* Bring in the second stage loader.
*/
return require_once __DIR__ . '/bootstrap.php';
| <?php
/**
* First stage loader
*
* Here we get things started by ensuring the PHP version we're running on
* is supported by the app. We'll display a friendly error page if not.
*
* Next, we'll check if the script is being run with PHP's built in web
* server, and make sure static assets are handled gracefully.
*
* Last but not least, we pass things off to the second stage loader
*/
/**
* Version must be greater than 5.3.3.
* See: https://github.com/bolt/bolt/issues/1531
*/
if (version_compare(PHP_VERSION, '5.3.3', '<')) {
require __DIR__ . '/legacy.php';
return false;
}
/**
* Return false if the requested file is available on the filesystem.
* See: http://silex.sensiolabs.org/doc/web_servers.html#php-5-4
*/
if (php_sapi_name() == 'cli-server') {
$filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (is_file($filename)) {
return false;
}
}
/**
* Bring in the second stage loader.
*/
return require_once __DIR__ . '/bootstrap.php';
|
Fix import path for url utilities. | from django.conf.urls import url, patterns
urlpatterns = patterns('',
url(r'^$', 'invite.views.index', name='index'),
url(r'^invite/$', 'invite.views.invite', name='invite'),
url(r'^resend/(?P<code>.*)/$', 'invite.views.resend', name='resend'),
url(r'^revoke/(?P<code>.*)/$', 'invite.views.revoke', name='revoke'),
url(r'^login/$', 'invite.views.log_in_user', name='login'),
url(r'^logout/$', 'invite.views.log_out_user', name='edit_logout'),
url(r'^amnesia/$', 'invite.views.amnesia', name='amnesia'),
url(r'^reset/$', 'invite.views.reset', name="reset"),
url(r'^signup/$', 'invite.views.signup', name="account_signup"),
url(r'^about/$', 'invite.views.about', name="about"),
)
| from django.conf.urls.defaults import url, patterns
urlpatterns = patterns('',
url(r'^$', 'invite.views.index', name='index'),
url(r'^invite/$', 'invite.views.invite', name='invite'),
url(r'^resend/(?P<code>.*)/$', 'invite.views.resend', name='resend'),
url(r'^revoke/(?P<code>.*)/$', 'invite.views.revoke', name='revoke'),
url(r'^login/$', 'invite.views.log_in_user', name='login'),
url(r'^logout/$', 'invite.views.log_out_user', name='edit_logout'),
url(r'^amnesia/$', 'invite.views.amnesia', name='amnesia'),
url(r'^reset/$', 'invite.views.reset', name="reset"),
url(r'^signup/$', 'invite.views.signup', name="account_signup"),
url(r'^about/$', 'invite.views.about', name="about"),
)
|
Add some events and url transform | var TC = require('tangram.cartodb');
var LeafletLayerView = require('./leaflet-layer-view');
var L = require('leaflet');
var LeafletCartoDBVectorLayerGroupView = L.Class.extend({
includes: [
LeafletLayerView.prototype
],
options: {
minZoom: 0,
maxZoom: 28,
tileSize: 256,
zoomOffset: 0,
tileBuffer: 50
},
events: {
featureOver: null,
featureOut: null,
featureClick: null
},
initialize: function (layerGroupModel, map) {
LeafletLayerView.call(this, layerGroupModel, this, map);
layerGroupModel.bind('change:urls', this._onURLsChanged, this);
this.tangram = new TC(map);
layerGroupModel.each(this._onLayerAdded, this);
layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this));
},
onAdd: function (map) {
L.Layer.prototype.onAdd.call(this, map);
},
_onLayerAdded: function (layer) {
var self = this;
layer.bind('change:meta change:visible change:cartocss', function (e) {
self.tangram.addLayer(e.attributes);
});
},
setZIndex: function () {},
_onURLsChanged: function (e, res) {
var url = res.tiles[0]
.replace('{layerIndexes}', 'mapnik')
.replace('.png', '.mvt');
this.tangram.addDataSource(url);
}
});
module.exports = LeafletCartoDBVectorLayerGroupView;
| var TC = require('tangram.cartodb');
var LeafletLayerView = require('./leaflet-layer-view');
var L = require('leaflet');
var LeafletCartoDBVectorLayerGroupView = L.Class.extend({
includes: [
LeafletLayerView.prototype
],
options: {
minZoom: 0,
maxZoom: 28,
tileSize: 256,
zoomOffset: 0,
tileBuffer: 50
},
events: {
featureOver: null,
featureOut: null,
featureClick: null
},
initialize: function (layerGroupModel, map) {
LeafletLayerView.call(this, layerGroupModel, this, map);
layerGroupModel.bind('change:urls', this._onURLsChanged, this);
this.tangram = new TC(map);
layerGroupModel.each(this._onLayerAdded, this);
layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this));
},
onAdd: function (map) {
L.Layer.prototype.onAdd.call(this, map);
},
_onLayerAdded: function (layer) {
var self = this;
layer.bind('change:meta', function (e) {
self.tangram.addLayer(e.attributes);
});
},
setZIndex: function (zIndex) {},
_onURLsChanged: function (e, res) {
this.tangram.addDataSource(res.tiles[0]);
}
});
module.exports = LeafletCartoDBVectorLayerGroupView;
|
Remove unnecessary variables in loader | const loaderUtils = require('loader-utils');
const path = require('path');
const deepMerge = require('./lib/deep-merge');
module.exports = function(source) {
const callback = this.async();
const options = loaderUtils.getOptions(this);
const overridePath = path.resolve(__dirname,
`test/cases/lib/${options.override}`);
this.cacheable && this.cacheable();
this.loadModule(overridePath,
function(err, overrideSource, sourceMap, module) {
if (err) { return callback(err); }
const override = overrideSource
.replace(/^ ?module.exports ?= ?/i, '')
.replace(/\;/g, '');
const mergedModule = deepMerge(JSON.parse(source), JSON.parse(override));
callback(null, mergedModule);
});
};
| const loaderUtils = require('loader-utils');
const path = require('path');
const deepMerge = require('./lib/deep-merge');
module.exports = function(source) {
const HEADER = '/**** Start Merge Loader ****/';
const FOOTER = '/**** End Merge Loader ****/';
const callback = this.async();
const options = loaderUtils.getOptions(this);
const thisLoader = this;
const overridePath = path.resolve(__dirname,
`test/cases/lib/${options.override}`);
this.cacheable && this.cacheable();
this.loadModule(overridePath,
function(err, overrideSource, sourceMap, module) {
if (err) { return callback(err); }
const override = overrideSource
.replace(/^ ?module.exports ?= ?/i, '')
.replace(/\;/g, '');
const mergedModule = deepMerge(JSON.parse(source), JSON.parse(override));
callback(null, mergedModule);
});
};
|
Switch node example to es6 | /*jshint node:true, esversion:6 */
"use strict";
const fs = require("fs");
const util = require("util");
const mp3Parser = require(__dirname + "/../../main");
const pathToMp3 = process.argv[2];
const toArrayBuffer = buffer => {
const bufferLength = buffer.length;
const uint8Array = new Uint8Array(new ArrayBuffer(bufferLength));
for (let i = 0; i < bufferLength; ++i) { uint8Array[i] = buffer[i]; }
return uint8Array.buffer;
};
if (!pathToMp3) {
console.log("please provide a path to an mp3 file, i.e. 'node parse.js <file>'");
process.exit(0);
}
fs.readFile(pathToMp3, (error, buffer) => {
if (error) {
console.log("Oops: " + error);
process.exit(1);
}
buffer = new DataView(toArrayBuffer(buffer));
const lastFrame = mp3Parser.readLastFrame(buffer);
const tags = mp3Parser.readTags(buffer);
util.puts("\nTags:\n-----\n" + util.inspect(tags, { depth: 5, colors: true }));
util.puts("\nLast frame:\n-----------\n" + util.inspect(lastFrame, { depth: 3, colors: true }));
});
| /*jshint node:true */
"use strict";
var fs = require("fs"),
util = require("util"),
mp3Parser = require(__dirname + "/../../main"),
pathToMp3 = process.argv[2],
toArrayBuffer = function (buffer) {
var bufferLength = buffer.length, i = 0,
uint8Array = new Uint8Array(new ArrayBuffer(bufferLength));
for (; i < bufferLength; ++i) { uint8Array[i] = buffer[i]; }
return uint8Array.buffer;
};
if (!pathToMp3) {
console.log("please give a path to an mp3 file, i.e. 'node parse.js <file>'");
process.exit(0);
}
fs.readFile(pathToMp3, function (error, buffer) {
if (error) {
console.log("Oops: " + error);
process.exit(1);
}
buffer = new DataView(toArrayBuffer(buffer));
var lastFrame = mp3Parser.readLastFrame(buffer),
tags = mp3Parser.readTags(buffer);
util.puts("\nTags:\n-----\n" + util.inspect(tags, { depth: 5, colors: true }));
util.puts("\nLast frame:\n-----------\n" + util.inspect(lastFrame, { depth: 3, colors: true }));
});
|
Add token and refresh_interval to return data | <?php
namespace Ibonly\FacebookAccountKit;
class FacebookAccountKit extends AccountKit
{
public function getUserId($code)
{
return $this->getData($code)['id'];
}
public function getAppToken($code)
{
return $this->getData($code);
}
public function facebookAccountKit($code)
{
$accountKitData = $this->data($code);
$token = $this->getAppToken($code);
$output = [
'id' => $accountKitData->id,
'phoneNumber' => '',
'email' => '',
'token' => $token->access_token,
'timeInterval' => $token->token_refresh_interval_sec
];
if (array_key_exists('phone', $accountKitData)) {
$output['phoneNumber'] = $accountKitData->phone->number ?? null;
}
if (array_key_exists('email', $data)) {
$output['email'] = $data->email->address ?? null;
}
return $output;
}
}
| <?php
namespace Ibonly\FacebookAccountKit;
class FacebookAccountKit extends AccountKit
{
public function getUserId($code)
{
return $this->getData($code)['id'];
}
public function getRefreshInterval($code)
{
return $this->getData($code)->token_refresh_interval_sec;
}
public function facebookAccountKit($code)
{
$accountKitData = $this->data($code);
$output = [
'id' => $accountKitData->id,
'phoneNumber' => '',
'email' => '',
];
if (array_key_exists('phone', $accountKitData)) {
$output['phoneNumber'] = $accountKitData->phone->number ?? null;
}
if (array_key_exists('email', $data)) {
$output['email'] = $data->email->address ?? null;
}
return $output;
}
}
|
Use ":num/index.html" link structure for non-pretty paginated pages | <?php namespace TightenCo\Jigsaw;
class BasicOutputPathResolver
{
public function link($path, $name, $type, $page = 1)
{
if ($page > 1) {
return sprintf('%s%s%s%s%s.%s', $this->trimPath($path), '/', $page, '/', $name, $type);
}
return sprintf('%s%s%s.%s', $this->trimPath($path), '/', $name, $type);
}
public function path($path, $name, $type, $page = 1)
{
return $this->link($path, $name, $type, $page);
}
public function directory($path, $name, $type, $page = 1)
{
if ($page > 1) {
return $this->trimPath($path) . '/' . $page;
}
return $this->trimPath($path);
}
private function trimPath($path)
{
return rtrim(ltrim($path, '/'), '/');
}
}
| <?php namespace TightenCo\Jigsaw;
class BasicOutputPathResolver
{
public function link($path, $name, $type, $page = 1)
{
if ($page > 1) {
return sprintf('%s%s%s%s%s.%s', $this->trimPath($path), '/', $name, '/', $page, $type);
}
return sprintf('%s%s%s.%s', $this->trimPath($path), '/', $name, $type);
}
public function path($path, $name, $type, $page = 1)
{
return $this->link($path, $name, $type, $page);
}
public function directory($path, $name, $type, $page = 1)
{
if ($page > 1) {
return $this->trimPath($path) . '/' . $name;
}
return $this->trimPath($path);
}
private function trimPath($path)
{
return rtrim(ltrim($path, '/'), '/');
}
}
|
Add a disclaimer for the shameness | import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Match, Miss } from 'react-router';
import App from './App';
import './index.css';
const getBaseUrl = () => {
let baseUrl = 'http://localhost:3001';
if (process.env.NODE_ENV === 'production') {
baseUrl = 'https://apiarycustomerseed.herokuapp.com';
} else if (process.env.NODE_ENV === 'CI') {
baseUrl = 'https://api.xyz.com:3001';
}
return baseUrl;
};
/*
I totally understand that I should probably be crucified for the way I am using
ReactRouter. You can do that when I'll be back in Prague.
*/
ReactDOM.render(
(<BrowserRouter>
<div>
<Match pattern="/:baseUrl" component={App} />
<Miss component={() => {
return <App params={{
baseUrl: getBaseUrl()
}}/>
}}/>
</div>
</BrowserRouter>),
document.getElementById('root')
);
| import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Match, Miss } from 'react-router';
import App from './App';
import './index.css';
const getBaseUrl = () => {
let baseUrl = 'http://localhost:3001';
if (process.env.NODE_ENV === 'production') {
baseUrl = 'https://apiarycustomerseed.herokuapp.com';
} else if (process.env.NODE_ENV === 'CI') {
baseUrl = 'https://api.xyz.com:3001';
}
return baseUrl;
};
ReactDOM.render(
(<BrowserRouter>
<div>
<Match pattern="/:baseUrl" component={App} />
<Miss component={() => {
return <App params={{
baseUrl: getBaseUrl()
}}/>
}}/>
</div>
</BrowserRouter>),
document.getElementById('root')
);
|
Use a varargs constructor instead of an array for the GVM Options | /*
* Copyright 2014 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 net.gvmtool.api;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* @author Noam Y. Tenne
*/
public class GvmOptions {
private final Set<GvmOption> options;
public GvmOptions(GvmOption...gvmOptions) {
options = new HashSet<>();
Collections.addAll(options, gvmOptions);
}
public boolean isInstall() {
return options.contains(GvmOption.INSTALL);
}
public boolean isDefault() {
return options.contains(GvmOption.DEFAULT);
}
public boolean isOffline() {
return options.contains(GvmOption.OFFLINE);
}
}
| /*
* Copyright 2014 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 net.gvmtool.api;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* @author Noam Y. Tenne
*/
public class GvmOptions {
private final Set<GvmOption> options;
public GvmOptions(GvmOption[] gvmOptions) {
options = new HashSet<>();
Collections.addAll(options, gvmOptions);
}
public boolean isInstall() {
return options.contains(GvmOption.INSTALL);
}
public boolean isDefault() {
return options.contains(GvmOption.DEFAULT);
}
public boolean isOffline() {
return options.contains(GvmOption.OFFLINE);
}
}
|
Add test for get skill by id | /* global describe, it, before */
var requirejs = require("requirejs");
var assert = require("assert");
var should = require("should");
var jsdom = require('mocha-jsdom');
var skill = require('fs').readFileSync('./test/spec/links_test.json', 'utf8');
requirejs.config({
baseUrl: 'app/',
nodeRequire: require
});
describe('Utils', function () {
var Utils;
jsdom();
before(function (done) {
requirejs(['scripts/Utils'],
function (Utils_Class) {
Utils = Utils_Class;
done();
});
});
var all_skills = JSON.parse(skill);
describe('D3 Links Test', function () {
it('should return correct d3 links info', function () {
Utils.parseDepends(all_skills.skills).toString().should.equal([{source: 1, target: 0}].toString())
});
});
describe('Get Skill By id', function () {
it('should return correct skill information by id', function () {
Utils.getSkillById(all_skills.skills, 1).toString().should.equal({ id: 1, name: 'Web' }.toString())
});
});
});
| /* global describe, it, before */
var requirejs = require("requirejs");
var assert = require("assert");
var should = require("should");
var jsdom = require('mocha-jsdom');
var skill = require('fs').readFileSync('./test/spec/links_test.json', 'utf8');
requirejs.config({
baseUrl: 'app/',
nodeRequire: require
});
describe('Utils', function () {
var Utils;
jsdom();
before(function (done) {
requirejs(['scripts/Utils'],
function (Utils_Class) {
Utils = Utils_Class;
done();
});
});
var all_skills = JSON.parse(skill);
describe('D3 Links Test', function () {
it('should return correct d3 links info', function () {
Utils.parseDepends(all_skills.skills).toString().should.equal([{source: 1, target: 0}].toString())
});
});
});
|
Fix a trivial indexing issue | package me.dilek.izlek.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class SeasonCollection implements Iterable<Season>, Serializable {
private static final long serialVersionUID = -4364084422273324469L;
private final List<Season> seasons;
public SeasonCollection() {
this.seasons = new ArrayList<>();
}
@SuppressWarnings("unchecked")
public Collection<Season> getSeasons() {
return (Collection<Season>) ((ArrayList<Season>) seasons).clone();
}
public void add(Season season) {
this.seasons.add(season);
}
@Override
public Iterator<Season> iterator() {
return seasons.iterator();
}
public void addEpisode(int season, int episode, String title,
String publishDate) {
while (seasons.size() < season) {
seasons.add(new Season(season));
}
Season s = seasons.get(season - 1);
s.addEpisode(episode, title, publishDate);
}
}
| package me.dilek.izlek.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class SeasonCollection implements Iterable<Season>, Serializable {
private static final long serialVersionUID = -4364084422273324469L;
private final List<Season> seasons;
public SeasonCollection() {
this.seasons = new ArrayList<>();
}
@SuppressWarnings("unchecked")
public Collection<Season> getSeasons() {
return (Collection<Season>) ((ArrayList<Season>) seasons).clone();
}
public void add(Season season) {
this.seasons.add(season);
}
@Override
public Iterator<Season> iterator() {
return seasons.iterator();
}
public void addEpisode(int season, int episode, String title,
String publishDate) {
while (seasons.size() < season - 1) {
seasons.add(new Season(seasons.size() + 1));
}
Season s = seasons.get(season - 1);
s.addEpisode(episode, title, publishDate);
}
}
|
Fix demo that was using Timer::cancel() from old event-loop api | <?php
require_once __DIR__ . '/../bootstrap.php';
use React\EventLoop\Factory;
use Rx\Disposable\CallbackDisposable;
use Rx\ObserverInterface;
use Rx\Scheduler\EventLoopScheduler;
$loop = Factory::create();
$observable = Rx\Observable::create(function (ObserverInterface $observer) use ($loop) {
$handler = function () use ($observer) {
$observer->onNext(42);
$observer->onCompleted();
};
// Change scheduler for here
$timer = $loop->addTimer(0.001, $handler);
return new CallbackDisposable(function () use ($loop, $timer) {
// And change scheduler for here
if ($timer) {
$loop->cancelTimer($timer);
}
});
});
$observable
->subscribeOn(new EventLoopScheduler($loop))
->subscribe($stdoutObserver);
$loop->run();
//Next value: 42
//Complete!
| <?php
require_once __DIR__ . '/../bootstrap.php';
use React\EventLoop\Factory;
use Rx\Disposable\CallbackDisposable;
use Rx\ObserverInterface;
use Rx\Scheduler\EventLoopScheduler;
$loop = Factory::create();
$observable = Rx\Observable::create(function (ObserverInterface $observer) use ($loop) {
$handler = function () use ($observer) {
$observer->onNext(42);
$observer->onCompleted();
};
// Change scheduler for here
$timer = $loop->addTimer(0.001, $handler);
return new CallbackDisposable(function () use ($timer) {
// And change scheduler for here
if ($timer) {
$timer->cancel();
}
});
});
$observable
->subscribeOn(new EventLoopScheduler($loop))
->subscribe($stdoutObserver);
$loop->run();
//Next value: 42
//Complete!
|
Add test to check if connection is closed after email is sent. | import smtplib
import unittest
from unittest import mock
from action import PrintAction, EmailAction
@mock.patch("builtins.print")
class PrintActionTest(unittest.TestCase):
def test_executing_action_prints_message(self, mock_print):
action = PrintAction()
action.execute("GOOG > $10")
mock_print.assert_called_with("GOOG > $10")
@mock.patch("smtplib.SMTP")
class EmailActionTest(unittest.TestCase):
def setUp(self):
self.action = EmailAction(to="bsmukasa@gmail.com")
def test_email_is_sent_to_the_right_server(self, mock_smtp_class):
self.action.execute("MSFT has crossed $10 price level")
mock_smtp_class.assert_called_with("email.stocks.com")
def test_connection_closed_after_sending_mail(self, mock_smtp_class):
mock_smtp = mock_smtp_class.return_value
self.action.execute("MSFT has crossed $10 price level")
mock_smtp.send_message.assert_called_with(mock.ANY)
self.assertTrue(mock_smtp.quit.called)
mock_smtp.assert_has_calls([
mock.call.send_message(mock.ANY),
mock.call.quit()
])
| import smtplib
import unittest
from unittest import mock
from action import PrintAction, EmailAction
@mock.patch("builtins.print")
class PrintActionTest(unittest.TestCase):
def test_executing_action_prints_message(self, mock_print):
action = PrintAction()
action.execute("GOOG > $10")
mock_print.assert_called_with("GOOG > $10")
@mock.patch("smtplib.SMTP")
class EmailActionTest(unittest.TestCase):
def setUp(self):
self.action = EmailAction(to="bsmukasa@gmail.com")
def test_email_is_sent_to_the_right_server(self, mock_smtp_class):
self.action.execute("MSFT has crossed $10 price level")
mock_smtp_class.assert_called_with("email.stocks.com")
|
Add trailing slash to endpoint url | const hapi = require('hapi');
const { graphqlHapi, graphiqlHapi } = require('graphql-server-hapi');
const rootSchema = require('./graphql/schema');
const dataLoaders = require('./graphql/data');
const config = require('../../config');
const server = new hapi.Server();
server.connection({
host: config.HOST,
port: config.PORT
});
server.register({
register: graphqlHapi,
options: {
path: '/graphql/',
graphqlOptions: {
schema: rootSchema,
context: { dataLoaders }
},
route: {
cors: true
}
}
});
server.register({
register: graphiqlHapi,
options: {
path: '/graphiql/',
graphiqlOptions: {
endpointURL: '/graphql/'
}
}
});
server.start(err => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
| const hapi = require('hapi');
const { graphqlHapi, graphiqlHapi } = require('graphql-server-hapi');
const rootSchema = require('./graphql/schema');
const dataLoaders = require('./graphql/data');
const config = require('../../config');
const server = new hapi.Server();
server.connection({
host: config.HOST,
port: config.PORT
});
server.register({
register: graphqlHapi,
options: {
path: '/graphql',
graphqlOptions: {
schema: rootSchema,
context: { dataLoaders }
},
route: {
cors: true
}
}
});
server.register({
register: graphiqlHapi,
options: {
path: '/graphiql',
graphiqlOptions: {
endpointURL: '/graphql'
}
}
});
server.start(err => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
|
Update nexus requirement so pip stops complaining. | #!/usr/bin/env python
# Credit to bartTC and https://github.com/bartTC/django-memcache-status for ideas
try:
from setuptools import setup, find_packages
from setuptools.command.test import test
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
class mytest(test):
def run(self, *args, **kwargs):
from runtests import runtests
runtests()
setup(
name='nexus-memcache',
version='0.3.6',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/nexus-memcache',
description = 'Memcache Plugin for Nexus',
packages=find_packages(),
zip_safe=False,
install_requires=[
'nexus-yplan>=1.6.0',
],
test_suite = 'nexus_memcache.tests',
include_package_data=True,
cmdclass={"test": mytest},
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
| #!/usr/bin/env python
# Credit to bartTC and https://github.com/bartTC/django-memcache-status for ideas
try:
from setuptools import setup, find_packages
from setuptools.command.test import test
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
class mytest(test):
def run(self, *args, **kwargs):
from runtests import runtests
runtests()
setup(
name='nexus-memcache',
version='0.3.6',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/nexus-memcache',
description = 'Memcache Plugin for Nexus',
packages=find_packages(),
zip_safe=False,
install_requires=[
'nexus>=0.1.3',
],
test_suite = 'nexus_memcache.tests',
include_package_data=True,
cmdclass={"test": mytest},
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
) |
Add uglify (minification) to the build task. | module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
build: {
src: "build"
}
},
copy: {
build: {
files: [
{
expand: true,
cwd: 'source/',
src: ['clever-style-switcher.js'],
dest: 'build/'
}
]
}
},
uglify: {
build: {
files: {
'build/css.min.js': ['source/clever-style-switcher.js']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('build', ['clean', 'copy', 'uglify']);
grunt.registerTask('default', ['build']);
}; | module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
build: {
src: "build"
}
},
copy: {
build: {
files: [
{
expand: true,
cwd: 'source/',
src: ['clever-style-switcher.js'],
dest: 'build/'
}
]
}
},
uglify: {
build: {
files: {
'build/css.min.js': ['source/clever-style-switcher.js']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('build', ['clean', 'copy']);
grunt.registerTask('default', ['build']);
}; |
Clear observable cursor using dedicated mobx method | import { Tracker } from 'meteor/tracker';
import { action } from 'mobx';
export default (actionPrefix = '', observableArray, handle, cursor) => {
if (handle.ready()) {
// initial fetch...
Tracker.nonreactive(() => {
action(`${actionPrefix}: initial fetch`, (comments) => {
observableArray.replace(comments);
})(cursor.fetch());
});
// ...and then observe
cursor.observe({
// we don't want that the addedAt function is triggered x times at the beginning
// just fetch them once (see above)
_suppress_initial: true,
addedAt: action(`${actionPrefix}: document added`, (document, atIndex) => {
observableArray.splice(atIndex, 0, document);
}),
changedAt: action(`${actionPrefix}: document changed`, (newDocument, oldDocument, atIndex) => {
observableArray.splice(atIndex, 1, newDocument);
}),
removedAt: action(`${actionPrefix}: document removed`, (oldDocument, atIndex) => {
observableArray.splice(atIndex, 1);
}),
movedTo: action(`${actionPrefix}: document moved`, (document, fromIndex, toIndex) => {
observableArray.splice(fromIndex, 1);
observableArray.splice(toIndex, 0, document);
}),
});
} else {
action(`${actionPrefix}: initialized`, () => {
observableArray.clear();
})();
}
};
| import { Tracker } from 'meteor/tracker';
import { action } from 'mobx';
export default (actionPrefix = '', storeAttribute, handle, cursor) => {
if (handle.ready()) {
// initial fetch...
Tracker.nonreactive(() => {
action(`${actionPrefix}: initial fetch`, (comments) => {
storeAttribute.replace(comments);
})(cursor.fetch());
});
// ...and then observe
cursor.observe({
// we don't want that the addedAt function is triggered x times at the beginning
// just fetch them once (see above)
_suppress_initial: true,
addedAt: action(`${actionPrefix}: document added`, (document, atIndex) => {
storeAttribute.splice(atIndex, 0, document);
}),
changedAt: action(`${actionPrefix}: document changed`, (newDocument, oldDocument, atIndex) => {
storeAttribute.splice(atIndex, 1, newDocument);
}),
removedAt: action(`${actionPrefix}: document removed`, (oldDocument, atIndex) => {
storeAttribute.splice(atIndex, 1);
}),
movedTo: action(`${actionPrefix}: document moved`, (document, fromIndex, toIndex) => {
storeAttribute.splice(fromIndex, 1);
storeAttribute.splice(toIndex, 0, document);
}),
});
} else {
action(`${actionPrefix}: initialized`, () => {
storeAttribute.replace([]);
})();
}
};
|
Fix an issue with the port number | require( 'dotenv' ).config();
var dropboxModule = require( './modules/dropbox.js' );
var googleDocsModule = require( './modules/googleDocs.js' );
var paypalModule = require( './modules/paypal.js' );
var express = require( 'express' );
var app = express();
app.set( 'port', ( process.env.Port || 30000 ) );
app.use( express.static( __dirname + '/public' ) );
app.get( '/googleapitoken', function( request, response ) {
googleDocsModule.googleAPIAuthorize( request, response );
});
app.get( '/trigger', function( request, response ) {
googleDocsModule.verifySecrets()
.then(function( res ) {
console.log( 'Application verified! Fetching PayPal rate.' );
paypalModule.fetchPaypalRate();
response.send( 'Triggered!' );
})
.catch(function( error ) {
var errorMessage = 'Failed to authenticate! (' + error + ')';
console.log( errorMessage );
response.send( errorMessage );
});
});
app.listen( app.get( 'port' ), function() {
console.log( 'Node app is running at localhost:' + app.get( 'port' ) );
});
| require( 'dotenv' ).config();
var dropboxModule = require( './modules/dropbox.js' );
var googleDocsModule = require( './modules/googleDocs.js' );
var paypalModule = require( './modules/paypal.js' );
var express = require( 'express' );
var app = express();
app.set( 'port', ( process.env.Port ) );
app.use( express.static( __dirname + '/public' ) );
app.get( '/googleapitoken', function( request, response ) {
googleDocsModule.googleAPIAuthorize( request, response );
});
app.get( '/trigger', function( request, response ) {
googleDocsModule.verifySecrets()
.then(function( res ) {
console.log( 'Application verified! Fetching PayPal rate.' );
paypalModule.fetchPaypalRate();
response.send( 'Triggered!' );
})
.catch(function( error ) {
var errorMessage = 'Failed to authenticate! (' + error + ')';
console.log( errorMessage );
response.send( errorMessage );
});
});
app.listen( app.get( 'port' ), function() {
console.log( 'Node app is running at localhost:' + app.get( 'port' ) );
});
|
Reset require cache back it original state on each run to avoid caching. | 'use strict';
var path = require('path');
var gutil = require('gulp-util');
var through2 = require('through2');
var Mocha = require('mocha');
module.exports = function (options) {
var mocha = new Mocha(options);
var cache = {};
for (var key in require.cache)
cache[key] = true;
return through2.obj(function (file, enc, cb) {
mocha.addFile(file.path);
this.push(file);
cb();
}, function (cb) {
try {
mocha.run(function (errCount) {
if (errCount > 0) {
this.emit('error', new gutil.PluginError('gulp-mocha', errCount + ' ' + (errCount === 1 ? 'test' : 'tests') + ' failed.'));
}
for (var key in require.cache)
if (!cache[key])
delete require.cache[key];
cb();
}.bind(this));
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-mocha', err));
cb();
}
});
};
| 'use strict';
var path = require('path');
var gutil = require('gulp-util');
var through2 = require('through2');
var Mocha = require('mocha');
module.exports = function (options) {
var mocha = new Mocha(options);
return through2.obj(function (file, enc, cb) {
delete require.cache[require.resolve(path.resolve(file.path))];
mocha.addFile(file.path);
this.push(file);
cb();
}, function (cb) {
try {
mocha.run(function (errCount) {
if (errCount > 0) {
this.emit('error', new gutil.PluginError('gulp-mocha', errCount + ' ' + (errCount === 1 ? 'test' : 'tests') + ' failed.'));
}
cb();
}.bind(this));
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-mocha', err));
cb();
}
});
};
|
Return exception when we have an issue reading an image file | # thesquirrel.org
#
# Copyright (C) 2015 Flying Squirrel Community Space
#
# thesquirrel.org is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# thesquirrel.org is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with thesquirrel.org. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render
from .models import EditorImage
from . import formatting
@login_required
def upload_image(request):
if 'file' not in request.FILES:
return JsonResponse({'error': 'no file given'})
else:
try:
image = EditorImage.objects.create_from_file(request.FILES['file'])
except Exception, e:
return JsonResponse({'error': str(e)})
return JsonResponse({'imageId': image.id})
def formatting_help(request):
return render(request, 'editor/formatting-help.html')
@login_required
def preview(request):
body = request.GET.get('body', '')
return JsonResponse({'body': formatting.render(body)})
| # thesquirrel.org
#
# Copyright (C) 2015 Flying Squirrel Community Space
#
# thesquirrel.org is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
# thesquirrel.org is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with thesquirrel.org. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render
from .models import EditorImage
from . import formatting
@login_required
def upload_image(request):
if 'file' not in request.FILES:
return JsonResponse({'error': 'no file given'})
else:
image = EditorImage.objects.create_from_file(request.FILES['file'])
return JsonResponse({'imageId': image.id})
def formatting_help(request):
return render(request, 'editor/formatting-help.html')
@login_required
def preview(request):
body = request.GET.get('body', '')
return JsonResponse({'body': formatting.render(body)})
|
Refactor for clarity around _week_start_at | import datetime
class Record(object):
def __init__(self, data):
self.data = data
self.meta = {}
if "_timestamp" in self.data:
day_of_week = self.data['_timestamp'].weekday()
delta_from_week_start = datetime.timedelta(days=day_of_week)
week_start = self.data['_timestamp'] - delta_from_week_start
self.meta['_week_start_at'] = week_start.replace(
hour=0,
minute=0,
second=0,
microsecond=0
)
def to_mongo(self):
return dict(
self.data.items() + self.meta.items()
)
def __eq__(self, other):
if not isinstance(other, Record):
return False
if self.data != other.data:
return False
if self.meta != other.meta:
return False
return True
| import datetime
class Record(object):
def __init__(self, data):
self.data = data
self.meta = {}
if "_timestamp" in self.data:
days_since_week_start = datetime.timedelta(
days=self.data['_timestamp'].weekday())
week_start = self.data['_timestamp'] - days_since_week_start
self.meta['_week_start_at'] = week_start.replace(
hour=0, minute=0, second=0, microsecond=0)
def to_mongo(self):
return dict(
self.data.items() + self.meta.items()
)
def __eq__(self, other):
if not isinstance(other, Record):
return False
if self.data != other.data:
return False
if self.meta != other.meta:
return False
return True
|
Fix PHPDoc return type and CS | <?php
namespace Halfpastfour\PHPChartJS\Options;
use Halfpastfour\PHPChartJS\ArraySerializableInterface;
use Halfpastfour\PHPChartJS\Delegate\ArraySerializable;
use Halfpastfour\PHPChartJS\Options\Layout\Padding;
use Zend\Json\Json;
/**
* Class Layout
*
* @package Halfpastfour\PHPChartJS\Options
*/
class Layout implements ArraySerializableInterface, \JsonSerializable
{
use ArraySerializable;
/**
* @var int|Padding
*/
private $padding;
/**
* @param int $padding
*/
public function setPadding($padding)
{
$this->padding = intval($padding);
}
/**
* @return int|Padding
*/
public function getPadding()
{
return $this->padding;
}
/**
* @return Padding
*/
public function padding()
{
if (is_null($this->padding)) {
$this->padding = new Padding();
}
return $this->padding;
}
/**
* @return string
* @throws \ReflectionException
* @throws \Zend_Reflection_Exception
*/
public function jsonSerialize()
{
return Json::encode($this->getArrayCopy());
}
}
| <?php
namespace Halfpastfour\PHPChartJS\Options;
use Halfpastfour\PHPChartJS\ArraySerializableInterface;
use Halfpastfour\PHPChartJS\Delegate\ArraySerializable;
use Halfpastfour\PHPChartJS\Options\Layout\Padding;
use Zend\Json\Json;
/**
* Class Layout
* @package Halfpastfour\PHPChartJS\Options
*/
class Layout implements ArraySerializableInterface, \JsonSerializable
{
use ArraySerializable;
/**
* @var int|Padding
*/
private $padding;
/**
* @param int $padding
*/
public function setPadding($padding)
{
$this->padding = intval($padding);
}
/**
* @return int
*/
public function getPadding()
{
return $this->padding;
}
/**
* @return Padding
*/
public function padding()
{
if (is_null($this->padding)) {
$this->padding = new Padding();
}
return $this->padding;
}
/**
* @return string
*/
public function jsonSerialize()
{
return Json::encode($this->getArrayCopy());
}
}
|
Improve safe mode notification using the new Orchestra\Messages::extend() API
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Orchestra\Support\Messages;
use Orchestra\Foundation\Services\UserMetaRepository;
App::make('orchestra.memory')->extend('user', function ($app, $name)
{
return new UserMetaRepository($app, $name);
});
/*
|--------------------------------------------------------------------------
| Bind Installation Interface
|--------------------------------------------------------------------------
|
| These interface allow Orchestra Platform installation process to be
| customized by the application when there a requirement for it.
|
*/
App::bind('Orchestra\Foundation\Installation\InstallerInterface', function ()
{
return new Orchestra\Foundation\Installation\Installer(App::make('app'));
});
App::bind('Orchestra\Foundation\Installation\RequirementInterface', function ()
{
return new Orchestra\Foundation\Installation\Requirement(App::make('app'));
});
/*
|--------------------------------------------------------------------------
| Inject Safe Mode Notification
|--------------------------------------------------------------------------
|
| This event listener would allow Orchestra Platform to display notification
| if the application is running on safe mode.
|
*/
Event::listen('composing: *', function ()
{
if ('on' === App::make('session')->get('orchestra.safemode'))
{
App::make('orchestra.messages')->extend(function ($messages)
{
$messages->add('info', trans('orchestra/foundation::response.safe-mode'));
});
}
});
| <?php
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Orchestra\Support\Messages;
use Orchestra\Foundation\Services\UserMetaRepository;
App::make('orchestra.memory')->extend('user', function ($app, $name)
{
return new UserMetaRepository($app, $name);
});
/*
|--------------------------------------------------------------------------
| Bind Installation Interface
|--------------------------------------------------------------------------
|
| These interface allow Orchestra Platform installation process to be
| customized by the application when there a requirement for it.
|
*/
App::bind('Orchestra\Foundation\Installation\InstallerInterface', function ()
{
return new Orchestra\Foundation\Installation\Installer(App::make('app'));
});
App::bind('Orchestra\Foundation\Installation\RequirementInterface', function ()
{
return new Orchestra\Foundation\Installation\Requirement(App::make('app'));
});
/*
|--------------------------------------------------------------------------
| Inject Safe Mode Notification
|--------------------------------------------------------------------------
|
| This event listener would allow Orchestra Platform to display notification
| if the application is running on safe mode.
|
*/
Event::listen('composing: *', function ()
{
if ('on' === App::make('session')->get('orchestra.safemode'))
{
$messages = App::make('orchestra.messages')->retrieve();
($messages instanceof Messages) or $messages = new Messages;
$messages->add('info', trans('orchestra/foundation::response.safe-mode'));
$messages->save();
}
});
|
Call setTimeout in test case | import { expect } from 'chai';
import { updateCellSource, executeCell } from '../../../src/notebook/actions';
import { liveStore, dispatchQueuePromise, waitForOutputs } from '../../utils';
describe('agendas.executeCell', function() {
this.timeout(5000);
it('produces the right output', (done) => {
setTimeout(done, 5000);
return liveStore((kernel, dispatch, store) => {
const cellId = store.getState().document.getIn(['notebook', 'cellOrder', 0]);
const source = 'print("a")';
dispatch(updateCellSource(cellId, source));
// TODO: Remove hack
// HACK: Wait 100ms before executing a cell because kernel ready and idle
// aren't enough. There must be another signal that we need to listen to.
return (new Promise(resolve => setTimeout(resolve, 100)))
.then(() => dispatch(executeCell(kernel.channels, cellId, source, true, undefined)))
.then(() => dispatchQueuePromise(dispatch))
.then(() => waitForOutputs(store, cellId))
.then(() => {
const output = store.getState().document.getIn(['notebook', 'cellMap', cellId, 'outputs', 0]).toJS();
expect(output.name).to.equal('stdout');
expect(output.text).to.equal('a\n');
expect(output.output_type).to.equal('stream');
});
});
});
});
| import { expect } from 'chai';
import { updateCellSource, executeCell } from '../../../src/notebook/actions';
import { liveStore, dispatchQueuePromise, waitForOutputs } from '../../utils';
describe('agendas.executeCell', function() {
this.timeout(5000);
it('produces the right output', () => {
return liveStore((kernel, dispatch, store) => {
const cellId = store.getState().document.getIn(['notebook', 'cellOrder', 0]);
const source = 'print("a")';
dispatch(updateCellSource(cellId, source));
// TODO: Remove hack
// HACK: Wait 100ms before executing a cell because kernel ready and idle
// aren't enough. There must be another signal that we need to listen to.
return (new Promise(resolve => setTimeout(resolve, 100)))
.then(() => dispatch(executeCell(kernel.channels, cellId, source, true, undefined)))
.then(() => dispatchQueuePromise(dispatch))
.then(() => waitForOutputs(store, cellId))
.then(() => {
const output = store.getState().document.getIn(['notebook', 'cellMap', cellId, 'outputs', 0]).toJS();
expect(output.name).to.equal('stdout');
expect(output.text).to.equal('a\n');
expect(output.output_type).to.equal('stream');
});
});
});
});
|
Fix big number format configuration | // @flow
import { observable, computed } from 'mobx';
import BigNumber from 'bignumber.js';
import Store from './lib/Store';
import CachedRequest from './lib/CachedRequest';
export default class SettingsStore extends Store {
@observable termsOfUseRequest = new CachedRequest(this.api, 'getTermsOfUse');
@observable bigNumberDecimalFormat = {
decimalSeparator: '.',
groupSeparator: ',',
groupSize: 3,
secondaryGroupSize: 0,
fractionGroupSeparator: ' ',
fractionGroupSize: 0
};
setup() {
this.registerReactions([
this._setBigNumberFormat,
]);
}
@computed get termsOfUse(): string {
return this.termsOfUseRequest.execute().result;
}
_setBigNumberFormat = () => {
BigNumber.config({ FORMAT: this.bigNumberDecimalFormat });
}
}
| // @flow
import { observable, computed } from 'mobx';
import BigNumber from 'bignumber.js';
import Store from './lib/Store';
import CachedRequest from './lib/CachedRequest';
export default class SettingsStore extends Store {
@observable termsOfUseRequest = new CachedRequest(this.api, 'getTermsOfUse');
@observable bigNumberDecimalFormat = {
decimalSeparator: '.',
groupSeparator: ' ',
groupSize: 3,
secondaryGroupSize: 0,
fractionGroupSeparator: ' ',
fractionGroupSize: 0
};
setup() {
this.registerReactions([
this._setBigNumberFormat,
]);
}
@computed get termsOfUse(): string {
return this.termsOfUseRequest.execute().result;
}
_setBigNumberFormat = () => {
BigNumber.config({ FORMAT: this.bigNumberDecimalFormat });
}
}
|
Print a more useful warning message | # -*- coding: utf-8 -*-
# Copyright 2014, Digital Reasoning
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import absolute_import
import sys
from .version import __version__, __version_info__ # NOQA
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
try:
from .celery import app as celery_app
except ImportError:
sys.stderr.write("Not importing celery... "
"Ignore if this if you're currently running setup.py.\n")
__copyright__ = "Copyright 2014, Digital Reasoning"
__license__ = "Apache License Version 2.0, January 2004"
__maintainer__ = "https://github.com/stackdio/stackdio"
| # -*- coding: utf-8 -*-
# Copyright 2014, Digital Reasoning
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import absolute_import
import sys
from .version import __version__, __version_info__ # NOQA
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
try:
from .celery import app as celery_app
except ImportError:
sys.stderr.write('Not importing celery... Ignore if this is running setup.py.\n')
__copyright__ = "Copyright 2014, Digital Reasoning"
__license__ = "Apache License Version 2.0, January 2004"
__maintainer__ = "https://github.com/stackdio/stackdio"
|
Change waitForDataAndSetState name into waitDataAndSetState | import { makeCancelable, cancelAll } from '../helpers/promises';
export function cancelAllPromises(component) {
if (!component.cancelablePromises) return;
return cancelAll(component.cancelablePromises);
}
export function waitDataAndSetState(dataPromise, component, stateName) {
const cancelablePromise = makeCancelable(dataPromise);
if (!component.cancelablePromises) component.cancelablePromises = []
component.cancelablePromises.push(cancelablePromise)
return cancelablePromise.promise
.then(data => {
const update = {};
update[stateName] = data;
component.setState(update);
})
.catch(err => {
if (err.isCanceled) return;
if (!component.state.errors.includes(err.message)) {
const errors = [...component.state.errors, err.message]
component.setState({ errors })
}
});
}
| import { makeCancelable, cancelAll } from '../helpers/promises';
export function cancelAllPromises(component) {
if (!component.cancelablePromises) return;
return cancelAll(component.cancelablePromises);
}
export function waitForDataAndSetState(dataPromise, component, stateName) {
const cancelablePromise = makeCancelable(dataPromise);
if (!component.cancelablePromises) component.cancelablePromises = []
component.cancelablePromises.push(cancelablePromise)
return cancelablePromise.promise
.then(data => {
const update = {};
update[stateName] = data;
component.setState(update);
})
.catch(err => {
if (err.isCanceled) return;
if (!component.state.errors.includes(err.message)) {
const errors = [...component.state.errors, err.message]
component.setState({ errors })
}
});
}
|
Implement sort ordering for SubTabView | import React, {Component} from 'react'
import {StyleSheet, View} from 'react-native'
import TabButton from './TabButton'
export default class extends Component {
state = {activeTab: 0}
render = () => (
<View style={{flex: 1}}>
{this.props.tabs.length < 2 ? null :
<View style={Styles.tabWrapper}>
{
this.props.tabs.sort(this.compareSortOrder).map(({title}, key) => (
<TabButton
key={key}
index={key}
text={title}
activeTab={this.state.activeTab}
changeTab={this.changeTab}
/>
))
}
</View>
}
{this.renderTab()}
</View>
)
renderTab = () => (
this.props.tabs.map((tab, key) => {
if (key == this.state.activeTab) {
const ContentView = tab.content
return <ContentView key={key}/>
}
})
)
changeTab = (key) => this.setState({activeTab: key})
compareSortOrder = (element1, element2) => element1.sortOrder - element2.sortOrder
}
const Styles = StyleSheet.create({
tabWrapper: {
flexDirection: 'row',
alignSelf: 'stretch',
alignContent: 'stretch',
justifyContent: 'space-between',
height: 40
}
}) | import React, {Component} from 'react'
import {StyleSheet, View} from 'react-native'
import TabButton from './TabButton'
export default class extends Component {
state = {activeTab: 0}
render = () => (
<View style={{flex: 1}}>
{this.props.tabs.length < 2 ? null :
<View style={Styles.tabWrapper}>
{
this.props.tabs.map(({title}, key) => (
<TabButton
key={key}
index={key}
text={title}
activeTab={this.state.activeTab}
changeTab={this.changeTab}
/>
))
}
</View>
}
{this.renderTab()}
</View>
)
renderTab = () => (
this.props.tabs.map((tab, key) => {
if (key == this.state.activeTab) {
const ContentView = tab.content
return <ContentView key={key}/>
}
})
)
changeTab = (key) => this.setState({activeTab: key})
}
const Styles = StyleSheet.create({
tabWrapper: {
flexDirection: 'row',
alignSelf: 'stretch',
alignContent: 'stretch',
justifyContent: 'space-between',
height: 40
}
}) |
Add logging NullHandler to prevent "no handler found" errors
This fixes the issue where "no handler found" errors would be printed by
the library if library clients did not set up logging. | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# 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.
"""d1_common
Shared code for DataONE Python libraries
"""
__version__ = "2.1.0"
# Set default logging handler to avoid "No handler found" warnings.
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
| # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# 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.
"""d1_common
Shared code for DataONE Python libraries
"""
__version__ = "2.1.0"
__all__ = [
'const',
'exceptions',
'upload',
'xmlrunner',
'types.exceptions',
'types.dataoneTypes',
'types.dataoneErrors',
'ext.mimeparser',
]
|
Remove .ssh keys on compute node from /mnt/home/salvus account, since this is a security risk (in case compute node is r00ted). | #!/usr/bin/env python
# This script is run by /etc/rc.local when booting up. It does special configuration
# depending on what images are mounted, etc.
import os
if os.path.exists('/mnt/home/'):
# Compute machine
if not os.path.exists('/mnt/home/aquota.group'):
os.system("quotacheck -cug /mnt/home")
os.system("quotaon -a")
# disable quotas for now, so that students in my class can do Sage development.
os.system('quotaoff -a')
# Restore user accounts
if os.path.exists('/mnt/home/etc/'):
os.system("cp /mnt/home/etc/* /etc/")
else:
os.system("mkdir -p /mnt/home/etc/")
# Setup /tmp so it is on the external disk image (has that quota) and is clean, since this is a fresh boot.
os.system("rm -rf /mnt/home/tmp; mkdir -p /mnt/home/tmp/; chmod +t /mnt/home/tmp; mount -o bind /mnt/home/tmp /tmp; chmod a+rwx /mnt/home/tmp/")
os.system("mkdir -p /mnt/home/scratch; mkdir -p /scratch; chmod +t /mnt/home/tmp; mount -o bind /mnt/home/scratch /scratch; chmod a+rwx /mnt/home/scratch/")
# Remove .ssh keys on compute node from /mnt/home/salvus account, since this is a security risk (in case compute node is r00ted).
os.system("rm -rf /mnt/home/salvus/.ssh/id_rsa*")
| #!/usr/bin/env python
# This script is run by /etc/rc.local when booting up. It does special configuration
# depending on what images are mounted, etc.
import os
if os.path.exists('/mnt/home/'):
# Compute machine
if not os.path.exists('/mnt/home/aquota.group'):
os.system("quotacheck -cug /mnt/home")
os.system("quotaon -a")
# disable quotas for now, so that students in my class can do Sage development.
os.system('quotaoff -a')
# Restore user accounts
if os.path.exists('/mnt/home/etc/'):
os.system("cp /mnt/home/etc/* /etc/")
else:
os.system("mkdir -p /mnt/home/etc/")
# Setup /tmp so it is on the external disk image (has that quota) and is clean, since this is a fresh boot.
os.system("rm -rf /mnt/home/tmp; mkdir -p /mnt/home/tmp/; chmod +t /mnt/home/tmp; mount -o bind /mnt/home/tmp /tmp; chmod a+rwx /mnt/home/tmp/")
os.system("mkdir -p /mnt/home/scratch; mkdir -p /scratch; chmod +t /mnt/home/tmp; mount -o bind /mnt/home/scratch /scratch; chmod a+rwx /mnt/home/scratch/")
|
Update schemavalidator version to 0.1.0b5 | from distutils.core import setup
setup(
name='shampoo',
packages=['shampoo'],
package_data={'shampoo': ['schemas/*.json']},
version='0.1.0b7',
description='Shampoo is a asyncio websocket protocol implementation for Autobahn',
author='Daan Porru (Wend)',
author_email='daan@wend.nl',
license='MIT',
url='https://github.com/wendbv/shampoo',
keywords=['websocket', 'protocol'],
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 3.5',
],
install_requires=['schemavalidator==0.1.0b5', 'autobahn==0.13.0'],
extras_require={
'test': ['pytest', 'pytest-cov', 'coverage', 'pytest-mock', 'coveralls'],
}
)
| from distutils.core import setup
setup(
name='shampoo',
packages=['shampoo'],
package_data={'shampoo': ['schemas/*.json']},
version='0.1.0b7',
description='Shampoo is a asyncio websocket protocol implementation for Autobahn',
author='Daan Porru (Wend)',
author_email='daan@wend.nl',
license='MIT',
url='https://github.com/wendbv/shampoo',
keywords=['websocket', 'protocol'],
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 3.5',
],
install_requires=['schemavalidator', 'autobahn==0.13.0'],
extras_require={
'test': ['pytest', 'pytest-cov', 'coverage', 'pytest-mock', 'coveralls'],
}
)
|
Fix indentation; use arrow function | import geojs from 'geojs/geo.js';
import VisComponent from '../../VisComponent';
export default class Geo extends VisComponent {
constructor (el, options) {
super(el);
this.plot = geojs.map({
node: el,
zoom: 6,
center: {x: 28.9550, y: 41.0136}
});
this.plot.createLayer('osm');
if (options.features) {
for (let i = 0; i < options.features.length; ++i) {
this.plot.createLayer('feature')
.createFeature(options.features[i].type)
.data(options.features[i].data)
.position(d => ({
x: d[options.features[i].position.x],
y: d[options.features[i].position.y]
}));
}
this.plot.draw();
}
}
render () {
this.plot.draw();
}
}
| import geojs from 'geojs/geo.js';
import VisComponent from '../../VisComponent';
export default class Geo extends VisComponent {
constructor (el, options) {
super(el);
this.plot = geojs.map({
node: el,
zoom: 6,
center: {x: 28.9550, y: 41.0136}
});
this.plot.createLayer('osm');
if (options.features) {
for (let i = 0; i < options.features.length; ++i) {
this.plot.createLayer('feature')
.createFeature(options.features[i].type)
.data(options.features[i].data)
.position(function (d) {
return {
x: d[options.features[i].position.x],
y: d[options.features[i].position.y]
};
});
}
this.plot.draw();
}
}
render () {
this.plot.draw();
}
}
|
Replace double quotes with single quotes as string delimiters
This commit replaces double quotes with single quotes as string delimiters
to improve consistency. | # -*- coding: utf-8 -*-
from flask_wtf import Form
from flask_wtf.recaptcha import RecaptchaField, Recaptcha
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedURLForm(Form):
url = StringField(
validators=[
validators.DataRequired(),
validators.URL(message='A valid URL is required'),
not_blacklisted_nor_spam
]
)
recaptcha = RecaptchaField(
validators=[
Recaptcha(
'Please click on the reCAPTCHA field to prove you are a human'
)
]
)
| # -*- coding: utf-8 -*-
from flask_wtf import Form
from flask_wtf.recaptcha import RecaptchaField, Recaptcha
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedURLForm(Form):
url = StringField(
validators=[
validators.DataRequired(),
validators.URL(message="A valid URL is required"),
not_blacklisted_nor_spam
]
)
recaptcha = RecaptchaField(
validators=[
Recaptcha(
"Please click on the reCAPTCHA field to prove you are a human"
)
]
)
|
Fix script for validating trees
Former-commit-id: e6409f5a586d34a3bcb03b2d55afc9b220aebe04 | #! /usr/bin/env python3
"""Test whether given Newick/NHX trees are valid for ProPhyle.
Author: Karel Brinda <kbrinda@hsph.harvard.edu>
Licence: MIT
Example:
$ prophyle_validate_tree.py ~/prophyle/bacteria.nw ~/prophyle/viruses.nw
"""
import os
import sys
import argparse
sys.path.append(os.path.dirname(__file__))
import prophylelib as pro
def main():
parser = argparse.ArgumentParser(description='Verify a Newick/NHX tree')
parser.add_argument('tree',
metavar='<tree.nw>',
type=str,
nargs='+',
help='phylogenetic tree (in Newick/NHX)',
)
args = parser.parse_args()
tree_fns = args.tree
ok = True
for tree_fn in tree_fns:
print("Validating '{}'".format(tree_fn))
tree = pro.load_nhx_tree(tree_fn, validate=False)
r = pro.validate_prophyle_nhx_tree(tree, verbose=True, throw_exceptions=False, output_fo=sys.stdout)
if r:
print(" ...OK")
else:
ok = False
print()
sys.exit(0 if ok else 1)
if __name__ == "__main__":
main()
| #! /usr/bin/env python3
"""Test whether given Newick/NHX trees are valid for ProPhyle.
Author: Karel Brinda <kbrinda@hsph.harvard.edu>
Licence: MIT
Example:
$ prophyle_validate_tree.py ~/prophyle/bacteria.nw ~/prophyle/viruses.nw
"""
import os
import sys
import argparse
sys.path.append(os.path.dirname(__file__))
import prophylelib as pro
def main():
parser = argparse.ArgumentParser(description='Verify a Newick/NHX tree')
parser.add_argument('tree',
metavar='<tree.nw>',
type=str,
nargs='+',
help='phylogenetic tree (in Newick/NHX)',
)
args = parser.parse_args()
tree_fns = args.tree
ok = True
for tree_fn in tree_fns:
print("Validating '{}'".format(tree_fn))
tree = pro.load_nhx_tree(tree_fn, validate=False)
r = pro.validate_prophyle_nhx_tree(tree, verbose=True, throw_exceptions=False, output=sys.stdout)
if r:
print(" ...OK")
else:
ok = False
print()
sys.exit(0 if ok else 1)
if __name__ == "__main__":
main()
|
coder/msgpack: Use umsgpack package for msgpack coder | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# 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.
import umsgpack
from message_coder import MessageCoderBase
umsgpack.compatibility = True
# set of functions to encode/decode data tokens to/from a json description
class MessageCoder(MessageCoderBase):
def encode(self, data):
return umsgpack.packb(data)
def decode(self, data):
data = umsgpack.unpackb(data)
return data
| # -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# 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.
import msgpack
from message_coder import MessageCoderBase
# set of functions to encode/decode data tokens to/from a json description
class MessageCoder(MessageCoderBase):
def encode(self, data):
return msgpack.packb(data)
def decode(self, data):
data = msgpack.unpackb(data)
return data
|
Change slot names for consistency | <!DOCTYPE html>
<html lang="<?php echo $sf_user->getCulture() ?>" dir="<?php echo sfCultureInfo::getInstance($sf_user->getCulture())->direction ?>">
<head>
<?php include_http_metas() ?>
<?php include_metas() ?>
<?php include_title() ?>
<link rel="shortcut icon" href="<?php echo public_path('favicon.ico') ?>"/>
<?php include_stylesheets() ?>
<?php include_component_slot('css') ?>
<?php if ($sf_context->getConfiguration()->isDebug()): ?>
<script type="text/javascript" charset="utf-8">
less = { env: 'development', optimize: 0, relativeUrls: true };
</script>
<?php endif; ?>
<?php include_javascripts() ?>
</head>
<body class="yui-skin-sam <?php echo $sf_context->getModuleName() ?> <?php echo $sf_context->getActionName() ?>">
<?php echo get_partial('header') ?>
<?php include_slot('before-content') ?>
<?php if (!include_slot('content')): ?>
<div class="container-fluid">
<?php echo $sf_content ?>
</div>
<?php endif; ?>
<?php include_slot('after-content') ?>
<?php echo get_partial('footer') ?>
</body>
</html>
| <!DOCTYPE html>
<html lang="<?php echo $sf_user->getCulture() ?>" dir="<?php echo sfCultureInfo::getInstance($sf_user->getCulture())->direction ?>">
<head>
<?php include_http_metas() ?>
<?php include_metas() ?>
<?php include_title() ?>
<link rel="shortcut icon" href="<?php echo public_path('favicon.ico') ?>"/>
<?php include_stylesheets() ?>
<?php include_component_slot('css') ?>
<?php if ($sf_context->getConfiguration()->isDebug()): ?>
<script type="text/javascript" charset="utf-8">
less = { env: 'development', optimize: 0, relativeUrls: true };
</script>
<?php endif; ?>
<?php include_javascripts() ?>
</head>
<body class="yui-skin-sam <?php echo $sf_context->getModuleName() ?> <?php echo $sf_context->getActionName() ?>">
<?php echo get_partial('header') ?>
<?php include_slot('pre') ?>
<?php if (!include_slot('content')): ?>
<div class="container-fluid">
<?php echo $sf_content ?>
</div>
<?php endif; ?>
<?php include_slot('post') ?>
<?php echo get_partial('footer') ?>
</body>
</html>
|
Refactor Point to use OrderedDict for positions, upper and lower | from collections import OrderedDict
class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> float lower_bound for each
scannable dimension. E.g. {"x": 0.95, "y": 2.15}
upper (dict): Dict of str position_name -> float upper_bound for each
scannable dimension. E.g. {"x": 1.05, "y": 2.25}
indexes (list): List of int indexes for each dataset dimension, fastest
changing last. E.g. [15]
"""
def __init__(self):
self.positions = OrderedDict()
self.lower = OrderedDict()
self.upper = OrderedDict()
self.indexes = []
| class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> float lower_bound for each
scannable dimension. E.g. {"x": 0.95, "y": 2.15}
upper (dict): Dict of str position_name -> float upper_bound for each
scannable dimension. E.g. {"x": 1.05, "y": 2.25}
indexes (list): List of int indexes for each dataset dimension, fastest
changing last. E.g. [15]
"""
def __init__(self):
self.positions = {}
self.lower = {}
self.upper = {}
self.indexes = []
|
Fix Redis connection over TLS
When Designate is configured to use Redis for coordination over a TLS connection, it will fail to connect with "ssl.SSLError: ('timed out',)".
This is caused by eventlet raising ssl.SSLError instead of the expected socket timeout the core libraries return.
This patch monkey-patches eventlet to return the proper exception.
Closes-Bug: #1989020
Change-Id: I5bd1c10d863212683752e05bb450e6f531ff7e72 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# 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.
import eventlet
from eventlet.green import ssl
import socket
eventlet.monkey_patch(os=False)
# Work around the eventlet issue that impacts redis using TLS.
# https://github.com/eventlet/eventlet/issues/692
ssl.timeout_exc = socket.timeout
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
| # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# 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.
import eventlet
eventlet.monkey_patch(os=False)
# Monkey patch the original current_thread to use the up-to-date _active
# global variable. See https://bugs.launchpad.net/bugs/1863021 and
# https://github.com/eventlet/eventlet/issues/592
import __original_module_threading as orig_threading # noqa
import threading # noqa
orig_threading.current_thread.__globals__['_active'] = threading._active
|
Return a set of codecs instead of a collection to strip the duplicates.
Each codec is in the map twice, once for name and once for
content-type. We don't need both copies returned. | /*
* Copyright 2014 Red Hat, Inc, and individual contributors.
*
* 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.projectodd.wunderboss.codecs;
import java.util.*;
public class Codecs {
public Codecs add(Codec codec) {
codecs.put(codec.name(), codec);
codecs.put(codec.contentType(), codec);
return this;
}
public Codec forName(String name) {
return codecs.get(name);
}
public Codec forContentType(String contentType) {
return codecs.get(contentType);
}
public Set<Codec> codecs() {
return Collections.unmodifiableSet(new HashSet<>(codecs.values()));
}
private final Map<String, Codec> codecs = new HashMap<>();
}
| /*
* Copyright 2014 Red Hat, Inc, and individual contributors.
*
* 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.projectodd.wunderboss.codecs;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Codecs {
public Codecs add(Codec codec) {
codecs.put(codec.name(), codec);
codecs.put(codec.contentType(), codec);
return this;
}
public Codec forName(String name) {
return codecs.get(name);
}
public Codec forContentType(String contentType) {
return codecs.get(contentType);
}
public Collection<Codec> codecs() {
return Collections.unmodifiableCollection(codecs.values());
}
private final Map<String, Codec> codecs = new HashMap<>();
}
|
Remove useless named return value
This cleans up the useless named return value stopCh at
SetupSignalHandler().
Kubernetes-commit: 2e560e797e22c44ac628581486d847c2d5bdbd59 | /*
Copyright 2017 The Kubernetes 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 server
import (
"os"
"os/signal"
)
var onlyOneSignalHandler = make(chan struct{})
// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
func SetupSignalHandler() <-chan struct{} {
close(onlyOneSignalHandler) // panics when called twice
stop := make(chan struct{})
c := make(chan os.Signal, 2)
signal.Notify(c, shutdownSignals...)
go func() {
<-c
close(stop)
<-c
os.Exit(1) // second signal. Exit directly.
}()
return stop
}
| /*
Copyright 2017 The Kubernetes 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 server
import (
"os"
"os/signal"
)
var onlyOneSignalHandler = make(chan struct{})
// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
func SetupSignalHandler() (stopCh <-chan struct{}) {
close(onlyOneSignalHandler) // panics when called twice
stop := make(chan struct{})
c := make(chan os.Signal, 2)
signal.Notify(c, shutdownSignals...)
go func() {
<-c
close(stop)
<-c
os.Exit(1) // second signal. Exit directly.
}()
return stop
}
|
Update name of rabbit queue | # Licensed to the StackStorm, Inc ('StackStorm') 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.
# All Exchanges and Queues related to liveaction.
from kombu import Exchange, Queue
from st2common.transport import publishers
HISTORY_XCHG = Exchange('st2.execution', type='topic')
class ActionExecutionPublisher(publishers.CUDPublisher):
def __init__(self, url):
super(ActionExecutionPublisher, self).__init__(url, HISTORY_XCHG)
def get_queue(name=None, routing_key=None, exclusive=False):
return Queue(name, HISTORY_XCHG, routing_key=routing_key, exclusive=exclusive)
| # Licensed to the StackStorm, Inc ('StackStorm') 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.
# All Exchanges and Queues related to liveaction.
from kombu import Exchange, Queue
from st2common.transport import publishers
HISTORY_XCHG = Exchange('st2.history', type='topic')
class ActionExecutionPublisher(publishers.CUDPublisher):
def __init__(self, url):
super(ActionExecutionPublisher, self).__init__(url, HISTORY_XCHG)
def get_queue(name=None, routing_key=None, exclusive=False):
return Queue(name, HISTORY_XCHG, routing_key=routing_key, exclusive=exclusive)
|
Make update previous key name | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import os
from cryptography.fernet import Fernet, MultiFernet
fernet = Fernet(os.environ['KOMBU_FERNET_KEY'])
fallback_fernet = None
try:
fallback_fernet = Fernet(os.environ['KOMBU_FERNET_KEY_PREVIOUS'])
except KeyError:
pass
else:
fernet = MultiFernet([fernet, fallback_fernet])
def fernet_encode(func):
def inner(message):
return fernet.encrypt(func(message))
return inner
def fernet_decode(func):
def inner(encoded_message):
if isinstance(encoded_message, unicode):
encoded_message = encoded_message.encode('utf-8')
message = fernet.decrypt(encoded_message)
return func(message)
return inner
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import os
from cryptography.fernet import Fernet, MultiFernet
fernet = Fernet(os.environ['KOMBU_FERNET_KEY'])
fallback_fernet = None
try:
fallback_fernet = Fernet(os.environ['OLD_KOMBU_FERNET_KEY'])
except KeyError:
pass
else:
fernet = MultiFernet([fernet, fallback_fernet])
def fernet_encode(func):
def inner(message):
return fernet.encrypt(func(message))
return inner
def fernet_decode(func):
def inner(encoded_message):
if isinstance(encoded_message, unicode):
encoded_message = encoded_message.encode('utf-8')
message = fernet.decrypt(encoded_message)
return func(message)
return inner
|
Fix 'windows' property of Tabpage objects | from util import RemoteMap, RemoteSequence
class Tabpage(object):
@property
def windows(self):
if not hasattr(self, '_windows'):
self._windows = RemoteSequence(self,
self._vim.Window,
lambda: self.get_windows())
return self._windows
@property
def vars(self):
if not hasattr(self, '_vars'):
self._vars = RemoteMap(lambda k: self.get_var(k),
lambda k, v: self.set_var(k, v))
return self._vars
@property
def number(self):
return self._handle
@property
def window(self):
return self.get_window()
@property
def valid(self):
return self.is_valid()
| from util import RemoteMap
class Tabpage(object):
@property
def windows(self):
if not hasattr(self, '_windows'):
self._windows = RemoteSequence(self,
self.Window,
lambda: self.get_windows())
return self._windows
@property
def vars(self):
if not hasattr(self, '_vars'):
self._vars = RemoteMap(lambda k: self.get_var(k),
lambda k, v: self.set_var(k, v))
return self._vars
@property
def number(self):
return self._handle
@property
def window(self):
return self.get_window()
@property
def valid(self):
return self.is_valid()
|
fix: Make PlaceholderDocs iterate over options again | <?php /** @var \nochso\WriteMe\Placeholder\PlaceholderDocs\TemplateData $this */ ?>
<?php foreach ($this->getPlaceholders() as $placeholder): ?>
<?php $class = $this->getClassForPlaceholder($placeholder); ?>
<?php $docBlock = $this->getClassDocBlock($class); ?>
<?= $this->header(1, $class->getShortName()) ?> `@@<?= $placeholder->getIdentifier() ?>@@`
<?= $docBlock->getText() ?>
<?= $this->header(2, 'Default options') ?>
```yaml
<?= $this->getOptionListYaml($placeholder->getDefaultOptionList()) ?>
```
<?php foreach ($placeholder->getDefaultOptionList()->getOptions() as $option): ?>
* `<?= $option->getPath() ?>`
<?= $this->indent(1, '*') ?> <?= $option->getDescription() ?>
<?php endforeach; ?>
<?php endforeach; ?>
| <?php /** @var \nochso\WriteMe\Placeholder\PlaceholderDocs\TemplateData $this */ ?>
<?php foreach ($this->getPlaceholders() as $placeholder): ?>
<?php $class = $this->getClassForPlaceholder($placeholder); ?>
<?php $docBlock = $this->getClassDocBlock($class); ?>
<?= $this->header(1, $class->getShortName()) ?> `@@<?= $placeholder->getIdentifier() ?>@@`
<?= $docBlock->getText() ?>
<?= $this->header(2, 'Default options') ?>
```yaml
<?= $this->getOptionListYaml($placeholder->getDefaultOptionList()) ?>
```
<?php foreach ($placeholder->getDefaultOptionList() as $option): ?>
* `<?= $option->getPath() ?>`
<?= $this->indent(1, '*') ?> <?= $option->getDescription() ?>
<?php endforeach; ?>
<?php endforeach; ?>
|
Use drop row by default | 'use strict';
/**
* @ngdoc directive
* @name grafterizerApp.directive:dropRowsFunction
* @description
* # dropRowsFunction
*/
angular.module('grafterizerApp')
.directive('dropRowsFunction', function(transformationDataModel) {
return {
templateUrl: 'views/pipelineFunctions/dropRowsFunction.html',
restrict: 'E',
link: function postLink(scope, element, attrs) {
if (!scope.function) {
scope.function = {
numberOfRows: 1,
take: false,
docstring: null
};
}
scope.$parent.generateCurrFunction = function() {
return new transformationDataModel.DropRowsFunction(parseInt(
scope.function.numberOfRows), scope.function.take, scope.function.docstring);
};
scope.doGrep = function() {
scope.$parent.selectefunctionName = 'grep';
};
scope.showUsage = false;
scope.switchShowUsage = function() {
scope.showUsage = !scope.showUsage;
};
}
};
});
| 'use strict';
/**
* @ngdoc directive
* @name grafterizerApp.directive:dropRowsFunction
* @description
* # dropRowsFunction
*/
angular.module('grafterizerApp')
.directive('dropRowsFunction', function(transformationDataModel) {
return {
templateUrl: 'views/pipelineFunctions/dropRowsFunction.html',
restrict: 'E',
link: function postLink(scope, element, attrs) {
if (!scope.function) {
scope.function = {
numberOfRows: 1,
take: true,
docstring: null
};
}
scope.$parent.generateCurrFunction = function() {
return new transformationDataModel.DropRowsFunction(parseInt(
scope.function.numberOfRows), scope.function.take, scope.function.docstring);
};
scope.doGrep = function() {
scope.$parent.selectefunctionName = 'grep';
};
scope.showUsage = false;
scope.switchShowUsage = function() {
scope.showUsage = !scope.showUsage;
};
}
};
});
|
Fix ContentBlocks dashboard preview render bug. | import React, { Component } from 'react';
import Box from 'grommet/components/Box';
import { BLOCK_TYPE_MAP } from 'grommet-cms/containers/Dashboard/DashboardContentBlocks/constants';
export default class ContentBlocks extends Component {
_renderBlocks(blocks) {
return blocks.map((block, index) => {
return (!block.edit) ? React.cloneElement(
BLOCK_TYPE_MAP[block.blockType].element,
{
...block,
key: `block-${index}`
}
) : undefined;
});
}
render() {
const blocks = (this.props.blocks)
? this._renderBlocks(this.props.blocks)
: undefined;
return (
<Box>
{blocks}
</Box>
);
}
};
| import React, { Component } from 'react';
import Box from 'grommet/components/Box';
import { BLOCK_TYPE_MAP } from 'grommet-cms/containers/Dashboard/DashboardContentBlocks/constants';
export default class ContentBlocks extends Component {
_renderBlocks(blocks) {
return blocks.map((block, index) =>
React.cloneElement(
BLOCK_TYPE_MAP[block.blockType].element,
{
...block,
key: `block-${index}`
}
)
);
}
render() {
const blocks = (this.props.blocks)
? this._renderBlocks(this.props.blocks)
: undefined;
return (
<Box>
{blocks}
</Box>
);
}
};
|
Check if obj is null to avoid TypeError in pino
Currently I'm getting this error in pino since some obj passed by pino to fast-safe-stringify is null. To avoid this and to restore JSON.stringify(null) behavior an additional null check is introduced here.
```
if (typeof obj === 'object' && typeof obj.toJSON !== 'function') {
^
TypeError: Cannot read property 'toJSON' of null
at EventEmitter.stringify (C:\p\codellama.io\web\server\node_modules\fast-safe-stringify\index.js:4:44)
at EventEmitter.asJson (C:\p\codellama.io\web\server\node_modules\pino\pino.js:137:22)
at EventEmitter.pinoWrite (C:\p\codellama.io\web\server\node_modules\pino\pino.js:193:16)
at EventEmitter.LOG (C:\p\codellama.io\web\server\node_modules\pino\lib\tools.js:117:10)
at C:\p\codellama.io\web\server\lib\stats.js:8:12
at C:\p\codellama.io\web\server\app\middleware.js:26:58
at Array.<anonymous> (C:\p\codellama.io\web\server\node_modules\express-req-metrics\index.js:22:7)
at listener (C:\p\codellama.io\web\server\node_modules\on-finished\index.js:169:15)
at onFinish (C:\p\codellama.io\web\server\node_modules\on-finished\index.js:100:5)
at callback (C:\p\codellama.io\web\server\node_modules\ee-first\index.js:55:10)
``` | module.exports = stringify
stringify.default = stringify
function stringify (obj) {
if (obj !== null && typeof obj === 'object' && typeof obj.toJSON !== 'function') {
decirc(obj, '', [], null)
}
return JSON.stringify(obj)
}
function Circle (val, k, parent) {
this.val = val
this.k = k
this.parent = parent
this.count = 1
}
Circle.prototype.toJSON = function toJSON () {
if (--this.count === 0) {
this.parent[this.k] = this.val
}
return '[Circular]'
}
function decirc (val, k, stack, parent) {
var keys, len, i
if (typeof val !== 'object' || val === null) {
// not an object, nothing to do
return
} else if (val instanceof Circle) {
val.count++
return
} else if (typeof val.toJSON === 'function') {
return
} else if (parent) {
if (~stack.indexOf(val)) {
parent[k] = new Circle(val, k, parent)
return
}
}
stack.push(val)
keys = Object.keys(val)
len = keys.length
i = 0
for (; i < len; i++) {
k = keys[i]
decirc(val[k], k, stack, val)
}
stack.pop()
}
| module.exports = stringify
stringify.default = stringify
function stringify (obj) {
if (typeof obj === 'object' && typeof obj.toJSON !== 'function') {
decirc(obj, '', [], null)
}
return JSON.stringify(obj)
}
function Circle (val, k, parent) {
this.val = val
this.k = k
this.parent = parent
this.count = 1
}
Circle.prototype.toJSON = function toJSON () {
if (--this.count === 0) {
this.parent[this.k] = this.val
}
return '[Circular]'
}
function decirc (val, k, stack, parent) {
var keys, len, i
if (typeof val !== 'object' || val === null) {
// not an object, nothing to do
return
} else if (val instanceof Circle) {
val.count++
return
} else if (typeof val.toJSON === 'function') {
return
} else if (parent) {
if (~stack.indexOf(val)) {
parent[k] = new Circle(val, k, parent)
return
}
}
stack.push(val)
keys = Object.keys(val)
len = keys.length
i = 0
for (; i < len; i++) {
k = keys[i]
decirc(val[k], k, stack, val)
}
stack.pop()
}
|
Stop pinning to specific patch versions
This package should not require specific patch versions. Rather, it
should express the broadest range of possible versions that it supports.
In the current `setup.py`, we are very particular about which versions
must be used. Because of the specificity, installing `clrsvsim` makes
updating any other dependent libraries (e.g. `numpy`) quite difficult.
Modern dependency managers like `poetry` on `pipenv` will loudly
complain about dependency conflicts, making `clrsvism` a problematic
dependency.
Instead, we should just specify each of these as the *minimum* version
required. If there's some reason that the package does not support the
latest versions, then we can sort that out at a later time. | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name = "clrsvsim",
version = "0.1.0",
description = "Color Genomics Structural Variant Simulator",
author = "Color Genomics",
author_email = "dev@color.com",
url = "https://github.com/ColorGenomics/clrsvsim",
packages = ["clrsvsim"],
install_requires=[
'cigar>=0.1.3',
'numpy>=1.10.1',
'preconditions>=0.1',
'pyfasta>=0.5.2',
'pysam>=0.10.0',
],
tests_require=[
# NOTE: `mock` is not actually needed in Python 3.
# `unittest.mock` can be used instead.
'mock>=2.0.0',
'nose>=1.3.7',
],
license = "Apache-2.0",
)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name = "clrsvsim",
version = "0.0.2",
description = "Color Genomics Structural Variant Simulator",
author = "Color Genomics",
author_email = "dev@color.com",
url = "https://github.com/ColorGenomics/clrsvsim",
packages = ["clrsvsim"],
install_requires=[
'cigar==0.1.3',
'numpy==1.10.1',
'preconditions==0.1',
'pyfasta==0.5.2',
'pysam==0.10.0',
],
tests_require=[
'mock==2.0.0',
'nose==1.3.7',
],
license = "Apache-2.0",
)
|
Mark test as fail in panic recovery function. | package main
import (
"fmt"
"os"
"runtime/debug"
"testing"
. "github.com/onsi/gomega"
"github.com/sclevine/agouti"
)
const (
PORT = 9009
)
var (
baseUrl = fmt.Sprintf("http://localhost:%v/admin", PORT)
driver *agouti.WebDriver
page *agouti.Page
)
func TestMain(m *testing.M) {
var t *testing.T
var err error
driver = agouti.Selenium()
driver.Start()
go Start(PORT)
page, err = driver.NewPage(agouti.Browser("chrome"))
if err != nil {
t.Error("Failed to open page.")
}
RegisterTestingT(t)
test := m.Run()
driver.Stop()
os.Exit(test)
}
func StopDriverOnPanic() {
var t *testing.T
if r := recover(); r != nil {
debug.PrintStack()
fmt.Println("Recovered in f", r)
driver.Stop()
t.Fail()
}
}
| package main
import (
"fmt"
"os"
"runtime/debug"
"testing"
. "github.com/onsi/gomega"
"github.com/sclevine/agouti"
)
const (
PORT = 9009
)
var (
baseUrl = fmt.Sprintf("http://localhost:%v/admin", PORT)
driver *agouti.WebDriver
page *agouti.Page
)
func TestMain(m *testing.M) {
var t *testing.T
var err error
driver = agouti.Selenium()
driver.Start()
go Start(PORT)
page, err = driver.NewPage(agouti.Browser("chrome"))
if err != nil {
t.Error("Failed to open page.")
}
RegisterTestingT(t)
test := m.Run()
driver.Stop()
os.Exit(test)
}
func StopDriverOnPanic() {
if r := recover(); r != nil {
debug.PrintStack()
fmt.Println("Recovered in f", r)
driver.Stop()
}
}
|
Fix Settings of Patients Summary. | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Col } from 'react-bootstrap';
export default class PTCustomCheckbox extends PureComponent {
static propTypes = {
title: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
isChecked: PropTypes.bool.isRequired,
onChange: PropTypes.func,
disabled: PropTypes.bool,
};
toggleCheckbox = () => {
const { disabled = false, name, onChange } = this.props;
return !disabled && onChange(name);
};
render() {
const { title, name, isChecked, disabled = false } = this.props;
return (
<Col xs={6} sm={4}>
<div className="wrap-fcustominp">
<div className={classNames('fcustominp-state', { disabled })} onClick={this.toggleCheckbox} >
<div className="fcustominp">
<input type="checkbox" id={`dashboard-${name}`} name={`dashboard-${name}`} checked={isChecked} onChange={this.toggleCheckbox} />
<label htmlFor={`dashboard-${name}`} />
</div>
<label htmlFor={`dashboard-${name}`} className="fcustominp-label">{title}</label>
</div>
</div>
</Col>
)
}
};
| import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Col } from 'react-bootstrap';
export default class PTCustomCheckbox extends PureComponent {
static propTypes = {
title: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
isChecked: PropTypes.bool.isRequired,
onChange: PropTypes.func,
disabled: PropTypes.bool,
};
toggleCheckbox = () => {
const { disabled = false, onChange } = this.props;
return !disabled && onChange(name);
};
render() {
const { title, name, isChecked, disabled = false } = this.props;
return (
<Col xs={6} sm={4}>
<div className="wrap-fcustominp">
<div className={classNames('fcustominp-state', { disabled })} onClick={this.toggleCheckbox} >
<div className="fcustominp">
<input type="checkbox" id={`dashboard-${name}`} name={`dashboard-${name}`} checked={isChecked} onChange={this.toggleCheckbox} />
<label htmlFor={`dashboard-${name}`} />
</div>
<label htmlFor={`dashboard-${name}`} className="fcustominp-label">{title}</label>
</div>
</div>
</Col>
)
}
};
|
Correct SocketIO path for Karma tests
The tests should no longer be erroring out. | /* eslint-env node */
module.exports = function (config) {
config.set({
basePath: 'public',
browsers: ['ChromeHeadlessCustom'],
files: [
'styles/index.css',
'scripts/mithril.min.js',
'scripts/underscore-min.js',
'scripts/tinyemitter.min.js',
'scripts/sw-update-manager.js',
'scripts/socket.io.min.js',
'scripts/clipboard.min.js',
'scripts/test.js'
],
reporters: ['dots'].concat(process.env.COVERAGE ? ['coverage'] : []),
frameworks: ['mocha', 'chai-dom', 'sinon-chai'],
preprocessors: {
'**/*.js': ['sourcemap'],
'scripts/test.js': process.env.COVERAGE ? ['coverage'] : []
},
coverageReporter: {
type: 'json',
dir: '../coverage/',
subdir: '.',
file: 'coverage-unmapped.json'
},
customLaunchers: {
ChromeHeadlessCustom: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
}
});
};
| /* eslint-env node */
module.exports = function (config) {
config.set({
basePath: 'public',
browsers: ['ChromeHeadlessCustom'],
files: [
'styles/index.css',
'scripts/mithril.min.js',
'scripts/underscore-min.js',
'scripts/tinyemitter.min.js',
'scripts/sw-update-manager.js',
'scripts/socket.io.slim.js',
'scripts/clipboard.min.js',
'scripts/test.js'
],
reporters: ['dots'].concat(process.env.COVERAGE ? ['coverage'] : []),
frameworks: ['mocha', 'chai-dom', 'sinon-chai'],
preprocessors: {
'**/*.js': ['sourcemap'],
'scripts/test.js': process.env.COVERAGE ? ['coverage'] : []
},
coverageReporter: {
type: 'json',
dir: '../coverage/',
subdir: '.',
file: 'coverage-unmapped.json'
},
customLaunchers: {
ChromeHeadlessCustom: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
}
});
};
|
[LOG4J2-787] Add lookup for JVM arguments. Add missing ctor.
git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1619302 13f79535-47bb-0310-9956-ffa450edef68 | package org.apache.logging.log4j.core.lookup;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.core.config.plugins.Plugin;
/**
* Maps JVM input arguments (but not main arguments) using JMX to acquire JVM arguments.
*
* @see java.lang.management.RuntimeMXBean#getInputArguments()
* @since 2.1
*/
@Plugin(name = "jvmrunargs", category = "Lookup")
public class JmxRuntimeInputArgumentsLookup extends MapLookup {
static {
List<String> argsList = ManagementFactory.getRuntimeMXBean().getInputArguments();
JMX_SINGLETON = new JmxRuntimeInputArgumentsLookup(MapLookup.toMap(argsList));
}
public static final JmxRuntimeInputArgumentsLookup JMX_SINGLETON;
/**
* Constructor when used directly as a plugin.
*/
public JmxRuntimeInputArgumentsLookup() {
super();
}
public JmxRuntimeInputArgumentsLookup(Map<String, String> map) {
super(map);
}
}
| package org.apache.logging.log4j.core.lookup;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.core.config.plugins.Plugin;
/**
* Maps JVM input arguments (but not main arguments) using JMX to acquire JVM arguments.
*
* @see java.lang.management.RuntimeMXBean#getInputArguments()
* @since 2.1
*/
@Plugin(name = "jvmrunargs", category = "Lookup")
public class JmxRuntimeInputArgumentsLookup extends MapLookup {
static {
List<String> argsList = ManagementFactory.getRuntimeMXBean().getInputArguments();
JMX_SINGLETON = new JmxRuntimeInputArgumentsLookup(MapLookup.toMap(argsList));
}
public static final JmxRuntimeInputArgumentsLookup JMX_SINGLETON;
public JmxRuntimeInputArgumentsLookup(Map<String, String> map) {
super(map);
}
}
|
Fix getValue, getReason when getting value from nested promises | 'use strict';
import { PENDING, FULFILLED, REJECTED, SETTLED, NEVER, HANDLED } from './state';
export function isPending(p) {
return (p.state() & PENDING) > 0;
}
export function isFulfilled(p) {
return (p.state() & FULFILLED) > 0;
}
export function isRejected(p) {
return (p.state() & REJECTED) > 0;
}
export function isSettled(p) {
return (p.state() & SETTLED) > 0;
}
export function isNever(p) {
return (p.state() & NEVER) > 0;
}
export function isHandled(p) {
return (p.state() & HANDLED) > 0;
}
export function silenceError(p) {
if (!isFulfilled(p)) {
p._runAction(silencer);
}
}
export function getValue(p) {
let n = p.near();
if (!isFulfilled(n)) {
throw new TypeError('getValue called on ' + p);
}
return n.value;
}
export function getReason(p) {
let n = p.near();
if (!isRejected(n)) {
throw new TypeError('getReason called on ' + p);
}
return n.value;
}
const silencer = {
fulfilled() {},
rejected(p) {
p._state |= HANDLED;
}
};
| 'use strict';
import { PENDING, FULFILLED, REJECTED, SETTLED, NEVER, HANDLED } from './state';
export function isPending(p) {
return (p.state() & PENDING) > 0;
}
export function isFulfilled(p) {
return (p.state() & FULFILLED) > 0;
}
export function isRejected(p) {
return (p.state() & REJECTED) > 0;
}
export function isSettled(p) {
return (p.state() & SETTLED) > 0;
}
export function isNever(p) {
return (p.state() & NEVER) > 0;
}
export function isHandled(p) {
return (p.state() & HANDLED) > 0;
}
export function silenceError(p) {
if (!isFulfilled(p)) {
p._runAction(silencer);
}
}
export function getValue(p) {
let n = p.near();
if (!isFulfilled(n)) {
throw new TypeError('getValue called on ' + p);
}
return p.value;
}
export function getReason(p) {
let n = p.near();
if (!isRejected(n)) {
throw new TypeError('getReason called on ' + p);
}
return p.value;
}
const silencer = {
fulfilled() {},
rejected(p) {
p._state |= HANDLED;
}
};
|
Fix issue where team page is not found | import React, { Component } from 'react'
import Helmet from 'react-helmet'
import { NavBar } from '../../components'
const styles = {
iframe: {
width: '100%',
}
}
class TeamPage extends Component {
componentDidMount() {
var iframe = this.refs.iframe
iframe.addEventListener('load', () => {
var iframeScrollHeight = iframe.contentWindow.document.body.scrollHeight + 'px'
iframe.height = iframeScrollHeight
})
}
render() {
return(
<div>
<Helmet title="Team" />
<NavBar />
<iframe ref="iframe" style={styles.iframe} src="/staticPage/team/index.html" />
</div>
)
}
}
export default TeamPage
| import React, { Component } from 'react'
import Helmet from 'react-helmet'
import { NavBar } from '../../components'
const styles = {
iframe: {
width: '100%',
}
}
class TeamPage extends Component {
componentDidMount() {
var iframe = this.refs.iframe
iframe.addEventListener('load', () => {
var iframeScrollHeight = iframe.contentWindow.document.body.scrollHeight + 'px'
iframe.height = iframeScrollHeight
})
}
render() {
return(
<div>
<Helmet title="Team" />
<NavBar />
<iframe ref="iframe" style={styles.iframe} src="/staticPage/team"/>
</div>
)
}
}
export default TeamPage
|
Fix copy and paste error on container-image
Closes: #57
Approved by: rhatdan | package main
import (
"fmt"
"github.com/urfave/cli"
)
var (
rmiDescription = "Removes one or more locally stored images."
rmiCommand = cli.Command{
Name: "rmi",
Usage: "Removes one or more images from local storage",
Description: rmiDescription,
Action: rmiCmd,
ArgsUsage: "IMAGE-NAME-OR-ID [...]",
}
)
func rmiCmd(c *cli.Context) error {
args := c.Args()
if len(args) == 0 {
return fmt.Errorf("image ID must be specified")
}
store, err := getStore(c)
if err != nil {
return err
}
for _, id := range args {
_, err := store.DeleteImage(id, true)
if err != nil {
return fmt.Errorf("error removing image %q: %v", id, err)
}
fmt.Printf("%s\n", id)
}
return nil
}
| package main
import (
"fmt"
"github.com/urfave/cli"
)
var (
rmiDescription = "Removes one or more locally stored images."
rmiCommand = cli.Command{
Name: "rmi",
Usage: "Removes one or more images from local storage",
Description: rmiDescription,
Action: rmiCmd,
ArgsUsage: "IMAGE-NAME-OR-ID [...]",
}
)
func rmiCmd(c *cli.Context) error {
args := c.Args()
if len(args) == 0 {
return fmt.Errorf("container ID must be specified")
}
store, err := getStore(c)
if err != nil {
return err
}
for _, id := range args {
_, err := store.DeleteImage(id, true)
if err != nil {
return fmt.Errorf("error removing image %q: %v", id, err)
}
fmt.Printf("%s\n", id)
}
return nil
}
|
Update selector for Delete Fork Link
Related to #1001 | import {h} from 'dom-chef';
import select from 'select-dom';
import * as pageDetect from '../libs/page-detect';
const repoUrl = pageDetect.getRepoURL();
export default function () {
const canDeleteFork = select.exists('.reponav-item[data-selected-links~="repo_settings"]');
const postMergeDescription = select('#partial-pull-merging .merge-branch-description');
if (canDeleteFork && postMergeDescription) {
const currentBranch = postMergeDescription.querySelector('.commit-ref');
const forkPath = currentBranch ? currentBranch.title.split(':')[0] : null;
if (forkPath && forkPath !== repoUrl) {
postMergeDescription.append(
<a id="refined-github-delete-fork-link" href={`/${forkPath}/settings`}>
Delete fork
</a>
);
}
}
}
| import {h} from 'dom-chef';
import select from 'select-dom';
import * as pageDetect from '../libs/page-detect';
const repoUrl = pageDetect.getRepoURL();
export default function () {
const canDeleteFork = select.exists('.reponav-item [data-selected-links~="repo_settings"]');
const postMergeDescription = select('#partial-pull-merging .merge-branch-description');
if (canDeleteFork && postMergeDescription) {
const currentBranch = postMergeDescription.querySelector('.commit-ref');
const forkPath = currentBranch ? currentBranch.title.split(':')[0] : null;
if (forkPath && forkPath !== repoUrl) {
postMergeDescription.append(
<a id="refined-github-delete-fork-link" href={`/${forkPath}/settings`}>
Delete fork
</a>
);
}
}
}
|
Revert "feat(builds): add mapping for Bamboo build status"
This reverts commit 96188b7dc0d3ed3acc20ec2e744fcf3850863405.
This is a problem of the bamboo collector | /*
* Copyright 2017 Banco Bilbao Vizcaya Argentaria, S.A..
*
* 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 com.bbva.arq.devops.ae.mirrorgate.core.utils;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration of build status.
*
*/
public enum BuildStatus {
Deleted,
Success,
Failure,
Unstable,
Aborted,
InProgress,
NotBuilt,
Unknown;
private static final Map<String, BuildStatus> MAPPING = new HashMap<>();
static{
MAPPING.put("not_built", NotBuilt);
for (BuildStatus buildStatus : values()) {
MAPPING.put(buildStatus.toString().toLowerCase(), buildStatus);
}
}
public static BuildStatus fromString(String value) {
String key = value.toLowerCase();
return MAPPING.containsKey(key) ? MAPPING.get(key): Unknown;
}
}
| /*
* Copyright 2017 Banco Bilbao Vizcaya Argentaria, S.A..
*
* 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 com.bbva.arq.devops.ae.mirrorgate.core.utils;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration of build status.
*
*/
public enum BuildStatus {
Deleted,
Success,
Failure,
Unstable,
Aborted,
InProgress,
NotBuilt,
Unknown;
private static final Map<String, BuildStatus> MAPPING = new HashMap<>();
static{
MAPPING.put("not_built", NotBuilt);
MAPPING.put("successful", Success);
MAPPING.put("failed", Failure);
for (BuildStatus buildStatus : values()) {
MAPPING.put(buildStatus.toString().toLowerCase(), buildStatus);
}
}
public static BuildStatus fromString(String value) {
String key = value.toLowerCase();
return MAPPING.containsKey(key) ? MAPPING.get(key): Unknown;
}
}
|
Change STRIPES_IFACE environment variable to STRIPES_HOST. | var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.cli.dev');
var app = express();
var compiler = webpack(config);
var port = process.env.STRIPES_PORT || 3000;
var host = process.env.STRIPES_HOST || 'localhost';
app.use(express.static(__dirname + '/public'));
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(port, host, function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://' + host + ':' + port);
});
| var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.cli.dev');
var app = express();
var compiler = webpack(config);
var port = process.env.STRIPES_PORT || 3000;
var host = process.env.STRIPES_IFACE || 'localhost';
app.use(express.static(__dirname + '/public'));
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(port, host, function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://' + host + ':' + port);
});
|
Fix typo and style for GSBPM sub process details | import React from 'react'
import { connectFromRoute } from '../routes'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADED } from 'sparql-connect'
import ServicesByGSBPMSubProcess from './services-by-gsbpm-subprocess'
// GSBPMSub comes from `connectFromRoute` (it's then passed to the sparql
// connected component, which keeps it in its own props)
function GSBPMSubProcessDetails({
GSBPMSub, loaded, label, code, definition }) {
return (
<div>
<dl className="dl-horizontal">
<dt>Label</dt>
<dd>{label}</dd>
<dt>Definition</dt>
<dd>{definition}</dd>
<dt>Code</dt>
<dd>{code}</dd>
<dt>Services</dt>
<dd>
<ServicesByGSBPMSubProcess GSBPMSub={GSBPMSub} />
</dd>
</dl>
</div>
)
}
export default connectFromRoute(
sparqlConnect.GSBPMSubProcessDetails(GSBPMSubProcessDetails)
)
| import React from 'react'
import { connectFromRoute } from '../routes'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADED } from 'sparql-connect'
import ServicesByGSBPMSubProcess from './services-by-gsbpm-subprocess'
// GSBPMSub comes from `connectFromRoute` (it's then passed to the sparql
// connected component, which keeps it in its own props)
function GSBPMSubProcessDetails({
GSBPMSub, loaded, label, code, definition }) {
return (
<div>
<dl className="dl-horizontal">
<dt>Label</dt>
<dd>{label}</dd>
<dt>Definition</dt>
<dd>{definition}</dd>
<dt>Cpde</dt>
<dd>{code}</dd>
<dt>Services implementing this GSBPM sub process</dt>
<dd>
<ServicesByGSBPMSubProcess GSBPMSub={GSBPMSub} />
</dd>
</dl>
</div>
)
}
export default connectFromRoute(
sparqlConnect.GSBPMSubProcessDetails(GSBPMSubProcessDetails)
)
|
Set HTTPS for map tiles service | export const NODE_ENV_PRODUCTION = process.env.NODE_ENV === 'production';
export const gaTrackingId = 'UA-97591265-1';
export const locale = 'en-US';
export const gameConfig = {
timeout: 15,
rounds: 20
};
export const gameStatus = {
started: 'started',
results: 'results',
paused: 'paused',
stopped: 'stopped'
};
export const gameModes = {
countryName: 'name',
flag: 'flag',
capital: 'capital'
};
export const mapConfig = {
attributions: '© <a href="https://www.mapbox.com/about/maps/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> <strong><a href="https://www.mapbox.com/map-feedback/" target="_blank">Improve this map</a></strong>',
serviceUrl: 'https://{s}.tiles.mapbox.com/v3/raffalli.i3ip4bic/{z}/{x}/{y}.png'
};
export const colors = {
'default': 'transparent',
active: '#0275d8',
greenOk: '#5cb85c',
redError: '#d9534f'
};
| export const NODE_ENV_PRODUCTION = process.env.NODE_ENV === 'production';
export const gaTrackingId = 'UA-97591265-1';
export const locale = 'en-US';
export const gameConfig = {
timeout: 15,
rounds: 20
};
export const gameStatus = {
started: 'started',
results: 'results',
paused: 'paused',
stopped: 'stopped'
};
export const gameModes = {
countryName: 'name',
flag: 'flag',
capital: 'capital'
};
export const mapConfig = {
attributions: '© <a href="https://www.mapbox.com/about/maps/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> <strong><a href="https://www.mapbox.com/map-feedback/" target="_blank">Improve this map</a></strong>',
serviceUrl: 'http://{s}.tiles.mapbox.com/v3/raffalli.i3ip4bic/{z}/{x}/{y}.png'
};
export const colors = {
'default': 'transparent',
active: '#0275d8',
greenOk: '#5cb85c',
redError: '#d9534f'
};
|
Fix a bug in removing cid img without attachments | 'use strict';
module.exports = function(html, attachments) {
attachments.forEach(function(attachment) {
attachment.applied = false;
var regexps = [
(attachment.fileName) ? new RegExp('<img[^>]*cid:' + attachment.fileName.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + '[@"\'][^>]*>', 'ig') : undefined,
(attachment.contentId) ? new RegExp('<img[^>]*cid:' + attachment.contentId.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + '[@"\'][^>]*>', 'ig') : undefined,
];
var content = Buffer.isBuffer(attachment.content) ? attachment.content.toString('base64') : attachment.content;
var extension = attachment.fileName.substr(attachment.fileName.lastIndexOf('.') + 1);
if(extension === 'jpeg') {
extension = 'jpg';
}
regexps.forEach(function(regexp) {
if(regexp && regexp.test(html)) {
attachment.applied = true;
html = html.replace(regexp, '<img src="data:image/' + extension + ';base64,' + content + '" />');
}
});
});
return html.replace(/<img[^>]*cid:[^>]*>/ig, '');
}; | 'use strict';
module.exports = function(html, attachments) {
attachments.forEach(function(attachment) {
attachment.applied = false;
var regexps = [
(attachment.fileName) ? new RegExp('<img[^>]*cid:' + attachment.fileName + '[@"\'][^>]*>', 'ig') : undefined,
(attachment.contentId) ? new RegExp('<img[^>]*cid:' + attachment.contentId + '[@"\'][^>]*>', 'ig') : undefined,
];
var content = Buffer.isBuffer(attachment.content) ? attachment.content.toString('base64') : attachment.content;
var extension = attachment.fileName.substr(attachment.fileName.lastIndexOf('.') + 1);
if(extension === 'jpeg') {
extension = 'jpg';
}
regexps.forEach(function(regexp) {
if(regexp && regexp.test(html)) {
attachment.applied = true;
html = html.replace(regexp, '<img src="data:image/' + extension + ';base64,' + content + '" />');
}
});
});
return html.replace(/<img[^>]*cid[^>]*>/ig, '');
}; |
Remove a redundant line in background page | // /////////////////////////////////////////////////////// //
// Load content via window.fetch in a background script, //
// from a content script //
// /////////////////////////////////////////////////////// //
// Load this file as background and content scripts
// Use in content_script as:
// backgroundFetch(url).then(doSomething)
if (location.protocol === 'chrome-extension:' || location.protocol === 'moz-extension:') {
// setup in background page
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'fetch') {
fetch(...message.arguments)
.then(response => response.json())
.then(sendResponse)
.catch(err => sendResponse(String(err)));
}
return true; // tell browser to await response
});
} else {
// setup in content script
window.backgroundFetch = function (...args) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({
action: 'fetch',
arguments: args
}, response => {
if (/^Error/.test(response)) {
reject(new Error(response.replace(/Error:? ?/, '')));
} else {
resolve(response);
}
});
});
};
}
| // /////////////////////////////////////////////////////// //
// Load content via window.fetch in a background script, //
// from a content script //
// /////////////////////////////////////////////////////// //
// Load this file as background and content scripts
// Use in content_script as:
// backgroundFetch(url).then(doSomething)
if (location.protocol === 'chrome-extension:' || location.protocol === 'moz-extension:') {
// setup in background page
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'fetch') {
fetch(...message.arguments)
.then(response => response.json())
.then(sendResponse)
.catch(err => sendResponse(String(err)));
}
return true; // tell browser to await response
});
} else {
// setup in content script
window.backgroundFetch = function () {
const args = [...arguments];
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({
action: 'fetch',
arguments: args
}, response => {
if (/^Error/.test(response)) {
reject(new Error(response.replace(/Error:? ?/, '')));
} else {
resolve(response);
}
});
});
};
}
|
Fix Constructor Calls Overridable Method. | package com.vaguehope.onosendai.model;
public class TweetBuilder {
private long id;
private String username;
private String body;
private long unitTimeSeconds;
private String avatarUrl;
// TODO include metas?
public TweetBuilder () {
reset();
}
public final void reset () {
this.id = 0L;
this.username = null;
this.body = null;
this.unitTimeSeconds = 0L;
this.avatarUrl = null;
}
public TweetBuilder id (final long v) {
this.id = v;
return this;
}
public TweetBuilder username (final String v) {
this.username = v;
return this;
}
public TweetBuilder body (final String v) {
this.body = v;
return this;
}
public TweetBuilder unitTimeSeconds (final long v) {
this.unitTimeSeconds = v;
return this;
}
public TweetBuilder avatarUrl (final String v) {
this.avatarUrl = v;
return this;
}
public Tweet build () {
Tweet t = new Tweet(this.id, this.username, this.body, this.unitTimeSeconds, this.avatarUrl);
reset();
return t;
}
}
| package com.vaguehope.onosendai.model;
public class TweetBuilder {
private long id;
private String username;
private String body;
private long unitTimeSeconds;
private String avatarUrl;
// TODO include metas?
public TweetBuilder () {
reset();
}
public void reset () {
this.id = 0L;
this.username = null;
this.body = null;
this.unitTimeSeconds = 0L;
this.avatarUrl = null;
}
public TweetBuilder id (final long v) {
this.id = v;
return this;
}
public TweetBuilder username (final String v) {
this.username = v;
return this;
}
public TweetBuilder body (final String v) {
this.body = v;
return this;
}
public TweetBuilder unitTimeSeconds (final long v) {
this.unitTimeSeconds = v;
return this;
}
public TweetBuilder avatarUrl (final String v) {
this.avatarUrl = v;
return this;
}
public Tweet build () {
Tweet t = new Tweet(this.id, this.username, this.body, this.unitTimeSeconds, this.avatarUrl);
reset();
return t;
}
}
|
CSRA-000: Add addtional app insights login | import superagent from 'superagent';
import buildAssessmentRequest from './buildAssessmentRequest';
const postAssessmentToBackend = (assessmentType, {
nomisId,
outcome,
viperScore,
questions,
answers,
reasons,
}, callback) => {
const riskAssessmentRequestParams = buildAssessmentRequest(assessmentType, {
nomisId,
outcome,
viperScore,
questions,
answers,
reasons,
});
const target = `${window.location.origin}/api/assessment`;
if (window.appInsights) {
window.appInsights.trackEvent('Posting to /api/assessment for:', { nomisId });
}
superagent.post(target, riskAssessmentRequestParams, (error, res) => {
if (error) {
if (window.appInsights) {
window.appInsights.trackEvent('Failed to store assessment for:', { nomisId, error });
}
callback(null);
} else {
callback(res.body.data.id);
}
});
};
export default postAssessmentToBackend;
| import superagent from 'superagent';
import buildAssessmentRequest from './buildAssessmentRequest';
const postAssessmentToBackend = (assessmentType, {
nomisId,
outcome,
viperScore,
questions,
answers,
reasons,
}, callback) => {
const riskAssessmentRequestParams = buildAssessmentRequest(assessmentType, {
nomisId,
outcome,
viperScore,
questions,
answers,
reasons,
});
const target = `${window.location.origin}/api/assessment`;
superagent.post(target, riskAssessmentRequestParams, (error, res) => {
if (error) {
if (window.appInsights) {
window.appInsights.trackEvent('Failed to store assessment for:', { nomisId, error });
}
callback(null);
} else {
callback(res.body.data.id);
}
});
};
export default postAssessmentToBackend;
|
Fix some missing escape replacements | /*******************************************************************************
* Copyright (c) 2010 David Green and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Green - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.wikitext.confluence.core.token;
import org.eclipse.mylyn.wikitext.core.parser.markup.PatternBasedElement;
import org.eclipse.mylyn.wikitext.core.parser.markup.PatternBasedElementProcessor;
/**
* @author David Green
*/
public class EscapedCharacterReplacementToken extends PatternBasedElement {
@Override
protected String getPattern(int groupOffset) {
// currently we only escape curly braces, however
// it's possible there may be others. The documentation only shows escaping these.
return "\\\\(\\{|\\}|\\[|\\]|\\||\\!)"; //$NON-NLS-1$
}
@Override
protected int getPatternGroupCount() {
return 1;
}
@Override
protected PatternBasedElementProcessor newProcessor() {
return new EscapedCharacterReplacementTokenProcessor();
}
private static class EscapedCharacterReplacementTokenProcessor extends PatternBasedElementProcessor {
@Override
public void emit() {
String character = group(1);
getBuilder().characters(character);
}
}
}
| /*******************************************************************************
* Copyright (c) 2010 David Green and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Green - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.wikitext.confluence.core.token;
import org.eclipse.mylyn.wikitext.core.parser.markup.PatternBasedElement;
import org.eclipse.mylyn.wikitext.core.parser.markup.PatternBasedElementProcessor;
/**
* @author David Green
*/
public class EscapedCharacterReplacementToken extends PatternBasedElement {
@Override
protected String getPattern(int groupOffset) {
// currently we only escape curly braces, however
// it's possible there may be others. The documentation only shows escaping these.
return "\\\\(\\{|\\}|\\[|\\])"; //$NON-NLS-1$
}
@Override
protected int getPatternGroupCount() {
return 1;
}
@Override
protected PatternBasedElementProcessor newProcessor() {
return new EscapedCharacterReplacementTokenProcessor();
}
private static class EscapedCharacterReplacementTokenProcessor extends PatternBasedElementProcessor {
@Override
public void emit() {
String character = group(1);
getBuilder().characters(character);
}
}
}
|
Use log10 to get the amount of digits | #!/bin/env python
import os
import sys
import math
def main():
if len(sys.argv) == 1 or sys.argv[1].lower() == "-h" or sys.argv[1].lower() == "--help":
print("Syntax: fenum.py [files...]")
print("\tEnumerate the given files (starting at 1) in the same order as they are passed to the script.")
return
for k,v in enumerate(sys.argv[1:], 1):
path, name = os.path.split(v if not v.endswith("/") else v[:-1])
if path:
path += "/"
try:
fname = "{}{} - {}".format(
path,
str(k).zfill(int(math.log10(len(sys.argv) - 1)) + 1),
name)
print("\"{}\" -> \"{}\"".format(v, fname))
os.rename(v, fname)
except Exception as e:
print(str(e))
main()
| #!/bin/env python
import os
import sys
def main():
if len(sys.argv) == 1 or sys.argv[1].lower() == "-h" or sys.argv[1].lower() == "--help":
print("Syntax: fenum.py [files...]")
print("\tEnumerate the given files (starting at 1) in the same order as they are passed to the script.")
return
for k,v in enumerate(sys.argv[1:], 1):
path, name = os.path.split(v if not v.endswith("/") else v[:-1])
if path:
path += "/"
try:
fname = "{}{} - {}".format(path, str(k).zfill(len(str(len(sys.argv) - 1))), name)
print("\"{}\" -> \"{}\"".format(v, fname))
os.rename(v, fname)
except Exception as e:
print(str(e))
main()
|
Fix decode error of README.rst during installation | # coding=utf-8
from setuptools import setup, find_packages
from codecs import open
setup(
name="tinydb",
version="2.1.0",
packages=find_packages(),
# development metadata
zip_safe=True,
# metadata for upload to PyPI
author="Markus Siemens",
author_email="markus@m-siemens.de",
description="TinyDB is a tiny, document oriented database optimized for "
"your happiness :)",
license="MIT",
keywords="database nosql",
url="https://github.com/msiemens/tinydb",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Topic :: Database",
"Topic :: Database :: Database Engines/Servers",
"Topic :: Utilities",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: Implementation :: PyPy",
"Operating System :: OS Independent"
],
long_description=open('README.rst', encoding='utf-8').read(),
)
| # coding=utf-8
from setuptools import setup, find_packages
setup(
name="tinydb",
version="2.1.0",
packages=find_packages(),
# development metadata
zip_safe=True,
# metadata for upload to PyPI
author="Markus Siemens",
author_email="markus@m-siemens.de",
description="TinyDB is a tiny, document oriented database optimized for "
"your happiness :)",
license="MIT",
keywords="database nosql",
url="https://github.com/msiemens/tinydb",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Topic :: Database",
"Topic :: Database :: Database Engines/Servers",
"Topic :: Utilities",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: Implementation :: PyPy",
"Operating System :: OS Independent"
],
long_description=open('README.rst', 'r').read(),
)
|
Support port mappings from origin | package io.core9.proxy;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.TreeMap;
import org.littleshoot.proxy.HostResolver;
public class Core9HostResolver implements HostResolver {
private final Map<String,Proxy> HOSTS = new TreeMap<String,Proxy>();
@Override
public InetSocketAddress resolve(String host, int port) throws UnknownHostException {
if(HOSTS.containsKey(host)) {
String origin = HOSTS.get(host).getOrigin();
if(origin.contains(":")) {
String [] temp = origin.split(":");
origin = temp[0];
port = Integer.parseInt(temp[1]);
}
return new InetSocketAddress(origin, port);
} else {
return null;
}
}
public Core9HostResolver addHost(Proxy proxy) {
HOSTS.put(proxy.getHostname(), proxy);
return this;
}
public Core9HostResolver removeHost(String address) {
HOSTS.remove(address);
return this;
}
public Proxy getProxySpecification(String hostname) {
return HOSTS.get(hostname);
}
public Core9HostResolver removeAllHosts() {
HOSTS.clear();
return this;
}
}
| package io.core9.proxy;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.TreeMap;
import org.littleshoot.proxy.HostResolver;
public class Core9HostResolver implements HostResolver {
private final Map<String,Proxy> HOSTS = new TreeMap<String,Proxy>();
@Override
public InetSocketAddress resolve(String host, int port) throws UnknownHostException {
if(HOSTS.containsKey(host)) {
return new InetSocketAddress(HOSTS.get(host).getOrigin(), port);
} else {
return null;
}
}
public Core9HostResolver addHost(Proxy proxy) {
HOSTS.put(proxy.getHostname(), proxy);
return this;
}
public Core9HostResolver removeHost(String address) {
HOSTS.remove(address);
return this;
}
public Proxy getProxySpecification(String hostname) {
return HOSTS.get(hostname);
}
public Core9HostResolver removeAllHosts() {
HOSTS.clear();
return this;
}
}
|
Revert "Deliberately break CS in order to demonstrate how Jenkins and Travis react to broken builds"
This reverts commit 28e5d5db51b794569f53f1f43e0aa72d7656acd8. | 'use strict';
/* global define */
define([
'jquery',
'services/calculator/calculator'
], function ($, Calculator) {
var component = 'calculator';
var calculate = function ($component) {
var operation = $component.find('option:selected').val();
var x = parseFloat($component.find('[name="x"]').val());
var y = parseFloat($component.find('[name="y"]').val());
var calculator = new Calculator(x, y);
var result = calculator.calculate(operation) || '';
$component.find('[name="z"]').val(result);
};
$(document).on('change', '.' + component + ' [name="operation"]', function (e) {
e.preventDefault();
var $this = $(this);
var $component = $this.closest('.' + component);
calculate($component);
}).on('click', '.' + component + ' [name="equals"]', function (e) {
e.preventDefault();
var $this = $(this);
var $component = $this.closest('.' + component);
calculate($component);
});
});
| 'use strict';
/* global define */
define([
'jquery',
'services/calculator/calculator'
], function ($, Calculator) {
var component = 'calculator';
while(true) { console.log('This is stupid') }
var calculate = function ($component) {
var operation = $component.find('option:selected').val();
var x = parseFloat($component.find('[name="x"]').val());
var y = parseFloat($component.find('[name="y"]').val());
var calculator = new Calculator(x, y);
var result = calculator.calculate(operation) || '';
$component.find('[name="z"]').val(result);
};
$(document).on('change', '.' + component + ' [name="operation"]', function (e) {
e.preventDefault();
var $this = $(this);
var $component = $this.closest('.' + component);
calculate($component);
}).on('click', '.' + component + ' [name="equals"]', function (e) {
e.preventDefault();
var $this = $(this);
var $component = $this.closest('.' + component);
calculate($component);
});
});
|
Use es6 language for the newer features. | package com.dnmaze.dncli.util;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
/**
* Created by blei on 6/19/16.
*/
public class JsUtil {
/**
* <p>A helper method to compile a javascript file and return
* an engine that is common.</p>
*
* @param script the javascript file
* @return the script engine
* @throws FileNotFoundException if file was not found
* @throws ScriptException if cannot eval the javascript file
*/
public static Invocable compileAndEval(File script)
throws ScriptException, FileNotFoundException {
File scriptDir = script.getParentFile();
NashornScriptEngineFactory scriptEngineFactory = new NashornScriptEngineFactory();
ScriptEngine scriptEngine =
scriptEngineFactory.getScriptEngine("-Ddncli.cwd=" + scriptDir.getAbsolutePath(),
"-scripting", "--language=es6");
FileInputStream fis = new FileInputStream(script);
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
CompiledScript compiledScript = ((Compilable) scriptEngine).compile(isr);
compiledScript.eval();
return (Invocable) compiledScript.getEngine();
}
}
| package com.dnmaze.dncli.util;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
/**
* Created by blei on 6/19/16.
*/
public class JsUtil {
/**
* <p>A helper method to compile a javascript file and return
* an engine that is common.</p>
*
* @param script the javascript file
* @return the script engine
* @throws FileNotFoundException if file was not found
* @throws ScriptException if cannot eval the javascript file
*/
public static Invocable compileAndEval(File script)
throws ScriptException, FileNotFoundException {
File scriptDir = script.getParentFile();
NashornScriptEngineFactory scriptEngineFactory = new NashornScriptEngineFactory();
ScriptEngine scriptEngine =
scriptEngineFactory.getScriptEngine("-Ddncli.cwd=" + scriptDir.getAbsolutePath(),
"-scripting");
FileInputStream fis = new FileInputStream(script);
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
CompiledScript compiledScript = ((Compilable) scriptEngine).compile(isr);
compiledScript.eval();
return (Invocable) compiledScript.getEngine();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.