text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Use imported views instead of lazy import | from django.conf.urls import patterns, url
try:
from account.decorators import login_required
except ImportError:
from django.contrib.auth.decorators import login_required
from .views import (
CancelView,
ChangeCardView,
ChangePlanView,
HistoryView,
SubscribeView,
webhook,
subscrib... | from django.conf.urls import patterns, url
try:
from account.decorators import login_required
except ImportError:
from django.contrib.auth.decorators import login_required
from .views import (
CancelView,
ChangeCardView,
ChangePlanView,
HistoryView,
SubscribeView
)
urlpatterns = patterns... |
Fix the logo component in Symfony 5 | <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Components\Logo;
use function... | <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Components\Logo;
use function... |
Make sure the remember token is set | <?php
namespace Adldap\Laravel\Tests;
use Mockery as m;
use Adldap\Laravel\Auth\ResolverInterface;
use Adldap\Laravel\Middleware\WindowsAuthenticate;
class WindowsAuthenticateTest extends DatabaseTestCase
{
public function test_handle()
{
$request = app('request');
$request->server->set('AUT... | <?php
namespace Adldap\Laravel\Tests;
use Mockery as m;
use Adldap\Laravel\Auth\ResolverInterface;
use Adldap\Laravel\Middleware\WindowsAuthenticate;
class WindowsAuthenticateTest extends DatabaseTestCase
{
public function test_handle()
{
$request = app('request');
$request->server->set('AUT... |
Fix error in site alias files conditional if | <?php
// Grab the "Global" settings from drupdates
$result = json_decode(exec('python ~/.drush/settings.py'), true);
$path = $result['workingDir']['value'];
$driver = $result['datastoreDriver']['value'];
$user = $result['datastoreSuperUser']['value'];
$pass = $result['datastoreSuperPword']['value'];
$port = $result['da... | <?php
// Grab the "Global" settings from drupdates
$result = json_decode(exec('python ~/.drush/settings.py'), true);
$path = $result['workingDir']['value'];
$driver = $result['datastoreDriver']['value'];
$user = $result['datastoreSuperUser']['value'];
$pass = $result['datastoreSuperPword']['value'];
$port = $result['da... |
FIX: Use a string in `q` instead of an object because special characters in the values of each key of an object are now escaped as expected. | // Dependencies
var nock = require('nock'),
solr = require('./../main'),
vows = require('vows'),
assert = require('assert'),
mocks = require('./mocks'),
fs = require('fs');
// Load configuration file
var config = JSON.parse(fs.readFileSync(__dirname + '/config.json'));
if(config.mocked){
//nock.re... | // Dependencies
var nock = require('nock'),
solr = require('./../main'),
vows = require('vows'),
assert = require('assert'),
mocks = require('./mocks'),
fs = require('fs');
// Load configuration file
var config = JSON.parse(fs.readFileSync(__dirname + '/config.json'));
if(config.mocked){
//nock.re... |
Send network data on start | var
util = require('util')
, stream = require('stream')
, os = require('os')
;
function network(opts, app) {
var
self = this
, initialize = function(cloud) {
self.log.debug("Initializing network module")
self.cloud = cloud;
self.emit('register', sel... | var
util = require('util')
, stream = require('stream')
, os = require('os')
;
function network(opts, app) {
var
self = this
, initialize = function(cloud) {
self.log.debug("Initializing network module")
self.cloud = cloud;
self.emit('register', sel... |
Fix for ambiguous suburbs that have brackets and screw some things up. | <?php
namespace SimpleQuiz\Utils;
class Location {
protected $_suburb = null;
protected $_district = null;
protected $_region = null;
protected $_state = null;
public function __construct($suburb) {
$this->loadBySuburb($suburb);
}
public function loadBySuburb($suburb) {
$... | <?php
namespace SimpleQuiz\Utils;
class Location {
protected $_suburb = null;
protected $_district = null;
protected $_region = null;
protected $_state = null;
public function __construct($suburb) {
$this->loadBySuburb($suburb);
}
public function loadBySuburb($suburb) {
$... |
Mark TimeStampedMixin.modified as an onupdate FetchedValue | from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
... | from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_defaul... |
Define user earlier so it can be used more | <?php
class BotController extends AuthenticatedController {
public function update( $boturl = '' ) {
$this->requireLogin();
require_once 'models/grader/bot.php';
if ( empty( $boturl ) ) {
go( 'bot', 'update', [ 'boturl_empty' => true ] );
}
... | <?php
class BotController extends AuthenticatedController {
public function update( $boturl = '' ) {
$this->requireLogin();
require_once 'models/grader/bot.php';
if ( empty( $boturl ) ) {
go( 'bot', 'update', [ 'boturl_empty' => true ] );
}
... |
Add clearTitleSegments method to seo helper
Former-commit-id: 7eaed8690b7c184f477a748e87ea13cb89bb9ef8
Former-commit-id: 52e068afc53274320ccd396396bb64f1c71343d0 | <?php
namespace Concrete\Core\Html\Service;
class Seo
{
private $siteName = '';
private $titleSegments = array();
private $titleSegmentSeparator = ' :: ';
private $titleFormat = '%1$s :: %2$s';
private $hasCustomTitle = false;
public function setSiteName($name)
{
$this->siteName = ... | <?php
namespace Concrete\Core\Html\Service;
class Seo
{
private $siteName = '';
private $titleSegments = array();
private $titleSegmentSeparator = ' :: ';
private $titleFormat = '%1$s :: %2$s';
private $hasCustomTitle = false;
public function setSiteName($name)
{
$this->siteName = ... |
Update default grunt task to run unit tests and cssmin | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
options: {
"sub": true
},
all: ['src/**/*.js']
},
connect: {
server: {
options: {
port: 8000,
hostname: '12... | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
options: {
"sub": true
},
all: ['src/**/*.js']
},
connect: {
server: {
options: {
port: 8000,
hostname: '12... |
Make feature_file_paths have no duplicates | import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = set()
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self... | import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = []
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
... |
Make the Entry class static
So we don't to instantiate it. Was getting weird errors :/
Found on SO somewhere. | import java.util.*;
public class Table {
public static class Entry {
public Integer iface;
public IPAddress destinationIP;
public IPAddress nextHop;
public Entry(String d, String n, Integer i) {
iface = i;
destinationIP = new IPAddress(d);
nextH... | import java.util.*;
public class Table {
public class Entry {
public Integer iface;
public IPAddress destinationIP;
public IPAddress nextHop;
public Entry(String d, String n, Integer i) {
iface = i;
destinationIP = new IPAddress(d);
nextHop = ne... |
Add compression and integrity checks | from msgpack import packb, unpackb, Unpacker
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
from checksum import add_integrity, check_integrity
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
... | from msgpack import packb, Unpacker
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
'data': obj.to_json()}
elif isinstance(obj, LazyN... |
Improve register error response from api to client | <?php
namespace App\Controllers;
class AuthController
{
public function login()
{
var_dump(input());
return $input;
}
public function register()
{
$inputs = input()->all(['email', 'password']);
if (!$this->isValid($inputs))
{
return 'form is no... | <?php
namespace App\Controllers;
class AuthController
{
public function login()
{
var_dump(input());
return $input;
}
public function register()
{
$inputs = input()->all(['email', 'password']);
if (!$this->isValid($inputs) || $this->isEmailExist($inputs['email']))... |
Add full_name field to API | from django.contrib.auth.models import User
from rest_framework import permissions, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, self).to_... | from django.contrib.auth.models import User
from rest_framework import permissions, routers, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, ... |
Remove Yices test from RPC prover test | from cryptol import cryptoltypes
from cryptol.bitvector import BV
import saw
from saw.proofscript import *
import unittest
from pathlib import Path
def cry(exp):
return cryptoltypes.CryptolLiteral(exp)
class ProverTest(unittest.TestCase):
@classmethod
def setUpClass(self):
saw.connect(reset_ser... | from cryptol import cryptoltypes
from cryptol.bitvector import BV
import saw
from saw.proofscript import *
import unittest
from pathlib import Path
def cry(exp):
return cryptoltypes.CryptolLiteral(exp)
class ProverTest(unittest.TestCase):
@classmethod
def setUpClass(self):
saw.connect(reset_ser... |
Stop the server if MongoDB is not started | var mongoose = require('mongoose');
var config = require('config');
var semver = require('semver')
// configure mongodb
mongoose.connect(config.mongodb.connectionString || 'mongodb://' + config.mongodb.user + ':' + config.mongodb.password + '@' + config.mongodb.server +'/' + config.mongodb.database);
mongoos... | var mongoose = require('mongoose');
var config = require('config');
var semver = require('semver')
// configure mongodb
mongoose.connect(config.mongodb.connectionString || 'mongodb://' + config.mongodb.user + ':' + config.mongodb.password + '@' + config.mongodb.server +'/' + config.mongodb.database);
mongoos... |
Fix html wrapper linter issue | import React, { PropTypes } from 'react';
const HtmlWrapper = ({ children, state, head, scripts, stylesheets }) => {
// eslint-disable-next-line react/no-danger
const content = (<div id="root" dangerouslySetInnerHTML={{ __html: children }} />);
const htmlAttributes = head.htmlAttributes.toComponent();
return ... | import React, { PropTypes } from 'react';
const HtmlWrapper = ({ children, state, head, scripts, stylesheets }) => {
// eslint-disable-next-line react/no-danger
const content = (<div id="root" dangerouslySetInnerHTML={{ __html: children }} />);
const htmlAttributes = head.htmlAttributes.toComponent();
return ... |
Set limit for leaderboard to 10 | <?php
namespace Badger\UserBundle\Doctrine\Repository;
use Doctrine\ORM\EntityRepository;
use Badger\UserBundle\Repository\UserRepositoryInterface;
/**
* @author Adrien Pétremann <petremann.adrien@gmail.com>
*/
class UserRepository extends EntityRepository implements UserRepositoryInterface
{
/**
* {@inhe... | <?php
namespace Badger\UserBundle\Doctrine\Repository;
use Doctrine\ORM\EntityRepository;
use Badger\UserBundle\Repository\UserRepositoryInterface;
/**
* @author Adrien Pétremann <petremann.adrien@gmail.com>
*/
class UserRepository extends EntityRepository implements UserRepositoryInterface
{
/**
* {@inhe... |
Move highstock exporting before export-csv plugin | module.exports = {
all: {
options: {
format: 'json_flat',
pretty: true
},
files: [{
dest: 'dist/javascript.json',
src: [
'src/javascript/lib/jquery.js',
'src/javascript/lib/highstock/highstock.js',
'src/j... | module.exports = {
all: {
options: {
format: 'json_flat',
pretty: true
},
files: [{
dest: 'dist/javascript.json',
src: [
'src/javascript/lib/jquery.js',
'src/javascript/lib/highstock/highstock.js',
'src/j... |
Change the failure status-code of the zen mock to a 503: Server is currently unavailable.
This is a more appropriate mock response. We then check for our app
issuing a: 502: Server received an invalid response from upstream server | <?php
class ZenTest extends Slim_Framework_TestCase {
// Use dependency injection to mock the Curl object.
public function testCanFetchZenFromGitHub() {
$expected = 'Never sniff a gift fish.';
$curl = $this->getMock('\Curl');
$curl->expects($this->any())
->method('get')
... | <?php
class ZenTest extends Slim_Framework_TestCase {
// Use dependency injection to mock the Curl object.
public function testCanFetchZenFromGitHub() {
$expected = 'Never sniff a gift fish.';
$curl = $this->getMock('\Curl');
$curl->expects($this->any())
->method('get')
... |
Rename of pre and elems to generic nodes | define([
'jquery', // src/jquery.js,
'defaults'
], function ($, defaults) {
function Crayon(element, options) {
console.error('construct');
this.element = element;
this.options = $.extend({}, defaults, options);
this.init();
}
// Define plugin
Crayon.prototype = {
nodes: null,
in... | define([
'jquery', // src/jquery.js,
'defaults'
], function ($, defaults) {
function Crayon(element, options) {
console.error('construct');
this.element = element;
this.options = $.extend({}, defaults, options);
this.init();
}
// Define plugin
Crayon.prototype = {
elems: null,
in... |
Add setOption method to change default configuration | <?php
namespace Datatheke\Bundle\PagerBundle\DataGrid\Handler\Http;
use Symfony\Component\HttpFoundation\Request;
use Datatheke\Bundle\PagerBundle\DataGrid\HttpDataGridInterface;
use Datatheke\Bundle\PagerBundle\DataGrid\DataGridView;
use Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler as PagerViewHandle... | <?php
namespace Datatheke\Bundle\PagerBundle\DataGrid\Handler\Http;
use Symfony\Component\HttpFoundation\Request;
use Datatheke\Bundle\PagerBundle\DataGrid\HttpDataGridInterface;
use Datatheke\Bundle\PagerBundle\DataGrid\DataGridView;
use Datatheke\Bundle\PagerBundle\Pager\Handler\Http\ViewHandler as PagerViewHandle... |
Change dot generate message to suggest PDF format. |
import click
from textx.metamodel import metamodel_from_file
from textx.lang import get_language
from textx.exceptions import TextXError
from txtools.vis import metamodel_export, model_export
@click.command()
@click.argument('model_file')
@click.option('-l', '--language', default='textx',
help='Registe... |
import click
from textx.metamodel import metamodel_from_file
from textx.lang import get_language
from textx.exceptions import TextXError
from txtools.vis import metamodel_export, model_export
@click.command()
@click.argument('model_file')
@click.option('-l', '--language', default='textx',
help='Registe... |
Add alt_text field for Media | # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics",... | # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics",... |
Add readline support with vi keybindings | #!/usr/bin/env python3
import os
import shutil
import sys
import readline
import traceback
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
return '%s $ ' % os.getcwd()
def read_command():
line = input(prompt())
... | #!/usr/bin/env python3
import os
import shutil
import sys
import traceback
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
print('%s $ ' % os.getcwd(), end='', flush=True)
def read_command():
return sys.stdin.readline()
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def r... |
Add method to get current number of fetched items. | package com.tinkerpop.gremlin.driver;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class ResultSet imp... | package com.tinkerpop.gremlin.driver;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class ResultSet imp... |
Install six for Python 2 & 3 compatibility | #!/usr/bin/env python2
from setuptools import setup
setup(name="sagbescheid",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["sagbescheid", "sagbescheid.notifiers"],
package_dir={"sagbescheid": "sagbescheid"},
download_url="https://github.com/mineo/sagbescheid/ta... | #!/usr/bin/env python2
from setuptools import setup
setup(name="sagbescheid",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["sagbescheid", "sagbescheid.notifiers"],
package_dir={"sagbescheid": "sagbescheid"},
download_url="https://github.com/mineo/sagbescheid/ta... |
PATCH should 204 on success
Closes #8 | 'use strict';
const BaseHandler = require('./BaseHandler');
class PatchHandler extends BaseHandler {
/**
* Write data to the DataStore and return the new offset.
*
* @param {object} req http.incomingMessage
* @param {object} res http.ServerResponse
* @return {function}
*/
send(... | 'use strict';
const BaseHandler = require('./BaseHandler');
class PatchHandler extends BaseHandler {
/**
* Write data to the DataStore and return the new offset.
*
* @param {object} req http.incomingMessage
* @param {object} res http.ServerResponse
* @return {function}
*/
send(... |
Change patient visit table ordering to be latest to oldest | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.core.urlresolvers import reverse
class BillingCode(models.Model):
nr_rvus = models.FloatField()
creation_date = models.DateTimeField('date created', default=timez... | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.core.urlresolvers import reverse
class BillingCode(models.Model):
nr_rvus = models.FloatField()
creation_date = models.DateTimeField('date created', default=timez... |
Allow disabling the autocharging behavior of the bank transfer moocher | from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from mooch.base import BaseMoocher, require_POST_m
from mooch.signals imp... | from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from mooch.base import BaseMoocher, require_POST_m
from mooch.signals imp... |
Allow local_site_reverse to take an actual LocalSite.
local_site_reverse was able to take a LocalSite's name, or a request
object, but if you actually had a LocalSite (or None), you'd have to
write your own conditional to extract the name and pass it.
Now, local_site_reverse can take a LocalSite. This saves a databas... | from __future__ import unicode_literals
from django.core.urlresolvers import NoReverseMatch, reverse
def local_site_reverse(viewname, request=None, local_site_name=None,
local_site=None, args=None, kwargs=None,
*func_args, **func_kwargs):
"""Reverses a URL name, retu... | from __future__ import unicode_literals
from django.core.urlresolvers import NoReverseMatch, reverse
def local_site_reverse(viewname, request=None, local_site_name=None,
args=None, kwargs=None, *func_args, **func_kwargs):
"""Reverses a URL name, returning a working URL.
This works muc... |
Remove test with integer > Integer.MAX. Replaced it with negative number test | package strings;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static strings.BaseConversion.baseConversion;
class BaseConversionTest {
private String expected;
private String input;
private int b1;
private int b2;
@Test
void baseConversion1() {... | package strings;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static strings.BaseConversion.baseConversion;
class BaseConversionTest {
private String expected;
private String input;
private int b1;
private int b2;
@Test
void baseConversion1() {... |
Allow to set the port in adhocracy.domain to make adhocracy work stand alone again. | import logging
from adhocracy import model
from pylons import config
log = logging.getLogger(__name__)
class InstanceDiscriminatorMiddleware(object):
def __init__(self, app, domain):
self.app = app
self.domain = domain
log.debug("Host name: %s." % domain)
def __call__(self, environ... | import logging
from adhocracy import model
from pylons import config
log = logging.getLogger(__name__)
class InstanceDiscriminatorMiddleware(object):
def __init__(self, app, domain):
self.app = app
self.domain = domain
log.debug("Host name: %s." % domain)
def __call__(self, environ... |
Handle the three get cases |
const getStorage = () => {
const data = window.localStorage.getItem('__chrome.storage.sync__')
if (data != null) {
return JSON.parse(data)
} else {
return {}
}
}
const setStorage = (storage) => {
const json = JSON.stringify(storage)
window.localStorage.setItem('__chrome.storage.sync__', json)
}
... |
const getStorage = () => {
const data = window.localStorage.getItem('__chrome.storage.sync__')
if (data != null) {
return JSON.parse(data)
} else {
return {}
}
}
const setStorage = (storage) => {
const json = JSON.stringify(storage)
window.localStorage.setItem('__chrome.storage.sync__', json)
}
... |
Increment version for 24-bit wav bug fix | __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.16.4',
author='James Robert',
author_email='jiaaro@gmail.com',
description='Manipulate ... | __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.16.3',
author='James Robert',
author_email='jiaaro@gmail.com',
description='Manipulate ... |
Modify query to return vertex count | 'use strict';
function prepareQuery(sql) {
var affectedTableRegexCache = {
bbox: /!bbox!/g,
scale_denominator: /!scale_denominator!/g,
pixel_width: /!pixel_width!/g,
pixel_height: /!pixel_height!/g
};
return sql
.replace(affectedTableRegexCache.bbox, 'ST_MakeEnvelope(0,0,0,0)')
... | 'use strict';
function prepareQuery(sql) {
var affectedTableRegexCache = {
bbox: /!bbox!/g,
scale_denominator: /!scale_denominator!/g,
pixel_width: /!pixel_width!/g,
pixel_height: /!pixel_height!/g
};
return sql
.replace(affectedTableRegexCache.bbox, 'ST_MakeEnvelope(0,0,0,0)')
... |
Add GUI support for Travis | module.exports = function(config) {
var configuration = {
client: {
captureConsole: false
},
plugins: [
'karma-chai',
'karma-sinon',
'karma-mocha',
'karma-chrome-launcher'
],
frameworks: ['mocha', 'sinon', 'chai']... | module.exports = function(config) {
var configuration = {
client: {
captureConsole: false
},
plugins: [
'karma-chai',
'karma-sinon',
'karma-mocha',
'karma-chrome-launcher'
],
frameworks: ['mocha', 'sinon', 'chai']... |
Fix Conversation validation on recipients | <?php
namespace FD\PrivateMessageBundle\Validator;
use FD\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Class ConversationValidator.
*/
class ConversationValidator
{
const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';
/*... | <?php
namespace FD\PrivateMessageBundle\Validator;
use FD\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Class ConversationValidator.
*/
class ConversationValidator
{
const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';
/*... |
Fix broken functional tests on windows
Something must have changed on the Appveyor side since this code
hasn't been touched recently. The issue was that a functional test
was referring to "/tmp" which is not valid on Windows. I'm surprised
this worked on Windows in the first place. | import os
import tempfile
import yaml
from test.framework.functional.base_functional_test_case import BaseFunctionalTestCase
from test.functional.job_configs import BASIC_JOB
class TestMasterEndpoints(BaseFunctionalTestCase):
def setUp(self):
super().setUp()
self._project_dir = tempfile.Tempora... | import os
import yaml
from test.framework.functional.base_functional_test_case import BaseFunctionalTestCase
from test.functional.job_configs import BASIC_JOB
class TestMasterEndpoints(BaseFunctionalTestCase):
def _start_master_only_and_post_a_new_job(self):
master = self.cluster.start_master()
... |
Add test injection in xml asserter | <?php
namespace mageekguy\atoum\xml;
use mageekguy\atoum;
use mageekguy\atoum\observable;
use mageekguy\atoum\runner;
use mageekguy\atoum\test;
class extension implements atoum\extension
{
public function __construct(atoum\configurator $configurator = null)
{
if ($configurator)
{
$... | <?php
namespace mageekguy\atoum\xml;
use mageekguy\atoum;
use mageekguy\atoum\observable;
use mageekguy\atoum\runner;
use mageekguy\atoum\test;
class extension implements atoum\extension
{
public function __construct(atoum\configurator $configurator = null)
{
if ($configurator)
{
$... |
Print HTTP content in verbose mode | # -*- coding: utf-8 -*-
"""Python implementation of the Readability Shortener API"""
import requests
try:
import simplejson as json
except ImportError:
import json
class Readability(object):
def __init__(self, url=None, verbose=None):
self.url = url or 'https://readability.com/api/shortener/v1'... | # -*- coding: utf-8 -*-
"""Python implementation of the Readability Shortener API"""
import requests
try:
import simplejson as json
except ImportError:
import json
class Readability(object):
def __init__(self, url=None, verbose=None):
self.url = url or 'https://readability.com/api/shortener/v1'... |
Use the new child_process.spawn API |
var log = require("../utils/log")
module.exports = function exec (cmd, args, env, pipe, cb) {
if (!cb) cb = pipe, pipe = false
if (!cb) cb = env, env = process.env
log(cmd+" "+args.map(JSON.stringify).join(" "), "exec")
var stdio = process.binding("stdio")
, fds = [ stdio.stdinFD || 0
, stdio.... |
var log = require("../utils/log")
module.exports = function exec (cmd, args, env, pipe, cb) {
if (!cb) cb = pipe, pipe = false
if (!cb) cb = env, env = process.env
log(cmd+" "+args.map(JSON.stringify).join(" "), "exec")
var stdio = process.binding("stdio")
, fds = [ stdio.stdinFD || 0
, stdio.... |
Replace deprecated slave_ok for read_preference in pymongo.Connection
See: http://api.mongodb.org/python/current/api/pymongo/connection.html | try:
from numbers import Number
import pymongo
from pymongo import ReadPreference
except ImportError:
Number = None
import diamond
class MongoDBCollector(diamond.collector.Collector):
"""Collects data from MongoDB's db.serverStatus() command
Collects all number values from the db.serverStatu... | try:
from numbers import Number
import pymongo
except ImportError:
Number = None
import diamond
class MongoDBCollector(diamond.collector.Collector):
"""Collects data from MongoDB's db.serverStatus() command
Collects all number values from the db.serverStatus() command, other
values are ignor... |
Fix help messages for commands | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='stor... | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='stor... |
Debug .vue files in browserify | var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some b... | var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some b... |
Fix a bug introduced in the latest revision, testing auth header in initialize_server_request now, thanks Chris McMichael for the report and patch | import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
# Django converts Authorization header in HTTP_AUTHORIZATION... | import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
oauth_request = oauth.OAuthRequest.from_request(request.meth... |
Fix status bar on analysis page | import { List as list } from 'immutable';
import { connect } from 'react-redux';
import { aBlockClicked } from '../../../actions/analysis.actions';
import { aContentBlockHovered } from '../../../actions/content.actions';
import React from 'react';
import PropTypes from 'prop-types';
import BlockPacker from '../../..... | import { List as list } from 'immutable';
import { connect } from 'react-redux';
import { aBlockClicked } from '../../../actions/analysis.actions';
import { aContentBlockHovered } from '../../../actions/content.actions';
import React from 'react';
import PropTypes from 'prop-types';
import BlockPacker from '../../..... |
Fix pattern scenario loader test | package website.automate.jwebrobot.loader;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import website.automate.jwebrobot.AbstractTest;
import website.automate.jwebrobot.ConfigurationProperties;
import website.automate.jwebrobot.exceptions.NonReadableFileException;
import java... | package website.automate.jwebrobot.loader;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import website.automate.jwebrobot.AbstractTest;
import website.automate.jwebrobot.ConfigurationProperties;
import website.automate.jwebrobot.exceptions.NonReadableFileException;
import java... |
fix(grid): Remove whitespace between polygon elements | import React, {PropTypes, Component} from 'react';
import Color from '~/src/tools/Color';
export default class Polygon extends Component {
static propTypes = {
points: PropTypes.array.isRequired,
fillColor: PropTypes.instanceOf(Color).isRequired
}
constructor(props){
super(props);
... | import React, {PropTypes, Component} from 'react';
import Color from '~/src/tools/Color';
export default class Polygon extends Component {
static propTypes = {
points: PropTypes.array.isRequired,
fillColor: PropTypes.instanceOf(Color).isRequired
}
constructor(props){
super(props);
... |
Add random GT to a given vcf | import pysam
from numpy.random import choice
def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01):
vcf_pointer = pysam.VariantFile(filename=input_vcf)
new_header = vcf_pointer.header.copy()
if "GT" not in new_header.formats:
new_header.formats.add("GT", "1", "String", "Conse... | import pysam
from numpy.random import choice
import math
def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01):
vcf_pointer = pysam.VariantFile(filename=input_vcf)
new_header = vcf_pointer.header.copy()
if "GT" not in new_header.formats:
new_header.formats.add("GT", "1", "Str... |
Use pysolr instead of haystack in indexing job | import itertools
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from haystack import site
import pysolr
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Runs any queued-up search indexing tasks."
def handle(self, **o... | import itertools
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from haystack import site
import pysolr
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Runs any queued-up search indexing tasks."
def handle(self, **o... |
Fix initialization of proof of worker index | angular.module('GLBrowserCrypto', [])
.factory('glbcProofOfWork', ['$q', function($q) {
// proofOfWork return the answer to the proof of work
// { [challenge string] -> [ answer index] }
var str2Uint8Array = function(str) {
var result = new Uint8Array(str.length);
for (var i = 0; i < str.length; i++) {
... | angular.module('GLBrowserCrypto', [])
.factory('glbcProofOfWork', ['$q', function($q) {
// proofOfWork return the answer to the proof of work
// { [challenge string] -> [ answer index] }
var str2Uint8Array = function(str) {
var result = new Uint8Array(str.length);
for (var i = 0; i < str.length; i++) {
... |
Add `is_acquired` property to FileLock | # -*- encoding: utf-8 -*-
import os
import fcntl
from tagcache.utils import open_file
class FileLock(object):
def __init__(self, path):
self.path = path
self.fd = None
@property
def is_acquired(self):
return self.fd is not None
def acquire(self, ex=False, nb=False):
... | # -*- encoding: utf-8 -*-
import os
import fcntl
from tagcache.utils import open_file
class FileLock(object):
def __init__(self, path):
self.path = path
self.fd = None
def acquire(self, ex=False, nb=False):
"""
Acquire a lock on a path.
:param ex (optional): defa... |
Support for true as config value (Default config is used if true is passed) | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace abexto\ydc\base\common;
/**
* Abstract Base Class for yDoctrine Components
*
* Component class which implements ... | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace abexto\ydc\base\common;
/**
* Abstract Base Class for yDoctrine Components
*
* Component class which implements ... |
Return XML path in case of errors | /*
*
* A simple script to create (or print) a JSON file from an XML file
*
*/
var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var output = './';
module.exports = (function () {
this.publishJSON = function (file, outputDir) {
parser.pa... | /*
*
* A simple script to create (or print) a JSON file from an XML file
*
*/
var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var output = './';
module.exports = (function () {
this.publishJSON = function (file, outputDir) {
parser.pa... |
Fix run tests with Celery | #!/usr/bin/env python
import sys
from optparse import OptionParser
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'USER': '',... | #!/usr/bin/env python
import sys
from optparse import OptionParser
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_celery_rpc',
'U... |
Use standard sms: format rather than MozActivity for SMS brick. | module.exports = {
className: 'sms',
template: require('./index.html'),
data: {
name: 'SMS',
icon: '/images/blocks_sms.png',
attributes: {
value: {
label: 'Phone #',
type: 'string',
value: '+18005555555'
},
... | module.exports = {
className: 'sms',
template: require('./index.html'),
data: {
name: 'SMS',
icon: '/images/blocks_sms.png',
attributes: {
value: {
label: 'Phone #',
type: 'string',
value: '+18005555555'
},
... |
Correct implementation of the while loop | import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.Generi... | import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.Generi... |
Disable min_priority filter for now | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_gam... | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.curre... |
Fix rasterio to version 0.36.0 now that 1.0 is out
There are some incompatibilities between the two. Until I can go to NHM
to upgrade their setup, I'll pin it to the old version. | from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',... | from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',... |
Remove unicode string markers which are removed in python3 | """Improve repository owner information
Revision ID: 30c0aec2ca06
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:45:05.241933
"""
# revision identifiers, used by Alembic.
revision = '30c0aec2ca06'
down_revision = '4fdf1059c4ba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
... | """Improve repository owner information
Revision ID: 30c0aec2ca06
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:45:05.241933
"""
# revision identifiers, used by Alembic.
revision = '30c0aec2ca06'
down_revision = '4fdf1059c4ba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
... |
Fix wrong path to flood data to push. | # coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"""Script to load flood test data for de... | # coding=utf-8
import os
import shutil
from tempfile import mkdtemp
from django.core.management.base import BaseCommand
from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood
class Command(BaseCommand):
"""Script to load flood test data for de... |
Remove modal padding around rebuild change list | import React from "react";
import { map, sortBy } from "lodash-es";
import { Row, Col, ListGroup, ListGroupItem, Panel } from "react-bootstrap";
import { LoadingPlaceholder } from "../../base";
export default function RebuildHistory ({ unbuilt, error }) {
const extraChanges = unbuilt.page_count > 1
? (
... | import React from "react";
import { map, sortBy } from "lodash-es";
import { Row, Col, ListGroup, ListGroupItem, Panel } from "react-bootstrap";
import { LoadingPlaceholder } from "../../base";
export default function RebuildHistory ({ unbuilt, error }) {
const extraChanges = unbuilt.page_count > 1
? (
... |
Fix to ensure the unsubscribe on next operator used for database queries can be reused | package foundation.stack.datamill.db.impl;
import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Ravi Chodavarapu (rchodava@gmail.com)
*/
public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> {
@Over... | package foundation.stack.datamill.db.impl;
import rx.Observable;
import rx.Subscriber;
import rx.exceptions.Exceptions;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Ravi Chodavarapu (rchodava@gmail.com)
*/
public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> {
priva... |
Make the irrelevant object a constant | IRRELEVANT = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', IRRELEVANT)
self.expected_after = kwargs.pop('after', IRRELEVANT)
def __... | irrelevant = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', irrelevant)
self.expected_after = kwargs.pop('after', irrelevant)
def __... |
Make commit_on_http_success commit for status codes from 200 to 399 and not only with 200
Signed-off-by: Álvaro Arranz García <3a7352a9ec78d7d17a9240a830621a1f159ca041@conwet.com> | from django.db.transaction import is_dirty, leave_transaction_management, rollback, commit, enter_transaction_management, managed
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponse
def commit_on_http_success(func, using=None):
"""
This decorator activates db commit on HTTP success res... | from django.db.transaction import is_dirty, leave_transaction_management, rollback, commit, enter_transaction_management, managed
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponse
def commit_on_http_success(func, using=None):
"""
This decorator activates db commit on HTTP success res... |
Remove trailing slash in GitLab url
Signed-off-by: kfei <1da1ad03e627cea4baf20871022464fcc6a4b2c4@kfei.net> | app
.factory("gitlab",
["$http", "$q", "Config",
function($http, $q, Config) {
function gitlab() {}
gitlab.prototype.imageUrl = function(path) {
return Config.gitlabUrl.replace(/\/*$/, "") + path;
};
gitlab.prototype.callapi = function(method, path) {
var deferred = $... | app
.factory("gitlab",
["$http", "$q", "Config",
function($http, $q, Config) {
function gitlab() {}
gitlab.prototype.imageUrl = function(path) {
return Config.gitlabUrl + path;
};
gitlab.prototype.callapi = function(method, path) {
var deferred = $q.defer();
v... |
Fix Installation Issues -> missing Boto3 | import setuptools
import codecs
import os.path
# Used to read the file
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
# Used to extract out the __version__
def get_version(rel_path):
for line in read... | import setuptools
import codecs
import os.path
# Used to read the file
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
# Used to extract out the __version__
def get_version(rel_path):
for line in read... |
Add tests for admin client models | /* global ic */
var ajax = function () {
return ic.ajax.request.apply(null, arguments);
};
// Used in API request fail handlers to parse a standard api error
// response json for the message to display
function getRequestErrorMessage(request, performConcat) {
var message,
msgDetail;
// Can't real... | /* global ic */
var ajax = window.ajax = function () {
return ic.ajax.request.apply(null, arguments);
};
// Used in API request fail handlers to parse a standard api error
// response json for the message to display
function getRequestErrorMessage(request, performConcat) {
var message,
msgDetail;
... |
Add send() method to chat object. | <?php
namespace MinePlus\WebSocketBundle;
use Symfony\Component\Console\Output\OutputInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
protected $output;
public function __construct(Outpu... | <?php
namespace MinePlus\WebSocketBundle;
use Symfony\Component\Console\Output\OutputInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
protected $output;
public function __construct(Outpu... |
Add CSS for moving cards down a little | 'use strict';
console.log('\'Allo \'Allo! Content script');
// https://gist.github.com/dkniffin/b6f5dd4e1bde716e7b32#gistcomment-1980578
function toggle_visibility(data_id) {
var matches = document.querySelectorAll(data_id);
[].forEach.call(matches, function(e) {
if(e.style.display == 'none') {
... | 'use strict';
console.log('\'Allo \'Allo! Content script');
// https://gist.github.com/dkniffin/b6f5dd4e1bde716e7b32#gistcomment-1980578
function toggle_visibility(data_id) {
var matches = document.querySelectorAll(data_id);
[].forEach.call(matches, function(e) {
if(e.style.display == 'none') {
... |
Check whether a layer existing on the map before trying to add it | const addPaintOptions = (options, layer) => {
if (layer.isPoint) {
options['type'] = 'circle'
options['paint'] = {
'circle-radius': [
'interpolate',
['exponential', 1],
['zoom'],
0, 1.5,
6, 4
],
'circle-color': layer.color,
'circle-opacity': 0.7... | const addPaintOptions = (options, layer) => {
if (layer.isPoint) {
options['type'] = 'circle'
options['paint'] = {
'circle-radius': [
'interpolate',
['exponential', 1],
['zoom'],
0, 1.5,
6, 4
],
'circle-color': layer.color,
'circle-opacity': 0.7... |
Change download url for release 0.3.6 | from distutils.core import setup
setup(
name = 'django-test-addons',
packages = ['test_addons'],
version = '0.3.6',
description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.',
author = 'Hakampreet Singh Pandher',
author_email = 'hspandher@outlook.c... | from distutils.core import setup
setup(
name = 'django-test-addons',
packages = ['test_addons'],
version = '0.3.5',
description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.',
author = 'Hakampreet Singh Pandher',
author_email = 'hspandher@outlook.c... |
Add support for lenient reading where reading too much is full of zeros. | package net.openhft.chronicle.bytes;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
public class ReadLenientTest {
@Test
public void testLenient() {
doTest(Bytes.allocateDirect(64));
do... | package net.openhft.chronicle.bytes;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
public class ReadLenientTest {
@Test
public void testLenient() {
doTest(Bytes.allocateDirect(64));
do... |
Add the flatten option for bar chart with numbers
Module appears to work in exactly the same way after doing this | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || 'uniqueEvents:sum';
var options = {
valueAttr: valueAttr,
ax... | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || 'uniqueEvents:sum';
var options = {
valueAttr: valueAttr,
ax... |
Raise version and change keywords for upcoming release | from setuptools import setup, find_packages
import os
version = '0.5'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
... | from setuptools import setup, find_packages
import os
version = '0.4'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
... |
Fix error typo and changed post request to use expected request body | import { EventEmitter } from 'events'
import axios from 'axios'
export default class RoomService extends EventEmitter {
constructor() {
super()
}
addRoom(timeslots) {
this.createRoom(room, this.hasBeenAdded.bind(this), this.getThem.bind(this))
}
getThem(userid) {
this.getRooms(userid, this.gott... | import { EventEmitter } from 'events'
import axios from 'axios'
export default class RoomService extends EventEmitter {
constructor() {
super()
}
addRoom(timeslots) {
this.createRoom(room, this.hasBeenAdded.bind(this), this.getThem.bind(this))
}
getThem(userid) {
this.getRooms(userid, this.gott... |
Fix bug with composed variants without parent context | import React from 'react';
import PropTypes from 'prop-types';
import { CONTEXT_KEY, contextType } from './connectVariants';
import _ from 'lodash';
export default class VariantProvider extends React.Component {
static propTypes = {
variants: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(... | import React from 'react';
import PropTypes from 'prop-types';
import { CONTEXT_KEY, contextType } from './connectVariants';
import _ from 'lodash';
export default class VariantProvider extends React.Component {
static propTypes = {
variants: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(... |
Clone object before processing JSON |
/**
*
*
* @param {object} object The output from Alpaca
* @return {object} A corrected version of the output. This should be a
* valid Swagger spec.
*/
module.exports = function processJSON (objectFuncParam) {
const object = JSON.parse(JSON.stringify(objectFuncParam));
if (obj... |
/**
*
*
* @param {object} object The output from Alpaca
* @return {object} A corrected version of the output. This should be a
* valid Swagger spec.
*/
module.exports = function processJSON (objectFuncParam) {
const object = objectFuncParam;
if (object.paths) {
/*
* T... |
Use the file's storage to determine whether the file exists or not.
The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage | from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template di... | from posixpath import exists
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of ... |
Use different TED talk - don't load insecure images. | <div id="mainWrapper" class="dark-bg">
<div id="header" >
<div class="row center-text">
<div class="small-12 columns">
<h1>You have reached Kyle's website.</h1>
</div>
</div>
</div>
<div id="content">
<div class="row center-text">
... | <div id="mainWrapper" class="dark-bg">
<div id="header" >
<div class="row center-text">
<div class="small-12 columns">
<h1>You have reached Kyle's website.</h1>
</div>
</div>
</div>
<div id="content">
<div class="row center-text">
... |
Fix class name in annotation | <?php
namespace HostBox\Components;
use Nette;
/**
* Class ComponentFactory
* @package HostBox\Components
*/
abstract class ComponentFactory extends Nette\Object {
/** @var mixed */
protected $config;
/** @var array */
protected $plugins;
public function __call($name, $args) {
if (s... | <?php
namespace HostBox\Components;
use Nette;
/**
* Class SocialPluginComponent
* @package HostBox\Components
*/
abstract class ComponentFactory extends Nette\Object {
/** @var mixed */
protected $config;
/** @var array */
protected $plugins;
public function __call($name, $args) {
... |
Use util.inherits instead of simple prototype assignment. | var RedisStore = require('connect-redis');
var url = require('url');
var util = require('util');
var envVariables = ['REDIS_SESSION_URI', 'REDIS_URI', 'REDIS_SESSION_URL', 'REDIS_URL', 'REDISTOGO_URL', 'OPENREDIS_URL'];
var fallback = 'redis://localhost:6379'
module.exports = function(connect){
var store = RedisStor... | var RedisStore = require('connect-redis');
var url = require('url');
var envVariables = ['REDIS_SESSION_URI', 'REDIS_URI', 'REDIS_SESSION_URL', 'REDIS_URL', 'REDISTOGO_URL', 'OPENREDIS_URL'];
var fallback = 'redis://localhost:6379'
module.exports = function(connect){
var store = RedisStore(connect);
function Krak... |
Prepend log entries to try to stay above the fold | (function() {
var opQueue = new OperationQueue(),
counter = 0;
function demoLog(msg) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(msg));
$("#logger").prepend(li);
}
$("#success").click(function() {
demoLog("Calling success han... | (function() {
var opQueue = new OperationQueue(),
counter = 0;
function demoLog(msg) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(msg));
$("#logger").append(li);
}
$("#success").click(function() {
demoLog("Calling success hand... |
Move those methods to own class [ci skip] | # -*- coding: utf-8 -*-
"""ICU (LEGO Island Configuration Utility).
Created 2015 Triangle717
<http://le717.github.io/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
class ActionsQueue:
def __init__(self):
self.queue = []
class Responses:
def __init__(self):
pa... | # -*- coding: utf-8 -*-
"""ICU (LEGO Island Configuration Utility).
Created 2015 Triangle717
<http://le717.github.io/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
class ActionsQueue:
def __init__(self):
self.queue = []
# Normal buttons
def btnBrowse(self, val):
... |
Add revid to Notification object
Since most edit-related notifications include revid attributes,
we should include the revids in the Notification objects as we're
building them (if they exist).
Change-Id: Ifdb98e7c79729a1c2f7a5c4c4366e28071a48239 | # -*- coding: utf-8 -*-
"""Classes and functions for working with the Echo extension."""
from __future__ import absolute_import, unicode_literals
import pywikibot
class Notification(object):
"""A notification issued by the Echo extension."""
def __init__(self, site):
"""Construct an empty Notifica... | # -*- coding: utf-8 -*-
"""Classes and functions for working with the Echo extension."""
from __future__ import absolute_import, unicode_literals
import pywikibot
class Notification(object):
"""A notification issued by the Echo extension."""
def __init__(self, site):
"""Construct an empty Notifica... |
Replace custom status codes with http module | module.exports = function (app, nus) {
var opts = app.get('opts')
, http = require('http')
, router = require('express').Router();
router.route('/shorten')
.post(function (req, res) {
nus.shorten(req.body['long_url'], function (err, reply) {
if (err) {
jsonResponse(res, err);
... | module.exports = function (app, nus) {
var opts = app.get('opts')
, router = require('express').Router();
router.route('/shorten')
.post(function (req, res) {
nus.shorten(req.body['long_url'], function (err, reply) {
if (err) {
jsonResponse(res, err);
} else if (reply) {
... |
Use lines list as stdout | package com.github.blindpirate.gogradle.task.go;
import java.io.File;
import java.util.List;
public class PackageTestContext {
private String packagePath;
private List<File> testFiles;
private List<String> stdout;
public String getPackagePath() {
return packagePath;
}
public List<Fil... | package com.github.blindpirate.gogradle.task.go;
import java.io.File;
import java.util.List;
public class PackageTestContext {
private String packagePath;
private List<File> testFiles;
private String stdout;
public String getPackagePath() {
return packagePath;
}
public List<File> get... |
Add wordpress-muplugin is allowable package type | <?php
namespace BeanstalkSatisGen\File;
class Composer extends Json
{
/**
* Returns whether or not this composer file is a satis package based on the
* contents.
*
* @return boolean
*/
public function isComposerPackage()
{
return
! empty($this->content) &&
... | <?php
namespace BeanstalkSatisGen\File;
class Composer extends Json
{
/**
* Returns whether or not this composer file is a satis package based on the
* contents.
*
* @return boolean
*/
public function isComposerPackage()
{
return
! empty($this->content) &&
... |
Create function to return all jobs by state
I moved this for security reasons (so we can use Auth). | <?php
namespace App\Http\Controllers;
use App\Job;
use App\Http\Controllers\Controller;
class JobController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show m... | <?php
namespace App\Http\Controllers;
use App\Job;
use App\Http\Controllers\Controller;
class JobController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show p... |
Watch unit tests and rerun on change | module.exports = function(grunt) {
grunt.initConfig({
concat: {
options: {
separator: ''
},
app: {
dest: 'deploy/app.js',
src: [
'src/intro.js.frag',
'src/*.js',
... | module.exports = function(grunt) {
grunt.initConfig({
concat: {
options: {
separator: ''
},
app: {
dest: 'deploy/app.js',
src: [
'src/intro.js.frag',
'src/*.js',
... |
refactor: Rename all streams tab key to 'allStreams'.
Reason behind this change is to avoid confusion as there is already tab with key 'streams' in home tabs. | /* @flow */
import React from 'react';
import { StyleSheet, Text } from 'react-native';
import { TabNavigator, TabBarTop } from 'react-navigation';
import { FormattedMessage } from 'react-intl';
import tabsOptions from '../styles/tabs';
import SubscriptionsContainer from '../streams/SubscriptionsContainer';
import Str... | /* @flow */
import React from 'react';
import { StyleSheet, Text } from 'react-native';
import { TabNavigator, TabBarTop } from 'react-navigation';
import { FormattedMessage } from 'react-intl';
import tabsOptions from '../styles/tabs';
import SubscriptionsContainer from '../streams/SubscriptionsContainer';
import Str... |
Remove the creation of a function in map render | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BaseChart } from 'react-jsx-highcharts';
class HighchartsMapChart extends Component {
static propTypes = {
getHighcharts: PropTypes.func.isRequired // Provided by HighchartsProvider
};
static defaultProps = {
callback... | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BaseChart } from 'react-jsx-highcharts';
class HighchartsMapChart extends Component {
static propTypes = {
getHighcharts: PropTypes.func.isRequired // Provided by HighchartsProvider
};
static defaultProps = {
callback... |
Use PackageName-x.x.x for consistency with CLI install usage. | <?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>
<div class="package">
<div class="grid_8 left">
<h2>
<a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name; ?>"><?php echo $context->name; ?></a>-<?php echo... | <?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>
<div class="package">
<div class="grid_8 left">
<h2>
<a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name; ?>"><?php echo $context->name; ?></a> ::
... |
Use props instead of state | import { h } from 'preact'
import Nav from '../components/Nav'
import Loading from '../components/Loading'
import displayDate from '../helpers/display-date'
const Wrapper = (props) => {
let textClass = ''
if (!props.showInfo)
textClass = 'hidden'
if (props.isLoading) {
return (
<Loading />
)... | import { h } from 'preact'
import Nav from '../components/Nav'
import Loading from '../components/Loading'
import displayDate from '../helpers/display-date'
const Wrapper = (props) => {
let textClass = ''
if (!props.showInfo)
textClass = 'hidden'
if (props.isLoading) {
return (
<Loading />
)... |
[hide_input_all] Fix loading for either before or after notebook loads. | // toggle display of all code cells' inputs
define([
'jquery',
'base/js/namespace',
'base/js/events'
], function(
$,
Jupyter,
events
) {
"use strict";
function set_input_visible(show) {
Jupyter.notebook.metadata.hide_input = !show;
if (show) $('div.input').show('slow')... | // toggle display of all code cells' inputs
define([
'jquery',
'base/js/namespace'
], function(
$,
IPython
) {
"use strict";
function set_input_visible(show) {
IPython.notebook.metadata.hide_input = !show;
if (show) $('div.input').show('slow');
else $('div.input').hide... |
Bump version number (so readthedocs picks it up). | """
"""
__version__ = '0.2'
__release__ = '0.2a1'
def inject_app_defaults():
"""
Automatically inject the default settings for this app.
If settings has already been configured, then we need to add
our defaults to that (if not overridden), and in all cases we
also want to inject our settings into ... | """
"""
__version__ = '0.1'
__release__ = '0.1a3'
def inject_app_defaults():
"""
Automatically inject the default settings for this app.
If settings has already been configured, then we need to add
our defaults to that (if not overridden), and in all cases we
also want to inject our settings i... |
Remove param check for backup type on v2.1 API
The backup type is only used by glance, so nova check it make
no sense; currently we have daily and weekly as only valid param
but someone may add 'monthly' as param. nova should allow it
and delegate the error. This patch removes check on v2.1 API.
Change-Id: I59bbc0f58... | # Copyright 2014 NEC Corporation. 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 ... | # Copyright 2014 NEC Corporation. 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.