text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Convert function to a one-liner.
See #1121. | const ascension = require('ascension')
const sort = ascension([ Number ], entry => [ entry.when ])
const Isochronous = require('isochronous')
class Printer {
constructor (destructible, write, format, interval) {
this._write = write
this._entries = []
this._format = format
const iso... | const ascension = require('ascension')
const sort = ascension([ Number ], entry => [ entry.when ])
const Isochronous = require('isochronous')
class Printer {
constructor (destructible, write, format, interval) {
this._write = write
this._entries = []
this._format = format
const iso... |
Hide create analysis modal on success | import React, { PropTypes } from "react";
import { Modal } from "react-bootstrap";
import { AlgorithmSelect, Button } from "virtool/js/components/Base";
const getInitialState = () => ({
algorithm: "pathoscope_bowtie"
});
export default class CreateAnalysis extends React.Component {
constructor (props) {
... | import React, { PropTypes } from "react";
import { Modal } from "react-bootstrap";
import { AlgorithmSelect, Button } from "virtool/js/components/Base";
const getInitialState = () => ({
algorithm: "pathoscope_bowtie"
});
export default class CreateAnalysis extends React.Component {
constructor (props) {
... |
Make ball fall through bottom wall again | /*
* This class handles collisions.
*/
'use strict';
import Vector from 'Vector.js';
export default class {
constructor(actorsInstance) {
this._actorsInstance = actorsInstance;
this._canvasObj = {};
}
moveComputerActors(canvasWidth, canvasHeight) {
let actors = this._actorsInstance.get();
for... | /*
* This class handles collisions.
*/
'use strict';
import Vector from 'Vector.js';
export default class {
constructor(actorsInstance) {
this._actorsInstance = actorsInstance;
this._canvasObj = {};
}
moveComputerActors(canvasWidth, canvasHeight) {
let actors = this._actorsInstance.get();
for... |
Add helpers for obtain indexes to connection manager. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from threading import local
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import utils
from . import base
class ConnectionManager(object):
def __init__(self):
self._connect... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from threading import local
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import utils
class ConnectionManager(object):
def __init__(self):
self._connections = local()
... |
Use Amp\call to run tasks
Handles generator to coroutine convertion and React promises automatically. | <?php
namespace Amp\Parallel\Worker\Internal;
use Amp\Coroutine;
use Amp\Parallel\Sync\Channel;
use Amp\Parallel\Worker\Environment;
use Amp\Promise;
use function Amp\call;
class TaskRunner {
/** @var \Amp\Parallel\Sync\Channel */
private $channel;
/** @var \Amp\Parallel\Worker\Environment */
privat... | <?php
namespace Amp\Parallel\Worker\Internal;
use Amp\Coroutine;
use Amp\Failure;
use Amp\Parallel\Sync\Channel;
use Amp\Parallel\Worker\Environment;
use Amp\Promise;
use Amp\Success;
class TaskRunner {
/** @var \Amp\Parallel\Sync\Channel */
private $channel;
/** @var \Amp\Parallel\Worker\Environment */... |
Update for new node definition syntax | import base64
import json
import Queue
import time
import logging
from boto import sns
from boto import sqs
from boto.sqs.message import Message, RawMessage
from nanomon.utils import yaml_includes
from nanomon.message import NanoMessage
from nanomon.queue import QueueWorker
from nanomon.queue.backends.sns_sqs import ... | import base64
import json
import Queue
import time
import logging
from boto import sns
from boto import sqs
from boto.sqs.message import Message, RawMessage
from nanomon.utils import yaml_includes
from nanomon.message import NanoMessage
from nanomon.queue import QueueWorker
from nanomon.queue.backends.sns_sqs import ... |
Refactor encoders to have base class | import datetime
import decimal
import logging
import elasticsearch
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoderMixin(object):
def default(self, obj):
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H... | import datetime
import decimal
import logging
import elasticsearch
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoder(_JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%... |
Remove showing of actual internal error to user and show in log instead | /**
* Created by Omnius on 03/08/2016.
*/
'use strict';
const Boom = require('boom');
module.exports = () => {
return (request, reply) => {
const server = request.server;
const redis = request.redis;
const dao = server.methods.dao;
const userDao = dao.userDao;
const aut... | /**
* Created by Omnius on 03/08/2016.
*/
'use strict';
const Boom = require('boom');
module.exports = () => {
return (request, reply) => {
const server = request.server;
const redis = request.redis;
const dao = server.methods.dao;
const userDao = dao.userDao;
const aut... |
Allow use of alternate Django test cases | from __future__ import absolute_import
from django.test import TestCase as dTestCase
from django.test import SimpleTestCase as dSimpleTestCase
from django.test.runner import DiscoverRunner
from snapshottest.reporting import reporting_lines
from .unittest import TestCase as uTestCase
class TestRunner(DiscoverRunner):... | from __future__ import absolute_import
from django.test import TestCase as dTestCase
from django.test.runner import DiscoverRunner
from snapshottest.reporting import reporting_lines
from .unittest import TestCase as uTestCase
class TestRunner(DiscoverRunner):
separator1 = "=" * 70
separator2 = "-" * 70
... |
Fix duration formatting in status chart
Numbers were not zero padded. | angular.module('ocWebGui.statusChart.service', ['ngResource'])
.factory('AgentStatusStats', function ($http) {
return {
stats: function (startDate, endDate, reportType) {
return $http.post('agent_statuses/stats', {
report_type: reportType,
team_name: 'Helpdesk',
start_d... | angular.module('ocWebGui.statusChart.service', ['ngResource'])
.factory('AgentStatusStats', function ($http) {
return {
stats: function (startDate, endDate, reportType) {
return $http.post('agent_statuses/stats', {
report_type: reportType,
team_name: 'Helpdesk',
start_d... |
Use best practice for array emptiness check | <?php
namespace Dotenv\Store;
use Dotenv\Exception\InvalidPathException;
use Dotenv\Store\File\Reader;
class FileStore implements StoreInterface
{
/**
* The file paths.
*
* @var string[]
*/
protected $filePaths;
/**
* Should file loading short circuit?
*
* @var bool
... | <?php
namespace Dotenv\Store;
use Dotenv\Exception\InvalidPathException;
use Dotenv\Store\File\Reader;
class FileStore implements StoreInterface
{
/**
* The file paths.
*
* @var string[]
*/
protected $filePaths;
/**
* Should file loading short circuit?
*
* @var bool
... |
Adjust områder request query params to only get published and DNT official områder | /**
* GET home page
*/
module.exports = function (app, options) {
"use strict";
var underscore = require('underscore');
var userGroupsFetcher = options.userGroupsFetcher;
var restProxy = options.restProxy;
/**
* GET list of routes (index page)
*/
var getRoutesIndex = function (req... | /**
* GET home page
*/
module.exports = function (app, options) {
"use strict";
var underscore = require('underscore');
var userGroupsFetcher = options.userGroupsFetcher;
var restProxy = options.restProxy;
/**
* GET list of routes (index page)
*/
var getRoutesIndex = function (req... |
Fix winmonitor script wrapper specification | import setuptools
from simplemonitor.version import VERSION
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="simplemonitor",
version=VERSION,
author="James Seward",
author_email="james@jamesoff.net",
description="A simple network and host monitor",
l... | import setuptools
from simplemonitor.version import VERSION
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="simplemonitor",
version=VERSION,
author="James Seward",
author_email="james@jamesoff.net",
description="A simple network and host monitor",
l... |
Use proper placeholders for future functionalities | const {i18n, React} = Serverboards
import Details from '../containers/details'
class DetailsTab extends React.Component{
constructor(props){
super(props)
this.state={
tab: "details"
}
}
render(){
let Section = () => null
const section = this.state.tab
switch(section){
case "... | const {i18n, React} = Serverboards
import Details from '../containers/details'
class DetailsTab extends React.Component{
constructor(props){
super(props)
this.state={
tab: "details"
}
}
render(){
let Section = () => null
const section = this.state.tab
switch(section){
case "... |
Handle empty location and leads data | from django import forms
from django.core.exceptions import ValidationError
from wye.profiles.models import UserType
from . import models
class RegionalLeadForm(forms.ModelForm):
class Meta:
model = models.RegionalLead
exclude = ()
def clean(self):
error_message = []
if (se... | from django import forms
from django.core.exceptions import ValidationError
from wye.profiles.models import UserType
from . import models
class RegionalLeadForm(forms.ModelForm):
class Meta:
model = models.RegionalLead
exclude = ()
def clean(self):
location = self.cleaned_data['loc... |
Make txrudp the sole distributed package. | """Setup module for txrudp."""
import codecs
from os import path
import sys
from setuptools import setup
_HERE = path.abspath(path.dirname(__file__))
with codecs.open(path.join(_HERE, 'README.md'), encoding='utf-8') as f:
_LONG_DESCRIPTION = f.read()
setup(
name='txrudp',
version='0.1.0',
descripti... | """Setup module for txrudp."""
import codecs
from os import path
import sys
from setuptools import find_packages, setup
_HERE = path.abspath(path.dirname(__file__))
with codecs.open(path.join(_HERE, 'README.md'), encoding='utf-8') as f:
_LONG_DESCRIPTION = f.read()
setup(
name='txrudp',
version='0.1.0'... |
Fix ping to check each connection, not only first one
(cherry picked from commit 72d4097) | <?php
namespace Enqueue\Bundle\Consumption\Extension;
use Doctrine\DBAL\Connection;
use Enqueue\Consumption\Context;
use Enqueue\Consumption\EmptyExtensionTrait;
use Enqueue\Consumption\ExtensionInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;
class DoctrinePingConnectionExtension implements ExtensionInterf... | <?php
namespace Enqueue\Bundle\Consumption\Extension;
use Doctrine\DBAL\Connection;
use Enqueue\Consumption\Context;
use Enqueue\Consumption\EmptyExtensionTrait;
use Enqueue\Consumption\ExtensionInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;
class DoctrinePingConnectionExtension implements ExtensionInterf... |
Remove the need for the Str facade | <?php
namespace Schuppo\PasswordStrength;
use Illuminate\Contracts\Validation\Factory;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\Translation\Translator;
class PasswordStrengthServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
*... | <?php
namespace Schuppo\PasswordStrength;
use Illuminate\Contracts\Validation\Factory;
use Illuminate\Support\ServiceProvider;
use Illuminate\Translation\Translator;
class PasswordStrengthServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
pu... |
Remove no longer valid comment - pdo_oci is maintaned by php people | <?php
namespace Doctrine\DBAL\Driver\PDOOracle;
use Doctrine\DBAL\Driver\AbstractOracleDriver;
use Doctrine\DBAL\Driver\PDO;
use Doctrine\DBAL\Exception;
use PDOException;
/**
* PDO Oracle driver.
*
* @deprecated Use {@link PDO\OCI\Driver} instead.
*/
class Driver extends AbstractOracleDriver
{
/**
* {@... | <?php
namespace Doctrine\DBAL\Driver\PDOOracle;
use Doctrine\DBAL\Driver\AbstractOracleDriver;
use Doctrine\DBAL\Driver\PDO;
use Doctrine\DBAL\Exception;
use PDOException;
/**
* PDO Oracle driver.
*
* WARNING: PDO Oracle is not maintained by Oracle or anyone in the PHP community,
* which leads us to the recommen... |
Fix specifying loadSchema() function from webpack configuration
Object.assign() assigns the properties to its first parameter, which results in ajvOptions immediately being overwritten with the defaults that are provided. The second time ajvOptions is passed, it has no effect, because configuration options have alread... | const Ajv = require('ajv');
const ajvPack = require('ajv-pack');
const loaderUtils = require('loader-utils');
const path = require('path');
module.exports = function (schemaStr, sourceMap) {
const done = this.async();
const loadSchema = uri => {
const filePath = path.resolve(this.co... | const Ajv = require('ajv');
const ajvPack = require('ajv-pack');
const loaderUtils = require('loader-utils');
const path = require('path');
module.exports = function (schemaStr, sourceMap) {
const done = this.async();
const loadSchema = uri => {
const filePath = path.resolve(this.co... |
Revert "require SQLAlchemy>=0.7.8 for readthedocs"
This reverts commit 689712e7ec4035e03934a4f32e788c133fa7a13c. | from setuptools import setup, find_packages
version = '0.1'
install_requires = [
'SQLAlchemy>0.7'
]
setup_requires = [
'nose'
]
tests_require = install_requires + [
'coverage',
'psycopg2',
]
setup(name='GeoAlchemy2',
version=version,
description="Using SQLAlchemy with Spat... | from setuptools import setup, find_packages
version = '0.1'
install_requires = [
'SQLAlchemy>=0.7.8'
]
setup_requires = [
'nose'
]
tests_require = install_requires + [
'coverage',
'psycopg2',
]
setup(name='GeoAlchemy2',
version=version,
description="Using SQLAlchemy with S... |
Rename test so it actually runs | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class WhitespaceTest(PyxformTestCase):
def test_over_trim(self):
self.assertPyxformXform(
name='issue96',
md="""
| survey | | | |
| | type | l... | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class WhitespaceTest(PyxformTestCase):
def test_over_trim(self):
self.assertPyxformXform(
name='issue96',
md="""
| survey | | | |
| | type | l... |
Fix bad refactor on PersistenceProvider | const NotificationBuilder = require('./notification/notification-builder');
class PersistenceProvider {
constructor(bridge) {
this.toSave = [];
this.bridge = bridge;
this.toProcessAction = [];
this.publications = [];
this.fetches = [];
this.toSave = [];
}
save(obj) {
this.toSave.push... | const NotificationBuilder = require('./notification/notification-builder');
class PersistenceProvider {
constructor(bridge) {
this.toSave = [];
this.bridge = bridge;
this.toProcessAction = [];
this.publications = [];
this.fetches = [];
}
save(obj) {
this.toSave.push(obj);
}
processA... |
Include the time in the email | #!/usr/bin/env python
import log
import time
from jinja2 import Template
import traceback
class Report(object):
TIME_FMT = ": %y/%m/%d %H:%M %z (%Z)"
def __init__(self):
self.logs = log.LogAggregator.new()
self.started = time.strftime(TIME_FMT)
def format_exception_as_reason(exc):
return ... | #!/usr/bin/env python
import log
from jinja2 import Template
import traceback
class Report(object):
def __init__(self):
self.logs = log.LogAggregator.new()
def format_exception_as_reason(exc):
return traceback.format_exc(exc)
@log.make_loggable
class UploadReport(Report):
TEMPLATE_FILENAME = '... |
Fix the compile error of define classes which derivate from other classes in class. | #--coding:utf-8--
#Platform
class BasePlatform(object):
"""
A template for codes which are dependent on platform, whatever shell type or system type.
Redefine members to modify the function.
"""
def __init__(self, shell = False):
if shell:
if os.name == 'posix':
... | #--coding:utf-8--
#Platform
class BasePlatform(object):
"""
A template for codes which are dependent on platform, whatever shell type or system type.
Redefine members to modify the function.
"""
def __init__(self, shell = False):
if shell:
if os.name == 'posix':
... |
Fix react multi child error of FunctionsList
If an error occured in func edit page and then switch back to func list,
will cause an react multi child error | /**
*
* FunctionsList
*
*/
import React, { PropTypes } from 'react';
import LoadingIndicator from 'components/LoadingIndicator';
import ErrorIndicator from 'components/ErrorIndicator';
import FunctionListItem from 'containers/FunctionListItem';
// import styled from 'styled-components';
import { FormattedMessage } fro... | /**
*
* FunctionsList
*
*/
import React, { PropTypes } from 'react';
import LoadingIndicator from 'components/LoadingIndicator';
import FunctionListItem from 'containers/FunctionListItem';
// import styled from 'styled-components';
import { FormattedMessage } from 'react-intl';
import commonMessages from 'messages';
... |
Create doctrine Annotations on Entity | <?php
namespace WiContact\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* @ORM\Entity
* @ORM\Table(name="contacts")
*/
class Contact
{
/**
*
* @var int @ORM\Id
* @ORM\Column(type="i... | <?php
namespace WiContact\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="contacts")
*/
class Contact
{
/**
*
* @var int
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;
/**... |
Fix the issue that get_or_create returns a tuple instead of one object. | import os
from optparse import make_option
from django.core.management import BaseCommand
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from obj_sys.models_ufs_obj import UfsObj
class FileTagger(DjangoCmdBase):
option_list = BaseCommand.option_list + (
make_option('--tag... | import os
from optparse import make_option
from django.core.management import BaseCommand
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from obj_sys.models_ufs_obj import UfsObj
class FileTagger(DjangoCmdBase):
option_list = BaseCommand.option_list + (
make_option('--tag... |
Change to reply only if target has karma | """Keeps track of karma counts.
@package ppbot
@syntax .karma <item>
"""
import re
from modules import *
class Karmamod(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
def _register_events(self):
self.add_command('karma', 'get_ka... | """Keeps track of karma counts.
@package ppbot
@syntax .karma <item>
"""
import re
from modules import *
class Karmamod(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
def _register_events(self):
self.add_command('karma', 'get_ka... |
Update Google Analystics Key path | <?php
include '../paasswd/analytics-key.inc.php';
// Override any of the default settings below:
$config['site_title'] = 'schmitt.co'; // Site title
$config['theme'] = 'default'; // Set the theme (defaults to "default")
// adv-meta
$config['adv_meta_values'] = array('descrip... | <?php
include '../analytics-key.inc.php';
// Override any of the default settings below:
$config['site_title'] = 'schmitt.co'; // Site title
$config['theme'] = 'default'; // Set the theme (defaults to "default")
// adv-meta
$config['adv_meta_values'] = array('description' =>... |
Install the proper version of Django | #!/usr/bin/env python
from subprocess import check_call, CalledProcessError
from setuptools import setup
import six
requirements = ['setuptools', 'mongoengine>=0.10.0']
if six.PY3:
requirements.append('django')
else:
requirements.append('django<2')
def convert_readme():
try:
check_call(["pand... | #!/usr/bin/env python
from subprocess import check_call, CalledProcessError
from setuptools import setup
def convert_readme():
try:
check_call(["pandoc", "-f", "markdown_github", "-t",
"rst", "-o", "README.rst", "README.md"])
except (OSError, CalledProcessError):
return o... |
Update renderer test for Unix lines | <?php
namespace Tga\OpenGraphBundle\Tests\Renderer;
use Symfony\Component\Routing\Router;
use Tga\OpenGraphBundle\Registry\Registry;
use Tga\OpenGraphBundle\Renderer\OpenGraphMapRenderer;
use Tga\OpenGraphBundle\Tests\Mock\Map;
class OpenGraphMapRendererTest extends \PHPUnit_Framework_TestCase
{
public function ... | <?php
namespace Tga\OpenGraphBundle\Tests\Renderer;
use Symfony\Component\Routing\Router;
use Tga\OpenGraphBundle\Registry\Registry;
use Tga\OpenGraphBundle\Renderer\OpenGraphMapRenderer;
use Tga\OpenGraphBundle\Tests\Mock\Map;
class OpenGraphMapRendererTest extends \PHPUnit_Framework_TestCase
{
public function ... |
Rename disableText prop to removeText in UiIcon test | import Vue from 'vue';
import UiIcon from '../src/UiIcon.vue';
describe('UiIcon.vue', function() {
it('should initialize with correct data/props', function() {
const vm = new Vue({
template: '<div><ui-icon icon="mail" :remove-text="true" v-ref:icon></ui-icon></div>',
components: {
... | import Vue from 'vue';
import UiIcon from '../src/UiIcon.vue';
describe('UiIcon.vue', function() {
it('should initialize with correct data/props', function() {
const vm = new Vue({
template: '<div><ui-icon icon="mail" :disable-text="true" v-ref:icon></ui-icon></div>',
components: {
... |
Fix IndexError when running command without arguments. | from getpass import getpass
from scrapy.commands.crawl import Command as BaseCommand
from scrapy.exceptions import UsageError
def sanitize_query(query):
return query.replace(' ', '+')
class Command(BaseCommand):
def short_desc(self):
return "Scrap people from LinkedIn"
def syntax(self):
... | from getpass import getpass
from scrapy.commands.crawl import Command as BaseCommand
def sanitize_query(query):
return query.replace(' ', '+')
class Command(BaseCommand):
def short_desc(self):
return "Scrap people from LinkedIn"
def syntax(self):
return "[options] <query>"
def add... |
Add shouldComponentUpdate to excludeMethods array. | var excludeMethods = [
/^constructor$/,
/^render$/,
/^component[A-Za-z]+$/,
/^shouldComponentUpdate$/
];
var displayNameReg = /^function\s+([a-zA-Z]+)/;
function isExcluded(methodName) {
return excludeMethods.some(function (reg) {
return reg.test(methodName) === false;
});
}
function bindToClass(sc... | var excludeMethods = [
/^constructor$/,
/^render$/,
/^component[A-Za-z]+$/
];
var displayNameReg = /^function\s+([a-zA-Z]+)/;
function isExcluded(methodName) {
return excludeMethods.some(function (reg) {
return reg.test(methodName) === false;
});
}
function bindToClass(scope, methods) {
var compone... |
Remove hardcoded localhost in one more place. |
/*
* Exporst function that checks if given emails of users are shown
* on the Teamview page. And if so how they are rendered: as text or link.
*
* It does not check exact emails, just count numbers.
*
* */
'use strict';
var
By = require('selenium-webdriver').By,
expect = require('chai')... |
/*
* Exporst function that checks if given emails of users are shown
* on the Teamview page. And if so how they are rendered: as text or link.
*
* It does not check exact emails, just count numbers.
*
* */
'use strict';
var
By = require('selenium-webdriver').By,
expect = require('chai')... |
Enforce events to be arrays | <?php
/*
* This file is part of Rocketeer
*
* (c) Maxime Fabre <ehtnam6@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace Rocketeer\Services\Config\Definition;
use Symfony\Component\Config\Definition\TreeBu... | <?php
/*
* This file is part of Rocketeer
*
* (c) Maxime Fabre <ehtnam6@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace Rocketeer\Services\Config\Definition;
use Symfony\Component\Config\Definition\TreeBu... |
Disable logging while running tests | var _ = require('underscore');
module.exports = function(opts) {
var config = {
base_url: '/database/:dbname/table/:table',
grainstore: {datasource: global.environment.postgres},
redis: global.environment.redis,
enable_cors: global.environment.enable_cors,
unbuffered_lo... | var _ = require('underscore');
module.exports = function(opts) {
var config = {
base_url: '/database/:dbname/table/:table',
grainstore: {datasource: global.environment.postgres},
redis: global.environment.redis,
enable_cors: global.environment.enable_cors,
unbuffered_lo... |
Fix typo in comment-space-inside message | import {
report,
ruleMessages
} from "../../utils"
export const ruleName = "comment-space-inside"
export const messages = ruleMessages(ruleName, {
expectedOpening: `Expected single space after "/*"`,
rejectedOpening: `Unexpected whitespace after "/*"`,
expectedClosing: `Expected single space before "*/"`,
... | import {
report,
ruleMessages
} from "../../utils"
export const ruleName = "comment-space-inside"
export const messages = ruleMessages(ruleName, {
expectedOpening: `Expected single space after "/*`,
rejectedOpening: `Unexpected whitespace after "/*`,
expectedClosing: `Expected single space before "*/"`,
r... |
Use PHP 8 constructor property promotion | <?php
declare(strict_types = 1);
/**
* /src/Request/ParamConverter/RestResourceConverter.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Request\ParamConverter;
use App\Resource\ResourceCollection;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bund... | <?php
declare(strict_types = 1);
/**
* /src/Request/ParamConverter/RestResourceConverter.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Request\ParamConverter;
use App\Resource\ResourceCollection;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bund... |
Change to use read-only router for data-apis | """
API Builder
Build dynamic API based on the provided SQLAlchemy model
"""
from managers import AlchemyModelManager
from viewsets import AlchemyModelViewSet
from routers import ReadOnlyRouter
class APIModelBuilder(object):
def __init__(self,
models,
base_managers,
... | """
API Builder
Build dynamic API based on the provided SQLAlchemy model
"""
from managers import AlchemyModelManager
from viewsets import AlchemyModelViewSet
from rest_framework_nested import routers
class APIModelBuilder(object):
def __init__(self,
models,
base_managers,
... |
Fix new method signature and moved delta variable in lcs recorder | /**
* @file: Subclass of LCS which allows to observe progress of the algorithm
* by intercepting function calls.
*/
DeltaJS.lcs.InstallLCSRecorder = function(lcs, recorder) {
var orig = {};
orig.compute = lcs.compute;
lcs.compute = function(callback, T, limit) {
if (typeof limit ===... | /**
* @file: Subclass of LCS which allows to observe progress of the algorithm
* by intercepting function calls.
*/
DeltaJS.lcs.InstallLCSRecorder = function(lcs, recorder) {
var orig = {};
orig.compute = lcs.compute;
lcs.compute = function(callback, T, limit) {
if (typeof limit ===... |
Replace _.pick by _.pickBy to support Lodash 4 | var Sequelize = require('sequelize'),
_ = Sequelize.Utils._;
module.exports = function(target) {
if (target instanceof Sequelize.Model) {
// Model
createHook(target);
} else {
// Sequelize instance
target.afterDefine(createHook);
}
}
function createHook(model) {
model.hook('beforeFindAfte... | var Sequelize = require('sequelize'),
_ = Sequelize.Utils._;
module.exports = function(target) {
if (target instanceof Sequelize.Model) {
// Model
createHook(target);
} else {
// Sequelize instance
target.afterDefine(createHook);
}
}
function createHook(model) {
model.hook('beforeFindAfte... |
Add dock block and todo task | <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS B... | <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS B... |
Fix to remove DeprecationWarning message from test log | # -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... | # -*- coding: ISO-8859-1 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2014, HFTools Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... |
Fix is blocked check for user status | <?php
namespace SumoCoders\FrameworkMultiUserBundle\ValueObject;
use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidStatusException;
final class Status
{
const ACTIVE = 'active';
const BLOCKED = 'blocked';
/** @var string */
private $status;
/**
* @param string $status
*
* ... | <?php
namespace SumoCoders\FrameworkMultiUserBundle\ValueObject;
use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidStatusException;
final class Status
{
const ACTIVE = 'active';
const BLOCKED = 'blocked';
/** @var string */
private $status;
/**
* @param string $status
*
* ... |
[MAILWEB-801] Use larger modal for Custom CSS | import React, { useState } from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import { FormModal, PrimaryButton, Label, Alert, TextArea } from 'react-components';
const CustomThemeModal = ({ onSave, theme: initialTheme = '', ...rest }) => {
const [theme, setTheme] = useState(initialTheme);... | import React, { useState } from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import { FormModal, PrimaryButton, Label, Alert, TextArea } from 'react-components';
const CustomThemeModal = ({ onSave, theme: initialTheme = '', ...rest }) => {
const [theme, setTheme] = useState(initialTheme);... |
Add correct project id to projects details webservice. The test fails | <?php
namespace fennecweb\ajax\details;
use \PDO as PDO;
/**
* Web Service.
* Returns a project according to the project ID.
*/
class Projects extends \fennecweb\WebService
{
/**
* @param $querydata[]
* @returns Array $result
* <code>
* array('project_id': {biomfile});
* </code>
*/
... | <?php
namespace fennecweb\ajax\details;
use \PDO as PDO;
/**
* Web Service.
* Returns a project according to the project ID.
*/
class Projects extends \fennecweb\WebService
{
/**
* @param $querydata[]
* @returns Array $result
* <code>
* array('project_id': {biomfile});
* </code>
*/
... |
Change script add API call | define('app/controllers/scripts', ['app/controllers/base_array', 'app/models/script'],
//
// Scripts Controller
//
// @returns Class
//
function (BaseArrayController, ScriptModel) {
'use strict';
return BaseArrayController.extend({
model: ScriptModel,
... | define('app/controllers/scripts', ['app/controllers/base_array', 'app/models/script'],
//
// Scripts Controller
//
// @returns Class
//
function (BaseArrayController, ScriptModel) {
'use strict';
return BaseArrayController.extend({
model: ScriptModel,
... |
Fix typo in variable name | import {Transform} from 'stream';
import SVGOptim from 'svgo';
import {PluginError} from 'gulp-util';
const PLUGIN_NAME = 'gulp-svgmin';
module.exports = function (opts) {
const stream = new Transform({objectMode: true});
let svgo;
if (typeof opts !== 'function') {
svgo = new SVGOptim(opts);
... | import {Transform} from 'stream';
import SVGOptim from 'svgo';
import {PluginError} from 'gulp-util';
const PLUGIN_NAME = 'gulp-svgmin';
module.exports = function (opts) {
const stream = new Transform({objectMode: true});
let svgo;
if (typeof options !== 'function') {
svgo = new SVGOptim(opts);
... |
BAP-10749: Develop data-collection provider for Permissions and Capabilities
- Mark unit tests as incomplete, because it's requre additional work | <?php
namespace Oro\Bundle\UserBundle\Tests\Unit\Provider;
use Oro\Bundle\UserBundle\Provider\RolePrivilegeCategoryProvider;
class CategoryProviderTest extends \PHPUnit_Framework_TestCase
{
/** @var RolePrivilegeCategoryProvider */
private $categoryProvider;
protected function setUp()
{
$th... | <?php
namespace Oro\Bundle\UserBundle\Tests\Unit\Provider;
use Oro\Bundle\UserBundle\Provider\RolePrivilegeCategoryProvider;
class CategoryProviderTest extends \PHPUnit_Framework_TestCase
{
/** @var RolePrivilegeCategoryProvider */
private $categoryProvider;
protected function setUp()
{
$th... |
Use return value in subgenerator test | import pytest
from resumeback import send_self
from . import CustomError, defer, wait_until_finished, State
def test_subgenerator_next():
ts = State()
def subgenerator(this):
yield defer(this.next)
ts.run = True
@send_self
def func(this):
yield from subgenerator(this)
... | import pytest
from resumeback import send_self
from . import CustomError, defer, wait_until_finished, State
def test_subgenerator_next():
ts = State()
def subgenerator(this):
yield defer(this.next)
ts.run = True
@send_self
def func(this):
yield from subgenerator(this)
... |
Send welcome message at very first of communication channel | #!/usr/bin/env python3
"""Example for aiohttp.web websocket server
"""
import os
from aiohttp import web
WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html')
async def wshandler(request):
resp = web.WebSocketResponse()
available = resp.can_prepare(request)
if not available:
with... | #!/usr/bin/env python3
"""Example for aiohttp.web websocket server
"""
import os
from aiohttp import web
WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html')
async def wshandler(request):
resp = web.WebSocketResponse()
available = resp.can_prepare(request)
if not available:
with... |
Check if has session with its own method | <?php
namespace Cart;
use Cart\Contracts\SessionContract;
/**
* Class Session
* @package Cart
*/
class Session implements SessionContract
{
/**
* @var string
*/
protected $name = '_cart';
/**
* Session constructor.
*/
public function __construct()
{
if ( ! $this->i... | <?php
namespace Cart;
use Cart\Contracts\SessionContract;
/**
* Class Session
* @package Cart
*/
class Session implements SessionContract
{
/**
* @var string
*/
protected $name = '_cart';
/**
* Session constructor.
*/
public function __construct()
{
if ( ! $this->i... |
Return immediately if request is not json
Fetching the contents before this check may result in OutOfMemory excpetion if the request is multipart with files. | <?php
/*
* This file is part of the qandidate/symfony-json-request-transformer package.
*
* (c) Qandidate.com <opensource@qandidate.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Qandidate\Common\Symfony\HttpKerne... | <?php
/*
* This file is part of the qandidate/symfony-json-request-transformer package.
*
* (c) Qandidate.com <opensource@qandidate.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Qandidate\Common\Symfony\HttpKerne... |
Disable JPEG decoder test for now. | package us.ihmc.codecs;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import us.ihmc.codecs.generated.FilterModeEnum;
import us.ihmc.codecs.gener... | package us.ihmc.codecs;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import org.junit.jupiter.api.Test;
import us.ihmc.codecs.generated.FilterModeEnum;
import us.ihmc.codecs.generated.YUVPicture;
import us.ihmc.codecs.... |
Add a new spec to test the simpler placemark | /*global defineSuite*/
defineSuite(['DynamicScene/KmlDataSource',
'DynamicScene/DynamicObjectCollection',
'Core/loadXML',
'Core/Event'
], function(
KmlDataSource,
loadXML,
DynamicObjectCollection,
... | /*global defineSuite*/
defineSuite(['DynamicScene/KmlDataSource',
'DynamicScene/DynamicObjectCollection',
'Core/loadXML',
'Core/Event'
], function(
KmlDataSource,
loadXML,
DynamicObjectCollection,
... |
Read HTTP error stream before closing it
It wasn't causing problems, but it looks odd. | package io.bitsquare.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
// TODO route over tor
public class HttpClient {
private final String baseUrl;
public HttpClient(String ... | package io.bitsquare.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
// TODO route over tor
public class HttpClient {
private final String baseUrl;
public HttpClient(String ... |
Make sure $_SERVER['HTTP_HOST'] is defined | <?php
namespace Systemblast\Engine\Http;
class Request
{
private static $instance = null;
public static function make()
{
// Check if instance is already exists
if (self::$instance == null) {
self::$instance = (new Request())->create();
}
return self::$instance;... | <?php
namespace Systemblast\Engine\Http;
class Request
{
private static $instance = null;
public static function make()
{
// Check if instance is already exists
if (self::$instance == null) {
self::$instance = (new Request())->create();
}
return self::$instance;... |
Add support for task-specific workers | ;(function (name, definition) {
var theModule = definition(),
hasDefine = typeof define === 'function' && define.amd,
hasExports = typeof module !== 'undefined' && module.exports;
if(hasDefine) // AMD Module
define(theModule);
else if(hasExports) // Node.js Module
module.exports = t... | ;(function (name, definition) {
var theModule = definition(),
hasDefine = typeof define === 'function' && define.amd,
hasExports = typeof module !== 'undefined' && module.exports;
if(hasDefine) // AMD Module
define(theModule);
else if(hasExports) // Node.js Module
module.exports = t... |
Revert "fix genetics accessRules problem"
This reverts commit 6284919a9db8b401b0506cffea048da399b765cf. | <?php
class DefaultController extends BaseEventTypeController
{
public function volumeRemaining($event_id)
{
$volume_remaining = 0;
if ($api = Yii::app()->moduleAPI->get('OphInDnaextraction')) {
$volume_remaining = $api->volumeRemaining($event_id);
}
return $volum... | <?php
class DefaultController extends BaseEventTypeController
{
public function volumeRemaining($event_id)
{
$volume_remaining = 0;
if ($api = Yii::app()->moduleAPI->get('OphInDnaextraction')) {
$volume_remaining = $api->volumeRemaining($event_id);
}
return $volum... |
Update shebang to use /usr/bin/env.
Remove the /ms/dist reference. | #!/usr/bin/env python2.6
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
#
# This module is part of Aquilon
"""Add /ms/dist to traceback of files compiled in /ms/dev."""
import sys
import py_compile
import re
def main(args=None):... | #!/ms/dist/python/PROJ/core/2.5.2-1/bin/python
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
#
# This module is part of Aquilon
"""Add /ms/dist to traceback of files compiled in /ms/dev."""
import sys
import py_compile
import re
... |
Fix PandA firmware issue with a hack | from malcolm.compat import str_
from malcolm.core.serializable import Serializable, deserialize_object
from malcolm.core.vmeta import VMeta
@Serializable.register_subclass("malcolm:core/ChoiceMeta:1.0")
class ChoiceMeta(VMeta):
"""Meta object containing information for a enum"""
endpoints = ["description", "... | from malcolm.compat import str_
from malcolm.core.serializable import Serializable, deserialize_object
from malcolm.core.vmeta import VMeta
@Serializable.register_subclass("malcolm:core/ChoiceMeta:1.0")
class ChoiceMeta(VMeta):
"""Meta object containing information for a enum"""
endpoints = ["description", "... |
Fix vex dialog being off topic | (function() {
'use strict';
angular.module('app.controllers.channels', []).
controller('Channels', Channels);
Channels.$inject = ['$rootScope', 'chat'];
function Channels($rootScope, chat) {
var vm = this;
$rootScope.selected = '#roomtest';
vm.select = function(cha... | (function() {
'use strict';
angular.module('app.controllers.channels', []).
controller('Channels', Channels);
Channels.$inject = ['$rootScope', 'chat'];
function Channels($rootScope, chat) {
var vm = this;
$rootScope.selected = '#roomtest';
vm.select = function(cha... |
Stop sharing the query builder, this was a bad idea | <?php
namespace ZerobRSS;
use \Auryn\Injector;
class Middlewares
{
/** @var Injector */
private $injector;
public function __construct(Injector $injector)
{
$this->injector = $injector;
}
/**
* Closure to load controllers
*/
public function controllerLoader($controlle... | <?php
namespace ZerobRSS;
use \Auryn\Injector;
class Middlewares
{
/** @var Injector */
private $injector;
public function __construct(Injector $injector)
{
$this->injector = $injector;
}
/**
* Closure to load controllers
*/
public function controllerLoader($controlle... |
Add track number and album artist to info | var osa = require('osa2')
function play(uri) {
if (uri)
return playTrack(uri)
return osa(() => Application('Spotify').play())()
}
function playTrack(uri) {
return osa((uri) => Application('Spotify').playTrack(uri))(uri)
}
function pause() {
return osa(() => Application('Spotify').pause())()
}... | var osa = require('osa2')
function play(uri) {
if (uri)
return playTrack(uri)
return osa(() => Application('Spotify').play())()
}
function playTrack(uri) {
return osa((uri) => Application('Spotify').playTrack(uri))(uri)
}
function pause() {
return osa(() => Application('Spotify').pause())()
}... |
Fix: Make sure includePaths default is specific for each file | var map = require('map-stream')
, sass = require('node-sass')
, path = require('path')
, gutil = require('gulp-util')
, ext = gutil.replaceExtension
;
module.exports = function (options) {
var opts = options ? options : {};
function nodeSass (file, cb) {
var fileDir = path.dirname(file.path);... | var map = require('map-stream')
, sass = require('node-sass')
, path = require('path')
, gutil = require('gulp-util')
, ext = gutil.replaceExtension
;
module.exports = function (options) {
var opts = options ? options : {};
function nodeSass (file, cb) {
if (file.isNull()) {
return cb(... |
Fix incorrect redirection after log in. | import angular from 'angular';
import uiRouter from 'angular-ui-router';
import view from './view';
//====================================================================
export default angular.module('xoWebApp.login', [
uiRouter,
])
.config(function ($stateProvider) {
$stateProvider.state('login', {
u... | import angular from 'angular';
import uiRouter from 'angular-ui-router';
import view from './view';
//====================================================================
export default angular.module('xoWebApp.login', [
uiRouter,
])
.config(function ($stateProvider) {
$stateProvider.state('login', {
u... |
feature: Create markdown doc files from source | /*
* grunt-dox
* https://github.com/iVantage/grunt-dox
*
* Copyright (c) 2014 Evan Sheffield
* Licensed under the MIT license.
*/
'use strict';
var dox = require('../node_modules/dox/index.js');
module.exports = function(grunt) {
grunt.registerMultiTask('dox', 'Creates documentation markdown for your source... | /*
* grunt-dox
* https://github.com/iVantage/grunt-dox
*
* Copyright (c) 2014 Evan Sheffield
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grun... |
Remove JWT_AUTH check from settings
JWT settings has been removed in OpenID change and currently there isn't use for this. | from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
settings['CKEDITOR_CONFIGS'] = {
'default': {
'stylesSet': [
{
"name": 'Lead',
... | from .util import get_settings, load_local_settings, load_secret_key
from . import base
settings = get_settings(base)
load_local_settings(settings, "local_settings")
load_secret_key(settings)
if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi":
raise ValueError("Refusing to run o... |
Correct error in client for streaming | define([
"Underscore",
"yapp/yapp",
"vendors/socket.io"
], function(_, yapp, io) {
var logging = yapp.Logger.addNamespace("updates");
var Updates = new (yapp.Class.extend({
/* Constructor */
initialize: function() {
this.url = [window.location.protocol, '//', window.locat... | define([
"Underscore",
"yapp/yapp",
"vendors/socket.io"
], function(_, yapp, io) {
var logging = yapp.Logger.addNamespace("updates");
var Updates = new (yapp.Class.extend({
/* Constructor */
initialize: function() {
this.url = [window.location.protocol, '//', window.locat... |
Set deprecated php-ext-zip used class | <?php
/**
* Created by PhpStorm.
* User: LPALQUILER-11
* Date: 29/08/2018
* Time: 17:30.
*/
namespace Greenter\Zip;
use ZipArchive;
/**
* Class ZipFileDecompress.
* @deprecated deprecated since version v4.0.3, use ZipFlyDecompress
*/
class ZipFileDecompress implements DecompressInterface
{
/**
* Ext... | <?php
/**
* Created by PhpStorm.
* User: LPALQUILER-11
* Date: 29/08/2018
* Time: 17:30.
*/
namespace Greenter\Zip;
use ZipArchive;
/**
* Class ZipFileDecompress.
*/
class ZipFileDecompress implements DecompressInterface
{
/**
* Extract files.
*
* @param string $content
* @param... |
Add errer handling for python code | #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.srv import ApplyGoals
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def get_waypo... | #!/usr/bin/env python
# coding UTF-8
import yaml
import rospy
from goal_sender_msgs.srv import ApplyGoals
from goal_sender_msgs.msg import GoalSequence
from goal_sender_msgs.msg import Waypoint
def read_yaml(path):
f = open(path, 'r')
waypoints = yaml.load(f)
f.close()
return waypoints
def get_waypo... |
Add showname to playlist API view.
* Even though it's obsolete now, we need it for old shows. | from rest_framework import serializers
from .models import Cd, Cdtrack, Show, Playlist, PlaylistEntry
class TrackSerializer(serializers.ModelSerializer):
album = serializers.StringRelatedField(
read_only=True
)
class Meta:
model = Cdtrack
fields = ('trackid', 'url', 'tracknum', 't... | from rest_framework import serializers
from .models import Cd, Cdtrack, Show, Playlist, PlaylistEntry
class TrackSerializer(serializers.ModelSerializer):
album = serializers.StringRelatedField(
read_only=True
)
class Meta:
model = Cdtrack
fields = ('trackid', 'url', 'tracknum', 't... |
Check if duration is null or undefined | /*
|--------------------------------------------------------------------------
| Utils
|--------------------------------------------------------------------------
*/
export default {
/**
* Parse an int to a more readable string
*
* @param int duration
* @return string
*/
parseDuration:... | /*
|--------------------------------------------------------------------------
| Utils
|--------------------------------------------------------------------------
*/
export default {
/**
* Parse an int to a more readable string
*
* @param int duration
* @return string
*/
parseDuration:... |
Use decode from the encoder | <?php
namespace Nats;
/**
* Class EncodedConnection
* @package Nats
*/
class EncodedConnection extends Connection {
/**
* @var Encoder|null
*/
private $encoder = null;
/**
* EncodedConnection constructor.
* @param ConnectionOptions|null $options
* @param Encoder|null $encoder
... | <?php
namespace Nats;
/**
* Class EncodedConnection
* @package Nats
*/
class EncodedConnection extends Connection {
/**
* @var Encoder|null
*/
private $encoder = null;
/**
* EncodedConnection constructor.
* @param ConnectionOptions|null $options
* @param Encoder|null $encoder
... |
Fix lookup in survey view | from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Alert, HouseholdSurveyJSON, TeamMember
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = [ 'url', 'username', 'email']
class SimpleUserSerializer... | from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Alert, HouseholdSurveyJSON, TeamMember
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = [ 'url', 'username', 'email']
class SimpleUserSerializer... |
Add data files to python packaging | import setuptools
import versioneer
if __name__ == "__main__":
my_packages=setuptools.find_packages()
setuptools.setup(
name='basis_set_exchange',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='The Quantum Chemistry Basis Set Exchange',
... | import setuptools
import versioneer
if __name__ == "__main__":
setuptools.setup(
name='basis_set_exchange',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='The Quantum Chemistry Basis Set Exchange',
author='The Molecular Sciences Software I... |
Remove use of assert statements since this does not conform to general best practice.
This is unfortunate, because the code is much more verbose than before and NOT as clear. | """
Functions related to HTTP Basic Authorization
"""
from functools import wraps
from flask import request, jsonify, current_app
def basic_auth(original_function):
"""
Wrapper. Verify that request.authorization exists and that its
contents match the application's config.basic_auth_credentials
dic... | """
Functions related to HTTP Basic Authorization
"""
from functools import wraps
from flask import request, Response, current_app
def basic_auth(original_function):
"""
Wrapper. Verify that request.authorization exists and that its
contents match the application's config.basic_auth_credentials
di... |
Create missing tables when lifting sails | /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/
module.exports.models = {
/******************************... | /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/
module.exports.models = {
/******************************... |
Add checking if lastPropId is undefined | "use strict";
module.exports = {
rules: {
"sort-object-props": function(context) {
var caseSensitive = context.options[0].caseSensitive;
var ignoreMethods = context.options[0].ignoreMethods;
var ignorePrivate = context.options[0].ignorePrivate;
var MSG = "Pr... | "use strict";
module.exports = {
rules: {
"sort-object-props": function(context) {
var caseSensitive = context.options[0].caseSensitive;
var ignoreMethods = context.options[0].ignoreMethods;
var ignorePrivate = context.options[0].ignorePrivate;
var MSG = "Pr... |
Remove unnecessary login during build model frontend test | casper.test.begin('build model', function suite(test) {
casper.start('http://localhost:5000', function() {
this.page.viewportSize = { width: 1920, height: 1080 };
// Build model
casper.then(function(){
this.evaluate(function() {
document.querySelector('#buildmod... | casper.test.begin('build model', function suite(test) {
casper.start('http://localhost:5000', function() {
this.page.viewportSize = { width: 1920, height: 1080 };
if(this.exists('form.login-form')){
this.fill('form.login-form', {
'login': 'testhandle@test.com',
... |
Remove `body_html_escaped`.
Add rendering filtered by formats. | # -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.encoding import smart_str
from mail_factory.messages import EmailMultiRelated
class PreviewMessage(EmailMultiRelated):
def has_body_html(self):
"""Test if a message contains an alternative rendering in text/html"""
return ... | from base64 import b64encode
from django.conf import settings
from mail_factory.messages import EmailMultiRelated
class PreviewMessage(EmailMultiRelated):
def has_body_html(self):
"""Test if a message contains an alternative rendering in text/html"""
return 'text/html' in self.alternatives
... |
Fix id column in migration | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePhpdebugbarStorageTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('phpde... | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePhpdebugbarStorageTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('phpde... |
Add suport for development installs. | # -*- coding: utf-8 -*-
try:
from setuptools import setup
from setuptools.command.install import install
except ImportError:
from distutils.core import setup
from distutils.core.command.install import install
class InstallCommand(install):
"""Install as noteboook extension"""
develop = False
... | # -*- coding: utf-8 -*-
try:
from setuptools import setup
from setuptools.command.install import install
except ImportError:
from distutils.core import setup
from distutils.core.command.install import install
class CustomInstallCommand(install):
"""Install as noteboook extension"""
def insta... |
Check if ip is in whitelist and not in blacklist
This can be useful when we define a subnet as whitelist but we want
to exclude a particular ip, for example:
whitelist 192.168.0.*
blacklist 192.168.0.50 | <?php
namespace Overflowsith\Firewall;
use Config;
use Str;
class Firewall
{
public static function isAllowed($ip)
{
switch(Config::get('firewall::config.mode')) {
case 'disabled':
return true;
break;
case 'enforcing':
return sel... | <?php
namespace Overflowsith\Firewall;
use Config;
use Str;
class Firewall
{
public static function isAllowed($ip)
{
switch(Config::get('firewall::config.mode')) {
case 'disabled':
return true;
break;
case 'enforcing':
return sel... |
Change bulk order email address to Tory | import logging
from django.core.mail import EmailMessage
from django.http import JsonResponse
from django.middleware import csrf
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
from rest_framework.decorators import api_view
@csrf_exempt
@api_view(['POST', 'GET'])
def send_c... | import logging
from django.core.mail import EmailMessage
from django.http import JsonResponse
from django.middleware import csrf
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
from rest_framework.decorators import api_view
@csrf_exempt
@api_view(['POST', 'GET'])
def send_c... |
Fix start for bin script. | "use strict";
var path = require("path");
exports.port = process.env.ARGO_PORT || 8000;
exports.staticFiles = path.resolve(__dirname, "../../client/");
exports.apiUrl = "/api";
exports.streamUrl = "/stream";
exports.environment = process.env.OANDA_ENVIRONMENT || "practice";
exports.accessToken = process.env.OANDA_T... | "use strict";
exports.port = process.env.ARGO_PORT || 8000;
exports.staticFiles = "./src/client/";
exports.apiUrl = "/api";
exports.streamUrl = "/stream";
exports.environment = process.env.OANDA_ENVIRONMENT || "practice";
exports.accessToken = process.env.OANDA_TOKEN || "ACCESS_TOKEN";
exports.accountId = process.en... |
Include filename in reported output. | 'use strict'
var standard = require('standard')
var format = require('util').format
var loaderUtils = require('loader-utils')
var snazzy = require('snazzy')
module.exports = function standardLoader (text) {
var self = this
var callback = this.async()
var config = loaderUtils.getOptions(this)
config.filename... | 'use strict'
var standard = require('standard')
var format = require('util').format
var loaderUtils = require('loader-utils')
var snazzy = require('snazzy')
module.exports = function standardLoader (text) {
var self = this
var callback = this.async()
var config = loaderUtils.getOptions(this)
this.cacheable(... |
Read the body selector from the module config (if present) | define(['module', 'knockout', 'jquery'], function (module, ko, $) {
var defaultBodySelector;
if (module && typeof module.config === 'function' && typeof module.config().bodySelector === 'string') {
defaultBodySelector = module.config().bodySelector;
} else {
defaultBodySelector = 'body';
}
var create... | define(['knockout', 'jquery'], function (ko, $) {
var defaultBodySelector = 'body';
var createGetContext = function createGetContext () {
return function getContext (elementAccessor) {
var context;
var element;
if (!elementAccessor) {
return;
}
element = $(elementAccesso... |
Refresh angular controllers after login | /// <reference path="../Services/AccountService.js" />
(function () {
'use strict';
angular
.module('GVA.Common')
.controller('AccountLoginController', AccountLoginController);
AccountLoginController.$inject = ['$scope', '$rootScope', '$route', 'AccountService'];
function AccountLogi... | /// <reference path="../Services/AccountService.js" />
(function () {
'use strict';
angular
.module('GVA.Common')
.controller('AccountLoginController', AccountLoginController);
AccountLoginController.$inject = ['$scope', '$rootScope', 'AccountService'];
function AccountLoginControlle... |
Implement a better way of validating incoming requests.
Signed-off-by: Jason Lewis <b136be6b8ecc2c62ceb9857ec62bf85489a45e0c@gmail.com> | <?php
namespace Dingo\Api\Http;
use Illuminate\Container\Container;
use Illuminate\Http\Request as IlluminateRequest;
class Validator
{
/**
* Container instance.
*
* @var \Illuminate\Container\Container
*/
protected $container;
/**
* Array of request validators.
*
* @v... | <?php
namespace Dingo\Api\Http;
use Illuminate\Http\Request as IlluminateRequest;
class Validator
{
protected $domain;
protected $prefix;
/**
* Create a new request validator instance.
*
* @param string $domain
* @param string $prefix
*
* @return void
*/
public fu... |
Fix relative portion of link. | from pyshelf.cloud.stream_iterator import StreamIterator
from flask import Response
class ArtifactListManager(object):
def __init__(self, container):
self.container = container
def get_artifact(self, path):
"""
Gets artifact or artifact list information.
Args:
... | from pyshelf.cloud.stream_iterator import StreamIterator
from flask import Response
class ArtifactListManager(object):
def __init__(self, container):
self.container = container
def get_artifact(self, path):
"""
Gets artifact or artifact list information.
Args:
... |
[AC-4857] Switch from () to __call__() | from abc import (
ABCMeta,
abstractmethod,
)
from impact.v1.helpers import (
STRING_FIELD,
)
class BaseHistoryEvent(object):
__metaclass__ = ABCMeta
CLASS_FIELDS = {
"event_type": STRING_FIELD,
"datetime": STRING_FIELD,
"latest_datetime": STRING_FIELD,
"description... | from abc import (
ABCMeta,
abstractmethod,
)
from impact.v1.helpers import (
STRING_FIELD,
)
class BaseHistoryEvent(object):
__metaclass__ = ABCMeta
CLASS_FIELDS = {
"event_type": STRING_FIELD,
"datetime": STRING_FIELD,
"latest_datetime": STRING_FIELD,
"description... |
FIX Use userforms template for member list field, fixes display rule issue | <?php
/**
* Creates an editable field that displays members in a given group
*
* @package userforms
*/
class EditableMemberListField extends EditableFormField
{
private static $singular_name = 'Member List Field';
private static $plural_name = 'Member List Fields';
private static $has_one = array(
... | <?php
/**
* Creates an editable field that displays members in a given group
*
* @package userforms
*/
class EditableMemberListField extends EditableFormField
{
private static $singular_name = 'Member List Field';
private static $plural_name = 'Member List Fields';
private static $has_one = array(
... |
Fix using HAPPO_IS_ASYNC with Storybook plugin
We weren't passing the right things to the remoteRunner, causing async
report rendering to fail with a cryptic "is not iterable (cannot read
property Symbol(Symbol.iterator))" error. | import { performance } from 'perf_hooks';
import Logger from './Logger';
import constructReport from './constructReport';
import loadCSSFile from './loadCSSFile';
export default async function remoteRunner(
{ apiKey, apiSecret, endpoint, targets, plugins, stylesheets },
{ generateStaticPackage },
{ isAsync },
)... | import { performance } from 'perf_hooks';
import Logger from './Logger';
import constructReport from './constructReport';
import loadCSSFile from './loadCSSFile';
export default async function remoteRunner(
{ apiKey, apiSecret, endpoint, targets, plugins, stylesheets },
{ generateStaticPackage, isAsync },
) {
c... |
Set staging db name as the live one. | "use strict";
var os = require("os"),
path = require("path"),
express = require("express"),
routes = require("./routes");
var app = express(),
hostname = os.hostname(),
port = process.env.CONPA_PORT || 8080,
documentRoot = path.resolve(__dirname, "../client"),
nodeModules = path... | "use strict";
var os = require("os"),
path = require("path"),
express = require("express"),
routes = require("./routes");
var app = express(),
hostname = os.hostname(),
port = process.env.CONPA_PORT || 8080,
documentRoot = path.resolve(__dirname, "../client"),
nodeModules = path... |
Fix debug plugin after hiding app title | enabled(){
this.isDebugging = false;
this.onKeyDown = (e) => {
// ==========================
// F4 key - toggle debug mode
// ==========================
if (e.keyCode === 115){
this.isDebugging = !this.isDebugging;
$(".nav-user-info").first().css("background-color", this.isDebugg... | enabled(){
this.isDebugging = false;
this.onKeyDown = (e) => {
// ==========================
// F4 key - toggle debug mode
// ==========================
if (e.keyCode === 115){
this.isDebugging = !this.isDebugging;
$(".app-title").first().css("background-color", this.isDebugging ... |
Fix custom template tag to work with django 1.8 | from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcon... | from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcon... |
Add Servlet Request Parameters Supports | package org.qfox.jestful.form;
import org.qfox.jestful.core.BeanContainer;
import org.qfox.jestful.core.Initialable;
import org.qfox.jestful.core.annotation.DELETE;
import org.qfox.jestful.core.annotation.GET;
import org.qfox.jestful.core.annotation.POST;
import org.qfox.jestful.core.annotation.PUT;
import org.qfox.je... | package org.qfox.jestful.form;
import org.qfox.jestful.core.BeanContainer;
import org.qfox.jestful.core.Initialable;
import org.qfox.jestful.core.annotation.DELETE;
import org.qfox.jestful.core.annotation.GET;
import org.qfox.jestful.core.annotation.POST;
import org.qfox.jestful.core.annotation.PUT;
import org.qfox.je... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.