text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update relative path for favicon | module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `content`,
path: `${__dirname}/../content`,
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
icon: `src/images/kitura.svg`
},
},
{
resolve: `... | module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `content`,
path: `${__dirname}/../content`,
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
icon: `${__dirname}/src/images/kitura.svg`
},
},
{
... |
Change view for login url. Add url for index page | """restaurant URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | """restaurant URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... |
Change to invalid keys policy. | "use strict"
var NCMBInstallationEx = module.exports = (function() {
var invalidKeys = [
'objectId'
, 'createDate'
, 'updateDate'
];
function NCMBInstallationEx(ncmb) {
this.__proto__.ncmb = ncmb;
this.__proto__.className = '/installations';
}
NCMBInstallationEx.prototype.register = functio... | "use strict"
var NCMBInstallationEx = module.exports = (function() {
var validKeys = [
'applicationName'
, 'appVersion'
, 'badge'
, 'channels'
, 'deviceToken'
, 'deviceType'
, 'sdkVersion'
, 'timeZone'
, 'acl'
];
function NCMBInstallationEx(ncmb) {
this.__proto__.ncmb = ncmb;
this.__proto__.cl... |
Fix failure handler alway throw exception | package com.admicro.vertxlet.core.handler.impl;
import com.admicro.vertxlet.core.handler.FailureHandler;
import com.admicro.vertxlet.core.HttpServerVerticle;
import com.admicro.vertxlet.core.db.IDbConnector;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Routin... | package com.admicro.vertxlet.core.handler.impl;
import com.admicro.vertxlet.core.handler.FailureHandler;
import com.admicro.vertxlet.core.HttpServerVerticle;
import com.admicro.vertxlet.core.db.IDbConnector;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Routin... |
Refactor timezone implementation to fix read/write date attributes | <?php
declare(strict_types=1);
namespace Rinvex\Support\Traits;
use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
trait HasTimezones
{
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
*
* @return \Illuminate\Support\Carbon
*/
... | <?php
declare(strict_types=1);
namespace Rinvex\Support\Traits;
use DateTimeZone;
use Illuminate\Support\Arr;
trait HasTimezones
{
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
* @return \Illuminate\Support\Carbon
*/
protected function asDateTime($value)
... |
Make verbose loading messages optional | import new
import sys
DEBUG = False
method_count = 0
def method(argcount, nlocals, stacksize, flags, codestring, constants, names,
varnames, filename, name, firstlineno, lnotab, modules, static):
global method_count
if DEBUG:
print 'define', name, method_count
method_count += 1
g... | import sys
method_count = 0
def method(argcount, nlocals, stacksize, flags, codestring, constants, names,
varnames, filename, name, firstlineno, lnotab, modules, static):
global method_count
print 'define', name, method_count
method_count += 1
globals_dict = {}
for module_name in modu... |
Store local url in a variable and display it once for both text and image. | L.controlCredits = function(t) {
return new L.CreditsControl(t)
}, L.CreditsControl = L.Control.extend({
options: {
position: "bottomright"
},
initialize: function(t) {
if (!t.text) throw "L.CreditsControl missing required option: text";
if (!t.image) throw "L.CreditsControl miss... | L.controlCredits = function(t) {
return new L.CreditsControl(t)
}, L.CreditsControl = L.Control.extend({
options: {
position: "bottomright"
},
initialize: function(t) {
if (!t.text) throw "L.CreditsControl missing required option: text";
if (!t.image) throw "L.CreditsControl miss... |
Remove Email module - missed tests | <?php namespace CodeIgniter\Config;
use Config\Format;
class ConfigTest extends \CIUnitTestCase
{
public function testCreateSingleInstance()
{
$Config = Config::get('Format', false);
$NamespaceConfig = Config::get('Config\\Format', false);
$this->assertInstanceOf(Format::class, $Config);
$this->a... | <?php namespace CodeIgniter\Config;
use Config\Email;
class ConfigTest extends \CIUnitTestCase
{
public function testCreateSingleInstance()
{
$Config = Config::get('Format', false);
$NamespaceConfig = Config::get('Config\\Format', false);
$this->assertInstanceOf(Format::class, $Config);
$this->as... |
Update URLs to be Vantiv | <?php
class Litle_LEcheck_Model_URL
{
public function toOptionArray()
{
return array(
array(
'value' => "https://www.testvantivcnp.com/sandbox/communicator/online",
'label' => 'Sandbox'
),
array(
'value' => "https://payments.vantivprelive.com/vap/... | <?php
class Litle_LEcheck_Model_URL
{
public function toOptionArray()
{
return array(
array(
'value' => "https://www.testlitle.com/sandbox/communicator/online",
'label' => 'Sandbox'
),
array(
'value' => "https://prelive.litle.com/vap/communicator/... |
Remove reference to Deadline in window title | import os
import sys
import avalon.api
import avalon.fusion
import pyblish_qml
def _install_fusion():
from pyblish_qml import settings
import pyblish_qml.host as host
sys.stdout.write("Setting up Pyblish QML in Fusion\n")
if settings.ContextLabel == settings.ContextLabelDefault:
settings.... | import os
import sys
import avalon.api
import avalon.fusion
import pyblish_qml
def _install_fusion():
from pyblish_qml import settings
import pyblish_qml.host as host
sys.stdout.write("Setting up Pyblish QML in Fusion\n")
if settings.ContextLabel == settings.ContextLabelDefault:
settings.... |
Allow empty data in value | def assign_to_variable_spec(data, spec, value):
if not spec.startswith('@') or not spec.endswith('@'):
raise ValueError("{} is not a reference".format(spec))
parts = spec.strip('@').split('.')
data[parts[0]] = {}
gen = data[parts[0]]
for part in parts[1:-1]:
gen[part] = {}
ge... | def assign_to_variable_spec(data, spec, value):
if not spec.startswith('@') or not spec.endswith('@'):
raise ValueError("{} is not a reference".format(spec))
parts = spec.strip('@').split('.')
data[parts[0]] = {}
gen = data[parts[0]]
for part in parts[1:-1]:
gen[part] = {}
ge... |
Fix nonprofit model is called nonprofit | /* eslint-disable no-process-exit */
require('babel/register');
require('dotenv').load();
var Rx = require('rx');
var app = require('../server/server');
var Nonprofits = app.models.Nonprofit;
var nonprofits = require('./nonprofits.json');
var destroy = Rx.Observable.fromNodeCallback(Nonprofits.destroyAll, Nonprofits)... | /* eslint-disable no-process-exit */
require('babel/register');
require('dotenv').load();
var Rx = require('rx');
var app = require('../server/server');
var Nonprofits = app.models.Challenge;
var nonprofits = require('./nonprofits.json');
var destroy = Rx.Observable.fromNodeCallback(Nonprofits.destroyAll, Nonprofits)... |
Change text-updating logic to match on title rather than ID | $(document).ready(function () {
$(".js-define").each(function(index) {
$(this).attr('id', "field-" + index);
$(this).popover({
"html": true,
"placement": "bottom",
"content": generateInputElement(index)
});
});
$(".js-use").click(function() {
... | $(document).ready(function () {
$(".js-define").each(function(index) {
$(this).attr('id', "field-" + index);
$(this).popover({
"html": true,
"placement": "bottom",
"content": generateInputElement(index)
});
});
$(".js-use").click(function() {
... |
Correct wrong inheritance on sponsorship_typo3 child_depart wizard. | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... |
Add source to the construction table. | @section('title')
Construction categories - Cataclysm: Dark Days Ahead
@endsection
<h1>Construction categories</h1>
<div class="row">
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked">
@foreach($categories as $category)
<li class="@if($category==$id) active @endif"><a href="{{ route(Route::currentRouteNam... | @section('title')
Construction categories - Cataclysm: Dark Days Ahead
@endsection
<h1>Construction categories</h1>
<div class="row">
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked">
@foreach($categories as $category)
<li class="@if($category==$id) active @endif"><a href="{{ route(Route::currentRouteNam... |
Add link to issue regarding loading defaults via Launcher.initialize(). | /*
* Copyright (c) 2015 Google, 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... | /*
* Copyright (c) 2015 Google, 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... |
Add @ as an invalid label name character | package com.todoist.model;
import java.util.regex.Pattern;
public class Sanitizers {
public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+";
public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:@";
public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+";... | package com.todoist.model;
import java.util.regex.Pattern;
public class Sanitizers {
public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+";
public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:";
public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+";
... |
Make it so that the past speakers go from newest to oldest. | <?php
class Speakers extends Illuminate\Filesystem\Filesystem {
public $speakersPath;
public function __construct()
{
$this->speakersPath = app_path() . "/views/speakers/details";
}
/**
* Gets all the speakers for view in the past speakers list.
*
* @return array of speakers
*/
public functi... | <?php
class Speakers extends Illuminate\Filesystem\Filesystem {
public $speakersPath;
public function __construct()
{
$this->speakersPath = app_path() . "/views/speakers/details";
}
/**
* Gets all the speakers for view in the past speakers list.
*
* @return array of speakers
*/
public functi... |
Fix bug. youtube block cannot be edited | 'use strict';
import ENTITY from '../entities';
import insertAtomicBlock from './insert-atomic-block';
import { replaceAtomicBlock } from './replace-block';
import { Entity } from 'draft-js';
import removeBlock from './remove-block';
const handleAtomicEdit = (editorState, blockKey, valueChanged) => {
const block = e... | 'use strict';
import ENTITY from '../entities';
import insertAtomicBlock from './insert-atomic-block';
import { replaceAtomicBlock } from './replace-block';
import { Entity } from 'draft-js';
import removeBlock from './remove-block';
const handleAtomicEdit = (editorState, blockKey, valueChanged) => {
const block = e... |
Fix on instead of live | // This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directl... | // This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directl... |
Add cancelFunc parameter for confirm dialog | define(
[
"dojo/dom-construct",
"dijit/form/Button",
"dijit/Dialog"
],
function (domConstruct, Button, Dialog) {
"use strict";
var dialog = null;
var createButton = function (label, onClickFunc) {
return new Button({
label: label,
onClick: function () {
if (onClickFunc) {
/* run ca... | define(
[
"dojo/dom-construct",
"dijit/form/Button",
"dijit/Dialog"
],
function (domConstruct, Button, Dialog) {
"use strict";
var dialog = null;
var createButton = function (label, onClickFunc) {
return new Button({
label: label,
onClick: function () {
if (onClickFunc) {
/* run ca... |
Fix directory path memory stats test | 'use strict';
var MemoryStats = require('../../src/models/memory_stats')
, SQliteAdapter = require('../../src/models/sqlite_adapter')
, chai = require('chai')
, expect = chai.expect
, chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
describe('MemoryStats', function() {
describe('.con... | 'use strict';
var MemoryStats = require('../../lib/models/memory_stats')
, SQliteAdapter = require('../../lib/models/sqlite_adapter')
, chai = require('chai')
, expect = chai.expect
, chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
describe('MemoryStats', function() {
describe('.con... |
Modify grunt writeln and fix grunt header to make grunt-newer quiet. | function initTimeGrunt(grunt) {
const timeGrunt = require('time-grunt');
timeGrunt(grunt);
}
function initLoadGruntConfig(grunt) {
const loadGruntConfig = require('load-grunt-config');
const options = {
jitGrunt: {
staticMappings: {
mochaTest: 'grunt-mocha-test',
express: 'grunt-express-server'
}... | function initTimeGrunt(grunt) {
const timeGrunt = require('time-grunt');
timeGrunt(grunt);
}
function initLoadGruntConfig(grunt) {
const loadGruntConfig = require('load-grunt-config');
const options = {
jitGrunt: {
staticMappings: {
mochaTest: 'grunt-mocha-test',
express: 'grunt-express-server'
}... |
Fix error testing on python 2.7 | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except OSError:
pass
transpiler.main(["--output-dir",... | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except FileNotFoundError:
pass
transpiler.main(["--ou... |
Make sure to preload facility config on the user profile page. | import store from 'kolibri.coreVue.vuex.store';
import redirectBrowser from 'kolibri.utils.redirectBrowser';
import ProfilePage from './views/ProfilePage';
import ProfileEditPage from './views/ProfileEditPage';
function preload(next) {
store.commit('CORE_SET_PAGE_LOADING', true);
store.dispatch('getFacilityConfig'... | import store from 'kolibri.coreVue.vuex.store';
import redirectBrowser from 'kolibri.utils.redirectBrowser';
import ProfilePage from './views/ProfilePage';
import ProfileEditPage from './views/ProfileEditPage';
export default [
{
path: '/',
component: ProfilePage,
beforeEnter(to, from, next) {
stor... |
Support preview mode (don't link, just print matches found) | package main
import (
"fmt"
"os"
"path/filepath"
"github.com/gmcnaughton/gofindhdr/findhdr"
)
func main() {
// inpath := "/Users/gmcnaughton/Pictures/Photos Library.photoslibrary/Masters/2017/02"
inpath := "./test"
outpath := "./out"
optlink := false
// Create output folder
if optlink {
err ... | package main
import (
"fmt"
"os"
"path/filepath"
"github.com/gmcnaughton/gofindhdr/findhdr"
)
func main() {
inpath := "/Users/gmcnaughton/Pictures/Photos Library.photoslibrary/Masters/2017/02"
// inpath := "./test"
outpath := "./out"
optlink := true
// Create output folder
_ = os.Mkdir(outpath, ... |
Use third person in tests' names | // This is free and unencumbered software released into the public domain.
// See the `UNLICENSE` file or <http://unlicense.org/> for more details.
package it.svario.xpathapi.jaxp.test;
import it.svario.xpathapi.jaxp.XPathAPI;
import org.testng.annotations.Test;
import org.w3c.dom.Node;
import static org.testng.Asser... | // This is free and unencumbered software released into the public domain.
// See the `UNLICENSE` file or <http://unlicense.org/> for more details.
package it.svario.xpathapi.jaxp.test;
import it.svario.xpathapi.jaxp.XPathAPI;
import org.testng.annotations.Test;
import org.w3c.dom.Node;
import static org.testng.Asser... |
Simplify these decorators, since we don't use the classes here anyway. | """Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make di... | """Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
class TempDirectory(object):
def __init__(self):
self.temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.c... |
Make ghostscript handle PDF/A colorspace correctly
Previously, if you tried to verify files generated by pdf_to_pdfa in a
verifier (like https://tools.pdfforge.org/validate-pdfa), you would get
errors relating to the lack of OutputIntent (6.2.3). The info in
https://stackoverflow.com/a/56459053/11416267 and
https://ww... | import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dN... | import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dN... |
Add failing test for Workbook file save function | import {Workbook} from '../src/parsing/workbook.js';
import {expect} from 'chai';
import fs from 'fs';
describe('Workbook parsing', () => {
let file = fs.readFileSync('example/example-with-data.xlsx');
let wb = new Workbook(file);
it('should build a Workbook instance from a binary file', () => {
... | import {Workbook} from '../src/parsing/workbook.js';
import {expect} from 'chai';
import fs from 'fs';
describe('Workbook parsing', () => {
let file = fs.readFileSync('example/example-with-data.xlsx');
let wb = new Workbook(file);
it('should build a Workbook instance from a binary file', () => {
... |
Use singular parameter name.
Use ::class notation. | <?php
$router->bind('block', function ($id) {
return app(\Modules\Block\Repositories\BlockRepository::class)->find($id);
});
$router->group(['prefix' =>'/block'], function () {
get('blocks', ['as' => 'admin.block.block.index', 'uses' => 'BlockController@index']);
get('blocks/create', ['as' => 'admin.block... | <?php
$router->bind('blocks', function ($id) {
return app('Modules\Block\Repositories\BlockRepository')->find($id);
});
$router->group(['prefix' =>'/block'], function () {
get('blocks', ['as' => 'admin.block.block.index', 'uses' => 'BlockController@index']);
get('blocks/create', ['as' => 'admin.block.bloc... |
Add phpdoc-style comments to SearchTerm | <?php
namespace SearchApi\Models;
/**
* Class SearchTerm - A search term is a basic unit that will be used to build a query for
* Search providers.
*
* @var $value string This will be a keyword from NerTagger, location from ReverseGeocoder, etc.
* @var $category string 'location', 'person', 'o... | <?php
namespace SearchApi\Models;
/**
* Class SearchTerm - A search term is a basic unit that will be used to build a query for
* Search providers.
*/
class SearchTerm {
public $value; // (string) This will be a keyword from NerTagger, location from ReverseGeocoder, etc.
public $category; //... |
gn: Fix issue with finding llvm when using python3
With python3, subprocess output is a byte sequence. This needs to be
decoded to string so that the string functions work. Fix it so we can
find LLVM when building perfetto.
Also fix 'print' operator which is a function in python3.
Bug: 147789115
Signed-off-by: Joel... | # Copyright (C) 2017 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | # Copyright (C) 2017 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
Read database config from file. Exit process if file not found. | var _ = require('underscore'),
fs = require('fs'),
path = require('path'),
PoemsRepository = require('../lib/repositories/poems_repository.js');
var dbConfig;
if(fs.existsSync(path.join(__dirname, "../db/config.json"))) {
dbConfig = require("../db/config.json");
} else {
console.log("The database config file was ... | var _ = require('underscore');
var PoemsRepository = require('../lib/repositories/poems_repository.js');
var poemsRepo = new PoemsRepository();
exports.list = function(req, res) {
poemsRepo.all(function(err, poems) {
res.render('poem/list', { poems: poems });
});
};
exports.edit = function(req, res) {
... |
Add missing licence header to migration | <?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Ad... | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddAutoStartDurationToMultiplayerRooms extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::tab... |
Fix ipams builtin package for darwin
Make ipams builtin package work for os x target as ipam
driver developers happen to be using os x as well.
Signed-off-by: Jana Radhakrishnan <045898bda7d4800fe4909a9831e702ab79e266be@docker.com> | // +build linux freebsd solaris darwin
package builtin
import (
"fmt"
"github.com/docker/libnetwork/datastore"
"github.com/docker/libnetwork/ipam"
"github.com/docker/libnetwork/ipamapi"
"github.com/docker/libnetwork/ipamutils"
)
// Init registers the built-in ipam service with libnetwork
func Init(ic ipamapi.C... | // +build linux freebsd solaris
package builtin
import (
"fmt"
"github.com/docker/libnetwork/datastore"
"github.com/docker/libnetwork/ipam"
"github.com/docker/libnetwork/ipamapi"
"github.com/docker/libnetwork/ipamutils"
)
// Init registers the built-in ipam service with libnetwork
func Init(ic ipamapi.Callback... |
Add reminder to fix backend link | import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { setContext } from 'apollo-link-context';
import fetch from 'isomorphic-unfetch';
let apolloClient = null;
// Polyfill fetch() on the server (used by apollo-c... | import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { setContext } from 'apollo-link-context';
import fetch from 'isomorphic-unfetch';
let apolloClient = null;
// Polyfill fetch() on the server (used by apollo-c... |
Fix tiny errors in Python code |
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shortu... |
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shortu... |
Add second argument checking to prevent unexpected behavior. | var path = require('path')
var p = {}
Object.keys(path).forEach(function (key) {
p[key] = path[key]
})
path = p
path.replaceExt = require('replace-ext')
path.normalizeTrim = function (str) {
var escapeRegexp = require('escape-string-regexp')
return path.normalize(str).replace(new RegExp(escapeRegexp(path.sep... | var path = require('path')
var p = {}
Object.keys(path).forEach(function (key) {
p[key] = path[key]
})
path = p
path.replaceExt = require('replace-ext')
path.normalizeTrim = function (str) {
var escapeRegexp = require('escape-string-regexp')
return path.normalize(str).replace(new RegExp(escapeRegexp(path.sep... |
Fix display of undefined attributes | #!/usr/bin/env node
exports.command = {
description: 'get an attribute for a project',
arguments: '<project> <attribute>'
};
if (require.main !== module) {
return;
}
var storage = require('../lib/storage.js');
var utilities = require('../lib/utilities.js');
var program = utilities.programDefaults('get', '<pro... | #!/usr/bin/env node
exports.command = {
description: 'get an attribute for a project',
arguments: '<project> <attribute>'
};
if (require.main !== module) {
return;
}
var storage = require('../lib/storage.js');
var utilities = require('../lib/utilities.js');
var program = utilities.programDefaults('get', '<pro... |
Raise coverage. Lets see if this can work with JaCoCo | package sortpom.exception;
import org.apache.maven.plugin.MojoFailureException;
/**
* Converts internal runtime FailureException in a method to a MojoFailureException in order to give nice output to
* the Maven framework
*/
public class ExceptionConverter {
private final Runnable method;
public ExceptionC... | package sortpom.exception;
import org.apache.maven.plugin.MojoFailureException;
/**
* Converts internal runtime FailureException in a method to a MojoFailureException in order to give nice output to
* the Maven framework
*/
public class ExceptionConverter {
private final Runnable method;
private FailureEx... |
Update help for the registry option, which is now a URI. | #!/usr/bin/env node
var updater = require('update-notifier'),
pkg = require('../package.json');
updater({pkg: pkg}).notify();
var yargs = require('yargs')
.option('registry', {
description: 'url of the registry to use',
default: 'https://registry.npmjs.org'
})
.help('help')
.version(function() { return ... | #!/usr/bin/env node
var updater = require('update-notifier'),
pkg = require('../package.json');
updater({pkg: pkg}).notify();
var yargs = require('yargs')
.option('registry', {
description: 'fully-qualified hostname of the registry to use',
default: 'https://registry.npmjs.org'
})
.help('help')
.version... |
OLMIS-3608: Move variable to comply with Java Code Conventions. | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* 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, e... | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* 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, e... |
Set default value for Registry.playbook | from django.db import models
from django.conf import settings
class Playbook(models.Model):
name = models.CharField(max_length=200)
inventory = models.CharField(max_length=200, default="hosts")
user = models.CharField(max_length=200, default="ubuntu")
directory = models.CharField(max_length=200, editab... | from django.db import models
from django.conf import settings
class Playbook(models.Model):
name = models.CharField(max_length=200)
inventory = models.CharField(max_length=200, default="hosts")
user = models.CharField(max_length=200, default="ubuntu")
directory = models.CharField(max_length=200, editab... |
Remove console.log from responce time | 'use strict';
var config = require('../config').default;
var metrics = null;
if (config.metrics) {
var StatsD = require('node-statsd');
metrics = new StatsD({
host: config.metrics.host,
prefix: config.metrics.name + '_' + (process.env.METRICS_NODE ? process.env.METRICS_NODE : '')
});
}
module.exports =... | 'use strict';
var config = require('../config').default;
var metrics = null;
if (config.metrics) {
var StatsD = require('node-statsd');
metrics = new StatsD({
host: config.metrics.host,
prefix: config.metrics.name + '_' + (process.env.METRICS_NODE ? process.env.METRICS_NODE : '')
});
}
module.exports =... |
Support JWT as a Bearer token | <?php
namespace hiapi\Core\Auth;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
abstract class AuthMiddleware implements MiddlewareInterface
{
/**
* @inheritDoc
*/
public func... | <?php
namespace hiapi\Core\Auth;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
abstract class AuthMiddleware implements MiddlewareInterface
{
/**
* @inheritDoc
*/
public func... |
Add log level setting to mailer function | # -*- coding: utf-8 -*-
import smtplib
import arrow
from email.mime.text import MIMEText
from logging import INFO as LOGGING_INFO, DEBUG as LOGGING_DEBUG
def send_on_email(report, subject, mail_from, mail_to, smtp_auth, log_level=LOGGING_INFO):
smtp_login, smtp_password = smtp_auth
msg = MIMEText(report.en... | # -*- coding: utf-8 -*-
import smtplib
import arrow
from email.mime.text import MIMEText
def send_on_email(report, subject, mail_from, mail_to, smtp_auth):
smtp_login, smtp_password = smtp_auth
msg = MIMEText(report.encode('utf-8'), 'html', 'utf-8')
msg["Subject"] = subject
msg["From"] = mail_from
... |
Disable delay on server responses | var express = require('express');
var path = require('path');
var logger = require('morgan');
var slow = require('connect-slow');
var HttpError = require('./lib/http-error');
var rootRouter = require('./routes/root/root-router');
var roomsRouter = require('./routes/rooms/rooms-router');
var messagesRouter = require('.... | var express = require('express');
var path = require('path');
var logger = require('morgan');
var slow = require('connect-slow');
var HttpError = require('./lib/http-error');
var rootRouter = require('./routes/root/root-router');
var roomsRouter = require('./routes/rooms/rooms-router');
var messagesRouter = require('.... |
Use no more than 1 process. | #!/usr/bin/env node
var app = require('./server/app'),
http = require('http'),
cluster = require('cluster'),
numCPU = 1, //require('os').cpus().length,
i = 0;
if (cluster.isMaster){
for (i; i<numCPU; i++){
cluster.fork();
}
cluster.on('fork', function(worker){
console.log('... | #!/usr/bin/env node
var app = require('./server/app'),
http = require('http'),
cluster = require('cluster'),
numCPU = require('os').cpus().length,
i = 0;
if (cluster.isMaster){
for (i; i<numCPU; i++){
cluster.fork();
}
cluster.on('fork', function(worker){
console.log('forke... |
Remove eof double line-break in service test | import { moduleFor, test } from 'ember-qunit';
moduleFor('service:flashes', 'Unit | Service | flashes', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
test('it allows to show an error', function (assert) {
let service = this.subject();
assert.equal(service.get('fl... | import { moduleFor, test } from 'ember-qunit';
moduleFor('service:flashes', 'Unit | Service | flashes', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
test('it allows to show an error', function (assert) {
let service = this.subject();
assert.equal(service.get('fl... |
Update the supported file types list exposed to QML to use the new dict correctly | from PyQt5.QtCore import QObject, pyqtSlot, pyqtProperty, pyqtSignal
from UM.Application import Application
from UM.Logger import Logger
class MeshFileHandlerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._mesh_handler = Application.getInstance().getMeshFileHandle... | from PyQt5.QtCore import QObject, pyqtSlot, pyqtProperty, pyqtSignal
from UM.Application import Application
from UM.Logger import Logger
class MeshFileHandlerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._mesh_handler = Application.getInstance().getMeshFileHandle... |
Change argument to require from relative to global path | /**
* @module client/main
*/
'use strict';
var app = require('app');
require('angular');
/**
* Each 'index' generated via grunt process dynamically includes all browserify common-js modules
* in js bundle
*/
require('./controllers/index');
require('./services/index');
require('./router');
var io = require('./li... | /**
* @module client/main
*/
'use strict';
var app = require('./app');
require('angular');
/**
* Each 'index' generated via grunt process dynamically includes all browserify common-js modules
* in js bundle
*/
require('./controllers/index');
require('./services/index');
require('./router');
var io = require('./... |
Use percent encoding for calculating the signature | package oauth
import (
"bytes"
"fmt"
)
var hex = "0123456789ABCDEF"
// encode percent-encodes a string as defined in RFC 3986.
func encode(s string) string {
var buf bytes.Buffer
for _, c := range []byte(s) {
if isEncodable(c) {
if c == '+' {
// replace plus-encoding with percent-encoding
buf.WriteS... | package oauth
import (
"bytes"
"fmt"
)
var hex = "0123456789ABCDEF"
// encode percent-encodes a string as defined in RFC 3986.
func encode(s string) string {
var buf bytes.Buffer
for _, c := range []byte(s) {
if isEncodable(c) {
buf.WriteByte('%')
buf.WriteByte(hex[c>>4])
buf.WriteByte(hex[c&15])
} ... |
Fix exception handling to extend colander.Invalid | from setuptools import setup
setup(
name='Py-Authorize',
version='1.0.1.3',
author='Vincent Catalano',
author_email='vincent@vincentcatlano.com',
url='https://github.com/vcatalano/py-authorize',
download_url='',
description='A full-featured Python API for Authorize.net.',
long_descript... | from setuptools import setup
setup(
name='Py-Authorize',
version='1.0.1.2',
author='Vincent Catalano',
author_email='vincent@vincentcatlano.com',
url='https://github.com/vcatalano/py-authorize',
download_url='',
description='A full-featured Python API for Authorize.net.',
long_descript... |
Check for account activity before password verification | """
byceps.services.authentication.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ..user.models.user import User
from ..user import service as user_service
from .exceptions import AuthenticationFailed
from .password ... | """
byceps.services.authentication.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ..user.models.user import User
from ..user import service as user_service
from .exceptions import AuthenticationFailed
from .password ... |
Handle missing fields in dataverse | import arrow
import dateparser
from share.normalize import *
class Person(Parser):
given_name = ParseName(ctx).first
family_name = ParseName(ctx).last
additional_name = ParseName(ctx).middle
suffix = ParseName(ctx).suffix
class Contributor(Parser):
person = Delegate(Person, ctx)
cited_name... | import arrow
import dateparser
from share.normalize import *
class Person(Parser):
given_name = ParseName(ctx).first
family_name = ParseName(ctx).last
additional_name = ParseName(ctx).middle
suffix = ParseName(ctx).suffix
class Contributor(Parser):
person = Delegate(Person, ctx)
cited_name... |
Fix sef map config provider | <?php
defined('M2_MICRO') or die('Direct Access to this location is not allowed.');
/**
* Sef map array
* @name $sef_map
* @package M2 Micro Framework
* @subpackage Library
* @author Alexander Chaika
* @since 0.2RC1
*/
return array(
'/\?modul... | <?php
defined('M2_MICRO') or die('Direct Access to this location is not allowed.');
/**
* Sef map array
* @name $sef_map
* @package M2 Micro Framework
* @subpackage Library
* @author Alexander Chaika
* @since 0.2RC1
*/
return array(
'/\?modul... |
Change URL back to sorseg.ru (brought up instance) | package com.dao.mydebts;
import okhttp3.MediaType;
/**
* @author Oleg Chernovskiy on 05.04.16.
*/
public class Constants {
//private static final String SERVER_ENDPOINT = "sorseg.ru:8080/debt/";
//private static final String SERVER_ENDPOINT = "http://demoth.no-ip.org:8080/debt/";
private static final S... | package com.dao.mydebts;
import okhttp3.MediaType;
/**
* @author Oleg Chernovskiy on 05.04.16.
*/
public class Constants {
//private static final String SERVER_ENDPOINT = "sorseg.ru:8080/debt/";
//private static final String SERVER_ENDPOINT = "http://demoth.no-ip.org:8080/debt/";
private static final S... |
Use bassoradio as temp stream for radiodiodi | var util = require('../src/util/seeds');
exports.seed = function(knex, Promise) {
const cities = {};
return knex('cities').select('*')
.then(rows => {
rows.forEach(city => {
cities[city.name] = city.id;
});
})
.then(() => util.insertOrUpdate(knex, 'radios', {
id: 1,
name: 'Rakkauden W... | var util = require('../src/util/seeds');
exports.seed = function(knex, Promise) {
const cities = {};
return knex('cities').select('*')
.then(rows => {
rows.forEach(city => {
cities[city.name] = city.id;
});
})
.then(() => util.insertOrUpdate(knex, 'radios', {
id: 1,
name: 'Rakkauden W... |
Test + travis = error | package main
import (
"fmt"
"testing"
"github.com/spf13/viper"
)
func TestSomething(t *testing.T) {
viper.SetConfigName("config")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
fmt.Printf("%v", err)
}
}
/*
func TestMain(m *testing.M) {
i18n.MustLoadTranslationFile("lang/en-US.all.js... | package main
import (
"fmt"
"os"
"testing"
"github.com/nicksnyder/go-i18n/i18n"
mylog "github.com/patrickalin/GoMyLog"
"github.com/spf13/viper"
)
func TestSomething(t *testing.T) {
viper.SetConfigName("config")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
fmt.Printf("%v", err)
}
... |
Increase the ES timeout to 1 minute. | import certifi
from django.apps import AppConfig
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from elasticsearch_dsl.connections import connections
class DocsConfig(AppConfig):
name = 'docs'
verbose_name = _('Documentation')
def ready(self):
super(DocsC... | import certifi
from django.apps import AppConfig
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from elasticsearch_dsl.connections import connections
class DocsConfig(AppConfig):
name = 'docs'
verbose_name = _('Documentation')
def ready(self):
super(DocsC... |
Tweak kv migration to improve compatibility across Django versions | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL)
]
operations = [
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
]
operations = [
migrations.CreateModel(
name=... |
Improve header collapse by using outerHeight | if (typeof jQuery === 'undefined') {
throw new Error('Custom JS requires jQuery...');
}
+function ($) {
'use strict';
$(document).ready(function () {
var outer = $('#affix-outer'),
collapse = $('#affix-collapse'),
sticky = $('#affix-sticky'),
wrapper = $('#affix-wrapper'),
set... | if (typeof jQuery === 'undefined') {
throw new Error('Custom JS requires jQuery...');
}
+function ($) {
'use strict';
$(document).ready(function () {
var outer = $('#affix-outer'),
collapse = $('#affix-collapse'),
sticky = $('#affix-sticky'),
wrapper = $('#affix-wrapper'),
set... |
Comment added; Scheduling still in question | var app = require('express');
const router = app.Router({ mergeParams: true });
var retrieval = require('../retrieval/retrieval');
var schedule = require('./algorithms-courseformat/courseMatrixUsage')
// .../api/scheduling?courses=['course1','course2',...,'courseN']
router.get('/', function(req, res){
if (!req.q... | var app = require('express');
const router = app.Router({ mergeParams: true });
var retrieval = require('../retrieval/retrieval');
var schedule = require('./algorithms-courseformat/courseMatrixUsage')
router.get('/', function(req, res){
if (!req.query.hasOwnProperty('courses')){
res.status(400).json({mes... |
Change formatting in JS files [skip ci] | const types = require('./types');
/**
* Redux action creator. Returns action for adding a post.
* @param {object} post Posts data
* @return {object} Action
*/
function addPost(post) {
return { type: types.POSTS_ADD, payload: post };
}
/**
* Redux action creator. Return posts sorting action.
* @param {strin... | const types = require('./types');
/**
* Redux action creator. Returns action for adding a post.
* @param {object} post Posts data
* @return {object} Action
*/
function addPost(post) {
return {type: types.POSTS_ADD, payload: post};
}
/**
* Redux action creator. Return posts sorting action.
* @param {string}... |
Remove vue from selectors and just use embedded html | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to sty... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to sty... |
Set default buffer size to 64M | 'use strict';
const ProgramError = require('./error/ProgramError');
class SortOptions
{
constructor(options = {})
{
this.path = 'sort';
this.unique = false;
this.numeric = false;
this.reverse = false;
this.stable = false;
this.merge = false;
this.ignoreCase = false;
this.sortByHash = false;
this.t... | 'use strict';
const ProgramError = require('./error/ProgramError');
class SortOptions
{
constructor(options = {})
{
this.path = 'sort';
this.unique = false;
this.numeric = false;
this.reverse = false;
this.stable = false;
this.merge = false;
this.ignoreCase = false;
this.sortByHash = false;
this.t... |
Use correct test class name | <?php
namespace SimplyTestable\ApiBundle\Tests\Controller;
use SimplyTestable\ApiBundle\Tests\Controller\BaseControllerJsonTestCase;
class GetActionTest extends BaseControllerJsonTestCase {
public static function setUpBeforeClass() {
self::setupDatabaseIfNotExists();
}
public function t... | <?php
namespace SimplyTestable\ApiBundle\Tests\Controller;
use SimplyTestable\ApiBundle\Tests\Controller\BaseControllerJsonTestCase;
class GetTokenTest extends BaseControllerJsonTestCase {
public static function setUpBeforeClass() {
self::setupDatabaseIfNotExists();
}
public function te... |
Add decodeWithMetadata function and improve documentation | 'use strict';
var leb = require('leb');
/**
* Provide operations for serializing/deserializing integer data into
* variable-length 64-bit LEB128 integer encoding [1].
*
* References:
* [1] https://en.wikipedia.org/wiki/LEB128
*
**/
var LEB128 = {
/**
* Encode an arbitrarily large positive integer value us... | 'use strict';
var leb = require('leb');
/**
* Provide operations for serializing/deserializing integer data into
* variable-length LEB128 integer encoding [1].
*
* References:
* [1] https://en.wikipedia.org/wiki/LEB128
*
**/
var LEB128 = {
/**
* Encode an arbitrarily large positive integer value using a s... |
Add more Python version classifiers | #!/usr/bin/env python
from setuptools import find_packages, setup
# Use quickphotos.VERSION for version numbers
version_tuple = __import__('quickphotos').VERSION
version = '.'.join([str(v) for v in version_tuple])
setup(
name='django-quick-photos',
version=version,
description='Latest Photos from Instagra... | #!/usr/bin/env python
from setuptools import find_packages, setup
# Use quickphotos.VERSION for version numbers
version_tuple = __import__('quickphotos').VERSION
version = '.'.join([str(v) for v in version_tuple])
setup(
name='django-quick-photos',
version=version,
description='Latest Photos from Instagra... |
Allow ignore to be called at class and field level | /*
* #%L
* BroadleafCommerce Common Libraries
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* 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... | /*
* #%L
* BroadleafCommerce Common Libraries
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* 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... |
Fix colorize otput if there is no config settings in global config file | <?php
if ( !defined( 'WP_CLI' ) ) return;
global $argv;
$env = $argv[1];
$config = array();
$config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml';
if ( is_readable( $config_path ) ){
$configurator = \WP_CLI::get_configurator();
$configurator->merge_yml( $config_path );
list( $config, $extra_config... | <?php
if ( !defined( 'WP_CLI' ) ) return;
global $argv;
$env = $argv[1];
$config = array();
$config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml';
if ( is_readable( $config_path ) ){
$configurator = \WP_CLI::get_configurator();
$configurator->merge_yml( $config_path );
list( $config, $extra_config... |
Fix wording for remote shares in settings page | <div class="section" id="fileSharingSettings" >
<h2><?php p($l->t('Remote Shares'));?></h2>
<input type="checkbox" name="outgoing_server2server_share_enabled" id="outgoingServer2serverShareEnabled"
value="1" <?php if ($_['outgoingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
<label ... | <div class="section" id="fileSharingSettings" >
<h2><?php p($l->t('File Sharing'));?></h2>
<input type="checkbox" name="outgoing_server2server_share_enabled" id="outgoingServer2serverShareEnabled"
value="1" <?php if ($_['outgoingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
<label f... |
Remove unused import from tests | from collections import defaultdict
import pytest
from funcy.funcmakers import *
def test_callable():
assert make_func(lambda x: x + 42)(0) == 42
def test_int():
assert make_func(0)('abc') == 'a'
assert make_func(2)([1,2,3]) == 3
assert make_func(1)({1: 'a'}) == 'a'
with pytest.raises(IndexErro... | import inspect
from collections import defaultdict
import pytest
from funcy.funcmakers import *
def test_callable():
assert make_func(lambda x: x + 42)(0) == 42
def test_int():
assert make_func(0)('abc') == 'a'
assert make_func(2)([1,2,3]) == 3
assert make_func(1)({1: 'a'}) == 'a'
with pytest.r... |
Use new user data API | var userData = require('./user-data.js')
document.addEventListener('DOMContentLoaded', function (event) {
var data = userData.getData()
updateIndex(data)
var clearAllButton = document.getElementById('clear-all-challenges')
clearAllButton.addEventListener('click', function () {
for (var chal in data) {
... | var ipc = require('ipc')
var fs = require('fs')
var userData
document.addEventListener('DOMContentLoaded', function (event) {
ipc.send('getUserDataPath')
ipc.on('haveUserDataPath', function (path) {
updateIndex('./data.json')
})
var clearAllButton = document.getElementById('clear-all-challenges')
cle... |
Remove ANSI escape sequences from panel output | import re
import sublime
ANSI_ESCAPE_RE = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
def normalize(string):
return ANSI_ESCAPE_RE.sub('', string.replace('\r\n', '\n').replace('\r', '\n'))
def panel(message, run_async=True):
message = normalize(str(message))
view = sublime.active_window().active_view()
... | import sublime
def universal_newlines(string):
return string.replace('\r\n', '\n').replace('\r', '\n')
def panel(message, run_async=True):
message = universal_newlines(str(message))
view = sublime.active_window().active_view()
if run_async:
sublime.set_timeout_async(
lambda: view... |
Allow RemoteController to connect to correct port.
Fixes #584 | #!/usr/bin/python
"""
Create a network where different switches are connected to
different controllers, by creating a custom Switch() subclass.
"""
from mininet.net import Mininet
from mininet.node import OVSSwitch, Controller, RemoteController
from mininet.topolib import TreeTopo
from mininet.log import setLogLevel
... | #!/usr/bin/python
"""
Create a network where different switches are connected to
different controllers, by creating a custom Switch() subclass.
"""
from mininet.net import Mininet
from mininet.node import OVSSwitch, Controller, RemoteController
from mininet.topolib import TreeTopo
from mininet.log import setLogLevel
... |
Add suport for HTML5 Galleries & Captions
See http://make.wordpress.org/core/2014/04/15/html5-galleries-captions-
in-wordpress-3-9/ for mor details | <?php
/**
* Shoestrap initial setup and constants
*/
function shoestrap_setup() {
// Make theme available for translation
load_theme_textdomain( 'shoestrap', get_template_directory() . '/lang' );
// Register wp_nav_menu() menus ( http://codex.wordpress.org/Function_Reference/register_nav_menus )
register_nav_men... | <?php
/**
* Shoestrap initial setup and constants
*/
function shoestrap_setup() {
// Make theme available for translation
load_theme_textdomain( 'shoestrap', get_template_directory() . '/lang' );
// Register wp_nav_menu() menus ( http://codex.wordpress.org/Function_Reference/register_nav_menus )
register_nav_men... |
Add credentials module to core list | from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPriv... | from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPriv... |
Refactor: Allow only the user-data fetching | from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, mixins, routers
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.viewsets import GenericViewSet
from core import serializers as api
from core.models import Image, Pin
from core.permissi... | from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, mixins, routers
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.viewsets import GenericViewSet
from core import serializers as api
from core.models import Image, Pin
from core.permissi... |
Add LogsManager to UserKit constructor | from requestor import Requestor
from users import UserManager
from invites import InviteManager
from emails import EmailManager
from session import Session
from widget import WidgetManager
from logs import LogsManager
class UserKit(object):
_rq = None
api_version = 1.0
api_base_url = None
api_key = No... | from requestor import Requestor
from users import UserManager
from invites import InviteManager
from emails import EmailManager
from session import Session
from widget import WidgetManager
class UserKit(object):
_rq = None
api_version = 1.0
api_base_url = None
api_key = None
users = None
invit... |
Fix stale function reference when calling context menu handler
Upon mounting, ContextMenuInterceptor retained the onWillShowContextMenu
prop as a direct function reference; when updating the component with
a new onWillShowContextMenu, the retained function was not updated. As
a result, right-clicking on the wrapped el... | import React from 'react';
import PropTypes from 'prop-types';
export default class ContextMenuInterceptor extends React.Component {
static propTypes = {
onWillShowContextMenu: PropTypes.func.isRequired,
children: PropTypes.element.isRequired,
}
static registration = new Map()
static handle(event) {
... | import React from 'react';
import PropTypes from 'prop-types';
export default class ContextMenuInterceptor extends React.Component {
static propTypes = {
onWillShowContextMenu: PropTypes.func.isRequired,
children: PropTypes.element.isRequired,
}
static registration = new Map()
static handle(event) {
... |
Fix test which didn't compile
git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@1158 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba |
package jsr181.jaxb.globalweather;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.ParameterStyle;
import javax.jws.soap.SOAPBinding.Style;
import javax.jws.soap.SOAPBinding.Use;
@WebService(serviceName = "GlobalWeather", targetNamespace = "http://www.webserviceX.NET... |
package jsr181.jaxb.globalweather;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.ParameterStyle;
import javax.jws.soap.SOAPBinding.Style;
import javax.jws.soap.SOAPBinding.Use;
import org.codehaus.xfire.fault.XFireFault;
@WebService(serviceName = "GlobalWeather", ... |
Remove Mock and create "empty" object on the fly | import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="email@domain.com"):
# create e... | from unittest.mock import MagicMock
import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="em... |
Make proxy proxy to backend | const merge = require('webpack-merge');
const config = require('./webpack.config');
const host = process.env.SDF_HOST || 'localhost';
const port = process.env.SDF_PORT || '3000';
const backendHost = process.env.SDF_BACKEND_HOST || 'backend';
const backendPort = process.env.SDF_BACKEND_PORT || '3000';
module.exports ... | const merge = require('webpack-merge');
const config = require('./webpack.config');
const host = process.env.SDF_HOST || 'localhost';
const port = process.env.SDF_PORT || '3000';
module.exports = merge.smart(config, {
devtool: 'eval-source-map',
module: {
rules: [
{
test: /\.css$/,
use: ... |
Change the if condition to check if ref is defined, rather than explicitly null or false. | /**
* Copy all properties from `props` onto `obj`.
* @param {object} obj Object onto which properties should be copied.
* @param {object} props Object from which to copy properties.
* @returns {object}
* @private
*/
export function extend(obj, props) {
for (let i in props) obj[i] = props[i];
return obj;
}
/** ... | /**
* Copy all properties from `props` onto `obj`.
* @param {object} obj Object onto which properties should be copied.
* @param {object} props Object from which to copy properties.
* @returns {object}
* @private
*/
export function extend(obj, props) {
for (let i in props) obj[i] = props[i];
return obj;
}
/** ... |
Use the array API types for the array API type annotations | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', '... | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', '... |
Allow controllers to be registered via options. | function Plugin(app, chat, options)
{
if(!options) {
throw new Error('No options specified for plugin.');
}
if(!options.name) {
throw new Error('No name specified for plugin');
}
this.name = options.name;
if(!options.version) {
throw new Error('No version specified for ... | function Plugin(app, chat, options)
{
if(!options) {
throw new Error('No options specified for plugin.');
}
if(!options.name) {
throw new Error('No name specified for plugin');
}
this.name = options.name;
if(!options.version) {
throw new Error('No version specified for ... |
Make is so that the pupa command can run | #!/usr/bin/env python
from setuptools import setup, find_packages
from pupa import __version__
long_description = ''
setup(name='pupa',
version=__version__,
packages=find_packages(),
author='James Turk',
author_email='jturk@sunlightfoundation.com',
license='BSD',
url='http://github... | #!/usr/bin/env python
from setuptools import setup, find_packages
from pupa import __version__
long_description = ''
setup(name='pupa',
version=__version__,
packages=find_packages(),
author='James Turk',
author_email='jturk@sunlightfoundation.com',
license='BSD',
url='http://github... |
Add standard, standard_level, theme to ga's
Go back to the list state after successful creation
See #81 | 'use strict';
module.exports =
/*@ngInject*/
function GrammarActivitiesCreateCmsCtrl (
$scope, _, GrammarActivity, $state
) {
$scope.grammarActivity = {};
$scope.grammarActivity.question_set = [{}];
function buildConcepts(set) {
return _.chain(set)
.map(function (s) {
return [s.concept_leve... | 'use strict';
module.exports =
/*@ngInject*/
function GrammarActivitiesCreateCmsCtrl (
$scope, _, GrammarActivity
) {
$scope.grammarActivity = {};
$scope.grammarActivity.question_set = [{}];
function buildConcepts(set) {
return _.chain(set)
.map(function (s) {
return [s.concept_level_0.$id,... |
Use strings.Builder instead of string concatenation.
#lint | // Copyright 2015 Google Inc. All Rights Reserved.
// This file is available under the Apache license.
package errors
import (
"fmt"
"strings"
"github.com/google/mtail/internal/vm/position"
"github.com/pkg/errors"
)
type compileError struct {
pos position.Position
msg string
}
func (e compileError) Error() s... | // Copyright 2015 Google Inc. All Rights Reserved.
// This file is available under the Apache license.
package errors
import (
"fmt"
"github.com/google/mtail/internal/vm/position"
"github.com/pkg/errors"
)
type compileError struct {
pos position.Position
msg string
}
func (e compileError) Error() string {
re... |
Disable shuffle button while shuffling in progress. | import React from 'react';
import PropTypes from 'prop-types';
import { useTranslator } from '@u-wave/react-translate';
import CircularProgress from '@material-ui/core/CircularProgress';
import Tooltip from '@material-ui/core/Tooltip';
import IconButton from '@material-ui/core/IconButton';
import ShuffleIcon from '@mat... | import React from 'react';
import PropTypes from 'prop-types';
import { useTranslator } from '@u-wave/react-translate';
import CircularProgress from '@material-ui/core/CircularProgress';
import Tooltip from '@material-ui/core/Tooltip';
import IconButton from '@material-ui/core/IconButton';
import ShuffleIcon from '@mat... |
Add Example 9 Lesson 4 | package ru.stqua.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqua.pft.addressbook.model.GroupData;
import java.util.HashSet;
import java.util.List;
public class GroupCreationTests extends TestBase{
@Test
public void testGroupCreation() {
app.getNavigationH... | package ru.stqua.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqua.pft.addressbook.model.GroupData;
import java.util.HashSet;
import java.util.List;
public class GroupCreationTests extends TestBase{
@Test
public void testGroupCreation() {
app.getNavigationH... |
Add jquery and use flotr basic. | window.FlashCanvasOptions = {
swfPath: 'lib/FlashCanvas/bin/'
};
yepnope([
'lib/jquery/jquery-1.7.1.min.js',
// IE
{
test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9),
yep : [
'lib/flotr2/lib/base64.js'
]
},
{
test : (naviga... | window.FlashCanvasOptions = {
swfPath: 'lib/FlashCanvas/bin/'
};
yepnope([
{
test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9),
yep : [
'lib/flotr2/lib/base64.js'
]
},
{
test : (navigator.appVersion.indexOf("MSIE") != -1),
ye... |
Fix error of unitdef package import after changing it's name | package coreos
import (
"github.com/bernardolins/clustereasy/scope"
"github.com/bernardolins/clustereasy/service/etcd"
"github.com/bernardolins/clustereasy/service/flannel"
"github.com/bernardolins/clustereasy/service/fleet"
"github.com/bernardolins/clustereasy/setup/types"
"github.com/bernardolins/clustereasy/u... | package coreos
import (
"github.com/bernardolins/clustereasy/scope"
"github.com/bernardolins/clustereasy/service/etcd"
"github.com/bernardolins/clustereasy/service/flannel"
"github.com/bernardolins/clustereasy/service/fleet"
"github.com/bernardolins/clustereasy/setup/types"
"github.com/bernardolins/clustereasy/u... |
Change the spanish password reminder sent language line for a more readable one. | <?php
return [
/*
|--------------------------------------------------------------------------
| Password Reminder Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are... | <?php
return [
/*
|--------------------------------------------------------------------------
| Password Reminder Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are... |
Fix a port related issue that persists. | require( 'dotenv' ).config();
var dropboxModule = require( './modules/dropbox.js' );
var googleDocsModule = require( './modules/googleDocs.js' );
var paypalModule = require( './modules/paypal.js' );
var express = require( 'express' );
var app = express();
app.set( 'port', ( process.env.PORT ) );
app.use( express.stati... | require( 'dotenv' ).config();
var dropboxModule = require( './modules/dropbox.js' );
var googleDocsModule = require( './modules/googleDocs.js' );
var paypalModule = require( './modules/paypal.js' );
var express = require( 'express' );
var app = express();
app.set( 'port', ( process.env.Port || 30000 ) );
app.use( expr... |
Change a bit of text | "use strict";
const { Event } = require("sosamba");
const { version: sosambaVersion } = require("sosamba/package.json");
const { version } = require("../package.json");
class CommandErrorEvent extends Event {
constructor(...args) {
super(...args, {
name: "commandError"
});
}
as... | "use strict";
const { Event } = require("sosamba");
const { version: sosambaVersion } = require("sosamba/package.json");
const { version } = require("../package.json");
class CommandErrorEvent extends Event {
constructor(...args) {
super(...args, {
name: "commandError"
});
}
as... |
Fix name - it is testing Character, not Team | from django.test import TestCase
from .models import Character, Team
class CharacterGetAbsoluteUrl(TestCase):
def test_slug_appears_in_url(self):
slug_value = "slug-value"
team = Team()
team.slug = "dont-care"
sut = Character()
sut.slug = slug_value
sut.team = t... | from django.test import TestCase
from .models import Character, Team
class TeamGetAbsoluteUrl(TestCase):
def test_slug_appears_in_url(self):
slug_value = "slug-value"
team = Team()
team.slug = "dont-care"
sut = Character()
sut.slug = slug_value
sut.team = team
... |
Add one more creation way and refactor test descriptions. | // 1: async - basics
// To do: make all tests pass, leave the assert lines unchanged!
describe('`async` defines an asynchronous function', function() {
describe('can be created by putting `async` before', () => {
it('a function expression', function() {
const f = async function() {};
assert.equal(f ... | // 1: async - basics
// To do: make all tests pass, leave the assert lines unchanged!
describe('`async` defines an asynchronous function', function() {
describe('can be created', () => {
it('by prefixing a function expression with `async`', function() {
const f = async function() {};
assert.equal(f ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.