text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Change the programme to avoid error, NEED TO BE FIXED | import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.*;
import machine.learning.ARL;
public class Programme {
public static void main(String[] args) throws FileNotFoundException {
ArrayList array = new ArrayList<Double>();... | import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.*;
import machine.learning.ARL;
public class Programme {
public static void main(String[] args) throws FileNotFoundException {
ArrayList array = new ArrayList<Double>();... |
Refactor to create role if not existing | Meteor.methods({
"createRoleIfNotExisting": function (roleName) {
/*
Check if a given role exists
create the role if it doesn't exist
*/
// Placeholder variable for role check
var roleExists;
// Get all existing roles
var roles = Meteor.roles.find().fetch();
// Flatten the role... | Meteor.methods({
"createAdminRoleIfNotDefined": function () {
// TODO: Refactor this process to allow user to specify admin role as parameter
// E.g. a config page where the user can input the desired string
// Define the admin role
var adminRole = 'admin';
// Placeholder variable for admin che... |
Improve formatting for NoIdItem in ResultSet tests | from .config import TweepyTestCase
from tweepy.models import ResultSet
class NoIdItem:
pass
class IdItem:
def __init__(self, id):
self.id = id
ids_fixture = [1, 10, 8, 50, 2, 100, 5]
class TweepyResultSetTests(TweepyTestCase):
def setUp(self):
self.results = ResultSet()
for i in... | from .config import TweepyTestCase
from tweepy.models import ResultSet
class NoIdItem: pass
class IdItem:
def __init__(self, id):
self.id = id
ids_fixture = [1, 10, 8, 50, 2, 100, 5]
class TweepyResultSetTests(TweepyTestCase):
def setUp(self):
self.results = ResultSet()
for i in ids... |
Use the session user to fetch org repos | /*jshint strict:true, trailing:false, unused:true, node:true */
'use strict';
require("babel/register");
var GitHub = require('../github');
var redis = require('../redis');
var Repo = require('../repo');
module.exports = function(req, res) {
var owner = req.params.owner;
var name = req.params.repo;
return... | /*jshint strict:true, trailing:false, unused:true, node:true */
'use strict';
require("babel/register");
var GitHub = require('../github');
var redis = require('../redis');
var Repo = require('../repo');
module.exports = function(req, res) {
var owner = req.params.owner;
var name = req.params.repo;
return... |
Fix travis testing on node < 8 | const gulp = require('gulp');
const util = require('gulp-util');
const babel = require('gulp-babel');
const mocha = require('gulp-mocha');
const eslint = require('gulp-eslint');
const src = 'src/index.js';
gulp.task('lint', () => (
gulp.src([src, 'test/*.js'])
.pipe(eslint())
.pipe(eslint.format())
));
gulp.ta... | const gulp = require('gulp');
const util = require('gulp-util');
const babel = require('gulp-babel');
const mocha = require('gulp-mocha');
const eslint = require('gulp-eslint');
const src = 'src/index.js';
gulp.task('lint', () =>
gulp.src([src, 'test/*.js'])
.pipe(eslint())
.pipe(eslint.format()),
);
gulp.task... |
Fix import in test loot tables provider | package info.u_team.u_team_test.data.provider;
import java.util.function.BiConsumer;
import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
import net.minecraft.loot.LootTable;
import net.minecraft.util.ResourceLocation;
public class TestLootTablesProvider extends CommonLootTablesProvider {
... | package info.u_team.u_team_test.data.provider;
import java.util.function.BiConsumer;
import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootTable;
public class TestLootTablesProvider extends CommonLootTable... |
Remove JS to not load hidden divs | // $(function () {
// $("img").not(":visible").each(function () {
// $(this).data("src", this.src);
// this.src = "";
// });
// var reveal = function (selector) {
// var img = $(selector);
// img[0].src = img.data("src");
// }
// });
$("#post_link6").click(function(... | $(function () {
$("img").not(":visible").each(function () {
$(this).data("src", this.src);
this.src = "";
});
var reveal = function (selector) {
var img = $(selector);
img[0].src = img.data("src");
}
});
$("#post_link6").click(function() {
event.preventDefault();
... |
Fix for bad merge decision | """
@author: JD Chodera
@author: JH Prinz
"""
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
from openpathsampling.engines import features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temper... | """
@author: JD Chodera
@author: JH Prinz
"""
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
import openpathsampling.engines.features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temperature... |
RESCOI-876: Check for characters in file path | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
Lic... | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
Lic... |
Define fallback case just once | <?php
namespace Concrete\Core\Support\Facade;
class Image extends Facade
{
public static function getFacadeAccessor()
{
if (class_exists('Imagick')) {
$imagick = new \Imagick();
$v = $imagick->getVersion();
list($version, $year, $month, $day, $q, $website) = sscanf... | <?php
namespace Concrete\Core\Support\Facade;
class Image extends Facade
{
public static function getFacadeAccessor()
{
if (class_exists('Imagick')) {
$imagick = new \Imagick();
$v = $imagick->getVersion();
list($version, $year, $month, $day, $q, $website) = sscanf... |
Check if array index has content | <?php
/**
* GitScrum v0.1.
*
* @author Renato Marinho <renato.marinho@s2move.com>
* @license http://opensource.org/licenses/GPL-3.0 GPLv3
*/
namespace GitScrum\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use GitScrum\Models\Sprint;
class IssueRequest extends FormRequest
{
/**
* Determine... | <?php
/**
* GitScrum v0.1.
*
* @author Renato Marinho <renato.marinho@s2move.com>
* @license http://opensource.org/licenses/GPL-3.0 GPLv3
*/
namespace GitScrum\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use GitScrum\Models\Sprint;
class IssueRequest extends FormRequest
{
/**
* Determine... |
Fix fos user mailer generated route to be absolute | <?php
namespace Redking\ParseBundle\Bridge\FOSUser;
use FOS\UserBundle\Mailer\TwigSwiftMailer as BaseMailer;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class Mailer extends BaseMailer
{
/**
* {@inheritdoc}
*/
public function sendResettingE... | <?php
namespace Redking\ParseBundle\Bridge\FOSUser;
use FOS\UserBundle\Mailer\TwigSwiftMailer as BaseMailer;
use FOS\UserBundle\Model\UserInterface;
class Mailer extends BaseMailer
{
/**
* {@inheritdoc}
*/
public function sendResettingEmailMessage(UserInterface $user, $route = 'fos_user_resetting_... |
Use buffered channel for graceful shutdown
According to https://golang.org/pkg/os/signal/#example_Notify
buffered channel should be used to avoid missing signal. | package main
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/labstack/echo"
"github.com/labstack/gommon/log"
)
func main() {
// Setup
e := echo.New()
e.Logger.SetLevel(log.INFO)
e.GET("/", func(c echo.Context) error {
time.Sleep(5 * time.Second)
return c.JSON(http.StatusOK, "OK")
})... | package main
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/labstack/echo"
"github.com/labstack/gommon/log"
)
func main() {
// Setup
e := echo.New()
e.Logger.SetLevel(log.INFO)
e.GET("/", func(c echo.Context) error {
time.Sleep(5 * time.Second)
return c.JSON(http.StatusOK, "OK")
})... |
fix(test-config): Change browser-name case, add browser list | /**
* From where to look for files, starting with the location of this file.
*/
basePath = '../';
/**
* This is the list of file patterns to load into the browser during testing.
*/
files = [
JASMINE,
JASMINE_ADAPTER,
'vendor/angular/angular.js',
'vendor/angular/angular-mocks.js',
'src/**/*.js',
'dist... | /**
* From where to look for files, starting with the location of this file.
*/
basePath = '../';
/**
* This is the list of file patterns to load into the browser during testing.
*/
files = [
JASMINE,
JASMINE_ADAPTER,
'vendor/angular/angular.js',
'vendor/angular/angular-mocks.js',
'src/**/*.js',
'dist... |
Update location of python file and send messages. | var pyshell = require('python-shell');
module.exports = function(RED) {
function LowerCaseNode(config) {
RED.nodes.createNode(this,config);
var node = this;
this.on('input', function(msg) {
msg.payload = msg.payload.toLowerCase();
node.send(msg);
})... | var pyshell = require('python-shell');
module.exports = function(RED) {
function LowerCaseNode(config) {
RED.nodes.createNode(this,config);
var node = this;
this.on('input', function(msg) {
msg.payload = msg.payload.toLowerCase();
node.send(msg);
})... |
Fix defaulting to events page, maybe.... | ---
layout: null
---
$(document).ready(function () {
$('a.events-button').click(function (e) {
if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
currentWidth = $('.panel-cover').width()
if (currentWidth < 960) {
$('.panel-cover').addClass('panel-cover--collapsed')
$('.content-wr... | ---
layout: null
---
$(document).ready(function () {
$('a.events-button').click(function (e) {
if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
currentWidth = $('.panel-cover').width()
if (currentWidth < 960) {
$('.panel-cover').addClass('panel-cover--collapsed')
$('.content-wr... |
Fix django model field docstring. | """
************************
Django model integration
************************
**Static Model** provides custom Django model fields in the
``staticmodel.django.models`` package:
* ``StaticModelCharField`` (sub-class of ``django.db.models.CharField``)
* ``StaticModelTextField`` (sub-class of ``django.db.models.TextF... | """
******************
Django integration
******************
**Static Model** provides two custom Django model fields in the
``staticmodel.django.fields`` module:
* ``StaticModelCharField`` (sub-class of ``django.db.models.CharField``)
* ``StaticModelIntegerField`` (sub-class of ``django.db.models.IntegerField``)
... |
Make `refresh` return self for chaining actions |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... |
Stop confirming ETA is 10 seconds ago, as it's possible that AutoFleetCharge
interrupt within that duration. | #!/usr/bin/env python
import logging
import time
import base
from kcaa import screens
logger = logging.getLogger('kcaa.manipulators.automission')
class CheckMissionResult(base.Manipulator):
def run(self):
logger.info('Checking mission result')
yield self.screen.check_mission_result()
class ... | #!/usr/bin/env python
import logging
import time
import base
from kcaa import screens
logger = logging.getLogger('kcaa.manipulators.automission')
class CheckMissionResult(base.Manipulator):
def run(self):
logger.info('Checking mission result')
yield self.screen.check_mission_result()
class ... |
Fix email case issues when restoring user pointers.
(imported from commit 84d3288dffc1cb010d8cd2a749fe71aa2a4d0df3) | from optparse import make_option
from django.core.management.base import BaseCommand
from zephyr.models import Realm, UserProfile
import simplejson
def dump():
pointers = []
for u in UserProfile.objects.select_related("user__email").all():
pointers.append((u.user.email, u.pointer))
file("dumped-poi... | from optparse import make_option
from django.core.management.base import BaseCommand
from zephyr.models import Realm, UserProfile
import simplejson
def dump():
pointers = []
for u in UserProfile.objects.select_related("user__email").all():
pointers.append((u.user.email, u.pointer))
file("dumped-poi... |
Check for globally installed binary | 'use strict';
var BinWrapper = require('bin-wrapper');
var path = require('path');
var pkg = require('../package.json');
/**
* Variables
*/
var BIN_VERSION = '0.7.5';
var BASE_URL = 'https://raw.github.com/imagemin/optipng-bin/v' + pkg.version + '/vendor/';
/**
* Initialize a new BinWrapper
*/
var bin = new Bi... | 'use strict';
var BinWrapper = require('bin-wrapper');
var path = require('path');
var pkg = require('../package.json');
/**
* Variables
*/
var BIN_VERSION = '0.7.5';
var BASE_URL = 'https://raw.github.com/imagemin/optipng-bin/v' + pkg.version + '/vendor/';
/**
* Initialize a new BinWrapper
*/
var bin = new Bi... |
Fix commented PaymentExpress card number | <?php
/*
* This file is part of the Omnipay package.
*
* (c) Adrian Macneil <adrian@adrianmacneil.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Omnipay\PaymentExpress\Message;
/**
* PaymentExpress PxPost Store ... | <?php
/*
* This file is part of the Omnipay package.
*
* (c) Adrian Macneil <adrian@adrianmacneil.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Omnipay\PaymentExpress\Message;
/**
* PaymentExpress PxPost Store ... |
Replace print statement with `warnings.warn`.
Also so that it doesn't need to be converted for Python3 compat. | #!/usr/bin/python
import optparse
import sys
import warnings
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
d... | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path,... |
Exclude test_runner from dist package | from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='baldr',
version='0.4.5',
url='https://github.com/timsavage/baldr',
license='LICENSE',
author='Tim Savage',
author_email='tim.savage@poweredby... | from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='baldr',
version='0.4.5',
url='https://github.com/timsavage/baldr',
license='LICENSE',
author='Tim Savage',
author_email='tim.savage@poweredby... |
Convert plugin to use Symfony events | <?php
namespace Grav\Plugin;
use Grav\Common\Plugin;
use Grav\Plugin\Taxonomylist;
class TaxonomylistPlugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents() {
return [
'onAfterTwigTemplatesPaths' => ['onAfterTwigTemplatesPaths', 0],
... | <?php
namespace Grav\Plugin;
use \Grav\Common\Plugin;
use \Grav\Common\Registry;
use \Grav\Plugin\Taxonomylist;
class TaxonomylistPlugin extends Plugin
{
/**
* Add current directory to twig lookup paths.
*/
public function onAfterTwigTemplatesPaths()
{
Registry::get('Twig')->twig_paths[]... |
Fix namespace of HTTP binding for jolie2wsdl. | package joliex.wsdl;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Francesco
*/
public enum NameSpacesEnum {
//TNS("tns","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.wsdl"),
//TNS_SCH("tnsxs","http://www.italianasoftware.com/w... | package joliex.wsdl;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Francesco
*/
public enum NameSpacesEnum {
//TNS("tns","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.wsdl"),
//TNS_SCH("tnsxs","http://www.italianasoftware.com/w... |
Make sort param request listener accept non-array configuration | <?php
namespace Alchemy\RestBundle\EventListener;
use Alchemy\RestBundle\Rest\Request\SortOptionsFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class SortParamRequestListener implements E... | <?php
namespace Alchemy\RestBundle\EventListener;
use Alchemy\RestBundle\Rest\Request\SortOptionsFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class SortParamRequestListener implements E... |
Fix logic for finding the user | const Verifier = require('feathers-authentication-local').Verifier;
const errors = require('feathers-errors');
module.exports = function createVerifier (options = {}, app) {
if (!options.userService) {
throw new Error('You must provide a `userService` in the options for the challenge-request strategy verifier');... | const Verifier = require('feathers-authentication-local').Verifier;
const errors = require('feathers-errors');
module.exports = function createVerifier (options = {}, app) {
if (!options.userService) {
throw new Error('You must provide a `userService` in the options for the challenge-request strategy verifier');... |
Include handlebars module in build process | define(["handlebars-compiler"], function (Handlebars) {
var buildMap = {},
templateExtension = ".hbs";
return {
// http://requirejs.org/docs/plugins.html#apiload
load: function (name, parentRequire, onload, config) {
// Get the template extension.
var ext = (config.hbs && config.hbs.tem... | define(["handlebars-compiler"], function (Handlebars) {
var buildMap = {},
templateExtension = ".hbs";
return {
// http://requirejs.org/docs/plugins.html#apiload
load: function (name, parentRequire, onload, config) {
// Get the template extension.
var ext = (config.hbs && config.hbs.tem... |
Use inputTrees for sass dir | var CachingWriter = require('broccoli-caching-writer');
var Compass = require('compass-compile');
CompassCompiler.prototype = Object.create(CachingWriter.prototype);
CompassCompiler.prototype.constructor = CompassCompiler;
function CompassCompiler(inputTrees, options) {
if (!(this instanceof CompassCompiler)) { ret... | var CachingWriter = require('broccoli-caching-writer');
var Compass = require('compass-compile');
CompassCompiler.prototype = Object.create(CachingWriter.prototype);
CompassCompiler.prototype.constructor = CompassCompiler;
function CompassCompiler(inputTrees, options) {
if (!(this instanceof CompassCompiler)) { ret... |
Remove the 'end' type from format() | var util = require('util');
var mochaFormatter = {
suite: "describe('%s', function () {",
test: "it('%s');",
end: '});'
};
function format(line, type) {
return util.format(mochaFormatter[type], line.trim());
}
function getIndentLength(line) {
return (line.match(/ {2}/g) || []).length;
}
module.exports ... | var util = require('util');
var mochaFormatter = {
suite: "describe('%s', function () {",
test: "it('%s');",
end: '});'
};
function format(line, type) {
if (type === 'end') {
return mochaFormatter.end;
} else {
return util.format(mochaFormatter[type], line.trim());
}
}
function getIndentLength... |
Fix name of font size map | /* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*******************************************************... | /* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*******************************************************... |
Add a test for the 'cf quota $QUOTA_NAME' command | package quotas_test
import(
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
. "github.com/onsi/gomega/gexec"
. "github.com/pivotal-cf-experimental/cf-test-helpers/cf"
)
var _ = Describe("CF Quota commands", func() {
It("can Create, Read, Update, and Delete quotas", func()... | package quotas_test
import(
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
. "github.com/onsi/gomega/gexec"
. "github.com/pivotal-cf-experimental/cf-test-helpers/cf"
)
var _ = Describe("CF Quota commands", func() {
It("can Create, Read, Update, and Delete quotas", func()... |
Put module.exports and function on same line | var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
module.exports = function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed.draft ? (ordinal(parsed.... | module.exports = reviewersEditionCompare
var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed... |
Use the enum constant as the default value | /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.frontend.find.configuration;
import org.springframework.context.annotation.Condition;
import org.springfra... | /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.frontend.find.configuration;
import org.springframework.context.annotation.Condition;
import org.springfra... |
MAke Eventer.removeListener work if no cbs bound for event, yet. | ;(function(exports) {
function Eventer() {
var callbacks = {};
this.addListener = function(obj, event, callback) {
callbacks[event] = callbacks[event] || [];
callbacks[event].push({
obj: obj,
callback: callback
});
return this;
};
this.addListener
this.on... | ;(function(exports) {
function Eventer() {
var callbacks = {};
this.addListener = function(obj, event, callback) {
callbacks[event] = callbacks[event] || [];
callbacks[event].push({
obj: obj,
callback: callback
});
return this;
};
this.addListener
this.on... |
Add a dependency on Scrapy | #!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='B... | #!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='B... |
Fix a bug where MappedBytes.writeUtf8 crashed the JVM if passed a null | package net.openhft.chronicle.bytes;
import org.junit.Test;
import java.io.File;
import java.io.RandomAccessFile;
import static org.junit.Assert.*;
public class MappedBytesTest {
@Test
public void shouldNotBeReadOnly() throws Exception {
MappedBytes bytes = MappedBytes.mappedBytes(File.createTempFi... | package net.openhft.chronicle.bytes;
import org.junit.Test;
import java.io.File;
import java.io.RandomAccessFile;
import static org.junit.Assert.*;
public class MappedBytesTest {
@Test
public void shouldNotBeReadOnly() throws Exception {
MappedBytes bytes = MappedBytes.mappedBytes(File.createTempFi... |
Set required in files related | <?php
class RelatedFileForm extends BaseForm
{
public function configure()
{
$this->widgetSchema['filenames'] = new sfWidgetFormInputFile();
$this->widgetSchema['filenames']->setLabel("Add File") ;
$this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file'));
$this->validato... | <?php
class RelatedFileForm extends BaseForm
{
public function configure()
{
$this->widgetSchema['filenames'] = new sfWidgetFormInputFile();
$this->widgetSchema['filenames']->setLabel("Add File") ;
$this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file'));
$this->validato... |
Remove self (not in class scope) | #!/usr/bin/env php
<?php
/*
* This file is part of the Certificationy CLI application.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__ . '/vendor/autoload... | #!/usr/bin/env php
<?php
/*
* This file is part of the Certificationy CLI application.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__ . '/vendor/autoload... |
Update expert card tests to use enzyme. | /* Copyright (C) 2018 Canonical Ltd. */
'use strict';
const React = require('react');
const enzyme = require('enzyme');
const ExpertCard = require('../expert-card/expert-card');
const EXPERTS = require('../expert-card/experts');
describe('ExpertCard', function() {
const renderComponent = (options = {}) => enzyme.... | /* Copyright (C) 2018 Canonical Ltd. */
'use strict';
const React = require('react');
const ExpertCard = require('../expert-card/expert-card');
const EXPERTS = require('../expert-card/experts');
const jsTestUtils = require('../../utils/component-test-utils');
describe('ExpertCard', function() {
function renderCom... |
Fix issue with default values — just implement in getters | const Sequelize = require('sequelize');
module.exports = {
JSONType: (fieldName, {defaultValue = {}} = {}) => ({
type: Sequelize.TEXT,
get: function get() {
const val = this.getDataValue(fieldName);
if (!val) { return defaultValue }
return JSON.parse(val);
},
set: function set(val) ... | const Sequelize = require('sequelize');
module.exports = {
JSONType: (fieldName, {defaultValue = '{}'} = {}) => ({
type: Sequelize.TEXT,
defaultValue,
get: function get() {
return JSON.parse(this.getDataValue(fieldName))
},
set: function set(val) {
this.setDataValue(fieldName, JSON.st... |
Fix pending test for PUT collection | var expect = require('expect.js');
var request = require('request');
var fixtures = require('./fixtures');
describe('PUT plural', function () {
it('should replace entire collection with given new collection... maybe'); /*, function (done) {
return done(); // TODO unimplemented
var poke = { name: 'Poke' };
... | var expect = require('expect.js');
var request = require('request');
var fixtures = require('./fixtures');
describe('PUT plural', function () {
before(fixtures.vegetable.init);
beforeEach(fixtures.vegetable.create);
after(fixtures.vegetable.deinit);
it('should replace entire collection with given new collect... |
Add protection for empty GitHub url. | 'use strict';
var GitHubApi = require('github');
var githubapi = new GitHubApi({
// required
version: "3.0.0",
// optional
timeout: 3000
});
exports.getPackageJson = function (user, repo, callback) {
if (!user) {
callback('GitHub user not valid.');
return;
}
if (!repo) {
callba... | 'use strict';
var GitHubApi = require('github');
var githubapi = new GitHubApi({
// required
version: "3.0.0",
// optional
timeout: 3000
});
exports.getPackageJson = function (user, repo, callback) {
if (!user) {
callback('GitHub user not valid.');
return;
}
if (!repo) {
callba... |
Allow for comments in the sql file that do not start the line. | import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **option... | import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **option... |
Fix date error in books model
Fix typos and the auto addition of date to the date_added field. | from django.db import models
from datetime import datetime
from django.utils import timezone
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
year = models.DateTimeField('year published',
help_text="Please use the following for... | from django.db import models
from datetime import date
from django.utils import timezone
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
year = models.DateTimeField('year published',
help_text="Please use the following format:... |
Update toJSON to return a string
Instead of returning the metadata object, it should return that object
encoded as a JSON string | 'use strict';
var R = require('ramda');
var isEmptyObj = R.pipe(R.keys, R.isEmpty);
function ModelRenderer(model) {
this.modelName = model.modelName;
this.attrs = model.attrs;
}
function attrToString(key, value) {
var output = '- ' + key;
if (R.has('primaryKey', value)) {
output += ' (primaryKey)';
}
... | 'use strict';
var R = require('ramda');
var isEmptyObj = R.pipe(R.keys, R.isEmpty);
function ModelRenderer(model) {
this.modelName = model.modelName;
this.attrs = model.attrs;
}
function attrToString(key, value) {
var output = '- ' + key;
if (R.has('primaryKey', value)) {
output += ' (primaryKey)';
}
... |
Drop use of namespaced oslo.i18n
Related-blueprint: drop-namespace-packages
Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0 | # Copyright 2014 Mirantis 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 ... | # Copyright 2014 Mirantis 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 ... |
Throw interrupted exceptions from stop().
Make the arquillian container use the SwarmExector/SwarmProcess bits. | /**
* Copyright 2015 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ... | /**
* Copyright 2015 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ... |
Generalize the printing of APA102 encoded buffers | // Copyright 2016 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// playing is a small app to play with the pins, nothing more. You are not
// expected to use it as-is.
package main
import (
"fmt"
"os"
"... | // Copyright 2016 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// playing is a small app to play with the pins, nothing more. You are not
// expected to use it as-is.
package main
import (
"fmt"
"os"
... |
Remove reference to web browsers in bazel documentation.
--
MOS_MIGRATED_REVID=115912069 | // Copyright 2014 The Bazel Authors. 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 appl... | // Copyright 2014 The Bazel Authors. 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 appl... |
Update replaceCount to handle multiple instances
The previous implementation assumed that the word being replaced was
only on a line once. This updates it to count the number of times the
old string was present. | package far
import (
"bufio"
"os"
"strings"
)
func FileExists(path string) bool {
_, err := os.Stat(path)
if err != nil {
return false
} else {
return true
}
}
func FindAndReplace(path, current, update string) (int, error) {
file, _ := os.Open(path)
defer file.Close()
var lines []string
scanner := b... | package far
import (
"bufio"
"os"
"strings"
)
func FileExists(path string) bool {
_, err := os.Stat(path)
if err != nil {
return false
} else {
return true
}
}
func FindAndReplace(path, current, update string) (int, error) {
file, _ := os.Open(path)
defer file.Close()
var lines []string
scanner := b... |
Add new validator that applies data_api_client.email_is_valid_for_admin_user to field | from flask.ext.wtf import Form
from wtforms import validators
from dmutils.forms import StripWhitespaceStringField
from .. import data_api_client
class AdminEmailAddressValidator(object):
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
if not data_... | from flask.ext.wtf import Form
from wtforms import validators
from dmutils.forms import StripWhitespaceStringField
class EmailAddressForm(Form):
email_address = StripWhitespaceStringField('Email address', validators=[
validators.DataRequired(message="Email can not be empty"),
validators.Email(mes... |
Fix Gulp config due to latest evolutions | /* === PLUGINS === */
const gulp = require('gulp'),
rimraf = require('gulp-rimraf'),
webpack = require('webpack-stream'),
sequence = require('run-sequence');
/* === CONFIG === */
const config = {
src: 'src/main/**/*',
target: 'dist/',
cfg: {
webpack: './webpack.config.js',
jshin... | /* === PLUGINS === */
const gulp = require('gulp'),
rimraf = require('gulp-rimraf'),
webpack = require('webpack-stream'),
sequence = require('run-sequence');
/* === CONFIG === */
const config = {
src: {
js: 'src/main/js/**/*',
},
target: 'dist/',
cfg: {
webpack: './webpack.c... |
Add Model in operation type | package model
import (
"fmt"
"github.com/jinzhu/gorm"
)
// Class is the metadata of the node
type Class struct {
gorm.Model
Name string //The name of NodeType
Base string //Base type name
Operations []Operation //Operation of type
}
// Operation is action of type
type Operation struct {
... | package model
import (
"fmt"
"github.com/jinzhu/gorm"
)
// Class is the metadata of the node
type Class struct {
gorm.Model
Name string //The name of NodeType
Base string //Base type name
Operations []Operation //Operation of type
}
// Operation is action of type
type Operation struct {
... |
Make sure port is an int | import socket
import os
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localho... | import socket
import os
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localho... |
Fix build break related to TUSCANY-1102
git-svn-id: d03bf258fa706134e13af30ae75b879a77d8986d@508535 13f79535-47bb-0310-9956-ffa450edef68 | package org.apache.tuscany.sdo.test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AllTests extends TestCase {
public static TestSuite suite() {
TestSuite suite = new TestSuite();
// suite.addTestSuite(ChangeSummaryOnDataObjectTestCase.class);
sui... | package org.apache.tuscany.sdo.test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AllTests extends TestCase {
public static TestSuite suite() {
TestSuite suite = new TestSuite();
// suite.addTestSuite(ChangeSummaryOnDataObjectTestCase.class);
sui... |
Add a test for mapPropsOnChange | import test from 'ava'
import React from 'react'
import { mapPropsOnChange, withState, flattenProp, compose } from '../'
import { mount } from 'enzyme'
import sinon from 'sinon'
test('mapPropsOnChange maps subset of owner props to child props', t => {
const mapSpy = sinon.spy()
const StringConcat = compose(
wi... | import test from 'ava'
import React from 'react'
import { mapPropsOnChange, withState, flattenProp, compose } from '../'
import { mount } from 'enzyme'
import sinon from 'sinon'
test('mapPropsOnChange maps subset of owner props to child props', t => {
const mapSpy = sinon.spy()
const StringConcat = compose(
wi... |
Add unit test to check if the environment returns a correct type | # coding=utf-8
'''
Test case for utils/__init__.py
'''
from __future__ import unicode_literals, print_function, absolute_import
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
try:
import pytest
except ImportError:
pyt... | # coding=utf-8
'''
Test case for utils/__init__.py
'''
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
try:
import pytest
except ImportError:
pytest = None
import salt.utils
@skipIf(pytest is None, 'PyTest is missing... |
Replace Entry's created's auto_now_add=True with default=datetime.now | from datetime import datetime
from django.db import models
from django.conf import settings
from tempel import utils
class Entry(models.Model):
content = models.TextField()
language = models.CharField(max_length=20,
choices=utils.get_languages())
created = models.DateTimeF... | from django.db import models
from django.conf import settings
from tempel import utils
class Entry(models.Model):
content = models.TextField()
language = models.CharField(max_length=20,
choices=utils.get_languages())
created = models.DateTimeField(auto_now_add=True)
act... |
Add comment about python2.7 specific code. | # coding: utf-8
from __future__ import absolute_import
from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
... | # coding: utf-8
from __future__ import absolute_import
from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
... |
Add create and remove file for setUp and tearDown | import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
global existing_bucket, test_dir, test_file
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
test_file = 'bucketeer_test_file'
def setUp(self):
# Create a bucket to test on existing bucket
... | import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
global existing_bucket, test_dir
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
def setUp(self):
# Create a bucket to test on existing bucket
connection = boto.connect_s3()
bucket = c... |
Make all changes to app/ run on all trybot platforms, not just the big three.
Anyone who's changing a header here may break the chromeos build.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/2838027
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@51000 4ff67af0-8c30-449e-8e8b-ad334ec8d88c | #!/usr/bin/python
# Copyright (c) 2009 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.
"""Makes sure that the app/ code is cpplint clean."""
INCLUDE_CPP_FILES_ONLY = (
r'.*\.cc$', r'.*\.h$'
)
EXCLUDE = (
# Autogener... | #!/usr/bin/python
# Copyright (c) 2009 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.
"""Makes sure that the app/ code is cpplint clean."""
INCLUDE_CPP_FILES_ONLY = (
r'.*\.cc$', r'.*\.h$'
)
EXCLUDE = (
# Autogener... |
Remove save call in build storage | import Dispatcher from '../dispatcher';
import Store from './store';
import {BUILDS_RECEIVE} from '../constants';
import {sortByAttributeComparator, Storage} from '../utils';
var storage = new Storage();
class BuildStore extends Store {
constructor() {
super();
this._loading = false;
this.key = 'builds'... | import Dispatcher from '../dispatcher';
import Store from './store';
import {BUILDS_RECEIVE} from '../constants';
import {sortByAttributeComparator, Storage} from '../utils';
var storage = new Storage();
class BuildStore extends Store {
constructor() {
super();
this._loading = false;
this.key = 'builds'... |
Split the start_date for better data entry (and Javascript date pickers). | import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
... | from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.in... |
Make PowerSet method more compact | // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package recursion
// PowerSet returns a power set of s.
// The length of s must be less then size of int.
// If the size is equal or bigger, then nil in... | // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package recursion
// PowerSet returns a power set of s.
// The length of s must be less then size of int.
// If the size is equal or bigger, then nil in... |
Remove old JS code in the normalization report
This fixes a JS `Uncaught TypeError` error in the normalization report
caused by code that was used to setup dialogs for displaying job
information but which were removed a few years ago. | /*
This file is part of Archivematica.
Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
Archivematica is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at ... | /*
This file is part of Archivematica.
Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
Archivematica is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at ... |
Support for actions in profile | import React, { Component } from 'react'
import { DrawerLabel } from '..'
import Avatar from 'material-ui/Avatar'
import RaisedButton from 'material-ui/RaisedButton'
import styles from './Profile.css'
const avatarStyles = {
width: 200,
height: 200,
marginLeft: 88,
marginTop: 32,
marginRight: 88,
marginB... | import React, { Component } from 'react'
import { DrawerLabel } from '..'
import Avatar from 'material-ui/Avatar'
import styles from './Profile.css'
const avatarStyles = {
width: 200,
height: 200,
marginLeft: 88,
marginTop: 32,
marginRight: 88,
marginBottom: 6
}
class Profile extends Component {
rende... |
Section: Set end_paragraph to True by default | # -*- coding: utf-8 -*-
"""
This module implements the class that deals with sections.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
from . import Container, Command
class SectionBase(Container):
"""A class that is the base for all section type classes."""
... | # -*- coding: utf-8 -*-
"""
This module implements the class that deals with sections.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
from . import Container, Command
class SectionBase(Container):
"""A class that is the base for all section type classes."""
... |
Update sim hooks for 2018 |
from hal_impl.sim_hooks import SimHooks
class PyFrcFakeHooks(SimHooks):
'''
Defines hal hooks that use the fake time object
'''
def __init__(self, fake_time):
self.fake_time = fake_time
super().__init__()
#
# Time related hooks
#
def getTime(self):
... | from hal_impl.data import hal_data
class PyFrcFakeHooks:
'''
Defines hal hooks that use the fake time object
'''
def __init__(self, fake_time):
self.fake_time = fake_time
#
# Hook functions
#
def getTime(self):
return self.fake_time.get()
def getFP... |
Deploy Travis CI build 377 to GitHub | #!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
import os
if os.path.exists('README.rst'):
README = open('README.rst').read()
else:
README = "" # a placeholder, readme is generated on release
CHANGES = open('CHANGES.md').read()
... | #!/usr/bin/env python
"""
Setup script for PythonTemplateDemo.
"""
import setuptools
from demo import __project__, __version__
import os
if os.path.exists('README.rst'):
README = open('README.rst').read()
else:
README = "" # a placeholder, readme is generated on release
CHANGES = open('CHANGES.md').read()
... |
Change MVC construct for User Fields. | <?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: user_forum-stat_include.php
| Author: Digitanium
+-------------------------... | <?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: user_forum-stat_include.php
| Author: Digitanium
+-------------------------... |
Fix problem with {property}-changed event
In polymer 2 the following change was made:
Property change notifications (property-changed events) aren't fired when
the value changes as a result of a binding from the host
(see https://polymer-library.polymer-project.org/2.0/docs/about_20).
The polymer team suggested to use... | /**
* @license
* 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 require... | /**
* @license
* 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 require... |
Add version and initialize AppHelper | define([
'jquery',
'underscore',
'backbone',
'router',
'helpers/app',
'helpers/conf',
'helpers/usertag',
'views/sidebar',
'views/user',
'views/search',
'text!templates/body.html',
'bootstrap'
], function ($, _, Backbone, Router, AppHelper, ConfHelper, UserTagHelper,
SidebarView, Use... | define([
'jquery',
'underscore',
'backbone',
'router',
'helpers/app',
'helpers/conf',
'helpers/usertag',
'views/sidebar',
'views/user',
'views/search',
'text!templates/body.html',
'bootstrap'
], function ($, _, Backbone, Router, AppHelper, ConfHelper, UserTagHelper,
SidebarView, Use... |
Comment out the Shove object, as we are not using it yet | """The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initializat... | """The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initializat... |
Add unique id for each wav file | import os
import logging
import gevent
from flask import Flask, render_template, url_for, redirect
from flask_sockets import Sockets
import io
import string
import random
app = Flask(__name__)
path = os.getcwd()
app.config['DEBUG'] = True
sockets = Sockets(app)
def rand_id(size=8):
return ''.join(random.SystemRan... | import os
import logging
import gevent
from flask import Flask, render_template, url_for, redirect
from flask_sockets import Sockets
import io
app = Flask(__name__)
path = os.getcwd()
app.config['DEBUG'] = True
sockets = Sockets(app)
@app.route('/', methods=['GET', 'POST'])
def main():
return redirect(url_for('st... |
Use PingFactory for more testable code | <?php
namespace Loct\Pinger\Provider;
use \Loct\Pinger\Command\PingCommand;
use \Loct\Pinger\PingFactory;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;
/**
* Service provider for command related classes and parameters.
*
* @author herloct <herloct@gmail.com>
*/
class CommandProvider implements Serv... | <?php
namespace Loct\Pinger\Provider;
use \Loct\Pinger\Command\PingCommand;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;
/**
* Service provider for command related classes and parameters.
*
* @author herloct <herloct@gmail.com>
*/
class CommandProvider implements ServiceProviderInterface
{
/*... |
Include radix in parseInt call
The default is not guaranteed to be 10. | (function () {
"use strict";
$(document).ready(function() {
if ($('select').is('#active_filter')){
var page_size = parseInt($('select').attr("value"), 10);
var table = $('table').dataTable(
{ "pageLength" : page_size,
"search": {
... | (function () {
"use strict";
$(document).ready(function() {
if ($('select').is('#active_filter')){
var page_size = parseInt($('select').attr("value"));
var table = $('table').dataTable(
{ "pageLength" : page_size,
"search": {
... |
Add example of logging setting for Manila
This change demonstrates how we can define logging setting specific to
manila-ui, so that operators can easily understand how to customize
logging level and so on.
Change-Id: Ia8505d988ed75e0358452b5b3c2889b364680f22 | # Copyright 2016 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | # Copyright 2016 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
Support event on root element |
// Events are in the Backbone form of
// {
// '[type] [selector]':'[function]'
// '[type]' :'[function]'
// }
// where selector may have a space, e.g. 'foo > bar'
function DOMViewMixin(view) {
var _this = this;
var events = view.events || {};
for (var key in events) {
if (events.hasOwnProperty(... |
// Events are in the Backbone form of
// {
// '[type] [selector]':'[function]'
// }
// where selector may have a space, e.g. 'foo > bar'
function DOMViewMixin(view) {
var _this = this;
var events = view.events || {};
for (var key in events) {
if (events.hasOwnProperty(key)) {
var firstSpaceIndex = ke... |
Remove unused import to fix flake8 | import os
import vcr
from django.test import TestCase
from django.core.management import call_command
from ...models import StopPoint, Service, Place
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures')
class ImportSingaporeTest(TestCase):
@classmethod
def setUpTestData(cls):
... | import os
import vcr
from django.test import TestCase, override_settings
from django.core.management import call_command
from ...models import StopPoint, Service, Place
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures')
class ImportSingaporeTest(TestCase):
@classmethod
def s... |
Fix wrong wording and spelling | export default {
today: 'I dag',
now: 'Nu',
backToToday: 'Gå til i dag',
ok: 'Ok',
clear: 'Annuller',
month: 'Måned',
year: 'År',
timeSelect: 'Vælg tidspunkt',
dateSelect: 'Vælg dato',
monthSelect: 'Vælg måned',
yearSelect: 'Vælg år',
decadeSelect: 'Vælg årti',
yearFormat: 'YYYY',
dateFormat... | export default {
today: 'I dag',
now: 'Nu',
backToToday: 'Tilbage til i dag',
ok: 'Ok',
clear: 'Annuler',
month: 'Måned',
year: 'År',
timeSelect: 'Vælg tidspunkt',
dateSelect: 'Vælg dato',
monthSelect: 'Vælg måned',
yearSelect: 'Vælg år',
decadeSelect: 'Vælg årti',
yearFormat: 'YYYY',
dateFo... |
Remove if branch to test django > 1.7 | import os
import sys
import dj_database_url
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
from django.test.runner import DiscoverRunner
BASEDIR = os.path.dirname(os.path.dirname(__file__))
settings.configure(
DATABASES={
'default': dj_database_u... | import os
import sys
import dj_database_url
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
from django.test.runner import DiscoverRunner
BASEDIR = os.path.dirname(os.path.dirname(__file__))
settings.configure(
DATABASES={
'default': dj_database_u... |
[CallResponder] Add calls to list of answered calls.
Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com> | package org.duckdns.raven.ttscallresponder.tts;
import org.duckdns.raven.ttscallresponder.domain.call.Call;
import org.duckdns.raven.ttscallresponder.domain.call.PersistentCallList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.Teleph... | package org.duckdns.raven.ttscallresponder.tts;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
public class StartAnsweringServiceReceiver extends BroadcastReceiver {
private static final Stri... |
Add slow down carousel speed | $(document).ready(function () {
$(".carousel-inner-download").cycle({
fx:'scrollVert',
pager: '.pager',
timeout: 4000,
speed: 1000,
// pause: 1,
});
$(".c1-right").on("click", function(e) {
var activeImage = $(".c1-image-shown");
var nextImage = activeImage.next();
if(nextImag... | $(document).ready(function () {
$(".carousel-inner-download").cycle({
fx:'scrollVert',
pager: '.pager',
timeout: 4000,
speed: 500,
// pause: 1,
});
$(".c1-right").on("click", function(e) {
var activeImage = $(".c1-image-shown");
var nextImage = activeImage.next();
if(nextImage... |
Stop PE server only if it was running | package protocolsupport;
import java.util.logging.Level;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import protocolsupport.injector.BungeeNettyChannelInjector;
import protocolsupport.injector.pe.PEProxyServer;
import protocolsupport.utils.Utils;
public class ProtocolSupport ext... | package protocolsupport;
import java.util.logging.Level;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import protocolsupport.injector.BungeeNettyChannelInjector;
import protocolsupport.injector.pe.PEProxyServer;
import protocolsupport.utils.Utils;
public class ProtocolSupport ext... |
Update for React changes in API. | /**
*/
var React = require('react');
var ReactDOM = require('react-dom');
exports.ResultModal = React.createClass({
/**
* Invoked immediately after updating occurs. This method is not called for the initial render.
*/
componentDidUpdate: function (prevProps, prevState) {
// Show only if truthy.
if (this.... | /**
* @jsx React.DOM
*/
var React = require('react');
exports.ResultModal = React.createClass({
/**
* Invoked immediately after updating occurs. This method is not called for the initial render.
*/
componentDidUpdate: function (prevProps, prevState) {
// Show only if truthy.
if (this.props.dieString) {
... |
Add Tag List Panel Handle to Main Gui Handle | package guitests.guihandles;
import guitests.GuiRobot;
import javafx.stage.Stage;
import seedu.todo.TestApp;
/**
* Provides a handle for the main GUI.
*/
public class MainGuiHandle extends GuiHandle {
public MainGuiHandle(GuiRobot guiRobot, Stage primaryStage) {
super(guiRobot, primaryStage, TestApp.AP... | package guitests.guihandles;
import guitests.GuiRobot;
import javafx.stage.Stage;
import seedu.todo.TestApp;
/**
* Provides a handle for the main GUI.
*/
public class MainGuiHandle extends GuiHandle {
public MainGuiHandle(GuiRobot guiRobot, Stage primaryStage) {
super(guiRobot, primaryStage, TestApp.AP... |
Fix possible memory leak in feed.
I've observed a memory leak (on API 17) apparently stemming from the new
functionality to fill in the bookmark icon when the featured article is
detected to be part of a reading list.
This seems to be caused by us passing an anonymous instance of a
CallbackTask.Callback object from F... | package org.wikipedia.concurrency;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class CallbackTask<T> extends SaneAsyncTask<T> {
public interface Callback<T> {
void success(T row);
}
public interface Task<T> {
T execute();
}
@NonNu... | package org.wikipedia.concurrency;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class CallbackTask<T> extends SaneAsyncTask<T> {
public interface Callback<T> {
void success(T row);
}
public interface Task<T> {
T execute();
}
@NonNu... |
Add test for metadata appearing on fastbootInfo | var expect = require('chai').expect;
var path = require('path');
var alchemistRequire = require('broccoli-module-alchemist/require');
var FastBootInfo = alchemistRequire('fastboot-info.js');
var FastBootResponse = alchemistRequire('fastboot-response.js');
var FastBootRequest = alchemistRequire('fastboot-request.js');
... | var expect = require('chai').expect;
var path = require('path');
var alchemistRequire = require('broccoli-module-alchemist/require');
var FastBootInfo = alchemistRequire('fastboot-info.js');
var FastBootResponse = alchemistRequire('fastboot-response.js');
var FastBootRequest = alchemistRequire('fastboot-request.js');
... |
Use info growl for game rating growl.
It fits better with the component. | angular.module( 'App.Game.RatingGrowl' ).service( 'Game_RatingGrowl', function( App, Api, Growls )
{
this.show = function( game )
{
// Don't show when not logged in.
if ( !App.user ) {
return;
}
// Don't show if ratings are disabled for the game.
if ( !game.ratings_enabled ) {
return;
}
// Don't... | angular.module( 'App.Game.RatingGrowl' ).service( 'Game_RatingGrowl', function( App, Api, Growls )
{
this.show = function( game )
{
// Don't show when not logged in.
if ( !App.user ) {
return;
}
// Don't show if ratings are disabled for the game.
if ( !game.ratings_enabled ) {
return;
}
// Don't... |
Send exception message with 500 error response | <?php
// load Tonic
require_once '../src/Tonic/Autoloader.php';
$config = array(
'load' => array('../*.php', '../src/Tyrell/*.php'), // load example resources
#'mount' => array('Tyrell' => '/nexus'), // mount in example resources at URL /nexus
#'cache' => new Tonic\MetadataCacheFile('/tmp/tonic.cache') //... | <?php
// load Tonic
require_once '../src/Tonic/Autoloader.php';
$config = array(
'load' => array('../*.php', '../src/Tyrell/*.php'), // load example resources
#'mount' => array('Tyrell' => '/nexus'), // mount in example resources at URL /nexus
#'cache' => new Tonic\MetadataCacheFile('/tmp/tonic.cache') //... |
Add missing `>` to top comment
:smile: | /**
* amputee.js
*
* Copyright © 2015 | Johnie Hjelm <johnie@hjelm.im>
*/
// Get all amputee elements
const amputee = document.getElementsByTagName('amputee');
/**
* Ajax function
*
* @return {string}
* @throws Will throw an error if the file does not exist.
*/
const httpGet = url => {
var xhr = new XMLHtt... | /**
* amputee.js
*
* Copyright © 2015 | Johnie Hjelm <johnie@hjelm.im
*/
// Get all amputee elements
const amputee = document.getElementsByTagName('amputee');
/**
* Ajax function
*
* @return {string}
* @throws Will throw an error if the file does not exist.
*/
const httpGet = url => {
var xhr = new XMLHttp... |
Fix migration to modify multiple documents | Migrations.add({
version: 1,
name: "Extract items to a separate collection from the nested field",
up: function () {
Flights.find({items: {$exists: true}}).forEach(function (flight) {
flight.items.forEach(function (item) {
var itemId = Items.insert(_.extend(item, {createdAt: new Date(), flightId... | Migrations.add({
version: 1,
name: "Extract items to a separate collection from the nested field",
up: function () {
Flights.find({items: {$exists: true}}).forEach(function (flight) {
flight.items.forEach(function (item) {
var itemId = Items.insert(_.extend(item, {createdAt: new Date(), flightId... |
Fix of library declaration used in documentation generation | /**
* @license
* Copyright 2019 The FOAM Authors. 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 ... | /**
* @license
* Copyright 2019 The FOAM Authors. 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 ... |
Make browserAction link to /messages | let username = ""
const init = () => {
console.log("Starting...");
chrome.alarms.create("checkmessages", {
periodInMinutes: 1
})
console.log("Alarm created!");
chrome.storage.sync.get(["username"], (v) => { username = v["username"] });
console.log("Username fetched!");
}
init()
chrome.alarms.onAla... | let username = ""
const init = () => {
console.log("Starting...");
chrome.alarms.create("checkmessages", {
periodInMinutes: 1
})
console.log("Alarm created!");
chrome.storage.sync.get(["username"], (v) => { username = v["username"] });
console.log("Username fetched!");
}
init()
chrome.alarms.onAla... |
Update dsub version to 0.3.7
PiperOrigin-RevId: 292945859 | # Copyright 2017 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 a... | # Copyright 2017 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 a... |
Load configuration from a custom location | <?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Mike van Riel <mike.vanriel@naenius.com>
* @copyright 2010-2018 Mike van Riel / Naenius (http://w... | <?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Mike van Riel <mike.vanriel@naenius.com>
* @copyright 2010-2018 Mike van Riel / Naenius (http://w... |
Fix regex matching coverage output
The coverage library now returns the file extensions. | import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 ... | import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 ... |
Update the PyPI version to 7.0.10. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team... | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.9',
packages=['todoist', 'todoist.managers'],
author='Doist Team'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.