text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Make sure we actually run JSCS..... @jwilsson | module.exports = function( grunt ) {
'use strict';
var srcFiles = [
'bot.js',
'*.botplug.js',
'Gruntfile.js'
];
grunt.initConfig({
pkg: grunt.file.readJSON( 'package.json' ),
jshint: {
all: srcFiles,
options: {
jshintrc: '... | module.exports = function( grunt ) {
'use strict';
var srcFiles = [
'bot.js',
'*.botplug.js',
'Gruntfile.js'
];
grunt.initConfig({
pkg: grunt.file.readJSON( 'package.json' ),
jshint: {
all: srcFiles,
options: {
jshintrc: '... |
Switch to headless chrome from chrome | const webpack = require('./webpack.config')
process.env.CHROME_BIN = require('puppeteer').executablePath()
module.exports = config => {
config.set({
frameworks: ['mocha', 'chai'],
files: ['test/components/index.js', 'test/components/*.js'],
preprocessors: {
'test/components/*.js': ['webpack']
}... | const webpack = require('./webpack.config')
module.exports = config => {
config.set({
frameworks: ['mocha', 'chai'],
files: [
{ pattern: 'test/components/*.js', watched: false }
],
preprocessors: {
'test/components/*.js': ['webpack']
},
webpack,
webpackMiddleware: {
stat... |
Allow version parsing code to use non-annotated tags | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_d... | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_d... |
Fix element(data) always returns 0 | /*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import 'semantic-ui-css/components/api';
import $ from 'jquery';
$.fn.extend({
taxonMoveUp() {
const e... | /*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import 'semantic-ui-css/components/api';
import $ from 'jquery';
$.fn.extend({
taxonMoveUp() {
const e... |
Fix missing class on friends listing page | {{--
Copyright 2015-2017 ppy Pty. Ltd.
This file is part of osu!web. osu!web is distributed with the hope of
attracting more community contributions to the core ecosystem of osu!.
osu!web is free software: you can redistribute it and/or modify
it under the terms of the Affero GNU General Public Li... | {{--
Copyright 2015-2017 ppy Pty. Ltd.
This file is part of osu!web. osu!web is distributed with the hope of
attracting more community contributions to the core ecosystem of osu!.
osu!web is free software: you can redistribute it and/or modify
it under the terms of the Affero GNU General Public Li... |
Enable cubemap texture lod in Plask | var glu = require('pex-glu');
var color = require('pex-color');
var sys = require('pex-sys');
var Context = glu.Context;
var Material = glu.Material;
var Program = glu.Program;
var Color = color.Color;
var merge = require('merge');
var fs = require('fs');
var Platform = sys.Platform;
var TexturedCubeMapGLSL = fs.readF... | var glu = require('pex-glu');
var color = require('pex-color');
var sys = require('pex-sys');
var Context = glu.Context;
var Material = glu.Material;
var Program = glu.Program;
var Color = color.Color;
var merge = require('merge');
var fs = require('fs');
var Platform = sys.Platform;
var TexturedCubeMapGLSL = fs.readF... |
[Java] Add comment for pre-order iteration. | package collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;
import binarytrees.TreeNode;
/**
* An iterator that iterates through a binary tree in pre-order.
*/
public class PreorderIterator<T> implements Iterator<T> {
private T nextItem;
private final Stack<Tr... | package collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;
import binarytrees.TreeNode;
public class PreorderIterator<T> implements Iterator<T> {
private T nextItem;
private final Stack<TreeNode<T>> stack;
public PreorderIterator(TreeNode<T> rootNode) {
thi... |
Reduce amount of calculations in broadphase. | /*globals define*/
define([
'physics/intersection'
], function( Intersection ) {
'use strict';
// Filter all physics entities that may be colliding.
function broadphase( entities ) {
var potentials = [];
var aabbs = entities.map(function( entity ) {
return entity.aabb();
});
var length ... | /*globals define*/
define([
'physics/intersection'
], function( Intersection ) {
'use strict';
// Filter all physics entities that may be colliding.
function broadphase( entities ) {
var potentials = [];
var aabb0,
aabb1;
entities.forEach(function( a ) {
aabb0 = a.aabb();
ent... |
Set a mode instead of prining it | package se.soy.gpg;
import java.util.List;
import java.util.ArrayList;
public class GPG {
// FIXME Remove when done
static<T> void println(T arg) { System.out.println(arg); }
public static void main(String[] args) {
println("main");
GPG.encrypt().armor().recipient("0xrecipient").output();
/*
GP... | package se.soy.gpg;
import java.util.List;
import java.util.ArrayList;
public class GPG {
// FIXME Remove when done
static<T> void println(T arg) { System.out.println(arg); }
public static void main(String[] args) {
println("main");
GPG.encrypt().armor().recipient("0xrecipient").output();
/*
GP... |
Set production as default environment | <?php
namespace MyTravel\Core\Config;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
final class ApplicationConfiguration implements ConfigurationInterface {
public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder();... | <?php
namespace MyTravel\Core\Config;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
final class ApplicationConfiguration implements ConfigurationInterface {
public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder();... |
Update test specs according to code modification | define(function(require) {
var test = require('../../test')
var assert = test.assert
//assert(seajs.log('seajs.log test', 'group') === undefined, 'group')
assert(seajs.log('a') === undefined, 'log')
assert(seajs.log('a ' + 1) === undefined, 'log')
assert(seajs.log('a', 'warn') === undefined, 'warn')
... | define(function(require) {
var test = require('../../test')
var assert = test.assert
assert(seajs.log('seajs.log test', 'group') === undefined, 'group')
assert(seajs.log('a') === undefined, 'log')
assert(seajs.log('a ' + 1) === undefined, 'log')
assert(seajs.log('a', 'warn') === undefined, 'warn')
as... |
Change name to texture name | package info.u_team.u_team_core.item.armor;
import net.minecraft.entity.Entity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.*;
public class UArmorItem extends ArmorItem {
protected final String textureName;
public UArmorItem(String textureName, Properties properties, IArmorMateri... | package info.u_team.u_team_core.item.armor;
import net.minecraft.entity.Entity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.*;
public class UArmorItem extends ArmorItem {
protected final String name;
public UArmorItem(String name, Properties properties, IArmorMaterial material, E... |
Update message passing method visibility | package io.elssa.net;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class MessageRouterBase {
private List<MessageListener> listeners
= Collections.synchronizedList(new ArrayList<>());
/**
* Adds a message listener (consumer) to this MessageRou... | package io.elssa.net;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class MessageRouterBase {
private List<MessageListener> listeners
= Collections.synchronizedList(new ArrayList<>());
/**
* Adds a message listener (consumer) to this MessageRou... |
Allow subsystems to not map a sqlachemy entity | import flask
from infosystem.common.subsystem.controller import *
from infosystem.common.subsystem.driver import *
from infosystem.common.subsystem.manager import *
from infosystem.common.subsystem.router import *
class Subsystem(flask.Blueprint):
def __init__(self, resource=None, router=None, controller=None, ... | import flask
from infosystem.common.subsystem.controller import *
from infosystem.common.subsystem.driver import *
from infosystem.common.subsystem.manager import *
from infosystem.common.subsystem.router import *
class Subsystem(flask.Blueprint):
def __init__(self, resource, router=None, controller=None, manag... |
Set auth token on page reloads | (function (angular) {
"use strict";
angular.module("mflAdminAppConfig", [
"sil.common.logging",
"sil.api.wrapper",
"sil.grid",
"mfl.auth.oauth2"
])
.constant("SERVER_URL", window.MFL_SETTINGS.SERVER_URL)
.constant("CREDZ", window.MFL_SETTINGS.CREDZ)
.config(["... | (function (angular) {
"use strict";
angular.module("mflAdminAppConfig", [
"sil.common.logging",
"sil.api.wrapper",
"sil.grid"
])
.constant("SERVER_URL", window.MFL_SETTINGS.SERVER_URL)
.constant("CREDZ", window.MFL_SETTINGS.CREDZ)
.config(["loggingConfigProvider", fun... |
Use Linkr-unique session cookie name | # flake8: noqa: E501
import config.options
# Flask-SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format(
database_user=config.options.DATABASE_USER,
database_password=config.options.DATABASE_PASSWORD,
database_host=config.options.DATABA... | # flake8: noqa: E501
import config.options
# Flask-SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'mysql://{database_user}:{database_password}@{database_host}/{database_name}'.format(
database_user=config.options.DATABASE_USER,
database_password=config.options.DATABASE_PASSWORD,
database_host=config.options.DATABA... |
qa: Remove race between connecting and shutdown on separate connections | #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framewo... | #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framewo... |
openid: Fix notice about unititialized variable. | <?php
/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}
$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$s... | <?php
/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}
$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$s... |
Fix retrieving model values for empty strings | <?php namespace Laraplus\Form\DataStores;
trait RetrievesModelValues
{
/**
* @var ArrayAccess|array
*/
protected $model = null;
/**
* @param ArrayAccess|array $model
*/
public function bind($model)
{
$this->model = $model;
}
/**
* @param string $name
... | <?php namespace Laraplus\Form\DataStores;
trait RetrievesModelValues
{
/**
* @var ArrayAccess|array
*/
protected $model = null;
/**
* @param ArrayAccess|array $model
*/
public function bind($model)
{
$this->model = $model;
}
/**
* @param string $name
... |
Add classifier indicating only Python2.7 support | import uuid
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
from setuptools import setup, find_packages
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm",
version="1.00.0"... | import uuid
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
from setuptools import setup, find_packages
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm",
version="1.00.0"... |
Use a list comprehension and set() to make the active_users query simpler and faster. | from datetime import timedelta, datetime
from django.db import models
from django.contrib.auth.models import User
class RequestManager(models.Manager):
def active_users(self, **options):
"""
Returns a list of active users.
Any arguments passed to this method will be
given t... | from datetime import timedelta, datetime
from django.db import models
from django.contrib.auth.models import User
class RequestManager(models.Manager):
def active_users(self, **options):
"""
Returns a list of active users.
Any arguments passed to this method will be
given t... |
Allow configuration to override app name | var express = require('express');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
function appCtor(cfg, pool) {
var app = express();
// app-wide default page title
app.locals.title =... | var express = require('express');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
function appCtor(cfg, pool) {
var app = express();
// app-wide default page title
app.locals.title =... |
Add skos_registry to the request.
Add the skos_registry to the request through the add_request_method
directive. | # -*- coding: utf8 -*-
from zope.interface import Interface
from skosprovider.registry import Registry
class ISkosRegistry(Interface):
pass
def _build_skos_registry(registry):
skos_registry = registry.queryUtility(ISkosRegistry)
if skos_registry is not None:
return skos_registry
skos_regi... | # -*- coding: utf8 -*-
from zope.interface import Interface
from skosprovider.registry import Registry
class ISkosRegistry(Interface):
pass
def _build_skos_registry(registry):
skos_registry = registry.queryUtility(ISkosRegistry)
if skos_registry is not None:
return skos_registry
skos_regi... |
Rename proc object config key from proc_entry to simply object. | import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
... | import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
... |
Add passive supervizer module support | /**
* Otagai.js
* Based on https://github.com/olafurnielsen/form5-node-express-mongoose-coffeescript
*/
var express = require('express'),
http = require('http'),
fs = require('fs'),
passport = require('passport'),
mongoose = require('mongoose'),
coffee = require('coffee-script')
var env = proce... | /**
* Otagai.js
* Based on https://github.com/olafurnielsen/form5-node-express-mongoose-coffeescript
*/
var express = require('express'),
http = require('http'),
fs = require('fs'),
passport = require('passport'),
mongoose = require('mongoose'),
coffee = require('coffee-script')
var env = proce... |
Add ability to specify defaults through hash | $.fn.filterByData = function(prop, val) {
return this.filter(
function() { return $(this).data(prop)==val; }
);
};
$(document).ready(function() {
var radios = $('.table-view.radio');
var saveBtn = $('#save');
var options = {};
var hash = window.location.hash.substring(1);
if (hash) {
try {
... | $(document).ready(function() {
var radios = $('.table-view.radio');
var saveBtn = $('#save');
radios.each(function (index) {
var radio = $(this);
var buttons = radio.find('li.table-view-cell > a');
buttons.click(function() {
buttons.removeClass('active');
$(this).addClass('active');
... |
Send pageview on app load and THEN listen | import React, { Component } from 'react';
import { Route, Router } from 'react-router';
import ReactGA from 'react-ga';
import createHistory from 'history/createBrowserHistory';
import ScrollToTop from 'shared/components/scrollToTop/scrollToTop';
import Home from './scenes/home/home';
const history = createHistory();
... | import React, { Component } from 'react';
import { Route, Router } from 'react-router';
import ReactGA from 'react-ga';
import createHistory from 'history/createBrowserHistory';
import ScrollToTop from 'shared/components/scrollToTop/scrollToTop';
import Home from './scenes/home/home';
const history = createHistory();
... |
Fix Ajax user form fields with pre-set values
`values[i].objectId` is only set for users added manually via the UI. For pre-existing usernames, only `values[i].value` exists. | /**
* Data handler for a user form builder field in an Ajax form.
*
* @author Matthias Schmidt
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/Form/Builder/Field/User
* @since 5.2
*/
define(['Core', '... | /**
* Data handler for a user form builder field in an Ajax form.
*
* @author Matthias Schmidt
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/Form/Builder/Field/User
* @since 5.2
*/
define(['Core', '... |
Change ready button to be a gradient to stand out | import { Button } from './Widgets';
export default class Ready extends React.Component {
ready(r) {
ws.send({cmd: r ? 'ready' : 'not_ready'});
}
render() {
const r = this.ready;
const btn =
!this.props.ready ?
<Button onClick={r.bind(this, true)}
... | import { Button } from './Widgets';
export default class Ready extends React.Component {
ready(r) {
ws.send({cmd: r ? 'ready' : 'not_ready'});
}
render() {
const r = this.ready;
const btn =
!this.props.ready ?
<Button bg="green" onClick={r.bind(this, true)}>
... |
Set default workers to 10 | #!/usr/bin/env node
var prerender = require('./lib');
process.env.PORT = process.env.PORT || 4000
var server = prerender({
workers: process.env.PHANTOM_CLUSTER_NUM_WORKERS || 10,
iterations: process.env.PHANTOM_WORKER_ITERATIONS || 10,
phantomBasePort: process.env.PHANTOM_CLUSTER_BASE_PORT || 12300,
me... | #!/usr/bin/env node
var prerender = require('./lib');
process.env.PORT = process.env.PORT || 4000
var server = prerender({
workers: process.env.PHANTOM_CLUSTER_NUM_WORKERS,
iterations: process.env.PHANTOM_WORKER_ITERATIONS || 10,
phantomBasePort: process.env.PHANTOM_CLUSTER_BASE_PORT || 12300,
messageT... |
Change naming for method receiver | package testclient
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/parnurzeal/gorequest"
)
// TODO consider drop *testing.T parameter
func New(t *testing.T, handler http.Handler) *gorequest.SuperAgent {
mockTransport := mockTransport{
handler: handler,
}
// Don't replace httpClien... | package testclient
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/parnurzeal/gorequest"
)
// TODO consider drop *testing.T parameter
func New(t *testing.T, handler http.Handler) *gorequest.SuperAgent {
mockTransport := mockTransport{
handler: handler,
}
// Don't replace httpClien... |
Change permission to correct codename of change_subject | from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.views.generic import ListView, UpdateView
from admin.subjects.forms import SubjectForm
from osf.models.subject import Subject
from osf.models.preprint_provider import PreprintProvider
class Su... | from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.views.generic import ListView, UpdateView
from admin.subjects.forms import SubjectForm
from osf.models.subject import Subject
from osf.models.preprint_provider import PreprintProvider
class Su... |
Remove non-standard homebrew install path | const { delimiter } = require("path");
const Color = require("color");
const which = require("which");
const shell = getShell();
module.exports.onWindow = (browserWindow) =>
browserWindow.setVibrancy("ultra-dark");
module.exports.decorateConfig = (config) =>
Object.assign({}, config, {
backgroundColor: Color... | const { delimiter } = require("path");
const Color = require("color");
const which = require("which");
const shell = getShell();
module.exports.onWindow = (browserWindow) =>
browserWindow.setVibrancy("ultra-dark");
module.exports.decorateConfig = (config) =>
Object.assign({}, config, {
backgroundColor: Color... |
OEE-620: Create REST API resource to get dictionary/enum items. Fix CS | <?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\ORM\QueryBuilder;
interface DictionaryValueListProviderInterface
{
/**
* Checks whether the provider supports a given entity
*
* @param string $className The FQCN of an entity
*
* @return bool TRUE if this provider supports t... | <?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\ORM\QueryBuilder;
interface DictionaryValueListProviderInterface
{
/**
* Checks whether the provider supports a given entity
*
* @param string $className The FQCN of an entity
*
* @return bool TRUE if this provider supports t... |
Fix missing MR widget status icons
Fix https://gitlab.com/gitlab-org/gitlab-ce/issues/40283
Regressed in
https://gitlab.com/gitlab-org/gitlab-ce/commit/d01d509bd8612f9879fa762de8ea3763bcff81cf | import ciIcon from '../../vue_shared/components/ci_icon.vue';
import loadingIcon from '../../vue_shared/components/loading_icon.vue';
export default {
props: {
status: { type: String, required: true },
showDisabledButton: { type: Boolean, required: false },
},
components: {
ciIcon,
loadingIcon,
... | import ciIcon from '../../vue_shared/components/ci_icon.vue';
import loadingIcon from '../../vue_shared/components/loading_icon.vue';
export default {
props: {
status: { type: String, required: true },
showDisabledButton: { type: Boolean, required: false },
},
components: {
ciIcon,
loadingIcon,
... |
Add in the init the newly introduced function | # expose the most frequently used functions in the top level.
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
... | # expose the most frequently used functions in the top level.
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
... |
Update download servlet to pull from cloud storage. | package com.google.sps.servlets;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import javax.servlet.ServletEx... | package com.google.sps.servlets;
import com.google.sps.workspace.Workspace;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServ... |
Fix for whitespace.py so that Windows will save Unix EOLs. | """Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(fi... | """Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(fi... |
Add test case for binary search tree program | // Program that creates a binary search tree: each node has up to two children, and all left descendants of a node is less than or equal to the node and all right descendants are greater than the node
// create node class
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
// create const... | // Program that creates a binary search tree: each node has up to two children, and all left descendants of a node is less than or equal to the node and all right descendants are greater than the node
// create node class
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
// create const... |
Fix issue with Windows paths | package org.rabix.executor.pathmapper.local;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Map;
import org.rabix.bindings.mapper.FileMappingException;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.executor.config.StorageConfiguration;
import com.goo... | package org.rabix.executor.pathmapper.local;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.rabix.bindings.mapper.FileMappingException;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.executor.config.StorageConfiguration;
import com.google.inject.Inject;
public c... |
Remove `objects' group as useless | from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.it... | from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.it... |
Use `let` instead of `var` for aliases | 'use strict';
// Dependencies
const cssnext = require('cssnext')
const path = require('path')
// Aliases
let basedir = __dirname
module.exports = {
paths: {
destination: path.join(basedir, 'dist'),
source: path.join(basedir, 'src'),
templates: path.join(basedir, 'templates')
},
processors: {
d... | 'use strict';
// Dependencies
const cssnext = require('cssnext')
const path = require('path')
// Aliases
var basedir = __dirname
module.exports = {
paths: {
destination: path.join(basedir, 'dist'),
source: path.join(basedir, 'src'),
templates: path.join(basedir, 'templates')
},
processors: {
d... |
refactor(components): Rename prop name => iconName | import React from 'react'
import PropTypes from 'prop-types'
import {SimpleMenu, MenuAnchor, Icon} from '..'
class IconMenu extends React.PureComponent {
static displayName = 'IconMenu'
static propTypes = {
children: PropTypes.node,
iconName: PropTypes.string,
open: PropTypes.bool,
}
static defau... | import React from 'react'
import PropTypes from 'prop-types'
import {SimpleMenu, MenuAnchor, Icon} from '..'
class IconMenu extends React.PureComponent {
static displayName = 'IconMenu'
static propTypes = {
children: PropTypes.node,
name: PropTypes.string,
open: PropTypes.bool,
}
static defaultPr... |
fix(travis): Use a cleaner way of excluding release tags | /* @flow */
import type { Template } from 'create-npm/lib/template'
export default function({
encryptedNpmToken,
encryptedGitHubToken
}: {
encryptedNpmToken: string,
encryptedGitHubToken: string
}): Template {
return {
path: '.travis.yml',
content: `
dist: xenial
language: node_js
n... | /* @flow */
import type { Template } from 'create-npm/lib/template'
export default function({
encryptedNpmToken,
encryptedGitHubToken
}: {
encryptedNpmToken: string,
encryptedGitHubToken: string
}): Template {
return {
path: '.travis.yml',
content: `
dist: xenial
language: node_js
n... |
Once: Remove assert on event.name (handled somewhere else) | 'use strict';
/**
* Once middleware will block an event if there is already a scheduled event
* @param {Event} event the event to check
* @param {DBWrkr} wrkr wrkr instance to work with
* @param {function} done callback
*/
function once(event, wrkr, done) {
const findSpec = {
name: event.name
};
if (e... | const assert = require('assert');
'use strict';
/**
* Once middleware will block an event if there is already a scheduled event
* @param {Event} event the event to check
* @param {DBWrkr} wrkr wrkr instance to work with
* @param {function} done callback
*/
function once(event, wrkr, done) {
assert(typeof event... |
Update access token for Instagram feed | const Instafeed = require('instafeed.js');
const $ = require('jquery');
var feed = new Instafeed({
get: 'user',
userId: '3120245646',
clientId: ' 5d325f2ba927465d9c3933be01ee870c',
accessToken: '3120245646.1677ed0.442f6331662045c0a14c9802e799ccf6',
resolution: 'standard_resolution',
template: '<div class="... | const Instafeed = require('instafeed.js');
const $ = require('jquery');
var feed = new Instafeed({
get: 'user',
userId: '3120245646',
clientId: '5d325f2ba927465d9c3933be01ee870c',
accessToken: '3120245646.5d325f2.0d425d18ec6e4e459683a3493c01c9cd',
resolution: 'standard_resolution',
template: '<div class="i... |
Add ability to exclude trunks by passing % before it
For example, ./run_nose -v %FilmTitles %BookTitles | import functools
import sys
import nose
from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk
__author__ = 'moskupols'
_multiprocess_shared_ = True
_all_trunks = set(trunks_registered())
_trunk_filter = _all_trunks
def trunk_parametrized(trunks=set(trunks_registered()))... | import functools
import sys
import nose
from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk
__author__ = 'moskupols'
_multiprocess_shared_ = True
_all_trunks = set(trunks_registered())
_trunk_filter = _all_trunks
def trunk_parametrized(trunks=set(trunks_registered()))... |
Add missing file to commit - Refactor app structure | import { combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form'
import { routerReducer } from 'react-router-redux'
import organization from '../app/home/Home/modules/organization'
import starredBoard from '../app/home/Home/modules/starredBoard'
import notification from '../app/home/Home/mod... | import { combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form'
import { routerReducer } from 'react-router-redux'
import organization from '../pages/home/Home/modules/organization'
import starredBoard from '../pages/home/Home/modules/starredBoard'
import notification from '../pages/home/Ho... |
Add install_requires and remove ctypes from requirements. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The Screen class lets you to do positioned writes to the dos terminal.
The Screen class also allows you to specify the colors for foreground and
background, to the extent the dos terminal allows.
"""
classifiers = """\
Development Status :: 3 - Alpha
Environment :: Win... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The Screen class lets you to do positioned writes to the dos terminal.
The Screen class also allows you to specify the colors for foreground and
background, to the extent the dos terminal allows.
"""
classifiers = """\
Development Status :: 3 - Alpha
Environment :: Win... |
Add 'string_types' as found in six. | """
Compatibility support for Python 2.7. Remove when Python 2.7 support is
no longer required.
"""
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
input = raw_input
except NameError:
input = input
try:
text_type = unicode
except NameError:
text_type = str... | """
Compatibility support for Python 2.7. Remove when Python 2.7 support is
no longer required.
"""
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
input = raw_input
except NameError:
input = input
try:
text_type = unicode
except NameError:
text_type = str... |
Include width and height in brand image | /* Tooling
/* ========================================================================== */
import { $assign as $, $dispatch, $replaceAll } from 'esri-global-shared';
/* Brand
/* ========================================================================== */
const prefix = 'esri-header-brand';
export default () => {
... | /* Tooling
/* ========================================================================== */
import { $assign as $, $dispatch, $replaceAll } from 'esri-global-shared';
/* Brand
/* ========================================================================== */
const prefix = 'esri-header-brand';
export default () => {
... |
Fix returned promise upon errors
Fixes #5. | 'use strict';
const execa = require('execa');
const getos = require('getos');
const pify = require('pify');
module.exports = () => {
if (process.platform !== 'linux') {
return Promise.reject(new Error('Only Linux systems are supported'));
}
return execa('lsb_release', ['-a', '--short']).then(res => {
const std... | 'use strict';
const execa = require('execa');
const getos = require('getos');
const pify = require('pify');
module.exports = () => {
if (process.platform !== 'linux') {
return Promise.reject(new Error('Only Linux systems are supported'));
}
return execa('lsb_release', ['-a', '--short']).then(res => {
const std... |
Add a skip_publish flag to the deploy task. | """Django project fabfile."""
import os
from fabric.api import puts, task
from fabric.utils import indent
from deploy import deploy_to_heroku, prepare_to_deploy, tag_project
from publish import update_staticfiles, upload_staticfiles
from settings import PROJECT_ENVIRONMENT, PROJECT_ROOT, SITE_NAME, STATIC_ROOT
@tas... | """Django project fabfile."""
import os
from fabric.api import puts, task
from fabric.utils import indent
from deploy import deploy_to_heroku, prepare_to_deploy, tag_project
from publish import update_staticfiles, upload_staticfiles
from settings import PROJECT_ENVIRONMENT, PROJECT_ROOT, SITE_NAME, STATIC_ROOT
@tas... |
Rename remaining 'shortName' refs to 'versionDisplayName' | package org.springframework.site.domain.projects;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class ProjectVersionTests {
@Test
public void getDisplayNameForCurrentVersion() {
ProjectRelease version = new ProjectRelease("1.2.3.R... | package org.springframework.site.domain.projects;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class ProjectVersionTests {
@Test
public void getShortNameForCurrentVersion() {
ProjectRelease version = new ProjectRelease("1.2.3.REL... |
Adjust blog test to use the base class | from test_base import MyHomeTest
from .models import BlogPost
class BlogTestCase(MyHomeTest):
def setUp(self):
BlogPost.objects.create(
datetime='2014-01-01T12:00:00Z',
title='livetitle',
content='livecontent',
live=True)
BlogPost.objects.create(
... | from django.test import SimpleTestCase, Client
from .models import BlogPost
class BlogTestCase(SimpleTestCase):
def setUp(self):
BlogPost.objects.create(
datetime='2014-01-01 12:00:00',
title='title',
content='content',
live=True)
def _test_get(self, url... |
Add null to return type for getRecentMedia | <?php
namespace Frontend\Modules\Instagram\Ajax;
use Frontend\Core\Engine\Base\AjaxAction as FrontendBaseAJAXAction;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Instagram\Engine\Model as FrontendInstagramModel;
use Symfony\Component\HttpFoundation\Response;
/**
* Fetches the recent user me... | <?php
namespace Frontend\Modules\Instagram\Ajax;
use Frontend\Core\Engine\Base\AjaxAction as FrontendBaseAJAXAction;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Instagram\Engine\Model as FrontendInstagramModel;
use Symfony\Component\HttpFoundation\Response;
/**
* Fetches the recent user me... |
Add more NTC unit tests | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np
class TestNTC(ob... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np
class TestNTC(ob... |
Return only tasks without start time for surprise | package jfdi.logic.commands;
import jfdi.logic.events.NoSurpriseEvent;
import jfdi.logic.events.SurpriseEvent;
import jfdi.logic.interfaces.Command;
import jfdi.storage.apis.TaskAttributes;
import jfdi.storage.apis.TaskDb;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.stream.Collecto... | package jfdi.logic.commands;
import jfdi.logic.events.NoSurpriseEvent;
import jfdi.logic.events.SurpriseEvent;
import jfdi.logic.interfaces.Command;
import jfdi.storage.apis.TaskAttributes;
import jfdi.storage.apis.TaskDb;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.stream.Collecto... |
Split data processing / checks to separate module | var NO_DATA = 'no data';
module.exports = {
prepareModuleForRender: function (dashboardConfig, module) {
var data = {
departmentCode: dashboardConfig.department.abbr.toLowerCase(),
dashboardSlug: dashboardConfig.slug,
dashboardTitle: dashboardConfig.title,
moduleType: module['module-type... | var NO_DATA = 'no data';
module.exports = {
prepareModuleForRender: function (dashboardConfig, module) {
var data = {
departmentCode: dashboardConfig.department.abbr.toLowerCase(),
dashboardSlug: dashboardConfig.slug,
dashboardTitle: dashboardConfig.title,
moduleType: module['module-type... |
Backport: Fix special keys opening menu when key is unbound
(backport of daec4de7bf091f84a789c90d3956f5aa91486203 to affected branches) | package squeek.speedometer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import org.lwjgl.input.Keyboard;
import squeek.speedometer.gui.screen.ScreenSpeedometerSettings;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.eventhandler.SubscribeEvent... | package squeek.speedometer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import org.lwjgl.input.Keyboard;
import squeek.speedometer.gui.screen.ScreenSpeedometerSettings;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.eventhandler.SubscribeEvent... |
Add explanation about default log level. | """Configuration file for harness.py
Author: Ian Huston
"""
import logging
# Directory structure
# Change the names of various directories
#Change to using the base run directory with bin, pyflation, scripts immediately below.
CODEDIRNAME = "."
RUNDIRNAME = "runs"
RESULTSDIRNAME = "results"
LOGDIRNAME = "applogs"
QS... | """Configuration file for harness.py
Author: Ian Huston
"""
import logging
# Directory structure
# Change the names of various directories
#Change to using the base run directory with bin, pyflation, scripts immediately below.
CODEDIRNAME = "."
RUNDIRNAME = "runs"
RESULTSDIRNAME = "results"
LOGDIRNAME = "applogs"
QS... |
Use fixed alpha for low pass filter
Previous calculation was wrong. t is the low pass' filter
time constant (!) and dT is the event delivery rate in nano
seconds.
Chose to use a constant for now (and to ignore delta time). | package de.markusfisch.android.shadereditor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
public class AccelerometerListener
implements SensorEventListener
{
private ShaderRenderer renderer;
private long last = 0;
public AccelerometerListener( ... | package de.markusfisch.android.shadereditor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
public class AccelerometerListener
implements SensorEventListener
{
private ShaderRenderer renderer;
private long last = 0;
public AccelerometerListener( ... |
Add link to Font Fabric website | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react/addons';
import styles from './Footer.less';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
export default class Footer {
render() {
var currentYear = new Date().getFullYear();
retur... | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react/addons';
import styles from './Footer.less';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
export default class Footer {
render() {
var currentYear = new Date().getFullYear();
retur... |
Set properties of AdminApi after ajax response | Discourse.AdminApi = Discourse.Model.extend({
VALID_KEY_LENGTH: 64,
keyExists: function(){
var key = this.get('key') || '';
return key && key.length === this.VALID_KEY_LENGTH;
}.property('key'),
generateKey: function(){
var adminApi = this;
Discourse.ajax('/admin/api/generate_key', {type: 'POS... | Discourse.AdminApi = Discourse.Model.extend({
VALID_KEY_LENGTH: 64,
keyExists: function(){
var key = this.get('key') || '';
return key && key.length === this.VALID_KEY_LENGTH;
}.property('key'),
generateKey: function(){
var adminApi = this;
Discourse.ajax('/admin/api/generate_key', {type: 'POS... |
Fix missing create=True attribute in docker tests | from __future__ import absolute_import
from __future__ import unicode_literals
import mock
from pre_commit.languages import docker
from pre_commit.util import CalledProcessError
def test_docker_is_running_process_error():
with mock.patch(
'pre_commit.languages.docker.cmd_output',
side_effect=Cal... | from __future__ import absolute_import
from __future__ import unicode_literals
import mock
from pre_commit.languages import docker
from pre_commit.util import CalledProcessError
def test_docker_is_running_process_error():
with mock.patch(
'pre_commit.languages.docker.cmd_output',
side_effect=Cal... |
Align with changes in OverviewTable. | /*jslint browser: true, single: true, maxlen: 120, eval: true, white: true */
/*global define */
/*global set_based_abc_inline_js*/
//----------------------------------------------------------------------------------------------------------------------
define(
'SetBased/Abc/Core/Page/CorePage',
['jquery',
'Set... | /*jslint browser: true, single: true, maxlen: 120, eval: true, white: true */
/*global define */
/*global set_based_abc_inline_js*/
//----------------------------------------------------------------------------------------------------------------------
define(
'SetBased/Abc/Core/Page/CorePage',
['jquery',
'Set... |
Use DIRECTORY_SEPARATOR instead of '/' | <?php
namespace CarlBennett\MVC\Libraries;
use \CarlBennett\MVC\Libraries\Exceptions\TemplateNotFoundException;
use \CarlBennett\MVC\Libraries\Logger;
use \SplObjectStorage;
final class Template {
protected $context;
protected $template;
public function __construct(&$context, $template) {
$this->addition... | <?php
namespace CarlBennett\MVC\Libraries;
use \CarlBennett\MVC\Libraries\Exceptions\TemplateNotFoundException;
use \CarlBennett\MVC\Libraries\Logger;
use \SplObjectStorage;
final class Template {
protected $context;
protected $template;
public function __construct(&$context, $template) {
$this->addition... |
Add package transip.service or else this is not installed | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read... | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read... |
Read the conf file using absolute paths | # Yith Library Server is a password storage server.
# Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publ... | # Yith Library Server is a password storage server.
# Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publ... |
mscgen: Change package name to sphinxcontrib-mscgen | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='mscgen',
version='0.3'... |
Remove override on createJSModules. Required for RN 0.57.0 |
package ca.bigdata.voice.dtmf;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.fac... |
package ca.bigdata.voice.dtmf;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.fac... |
CC-5781: Upgrade script for new storage quota implementation
Include propel library | <?php
require_once 'propel/runtime/lib/Propel.php';
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusic... | <?php
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByDbTyp... |
Replace shaded import with non-shaded one | package uk.ac.ebi.atlas.commons.writers.impl;
import au.com.bytecode.opencsv.CSVWriter;
import com.google.common.base.Throwables;
import uk.ac.ebi.atlas.commons.writers.TsvWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class TsvWriterImpl implements TsvWriter {
private ... | package uk.ac.ebi.atlas.commons.writers.impl;
import au.com.bytecode.opencsv.CSVWriter;
import autovalue.shaded.com.google.common.common.base.Throwables;
import uk.ac.ebi.atlas.commons.writers.TsvWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class TsvWriterImpl implements T... |
Use instanstanceof Array when checking for array | import { MicroState } from 'ember-microstates';
export default MicroState.extend({
initialValueFor([array]) {
if (array === undefined) {
return [];
} else if (array instanceof Array) {
return array;
} else {
return [ array ];
}
},
prototypeFor(value = []) {
let wrapped = v... | import { MicroState } from 'ember-microstates';
export default MicroState.extend({
initialValueFor([array]) {
if (array === undefined) {
return [];
} else if (array && array.length != null && array.forEach) {
return array;
} else {
return [ array ];
}
},
prototypeFor(value = [... |
Make legend a bit better |
requirejs.config({
paths: {
'jquery': './lib/components/jquery/dist/jquery.min'
}
});
require( [ 'src/graph' ] , function( Graph ) {
var functions = [
function( domGraph ) {
var graph = new Graph( domGraph );
graph.newSerie("serieTest")
.setLabel( "My serie" )
.autoAxis()
.setData( [ [1, 2], [2, 5],... |
requirejs.config({
paths: {
'jquery': './lib/components/jquery/dist/jquery.min'
}
});
require( [ 'src/graph' ] , function( Graph ) {
var functions = [
function( domGraph ) {
var graph = new Graph( domGraph );
graph.newSerie("serieTest")
.setLabel( "My serie" )
.autoAxis()
.setData( [ [1, 2], [2, 5],... |
Fix the request.POST, usage of formset and redirect at the end | from django.contrib.auth.decorators import permission_required
from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404, redirect
from .forms import ReportForm, CopyFormSet
from .models import Report
@permission_required('reports.add_report', login_url='members:login')
def a... | from django.contrib.auth.decorators import permission_required
from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404
from .forms import ReportForm, CopyFormSet
from .models import Report
@permission_required('reports.add_report', login_url='members:login')
def add_report(... |
Implement the methods for the asserts | /**
* Created with IntelliJ IDEA.
* User: jhasmanyquiroz
* Date: 11/10/15
* Time: 11:00 AM
* To change this template use File | Settings | File Templates.
*/
package steps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import ui.PageTransporter;
import ui.... | /**
* Created with IntelliJ IDEA.
* User: jhasmanyquiroz
* Date: 11/10/15
* Time: 11:00 AM
* To change this template use File | Settings | File Templates.
*/
package steps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import ui.PageTransporter;
public cl... |
Add a function for easily getting the top level domain of a URL | var Class = require('./Class')
var URL = Class(function() {
this._extractionRegex = new RegExp([
'^', // start at the beginning of the string
'((\\w+:)?//)?', // match a possible protocol, like http://, ftp://, or // for a relative url
'(\\w[\\w\\.]+)?', // match a possible domain
'(\\/[^\\?#]+)?', ... | var Class = require('./Class')
var URL = Class(function() {
this._extractionRegex = new RegExp([
'^', // start at the beginning of the string
'((\\w+:)?//)?', // match a possible protocol, like http://, ftp://, or // for a relative url
'(\\w[\\w\\.]+)?', // match a possible domain
'(\\/[^\\?#]+)?', ... |
Add mesh points to plot | """
===============================
Piecewise Affine Transformation
===============================
This example shows how to use the Piecewise Affine Transformation.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import PiecewiseAffineTransform, warp
from skimage import data
image = ... | """
===============================
Piecewise Affine Transformation
===============================
This example shows how to use the Piecewise Affine Transformation.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import PiecewiseAffineTransform, warp
from skimage import data
image = ... |
Fix lib import for linux platforms | const { copyFileSync, existsSync } = require('fs')
const { join } = require('path')
const IS_LINUX = !['win32', 'darwin'].includes(process.platform)
if (!IS_LINUX) {
const baseDir = ({
'darwin': '/usr/local/lib',
'win32': 'C:\\Windows\\system32'
}[process.platform])
const libFilename = ({
'darwin':... | const { copyFileSync, existsSync } = require('fs')
const { join } = require('path')
const IS_LINUX = !['win32', 'darwin'].includes(process.platform)
const baseDir = ({
'darwin': '/usr/local/lib',
'win32': 'C:\\Windows\\system32'
}[process.platform])
const libFilename = ({
'darwin': 'libmpv.1.dylib',
'win32':... |
Use relative url for logfile
fixes #263 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... |
Fix prematurely firing reviewLinker directive | "use strict";
angular.module('arethusa.review').directive('reviewLinker', [
'review',
'translator',
function(review, translator) {
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs) {
scope.review = review;
scope.translations = {};
translator('... | "use strict";
angular.module('arethusa.review').directive('reviewLinker', [
'review',
'translator',
function(review, translator) {
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs) {
scope.review = review;
scope.translations = {};
translator('... |
Remove unused Closure compiler configuration
Files are compiled using Uglifier, which has its own config. | ({
appDir: "./app",
baseUrl: "scripts",
mainConfigFile: "./app/scripts/main.js",
dir: "./build",
pragmasOnSave: {
excludeTpl: true
},
excludeShallow: [
'css-builder',
'less-builder',
'lessc-server'
],
findNestedDependencies: true,
optimize: "uglify",
f... | ({
appDir: "./app",
baseUrl: "scripts",
mainConfigFile: "./app/scripts/main.js",
dir: "./build",
pragmasOnSave: {
excludeTpl: true
},
excludeShallow: [
'css-builder',
'less-builder',
'lessc-server'
],
findNestedDependencies: true,
optimize: "uglify",
c... |
Allow submits from LostPasswordForm through | <?php
/**
* Description of MemberLoginFilter
*
* @author marcus
*/
class MemberLoginFilter implements RequestFilter
{
public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
{
}
/**
* Check if we're in a login request. If so, we're going to ex... | <?php
/**
* Description of MemberLoginFilter
*
* @author marcus
*/
class MemberLoginFilter implements RequestFilter
{
public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
{
}
/**
* Check if we're in a login request. If so, we're going to ex... |
Make flag parsing example a bit more idiomatic | // Copyright (c) 2010 AFP Authors
// This source code is released under the terms of the
// MIT license. Please see the file LICENSE for license details.
//This is not a legal Go program, rather it provides a skeletal
//filter to serve as a minimal base for developing filters.
package <packagename>
import (
"afp"
... | // Copyright (c) 2010 AFP Authors
// This source code is released under the terms of the
// MIT license. Please see the file LICENSE for license details.
//This is not a legal Go program, rather it provides a skeletal
//filter to serve as a minimal base for developing filters.
package <packagename>
import (
"afp"
... |
Add test for attribute instance assertion | import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_name_should_not_be_instance(self):
with self.assertRaises(AssertionError):
Attribute(name='instance')
... | import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
... |
Designer: Add missing index command in revision | """Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def up... | """Add backside_template column
Revision ID: 3ca338ed5192
Revises: 35d76c40ca48
Create Date: 2017-05-17 11:33:30.295538
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '3ca338ed5192'
down_revision = '35d76c40ca48'
branch_labels = None
depends_on = None
def up... |
Resolve spacing inconsistency (no space before function parameters) | ;(function(global, factory) {
// Use UMD pattern to expose exported functions
if (typeof exports === 'object') {
// Expose to Node.js
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// Expose to RequireJS
define([], factory);
}
// Expose to global object (... | ;(function(global, factory) {
// Use UMD pattern to expose exported functions
if (typeof exports === 'object') {
// Expose to Node.js
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// Expose to RequireJS
define([], factory);
}
// Expose to global object (... |
Allow value to be set externally.
Currently the medium editor's value is only set on init. That makes
it impossible to reset a form on submit, for example. This commit
adds an observer that ensures the value is updated if the editor's
value differs from the component's value. | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'div',
attributeBindings: ['contenteditable'],
editable: true,
isUserTyping: false,
plaintext: false,
classNames: ['editable'],
contenteditable: (function() {
var editable = this.get('editable');
return editable ? 'true' : ... | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'div',
attributeBindings: ['contenteditable'],
editable: true,
isUserTyping: false,
plaintext: false,
classNames: ['editable'],
contenteditable: (function() {
var editable = this.get('editable');
return editable ? 'true' : ... |
Remove scrollLink attr from scholarship linkButton | import React, { Component } from 'react';
import LinkButton from 'shared/components/linkButton/linkButton';
import PropTypes from 'prop-types';
import styles from './preview.css';
class Preview extends Component {
render() {
const { scholarship } = this.props;
return (
<div className={styles.preview}>
... | import React, { Component } from 'react';
import LinkButton from 'shared/components/linkButton/linkButton';
import PropTypes from 'prop-types';
import styles from './preview.css';
class Preview extends Component {
render() {
const { scholarship } = this.props;
return (
<div className={styles.preview}>
... |
Use public key as id. | import json
import socket
from crypto import retrieve_key
from orderbook import create_confirm
def send_msg(ip, port, message):
'''Sends a raw string to the given ip and port. Closes the socket and returns the response.'''
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
... | import json
import socket
from orderbook import create_confirm
def send_msg(ip, port, message):
'''Sends a raw string to the given ip and port. Closes the socket and returns the response.'''
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
sock.sendall(m... |
Check if you are using python 3.3+ | # -*- coding: utf-8 -*-
"""
A text interface to Taiga.
"""
from __future__ import print_function
import sys
if sys.version_info[0] < 3 or sys.version_info[1] < 3:
print("Sorry, taiga-ncurses needs python >= 3.3", file=sys.stderr)
sys.exit(-1)
from taiga_ncurses import __name__, __description__, __version__
... | # -*- coding: utf-8 -*-
"""
A text interface to Taiga.
"""
from taiga_ncurses import __name__, __description__, __version__
from setuptools import setup, find_packages
REQUIREMENTS = [
"requests==2.5.0",
"urwid>=1.3.0",
"x256==0.0.3"
]
NAME = __name__
DESCRIPTION = __description__
VERSION = "{0}.{1}".... |
Add a feed_storage and feed_cache to our Globals object. | """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... |
Fix branches being mixed in Tree structure | package net.acomputerdog.core.tree;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Branch<T> {
private final Branch<T> parent;
private final List<Branch<T>> branches = new LinkedList<Branch<T>>();
private final List<Leaf<T>> leaves = new LinkedList<Leaf<T>>(... | package net.acomputerdog.core.tree;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Branch<T> {
private final Branch<T> parent;
private final Set<Branch<T>> branches = new HashSet<Branch<T>>();
private final Set<Leaf<T>> leaves = new HashSet<Leaf<T>>();
priva... |
Add values to new field one at a time to avoid adding an ArrayList object. | package org.myrobotlab.document.transformer;
import org.myrobotlab.document.transformer.StageConfiguration;
import java.util.List;
import org.myrobotlab.document.Document;
/**
* This stage will rename the field on a document.
* @author kwatters
*
*/
public class RenameField extends AbstractStage {
private Str... | package org.myrobotlab.document.transformer;
import org.myrobotlab.document.transformer.StageConfiguration;
import java.util.List;
import org.myrobotlab.document.Document;
/**
* This stage will rename the field on a document.
* @author kwatters
*
*/
public class RenameField extends AbstractStage {
private Str... |
Fix an actual schema validation error in one of the tests | import pytest
import python_jsonschema_objects as pjo
@pytest.fixture
def test_class():
schema = {
'title': 'Example',
'properties': {
"claimed_by": {
"id": "claimed",
"type": ["string", "integer", "null"],
"description": "Robots Only. ... | import pytest
import python_jsonschema_objects as pjo
@pytest.fixture
def test_class():
schema = {
'title': 'Example',
'properties': {
"claimed_by": {
"id": "claimed",
"type": ["string", "integer", "null"],
"description": "Robots Only. ... |
Fix default object and validation | 'use strict';
var assert = require('assert')
var dataServiceFactory = require('./dataService')
function createDataServices(config) {
var dataServices = {}
config.forEach((dsConfig) => {
dataServices[dsConfig.name] = dataServiceFactory(dsConfig)
})
return dataServices
}
/**
* DataService controller.
... | 'use strict';
var assert = require('assert')
var dataServiceFactory = require('./dataService')
function createDataServices(config) {
var dataServices = {}
config.forEach((dsConfig) => {
dataServices[dsConfig.name] = dataServiceFactory(dsConfig)
})
return dataServices
}
/**
* DataService controller.
... |
Comment addition and interface change from Vector to AbstractList | import java.util.AbstractList;
/**
*
*/
/**
* An interface for password store objects.
*
* @author Miltiadis Allamanis
*
*/
public interface IPasswordStore {
/**
* Return a list of all the stored passwords.
*
* @return a vector containing the ids of stored passwords
*/
public AbstractList<String>... | import java.util.Vector;
/**
*
*/
/**
* An interface for password store objects.
*
* @author Miltiadis Allamanis
*
*/
public interface IPasswordStore {
/**
* Return a list of all the stored passwords.
*
* @return a vector containing the ids of stored passwords
*/
public Vector<String> getAllStore... |
Use dot notation to calm jshint. | define(function(require, exports, module) {
"use strict";
var Backbone = require("backbone");
var candidatesTemplate = require("text!templates/candidates.html");
var CandidatesView = Backbone.View.extend({
tpl: _.template(candidatesTemplate),
render: function() {
this.$el.html(this.tpl({pairs: this._pair... | define(function(require, exports, module) {
"use strict";
var Backbone = require("backbone");
var candidatesTemplate = require("text!templates/candidates.html");
var CandidatesView = Backbone.View.extend({
tpl: _.template(candidatesTemplate),
render: function() {
this.$el.html(this.tpl({pairs: this._pair... |
Add tests to the package | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup, Extension
from sysctl import get_version
modules = [
Extension(
'sysctl/_sysctl',
sources=['sysctl/_sysctl.c'],
extra_compile_args=["-Wall"],
)
]
setup(
name='sysctl',
version=get... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup, Extension
from sysctl import get_version
modules = [
Extension(
'sysctl/_sysctl',
sources=['sysctl/_sysctl.c'],
extra_compile_args=["-Wall"],
)
]
setup(
name='sysctl',
version=get... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.