text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update to new (unburned) webhook.site URL | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const chai = require('chai')
const expect = chai.expect
describe('webhook', () => {
const webhook = require('../../lib/webhook')
const challenge = {
key: 'key',
name: 'name'
}
describe('notify', () => {
it('fails... | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const chai = require('chai')
const expect = chai.expect
describe('webhook', () => {
const webhook = require('../../lib/webhook')
const challenge = {
key: 'key',
name: 'name'
}
describe('notify', () => {
it('fails... |
Fix permission check in `UserContentAction::validateBulkRevert()` | <?php
namespace wcf\data\user;
use wcf\system\edit\EditHistoryManager;
use wcf\system\WCF;
/**
* Executes actions on user generated content.
*
* @author Tim Duesterhus
* @copyright 2001-2015 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package co... | <?php
namespace wcf\data\user;
use wcf\system\edit\EditHistoryManager;
use wcf\system\WCF;
/**
* Executes actions on user generated content.
*
* @author Tim Duesterhus
* @copyright 2001-2015 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package co... |
Add a trailing slash to the paginated talk list | from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
... | from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
... |
Change embeded struct CensusData's error structure | // The census package is used to query data from the census API.
//
// It's centered more so around data from Planetside 2
package census
import (
"strings"
)
var BaseURL = "http://census.daybreakgames.com/"
var BaseURLOld = "http://census.soe.com/"
func init() {
//BaseURL = BaseURLOld
}
// CensusData is a struct... | // The census package is used to query data from the census API.
//
// It's centered more so around data from Planetside 2
package census
import (
"strings"
)
var BaseURL = "http://census.daybreakgames.com/"
var BaseURLOld = "http://census.soe.com/"
func init() {
//BaseURL = BaseURLOld
}
// CensusData is a struct... |
Remove phar:// from file path | <?php
namespace falkirks\simplewarp\utils;
use pocketmine\plugin\PharPluginLoader;
use pocketmine\plugin\PluginBase;
use pocketmine\utils\Utils;
class ChecksumVerify {
const POGGIT_ENDPOINT = "https://poggit.pmmp.io/get.sha1/";
/**
* WARNING! This is a blocking function that performs a web request.
... | <?php
namespace falkirks\simplewarp\utils;
use pocketmine\plugin\PharPluginLoader;
use pocketmine\plugin\PluginBase;
use pocketmine\utils\Utils;
class ChecksumVerify {
const POGGIT_ENDPOINT = "https://poggit.pmmp.io/get.sha1/";
/**
* WARNING! This is a blocking function that performs a web request.
... |
Add cacheable flag to webpack loader. | // This loader replaces each require(*.coffee) by require(./noco-loader.js!*.coffee)
// and compile the result to JS.
// Its purpose is to avoid adding any code in the webpack.config.js of the parent project.
var coffee = require('coffee-script');
var path = __filename.replace(/\\/g,'/');
var exp = RegExp(/require([\(... | // This loader replaces each require(*.coffee) by require(./noco-loader.js!*.coffee)
// and compile the result to JS.
// Its purpose is to avoid adding any code in the webpack.config.js of the parent project.
var coffee = require('coffee-script');
var path = __filename.replace(/\\/g,'/');
var exp = RegExp(/require([\(... |
Replace missing Mongo to MongoClient | package org.jongo.util;
import com.mongodb.MongoClient;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import com.mongodb.DB;
import com.mongodb.Mongo;
public class EmbeddedMongoRule implements TestRule {
private static DB db;
public static MongoCl... | package org.jongo.util;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import com.mongodb.DB;
import com.mongodb.Mongo;
public class EmbeddedMongoRule implements TestRule {
private static DB db;
public static Mongo getMongo() {
return MongoHolder... |
Fix unit test for essentia dissonance | #! /usr/bin/env python
from unit_timeside import unittest, TestRunner
from timeside.plugins.decoder.file import FileDecoder
from timeside.core import get_processor
from timeside.core.tools.test_samples import samples
class TestEssentiaDissonance(unittest.TestCase):
def setUp(self):
self.analyzer = get_... | #! /usr/bin/env python
from unit_timeside import unittest, TestRunner
from timeside.plugins.decoder.file import FileDecoder
from timeside.core import get_processor
from timeside.core.tools.test_samples import samples
class TestEssentiaDissonance(unittest.TestCase):
def setUp(self):
self.analyzer = get_... |
Allow mixed in PHP 8 for manipulation | <?php
namespace Psalm\Type\Atomic;
class TMixed extends \Psalm\Type\Atomic
{
/** @var bool */
public $from_loop_isset = false;
public function __construct(bool $from_loop_isset = false)
{
$this->from_loop_isset = $from_loop_isset;
}
public function __toString(): string
{
r... | <?php
namespace Psalm\Type\Atomic;
class TMixed extends \Psalm\Type\Atomic
{
/** @var bool */
public $from_loop_isset = false;
public function __construct(bool $from_loop_isset = false)
{
$this->from_loop_isset = $from_loop_isset;
}
public function __toString(): string
{
r... |
Add pythonic way to concatenate strings. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://{host}:{port}/metrics/snapshot'.format(host=host, port=port)
)
data = json.load(response)
# print json.dumps(dat... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://' + host + ':' + port + '/metrics/snapshot')
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=Tru... |
Remove whitespace & use same order as in readme | #!/usr/bin/env node
var argv = process.argv.splice(2)
var log = require('./helpers/log.js')
var whitelist = ['build', 'run', 'test', 'lint', 'setup']
if (argv.length === 0 || argv[0] === 'help') {
console.log('abc [command]')
console.log('')
console.log('Commands:')
console.log(' setup Creates the ... | #!/usr/bin/env node
var argv = process.argv.splice(2)
var log = require('./helpers/log.js')
var whitelist = ['build', 'run', 'test', 'lint', 'setup']
if (argv.length === 0 || argv[0] === 'help') {
console.log('abc [command]\n\nCommands:')
console.log(' build Compiles the source files from src/ into a b... |
Change anchor placement to avoid flash | (function($) {
// SVG polyfill
svg4everybody();
// Deep anchor links for headings
anchors.options = {
placement: 'left',
visible: 'touch',
icon: '#'
}
anchors.add('.post h3, .post h4, .post h5, post h6, .page h3, .page h4, .page h5, page h6, .archive-overview h3, .archiv... | (function($) {
// SVG polyfill
svg4everybody();
// Deep anchor links for headings
anchors.options = {
placement: 'right',
visible: 'touch',
icon: '#'
}
anchors.add('.post h3, .post h4, .post h5, post h6, .page h3, .page h4, .page h5, page h6, .archive-overview h3, .archi... |
Stop ID should be string so zeros don't get truncated | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBusWatchListsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('bus_watch_lists', function (Blueprint $table) {
... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBusWatchListsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('bus_watch_lists', function (Blueprint $table) {
... |
Allow ol-mapbox-style to import from ol/style/Style etc. | const fs = require('fs');
const path = require('path');
const cases = path.join(__dirname, 'cases');
const caseDirs = fs.readdirSync(cases).filter((name) => {
let exists = true;
try {
fs.accessSync(path.join(cases, name, 'main.js'));
} catch (err) {
exists = false;
}
return exists;
});
const entry ... | const fs = require('fs');
const path = require('path');
const cases = path.join(__dirname, 'cases');
const caseDirs = fs.readdirSync(cases).filter((name) => {
let exists = true;
try {
fs.accessSync(path.join(cases, name, 'main.js'));
} catch (err) {
exists = false;
}
return exists;
});
const entry ... |
Add Ability to forward Post Data | var url = require('url')
var HttpClient = function() {}
HttpClient.prototype.fetch = function (requestOptions) {
var self = this;
var urlSplit = url.parse(requestOptions.url);
var isHttps = urlSplit.protocol === 'https:'
var http = require(isHttps ? 'https' : 'http');
var options = {
hostname: urlSplit.h... | var url = require('url')
var HttpClient = function() {}
HttpClient.prototype.fetch = function (requestOptions) {
var self = this;
var urlSplit = url.parse(requestOptions.url);
var isHttps = urlSplit.protocol === 'https:'
var http = require(isHttps ? 'https' : 'http');
var options = {
hostname: urlSplit.h... |
Fix for pip 10.0 and later | import pip
import xblog
from setuptools import setup
from setuptools import find_packages
try: # for pip >= 10
from pip._internal.req import parse_requirements
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
REQUIREMENTS_FILE = "xblog/requirements.txt"
requirements = [str(ir.r... | from setuptools import setup
from setuptools import find_packages
from pip.req import parse_requirements
import pip
import xblog
REQUIREMENTS_FILE = "xblog/requirements.txt"
requirements = [str(ir.req) for ir in parse_requirements(REQUIREMENTS_FILE, session=pip.download.PipSession())]
setup(
name='django-xblog'... |
Add debug to form in test | <?php
namespace MediaMonks\SonataMediaBundle\Tests\Functional;
class ImageProviderTest extends AbstractProviderTestAbstract
{
public function testImage()
{
$provider = 'image';
$crawler = $this->client->request('GET', self::BASE_PATH.'create?provider='.$provider);
$form = $crawler->s... | <?php
namespace MediaMonks\SonataMediaBundle\Tests\Functional;
class ImageProviderTest extends AbstractProviderTestAbstract
{
public function testImage()
{
$provider = 'image';
$crawler = $this->client->request('GET', self::BASE_PATH.'create?provider='.$provider);
$form = $crawler->s... |
Use sudo to change db user password. | from argyle.base import upload_template
from fabric.api import sudo, task
@task
def create_db_user(username, password=None, flags=None):
"""Create a databse user."""
flags = flags or u'-D -A -R'
sudo(u'createuser %s %s' % (flags, username), user=u'postgres')
if password:
change_db_user_passwo... | from argyle.base import upload_template
from fabric.api import sudo, task
@task
def create_db_user(username, password=None, flags=None):
"""Create a databse user."""
flags = flags or u'-D -A -R'
sudo(u'createuser %s %s' % (flags, username), user=u'postgres')
if password:
change_db_user_passwo... |
FIX fiscal position no source tax | from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
result = super(account_fiscal_position, self).map_tax(
cr, uid, fposition_id, taxes, contex... | from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
result = super(account_fiscal_position, self).map_tax(
cr, uid, fposition_id, taxes, contex... |
Fix hierarchical/inherit issue with styles for Tooltip | package io.bisq.gui.components;
import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
public class HyperlinkWithIcon extends Hyperlink {
public HyperlinkWithIcon... | package io.bisq.gui.components;
import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
public class HyperlinkWithIcon extends Hyperlink {
public HyperlinkWithIcon... |
Correct the packaging of packages on winsys
modified setup.py | from distutils.core import setup
import winsys
if __name__ == '__main__':
setup (
name='WinSys',
version=winsys.__version__,
url='http://code.google.com/p/winsys',
download_url='http://timgolden.me.uk/python/downloads/winsys',
license='MIT',
author='Tim Golden',
... | from distutils.core import setup
import winsys
if __name__ == '__main__':
setup (
name='WinSys',
version=winsys.__version__,
url='http://svn.timgolden.me.uk/winsys',
download_url='http://timgolden.me.uk/python/downloads',
license='MIT',
author='Tim Golden',
auth... |
Fix pep8 error with new newline
Change-Id: I47b12c62eb1653bcbbe552464aab72c486bbd1cc | #! /usr/bin/env python
# Copyright Lajos Katona
#
# 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... | #! /usr/bin/env python
# Copyright Lajos Katona
#
# 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... |
Fix to make site packages more generic in tests | from datetime import datetime
from django.conf import settings
from django.test import TestCase
from package.tests import data, initial_data
from searchv2.utils import remove_prefix, clean_title
class UtilFunctionTest(TestCase):
def setUp(self):
self.values = []
for value in ["-me",".me",... | from datetime import datetime
from django.test import TestCase
from package.tests import data, initial_data
from searchv2.utils import remove_prefix, clean_title
class UtilFunctionTest(TestCase):
def test_remove_prefix(self):
values = ["django-me","django.me","django/me","django_me"]
f... |
Fix 'class DataverseFile' to handle old and new response format
Tests were failing after swith to new server/version | from __future__ import absolute_import
from dataverse.utils import sanitize
class DataverseFile(object):
def __init__(self, dataset, name, file_id=None):
self.dataset = dataset
self.name = sanitize(name)
self.id = file_id
self.download_url = '{0}/access/datafile/{1}'.format(
... | from __future__ import absolute_import
from dataverse.utils import sanitize
class DataverseFile(object):
def __init__(self, dataset, name, file_id=None):
self.dataset = dataset
self.name = sanitize(name)
self.id = file_id
self.download_url = '{0}/access/datafile/{1}'.format(
... |
Fix parrot variant on 1.17 | package protocolsupport.protocol.typeremapper.entity.format.metadata.types.living.tameable;
import protocolsupport.protocol.typeremapper.entity.format.metadata.object.value.NetworkEntityMetadataObjectIndexValueNoOpTransformer;
import protocolsupport.protocol.typeremapper.entity.format.metadata.types.base.TameableNetwo... | package protocolsupport.protocol.typeremapper.entity.format.metadata.types.living.tameable;
import protocolsupport.protocol.typeremapper.entity.format.metadata.object.value.NetworkEntityMetadataObjectIndexValueNoOpTransformer;
import protocolsupport.protocol.typeremapper.entity.format.metadata.types.base.TameableNetwo... |
Add some tiny docstring to the unicode method | import threading
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pluginmodel import CMSPlugin
from cmsplugin_simple_markdown import utils
localdata = threading.local()
localdata.TEMPLATE_CHOICES = utils.autodiscover_templates()
TEMPLATE_CHOICES = localdata.TEMPLATE... | import threading
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pluginmodel import CMSPlugin
from cmsplugin_simple_markdown import utils
localdata = threading.local()
localdata.TEMPLATE_CHOICES = utils.autodiscover_templates()
TEMPLATE_CHOICES = localdata.TEMPLATE... |
Fix InspectorMemoryTest.testGetDOMStats to have consistent
behaviour on CrOS and desktop versions of Chrome. Starting the
browser in CrOS requires navigating through an initial setup
that does not leave us with a tab at "chrome://newtab". This workaround
runs the test in a new tab on all platforms for consistency.
BUG... | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from telemetry.test import tab_test_case
class InspectorMemoryTest(tab_test_case.TabTestCase):
def testGetDOMStats(self):
unittest_data_... | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from telemetry.test import tab_test_case
class InspectorMemoryTest(tab_test_case.TabTestCase):
def testGetDOMStats(self):
unittest_data_... |
Refactor test example with syllable breaks
- no doubt there will be disagreements & ambiguities, but at least we can assert what the code can/should be doing more precisely | 'use strict';
let mocha = require('mocha');
let should = require('should');
//apply the plugin
const syllables = require('../../src/index.js');
const nlp = require('nlp_compromise');
nlp.plugin(syllables);
describe('syllables', function() {
//americanize it
it('verify syllables for term', function(done) {
let... | 'use strict';
let mocha = require('mocha');
let should = require('should');
//apply the plugin
const syllables = require('../../src/index.js');
const nlp = require('nlp_compromise');
nlp.plugin(syllables);
describe('syllables', function() {
//americanize it
it('count syllables for term', function(done) {
let ... |
Revert "Revert "import BS sources""
This reverts commit 1bd13ac67152b33f974ce32402100a0f651c3091. | /*
* This is the main entry point.
*
* You can import other modules here, including external packages. When bundling using rollup you can mark those modules as external and have them excluded or, if they have a jsnext:main entry in their package.json (like this package does), let rollup bundle them into your dist fi... | /*
* This is the main entry point.
*
* You can import other modules here, including external packages. When bundling using rollup you can mark those modules as external and have them excluded or, if they have a jsnext:main entry in their package.json (like this package does), let rollup bundle them into your dist fi... |
Fix the previous commit =) | const DEFAULT_VALUES = {
atomicNumber : 1,
chemicalSymbol : 'H',
name : 'Hydrogen'
};
const ELEMENTS_VALUE = {
'hydrogen' : {
name : 'Hydrogen',
atomicNumber : 1,
chemicalSymbol : 'H'
},
'helium' : {
name : 'Helium',
atomicNumber : 2,
chemicalSymbol : 'He'
}
}
/* Represents an at... | const DEFAULT_VALUES = {
atomicNumber : 1,
chemicalSymbol : 'H',
name : 'Hydrogen'
};
const ELEMENTS_VALUE = {
'hydrogen' : {
name : 'Hydrogen',
atomicNumber : 1,
chemicalSymbol : 'H'
},
'helium' : {
name : 'Helium',
atomicNumber : 2,
chemicalSymbol : 'He'
}
}
class Element {
... |
Update css for save button. | $('#dripbot-title').css({
"display": "inline-block",
"margin-right": "20px"
});
$('#dripbot').css({
"text-align": "left"
});
$('#dripbot-toggle.stop').css({
"background-color": "#e9656d",
"color": "white",
"margin-top": "-10px"
});
$('#dripbot ul li p').css({
"margin-bottom":"5px",
"margin-right": "... | $('#dripbot-title').css({
"display": "inline-block",
"margin-right": "20px"
});
$('#dripbot').css({
"text-align": "left"
});
$('#dripbot-toggle.stop').css({
"background-color": "#e9656d",
"color": "white",
"margin-top": "-10px"
});
$('#dripbot ul li p').css({
"margin-bottom":"5px",
"margin-right": "... |
Drop usageof fluent interface on mocking
Psalm is not failing now ! | <?php
declare(strict_types=1);
namespace ProxyManagerTest\Exception;
use PHPUnit\Framework\TestCase;
use ProxyManager\Exception\FileNotWritableException;
use Webimpress\SafeWriter\Exception\ExceptionInterface as FileWriterException;
/**
* Tests for {@see \ProxyManager\Exception\FileNotWritableException}
*
* @cov... | <?php
declare(strict_types=1);
namespace ProxyManagerTest\Exception;
use PHPUnit\Framework\TestCase;
use ProxyManager\Exception\FileNotWritableException;
use Webimpress\SafeWriter\Exception\ExceptionInterface as FileWriterException;
/**
* Tests for {@see \ProxyManager\Exception\FileNotWritableException}
*
* @cov... |
Handle 'end' event in the right way | const Duplex = require('stream').Duplex;
const Transform = require('stream').Transform;
const JlTransform = require('./JlTransform');
class JlTransformsChain extends Transform
{
constructor(streams)
{
super({
objectMode: true
});
this.inputType = JlTransform.ANY;
this.outputType = JlTransform.ANY;
thi... | const Duplex = require('stream').Duplex;
const Transform = require('stream').Transform;
const JlTransform = require('./JlTransform');
class JlTransformsChain extends Transform
{
constructor(streams)
{
super({
objectMode: true
});
this.inputType = JlTransform.ANY;
this.outputType = JlTransform.ANY;
thi... |
Use data-bgset instead of data-bg.
https://github.com/aFarkas/lazysizes/issues/101 | <?php // [1] Regular background image; resized thumb (thumbs.dev.width) ?>
<?php if($lazyload == false && c::get('resrc') == false): ?>
style="background-image:url(<?php echo $thumburl; ?>);"<?php if($class): echo ' class="' . $class . '"'; endif; ?>
<?php endif; ?>
<?php // [2] Lazyload image; resized thumb (thumbs.... | <?php // [1] Regular background image; resized thumb (thumbs.dev.width) ?>
<?php if($lazyload == false && c::get('resrc') == false): ?>
style="background-image:url(<?php echo $thumburl; ?>);"<?php if($class): echo ' class="' . $class . '"'; endif; ?>
<?php endif; ?>
<?php // [2] Lazyload image; resized thumb (thumbs.... |
[TASK] Add sorting to faqs table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFaqsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('polyfaq_faqs', function (Blueprint $table) {
$... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFaqsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('polyfaq_faqs', function (Blueprint $table) {
$... |
Make test variable names a little more specific | package reuseport
import (
"context"
"net"
"testing"
"github.com/stretchr/testify/require"
)
func testDialFromListeningPort(t *testing.T, network string) {
lc := net.ListenConfig{
Control: Control,
}
ctx := context.Background()
ll, err := lc.Listen(ctx, network, "localhost:0")
require.NoError(t, err)
rl,... | package reuseport
import (
"context"
"net"
"testing"
"github.com/stretchr/testify/require"
)
func testDialFromListeningPort(t *testing.T, network string) {
lc := net.ListenConfig{
Control: Control,
}
ctx := context.Background()
l1, err := lc.Listen(ctx, network, "localhost:0")
require.NoError(t, err)
l2,... |
Use relative imports in the package. | #!/usr/bin/env python2
'''Resize images using the FFT
FFTresize resizes images using zero-padding in the frequency domain.
'''
from numpy import zeros as _zeros
from . import fftinterp
from . import imutils
__author__ = 'Mansour Moufid'
__copyright__ = 'Copyright 2013, Mansour Moufid'
__license__ = 'ISC'
__versi... | #!/usr/bin/env python2
'''Resize images using the FFT
FFTresize resizes images using zero-padding in the frequency domain.
'''
from fftinterp import interp2
import imutils
from numpy import zeros as _zeros
__author__ = 'Mansour Moufid'
__copyright__ = 'Copyright 2013, Mansour Moufid'
__license__ = 'ISC'
__version... |
Add support for json decoding | <?php
require_once __DIR__.'/../vendor/autoload.php';
use Silex\Application;
use Eyewitness\Router;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
include __DIR__.'/config.php';
// Basic App Setup Stuff
$app = new Application();
$app['debug'] = $debug;
$router = new... | <?php
require_once __DIR__.'/../vendor/autoload.php';
use Silex\Application;
use Eyewitness\Router;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
include __DIR__.'/config.php';
// Basic App Setup Stuff
$app = new Application();
$app['debug'] = $debug;
$router = new... |
Add data to log in liveClipping | <?php
/**
* @package plugins.cuePoints
* @subpackage Scheduler
*/
class KLiveClippingCopyCuePointEngine extends KLiveToVodCopyCuePointEngine
{
//override set status to HANDLED as LiveToVod engine
protected static function postProcessCuePoints($copiedCuePointIds) {}
protected function shouldCop... | <?php
/**
* @package plugins.cuePoints
* @subpackage Scheduler
*/
class KLiveClippingCopyCuePointEngine extends KLiveToVodCopyCuePointEngine
{
//override set status to HANDLED as LiveToVod engine
protected static function postProcessCuePoints($copiedCuePointIds) {}
protected function shouldCop... |
Fix settings update when unknown theme is stored | "use strict";
import socket from "../socket";
import upload from "../upload";
import store from "../store";
socket.once("configuration", function(data) {
store.commit("serverConfiguration", data);
// 'theme' setting depends on serverConfiguration.themes so
// settings cannot be applied before this point
store.di... | "use strict";
import socket from "../socket";
import upload from "../upload";
import store from "../store";
socket.once("configuration", function(data) {
store.commit("serverConfiguration", data);
// 'theme' setting depends on serverConfiguration.themes so
// settings cannot be applied before this point
store.di... |
Remove obsolete requirement of pyexiv2. | #! /usr/bin/python
from distutils.core import setup
try:
from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
# Python 2.x
from distutils.command.build_py import build_py
import photo
import re
DOCLINES = photo.__doc__.split("\n")
DESCRIPTION = DOCLINES[0]
LONG... | #! /usr/bin/python
from distutils.core import setup
try:
from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
# Python 2.x
from distutils.command.build_py import build_py
import photo
import re
DOCLINES = photo.__doc__.split("\n")
DESCRIPTION = DOCLINES[0]
LONG... |
Use gmpy2 instead of numpy | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import gmpy2
from gmpy2 import mpq, mpfr
def ulp(v):
return mpq(2) ** v.as_mantissa_exp()[1]
def round(mode):
def decorator(f):
def wrapped(v1, v2):
with gmpy2.local_context(round=mode):
return f(v1, v2)
retu... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import numpy as np
def get_exponent(v):
if isinstance(v, np.float32):
mask, shift, offset = 0x7f800000, 23, 127
else:
raise NotImplementedError('The value v can only be of type np.float32')
return ((v.view('i') & mask) >> shift) - off... |
Add version to PHP70 dependency | import Dependency from './Dependency'
/**
* The base class for defining your application's dependencies and installation
* proceedures.
*/
export default class Php70 extends Dependency {
default()
{
this.dependencyName = 'PHP 7.0'
this.dependencyLink = 'http://php.net/'
this.depende... | import Dependency from './Dependency'
/**
* The base class for defining your application's dependencies and installation
* proceedures.
*/
export default class Php70 extends Dependency {
default()
{
this.dependencyName = 'Php'
this.dependencyLink = 'http://php.net/'
this.dependencyD... |
Add argument to generation to create doctype | var _ = require('lodash');
var builder = require('xmlbuilder');
var utils = require('./utils');
var generate = require('./generate');
var parse = require('./parse');
function XMLSchema(schema) {
this.schema = schema;
}
// Create a xml string from a schema
XMLSchema.prototype.generate = function(value, options, d... | var _ = require('lodash');
var builder = require('xmlbuilder');
var utils = require('./utils');
var generate = require('./generate');
var parse = require('./parse');
function XMLSchema(schema) {
this.schema = schema;
}
// Create a xml string from a schema
XMLSchema.prototype.generate = function(value, options) {... |
Update tests up to status code change | 'use strict';
var expect = require('expect.js');
exports.successResponseCallback = function successResponseCallback(cb, close) {
return function testSuccessResp(res) {
res.setEncoding('utf8');
expect(res.statusCode).to.be(200);
expect(res.headers['content-type']).to.be('text/javascript; charset=utf-8');... | 'use strict';
var expect = require('expect.js');
exports.successResponseCallback = function successResponseCallback(cb, close) {
return function testSuccessResp(res) {
res.setEncoding('utf8');
expect(res.statusCode).to.be(200);
expect(res.headers['content-type']).to.be('text/javascript; charset=utf-8');... |
Enable domain config only for sqlserver | import mysql from './mysql';
import postgresql from './postgresql';
import sqlserver from './sqlserver';
import cassandra from './cassandra';
/**
* List of supported database clients
*/
export const CLIENTS = [
{
key: 'mysql',
name: 'MySQL',
defaultPort: 3306,
disabledFeatures: [
'server:sch... | import mysql from './mysql';
import postgresql from './postgresql';
import sqlserver from './sqlserver';
import cassandra from './cassandra';
/**
* List of supported database clients
*/
export const CLIENTS = [
{
key: 'mysql',
name: 'MySQL',
defaultPort: 3306,
disabledFeatures: [
'server:sch... |
Remove buildnumber from version when tag | var jsonfile = require('jsonfile');
// Read in the file to be patched
var file = process.argv[2]; // e.g. '../src/MyProject/project.json'
if (!file)
console.log("No filename provided");
console.log("File: " + file);
// Read in the build version (this is provided by the CI server)
var version = process.argv[3]; //... | var jsonfile = require('jsonfile');
// Read in the file to be patched
var file = process.argv[2]; // e.g. '../src/MyProject/project.json'
if (!file)
console.log("No filename provided");
console.log("File: " + file);
// Read in the build version (this is provided by the CI server)
var version = process.argv[3]; //... |
Use system module to get command line arguments | /**
* PhantomJS-based web performance metrics collector
*
* Usage:
* node phantomas.js
* --url=<page to check>
* --debug
* --verbose
*
* @version 0.2
*/
// parse script arguments
var args = require("system").args,
params = require('./lib/args').parse(args),
phantomas = require('./core/phantomas')... | /**
* PhantomJS-based web performance metrics collector
*
* Usage:
* node phantomas.js
* --url=<page to check>
* --debug
* --verbose
*
* @version 0.2
*/
// parse script arguments
var params = require('./lib/args').parse(phantom.args),
phantomas = require('./core/phantomas').phantomas;
// run phan... |
Create root page for api.openresolve.com | import os
from flask import Flask, jsonify
from flask_restful import Api
from dns.resolver import Resolver
from flask_cors import CORS
dns_resolver = Resolver()
def create_app(config_name):
app = Flask(__name__)
if config_name == 'dev':
app.config.from_object('resolverapi.config.DevelopmentConfig')... | import os
from flask import Flask
from flask_restful import Api
from dns.resolver import Resolver
from flask_cors import CORS
dns_resolver = Resolver()
def create_app(config_name):
app = Flask(__name__)
if config_name == 'dev':
app.config.from_object('resolverapi.config.DevelopmentConfig')
else... |
Add rowspan and colspan attribute bindings
Added rowspan and colspan attribute bindings for table header. | import Ember from 'ember';
import layout from './template';
const {
computed
} = Ember;
export default Ember.Component.extend({
attributeBindings: ['rowspan', 'colspan'],
layout: layout,
tagName: 'th',
classNameBindings: ['sortType', 'isSortable:sortable', 'isActiveColumn:active'],
isSortable: false,
b... | import Ember from 'ember';
import layout from './template';
const {
computed
} = Ember;
export default Ember.Component.extend({
layout: layout,
tagName: 'th',
classNameBindings: ['sortType', 'isSortable:sortable', 'isActiveColumn:active'],
isSortable: false,
bindSort: function () {
var sort = this.ge... |
Throw on non-int array lenghts | 'use strict';
const EasyObjectValue = require('../values/EasyObjectValue');
const ObjectValue = require('../values/ObjectValue');
const ArrayValue = require('../values/ArrayValue');
const CompletionRecord = require('../CompletionRecord');
class ArrayObject extends EasyObjectValue {
*call(thiz, args, s) {
if ( args... | 'use strict';
const EasyObjectValue = require('../values/EasyObjectValue');
const ObjectValue = require('../values/ObjectValue');
const ArrayValue = require('../values/ArrayValue');
class ArrayObject extends EasyObjectValue {
*call(thiz, args, s) {
if ( args.length === 1 && args[0].jsTypeName === 'number' ) {
l... |
Change for local pid prefix | package org.jsoftware.tjconsole.local;
import com.sun.tools.attach.VirtualMachine;
/**
* Check if tools.jar is available
* Receive local java PIDs
* Try to load agent for JMX
* @author szalik
*/
public class ProcessListManagerLoader {
public static final String LOCAL_PREFIX = "LOCAL:";
private static Pro... | package org.jsoftware.tjconsole.local;
import com.sun.tools.attach.VirtualMachine;
/**
* Check if tools.jar is available
* Receive local java PIDs
* Try to load agent for JMX
* @author szalik
*/
public class ProcessListManagerLoader {
public static final String LOCAL_PREFIX = "LOCAL ";
private static Pro... |
Switch example to geojson primitives | /**
* Takes a bounding box and returns a new bounding box with a size expanded or contracted
* by a factor of X.
*
* @module turf/size
* @category measurement
* @param {Array<number>} bbox a bounding box
* @param {number} factor the ratio of the new bbox to the input bbox
* @return {Array<number>} the resized b... | /**
* Takes a bounding box and returns a new bounding box with a size expanded or contracted
* by a factor of X.
*
* @module turf/size
* @category measurement
* @param {Array<number>} bbox a bounding box
* @param {number} factor the ratio of the new bbox to the input bbox
* @return {Array<number>} the resized b... |
Support for variable number of layers | import numpy as np
from scipy.special import expit
from sklearn import ensemble
def get_activations(exp_data, w, b):
exp_data = np.transpose(exp_data)
prod = exp_data.dot(w)
prod_with_bias = prod + b
return( expit(prod_with_bias) )
# Order of *args: first all the weights and then all the biases
def ru... | import numpy as np
# import pandas as pd
# import sys
from scipy.special import expit
from sklearn import ensemble
def get_activations(exp_data, w, b):
exp_data = np.transpose(exp_data)
prod = exp_data.dot(w)
prod_with_bias = prod + b
return( expit(prod_with_bias) )
# Order of *args: first all the wei... |
Change how the test asserts a file has been deleted.
git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@63 c7a0535c-eda6-11de-83d8-6d5adf01d787 | /*
* Mutability Detector
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Further licensing information for this project can be found in
* license/LICENSE.txt
*/
package org.mutabilitydetector.cli;
import static org.j... | /*
* Mutability Detector
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Further licensing information for this project can be found in
* license/LICENSE.txt
*/
package org.mutabilitydetector.cli;
import static org.j... |
Stop calling unregisterWorkqueue which was removed in gerrit
Change-Id: I9e60c229bab42b893c565196ce058000c647783e | // Copyright (C) 2017 The Android Open Source Project
//
// 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 ... | // Copyright (C) 2017 The Android Open Source Project
//
// 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 ... |
tests/basics: Add test for throw into yield-from with normal return.
This test was found by missing coverage of a branch in py/nativeglue.c. | def gen():
try:
yield 1
except ValueError as e:
print("got ValueError from upstream!", repr(e.args))
yield "str1"
raise TypeError
def gen2():
print((yield from gen()))
g = gen2()
print(next(g))
print(g.throw(ValueError))
try:
print(next(g))
except TypeError:
print("got Type... | def gen():
try:
yield 1
except ValueError as e:
print("got ValueError from upstream!", repr(e.args))
yield "str1"
raise TypeError
def gen2():
print((yield from gen()))
g = gen2()
print(next(g))
print(g.throw(ValueError))
try:
print(next(g))
except TypeError:
print("got Type... |
Add normal field to test model | from django.db.models import loading
from django.contrib.gis.db import models
from django.contrib.gis.geos import GEOSGeometry
from mapentity.models import MapEntityMixin
class MushroomSpot(models.Model):
name = models.CharField(max_length=100, default='Empty')
serialized = models.CharField(max_length=200, n... | from django.db.models import loading
from django.contrib.gis.db import models
from django.contrib.gis.geos import GEOSGeometry
from mapentity.models import MapEntityMixin
class MushroomSpot(models.Model):
serialized = models.CharField(max_length=200, null=True, default=None)
"""geom as python attribute"""
... |
Add a failing test for objects with quoted keys. | import check from './support/check';
describe('objects', () => {
it('adds curly braces immediately around a single-line object', () => {
check(`
a b: c, d: e
`, `
a({b: c, d: e});
`);
});
it.skip('indents and loosely wraps multi-line objects if needed', () => {
check(`
a: b
... | import check from './support/check';
describe('objects', () => {
it('adds curly braces immediately around a single-line object', () => {
check(`
a b: c, d: e
`, `
a({b: c, d: e});
`);
});
it.skip('indents and loosely wraps multi-line objects if needed', () => {
check(`
a: b
... |
Clarify functionality of JournalledInsertNode by simplifying code | package org.apache.calcite.adapter.jdbc;
import io.pivotal.beach.calcite.programs.BasicForcedRule;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import o... | package org.apache.calcite.adapter.jdbc;
import io.pivotal.beach.calcite.programs.BasicForcedRule;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import o... |
Fix service provider import path | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Jenssegers\Rollbar\RollbarServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
... | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
... |
Fix in/active state of check item | import Item from './item';
export default class CheckItem extends Item {
constructor() {
super();
this._root
.classed('check', true)
.styles({
'cursor': 'pointer'
});
this._check = this
.icon()
.class('ion-ios-circle-outline')
.size('1.5em');
this._check... | import Item from './item';
export default class CheckItem extends Item {
constructor() {
super();
this._root
.classed('check', true)
.styles({
'cursor': 'pointer'
});
this._check = this
.icon()
.class('ion-ios-circle-outline')
.size('1.5em');
this._check... |
UP-4802: Add since annotation to getImageCaptions | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in ... | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in ... |
Declare default timezone in controllers which use date function | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Stations extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('stationsFetcher');
date_default_timezone_set('Europe/Zagreb');
}
public function _remap($method)
{
$trainNo = int... | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Stations extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('stationsFetcher');
}
public function _remap($method)
{
$trainNo = intval($method);
if ($trainNo > 0)
{
$thi... |
Use new back-end sample's path instead of url | class ApiClient {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
getSamples() {
let apiClient = this;
return fetch(`${apiClient.baseUrl}/samples`)
.then((response) => {
if (response.status === 200) {
return response.json();
}
throw new Error(`Server replied... | class ApiClient {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
getSamples() {
return fetch(`${this.baseUrl}/samples`)
.then((response) => {
if (response.status === 200) {
return response.json();
}
throw new Error(`Server replied with ${response.status}`);
... |
Use es6 imports instead of require | import {run} from '@cycle/xstream-run';
import {makeDOMDriver, div} from '@cycle/dom';
import xs from 'xstream';
import Scratchpad from './src/scratchpad';
const startingCode = `
import {run} from '@cycle/xstream-run';
import {makeDOMDriver, div, button} from '@cycle/dom';
import _ from 'lodash';
import xs from 'xstr... | import {run} from '@cycle/xstream-run';
import {makeDOMDriver, div} from '@cycle/dom';
import xs from 'xstream';
import Scratchpad from './src/scratchpad';
const startingCode = `
const Cycle = require('@cycle/xstream-run');
const {makeDOMDriver, div, button} = require('@cycle/dom');
const _ = require('lodash');
const... |
Add a test for ``Enum.__repr__``; ``spiralgalaxygame.sentinel`` now has full coverage. | import unittest
from spiralgalaxygame.sentinel import Sentinel, Enum
class SentinelTests (unittest.TestCase):
def setUp(self):
self.s = Sentinel('thingy')
def test_name(self):
self.assertIs(self.s.name, 'thingy')
def test_repr(self):
self.assertEqual(repr(self.s), '<Sentinel thi... | import unittest
from spiralgalaxygame.sentinel import Sentinel, Enum
class SentinelTests (unittest.TestCase):
def setUp(self):
self.s = Sentinel('thingy')
def test_name(self):
self.assertIs(self.s.name, 'thingy')
def test_repr(self):
self.assertEqual(repr(self.s), '<Sentinel thi... |
Fix bug in admin_module checking | from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reac... | from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reac... |
Add Rector with PHP 7.3 | <?php /** @noinspection PhpFullyQualifiedNameUsageInspection */
declare(strict_types=1);
use Rector\Core\Configuration\Option;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator)... | <?php /** @noinspection PhpFullyQualifiedNameUsageInspection */
declare(strict_types=1);
use Rector\Core\Configuration\Option;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator)... |
Declare Python 3 support, bump version. | # -*- coding: utf-8 -*-
from setuptools import setup
VERSION = '0.6'
setup(
name='conllu',
packages=["conllu"],
version=VERSION,
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
author=u'Emil Stenström',
author_email='em@kth.se',
url='https://... | # -*- coding: utf-8 -*-
from setuptools import setup
VERSION = '0.5'
setup(
name='conllu',
packages=["conllu"],
version=VERSION,
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
author=u'Emil Stenström',
author_email='em@kth.se',
url='https://... |
book-store: Use book price constant in calculation | BOOK_PRICE = 8
def _group_price(size):
discounts = [0, .05, .1, .2, .25]
if not (0 < size <= 5):
raise ValueError('size must be in 1..' + len(discounts))
return BOOK_PRICE * size * (1 - discounts[size - 1])
def calculate_total(books, price_so_far=0.):
if not books:
return price_so_fa... | BOOK_PRICE = 8
def _group_price(size):
discounts = [0, .05, .1, .2, .25]
if not (0 < size <= 5):
raise ValueError('size must be in 1..' + len(discounts))
return 8 * size * (1 - discounts[size - 1])
def calculate_total(books, price_so_far=0.):
if not books:
return price_so_far
gr... |
Fix oauth2 revoke URI, new URL doesn't seem to work | # Copyright 2015 Google Inc. All rights reserved.
#
# 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 ... | # Copyright 2015 Google Inc. All rights reserved.
#
# 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 ... |
Change boolean to reporter for block with dropdowns | (function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
// Block... | (function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
// Block... |
Fix undefined error if sourcemaps option not defined | var StubGenerator = require('./stub-generator');
var CachingBrowserify = require('./caching-browserify');
var mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-browserify',
included: function(app){
this.app = app;
this.options = {
root: this.app.project.root,
browse... | var StubGenerator = require('./stub-generator');
var CachingBrowserify = require('./caching-browserify');
var mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-browserify',
included: function(app){
this.app = app;
this.options = {
root: this.app.project.root,
browse... |
Use new send() function arguments | /*jslint node: true */
var path = require('path');
var logger = require('loge');
var send = require('send');
var Router = require('regex-router');
var roots = {
static: path.join(__dirname, '..', 'static'),
templates: path.join(__dirname, '..', 'templates'),
};
var R = new Router(function(req, res) {
res.die(40... | /*jslint node: true */
var path = require('path');
var logger = require('loge');
var send = require('send');
var Router = require('regex-router');
var roots = {
static: path.join(__dirname, '..', 'static'),
templates: path.join(__dirname, '..', 'templates'),
};
var R = new Router(function(req, res) {
res.die(40... |
Fix an issue that tables not be removed in end of each test | # -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
cl... | # -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
cl... |
Use a placeholder string instead of a README.
Until I work out why README.rst isn't being included, use this. | import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
version="0.0.7",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
... | import setuptools
REQUIREMENTS = [
"docopt==0.6.1",
"feedparser==5.1.3",
"jabberbot==0.15",
"xmpppy==0.5.0rc1",
]
if __name__ == "__main__":
setuptools.setup(
name="dudebot",
version="0.0.7",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
... |
Remove getDriverName method call from the exception message | <?php
namespace Maghead\TableParser;
use InvalidArgumentException;
use Magsql\Driver\BaseDriver;
use Magsql\Driver\MySQLDriver;
use Magsql\Driver\PgSQLDriver;
use Magsql\Driver\SQLiteDriver;
use Maghead\Runtime\Connection;
class TableParser
{
public static function create(Connection $c, BaseDriver $d)
{
... | <?php
namespace Maghead\TableParser;
use InvalidArgumentException;
use Magsql\Driver\BaseDriver;
use Magsql\Driver\MySQLDriver;
use Magsql\Driver\PgSQLDriver;
use Magsql\Driver\SQLiteDriver;
use Maghead\Runtime\Connection;
class TableParser
{
public static function create(Connection $c, BaseDriver $d)
{
... |
Fix issue with null timestamps on campaign object.
These are sometimes null, causing an issue calling the date formatting
method. Why? :( | <?php
namespace Northstar\Http\Transformers;
use Northstar\Models\Campaign;
use League\Fractal\TransformerAbstract;
class CampaignTransformer extends TransformerAbstract
{
/**
* @param Campaign $campaign
* @return array
*/
public function transform(Campaign $campaign)
{
return [
... | <?php
namespace Northstar\Http\Transformers;
use Northstar\Models\Campaign;
use League\Fractal\TransformerAbstract;
class CampaignTransformer extends TransformerAbstract
{
/**
* @param Campaign $campaign
* @return array
*/
public function transform(Campaign $campaign)
{
return [
... |
[Refactoring] Split the function for call and wait processes | import chain from './chain';
import {clone} from './utils';
function vq(el, props, opts = null) {
if (!el || !props) throw new Error('Must have two or three args');
if (!opts) {
if (!('p' in props && 'o' in props)) {
throw new Error('2nd arg must have `p` and `o` property when only two args is given');
... | import chain from './chain';
import {clone} from './utils';
function vq(el, props, opts = null) {
if (!el || !props) throw new Error('Must have two or three args');
if (!opts) {
if (!('p' in props && 'o' in props)) {
throw new Error('2nd arg must have `p` and `o` property when only two args is given');
... |
Disable new test from r1779 for the android generator.
BUG=gyp:379
TBR=torne@chromium.org
Review URL: https://codereview.chromium.org/68333002
git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@1782 78cadc50-ecff-11dd-a971-7dbc132099af | #!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that copying files preserves file attributes.
"""
import TestGyp
import os
import stat
import sys
def check_attribs(path, e... | #!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that copying files preserves file attributes.
"""
import TestGyp
import os
import stat
import sys
def check_attribs(path, e... |
Fix main fn to not rethrow | // Core coroutine runner
function run(coroutine) {
return new Promise(function (resolve, reject) {
(function next(value, exception) {
var result;
try {
result = exception ? coroutine.throw(value) : coroutine.next(value);
}
catch (error) {
return reject(error);
}
if (result.done) return reso... | // Core coroutine runner
function run(coroutine) {
return new Promise(function (resolve, reject) {
(function next(value, exception) {
var result;
try {
result = exception ? coroutine.throw(value) : coroutine.next(value);
}
catch (error) {
return reject(error);
}
if (result.done) return reso... |
Remove multilanguage picture titles since they pollute all other picture entities | <?php
namespace MssPhp\Schema\Response;
use JMS\Serializer\Annotation\AccessType;
use JMS\Serializer\Annotation\Type;
class Picture {
/**
* @AccessType("public_method")
* @Type("string")
*/
public $url;
public function getUrl()
{
return $this->url;
}
public function s... | <?php
namespace MssPhp\Schema\Response;
use JMS\Serializer\Annotation\AccessType;
use JMS\Serializer\Annotation\Type;
class Picture {
/**
* @AccessType("public_method")
* @Type("string")
*/
public $url;
public function getUrl()
{
return $this->url;
}
public function s... |
Update error handling and provide better error message | var async = require('async'),
boom = require('boom'),
defaultData = {'success' : true};
function Series(arr) {
this.arr = arr;
Validate(arr);
}
function Validate(arr) {
var len = arr.length;
while(len--) {
if(typeof arr[len] !== 'function') {
throw new Error('Arguments passed in hapi-next must be functions... | var async = require('async'),
boom = require('boom'),
defaultData = {'success' : true};
function Series(arr) {
this.arr = arr;
}
function Validate(arr) {
var len = arr.length;
while(len--) {
if(typeof arr[len] !== 'function') {
throw new Error('')
}
}
}
Series.prototype.execute = function(request,reply)... |
Make title in archive page link to article. | <article <?php post_class(); ?>>
<header>
<?php if (($posts[0]->post_type != 'faq') && ($posts[0]->post_type != 'service')) : ?>
<h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php else: ?>
<?php $content_class = "large_text_display"; ?>
<a class="arch... | <article <?php post_class(); ?>>
<header>
<?php if (($posts[0]->post_type != 'faq') && ($posts[0]->post_type != 'service')) : ?>
<h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php else: ?>
<?php $content_class = "large_text_display"; ?>
<h2 class="ent... |
Add password handling to default factory. | from django.contrib.auth.models import User
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequenc... | from django.contrib.auth.models import User
from django.test import TestCase
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)... |
Fix app after updating to PHP 7.4 | <?php
namespace App\Exceptions;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
class Handler ... | <?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
... |
Extend Phi expression to work with more than 2 values |
from .base import SimSootExpr
import logging
l = logging.getLogger('angr.engines.soot.expressions.phi')
class SimSootExpr_Phi(SimSootExpr):
def __init__(self, expr, state):
super(SimSootExpr_Phi, self).__init__(expr, state)
def _execute(self):
locals_option = [self._translate_value(v) for v ... |
from .base import SimSootExpr
class SimSootExpr_Phi(SimSootExpr):
def __init__(self, expr, state):
super(SimSootExpr_Phi, self).__init__(expr, state)
def _execute(self):
if len(self.expr.values) != 2:
import ipdb; ipdb.set_trace();
v1, v2 = [self._translate_value(v) for... |
Return error if no items could be fetched | 'use strict';
var cheerio = require('cheerio');
var got = require('got');
/**
* w3counter API
*
* @param {String} type
* @param {Function} cb
* @api public
*/
module.exports = function (type, cb) {
var types = {
browser: 'Web Browsers',
country: 'Countries',
os: 'Operating Systems',... | 'use strict';
var cheerio = require('cheerio');
var got = require('got');
/**
* w3counter API
*
* @param {String} type
* @param {Function} cb
* @api public
*/
module.exports = function (type, cb) {
var types = {
browser: 'Web Browsers',
country: 'Countries',
os: 'Operating Systems',... |
Fix StyleKeeper context after ES6 conversion
`this.context` is inaccessible in the constructor unless you pass the
arguments to the component constructor (the second arg is context) | /* @flow */
import React, {Component} from 'react';
import StyleKeeper from '../style-keeper';
export default class StyleSheet extends Component {
// $FlowStaticPropertyWarning
static contextTypes = {
_radiumStyleKeeper: React.PropTypes.instanceOf(StyleKeeper)
};
constructor() {
super(...arguments);... | /* @flow */
import React, {Component} from 'react';
import StyleKeeper from '../style-keeper';
export default class StyleSheet extends Component {
// $FlowStaticPropertyWarning
static contextTypes = {
_radiumStyleKeeper: React.PropTypes.instanceOf(StyleKeeper)
};
constructor() {
super();
this.s... |
Remove line replace laravel namespace | <?php
namespace Caffeinated\Modules\Console;
use Module;
use Illuminate\Support\Str;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
use Illuminate\Console\GeneratorCommand as LaravelGeneratorCommand;
abstract class GeneratorCommand extends LaravelGeneratorCommand
{
/**
... | <?php
namespace Caffeinated\Modules\Console;
use Module;
use Illuminate\Support\Str;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
use Illuminate\Console\GeneratorCommand as LaravelGeneratorCommand;
abstract class GeneratorCommand extends LaravelGeneratorCommand
{
/**
... |
:white_check_mark: Test for inclusion of icon data. | const minecraftItems = require('../')
const tap = require('tap')
const testItem = (test, item, name) => {
test.type(item, 'object')
test.equal(item.name, name)
test.notEqual(typeof item.id, 'undefined', 'items should have an id property')
test.notEqual(typeof item.type, 'undefined', 'items should have a type p... | const minecraftItems = require('../')
const tap = require('tap')
const testItem = (test, item, name) => {
test.type(item, 'object')
test.equal(item.name, name)
test.end()
}
tap.test('should be able to get an item by numeric type', t => {
testItem(t, minecraftItems.get(1), 'Stone')
})
tap.test('should be able... |
Use test parent class inheritance to avoid boiler plate code. | package com.oneandone.snmpman;
import org.snmp4j.smi.OctetString;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.testng.Assert.assertTrue;
public class SnmpmanAgentTest extends AbstractSnmpmanTest {
@Test
public void testSnm... | package com.oneandone.snmpman;
import org.snmp4j.smi.OctetString;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.testng.Assert... |
Fix unnamed SQL parameters not being escaped (api) | const util = require('util');
const mysql = require('mysql');
// Open the database connection.
const db = mysql.createConnection({
host: process.env['DB_HOST'],
port: process.env['DB_PORT'],
user: process.env['DB_USER'],
password: process.env['DB_PASS'],
database: process.env['DB_NAME'],
multipleStatements: true... | const util = require('util');
const mysql = require('mysql');
// Open the database connection.
const db = mysql.createConnection({
host: process.env['DB_HOST'],
port: process.env['DB_PORT'],
user: process.env['DB_USER'],
password: process.env['DB_PASS'],
database: process.env['DB_NAME'],
multipleStatements: true... |
Use === instead of == | 'use strict';
module.exports = class PivotBuffer {
constructor(size) {
this.size = size;
this.$buffer = new Buffer(size);
this.$buffer.fill(0);
this.$curSize = 0;
}
append(buffer) {
if (buffer.length === 0) {
return;
}
if (... | 'use strict';
module.exports = class PivotBuffer {
constructor(size) {
this.size = size;
this.$buffer = new Buffer(size);
this.$buffer.fill(0);
this.$curSize = 0;
}
append(buffer) {
if (buffer.length == 0) {
return;
}
if (b... |
Fix typo after file renaming | /* global fetch */
import React from 'react';
import 'whatwg-fetch';
export default class UserStatisticsPage extends React.Component {
constructor(props) {
super(props);
this.state = { successRate: 0 };
this.getUserStatistics();
}
getUserStatistics() {
fetch(`api/statistics/${this.props.username... | /* global fetch */
import React from 'react';
import 'whatwg-fetch';
export default class UserStatisticPage extends React.Component {
constructor(props) {
super(props);
this.state = { successRate: 0 };
this.getUserStatistics();
}
getUserStatistics() {
fetch(`api/statistics/${this.props.username}... |
Fix endpoint url generation for graphiql | <?php
declare(strict_types=1);
namespace LotGD\Crate\GraphQL\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Tem... | <?php
declare(strict_types=1);
namespace LotGD\Crate\GraphQL\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Tem... |
Add setGrid and resetGrid functions | #!/usr/bin/env python
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
ro... | #!/usr/bin/env python
def createBlankGrid(row,column):
blankgrid = [[0 for x in range(column)] for y in range(row)]
return blankgrid
def getHeight(grid):
return len(grid)
def getWidth(grid):
return len(grid[0])
def printGrid(grid):
numRow = len(grid)
for i in range(0,numRow):
ro... |
Fix use of escape characters in "set terminal title" segment.
Escape characters were incorrect for non-BASH shells. | def add_term_title_segment():
term = os.getenv('TERM')
if not (('xterm' in term) or ('rxvt' in term)):
return
if powerline.args.shell == 'bash':
set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]'
elif powerline.args.shell == 'zsh':
set_title = '\033]0;%n@%m: %~\007'
else:
imp... | def add_term_title_segment():
term = os.getenv('TERM')
if not (('xterm' in term) or ('rxvt' in term)):
return
if powerline.args.shell == 'bash':
set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]'
elif powerline.args.shell == 'zsh':
set_title = '\\e]0;%n@%m: %~\\a'
else:
impor... |
Store variables for signal status
Former-commit-id: e4d925bcfd4543eb9dc309091b0098b3c8e6ccd5 | /**
* Get the network speed from zebedee/ping endpoint and output the network health
**/
function networkStatus(ping) {
var $good = $('.icon-status--good'),
$ok = $('.icon-status--ok'),
$poor = $('.icon-status--poor'),
$veryPoor = $('.icon-status--very-poor');
if (ping > 0 && ping <... | /**
* Get the network speed from zebedee/ping endpoint and output the network health
**/
function networkStatus(ping) {
if (ping > 0 && ping < 100) {
$('.icon-status div').css({"opacity": "1.0"});
} else if (ping >= 100 && ping < 200) {
$('.icon-status--good').css({"opacity": "0.2"});
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.