text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
feat(shop): Create relationship for shop table
Create relationship for shop table
see #141 | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
public function cities()
{
return $this->hasMany('App\City');
}
public function districts()
{
return $th... | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
public function cities()
{
return $this->hasMany('App\City');
}
public function districts()
{
return $th... |
Add tasks to list of mq tasks | from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftes... | from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftes... |
Add backwards compatability for Adobe Lightroom
Because it was renamed it may result in unexpected errors --> breaking
changes.
This is a temporary solution to circumvent the problem. This can be
removed once some other breaking changes are also present and a major
new version is released. I propose removing this ... | #!/usr/bin/env node
/**
* @fileoverview
* Compiles our icons into static .js files that can be imported in the browser
* and are tree-shakeable.
* The static .js files go in icons/{filename}.js.
* Also generates an index.js that exports all icons by title, but is not tree-shakeable
*/
const dataFile = "../_data/... | #!/usr/bin/env node
/**
* @fileoverview
* Compiles our icons into static .js files that can be imported in the browser
* and are tree-shakeable.
* The static .js files go in icons/{filename}.js.
* Also generates an index.js that exports all icons by title, but is not tree-shakeable
*/
const dataFile = "../_data/... |
Remove globus interface from mcapi - now in its own server | #!/usr/bin/env python
from mcapi.mcapp import app, mcdb_connect
from mcapi import utils, access
from mcapi import objects, cache
from mcapi.user import account, usergroups, projects
from os import environ
import optparse
import signal
from mcapi import apikeydb
_HOST = environ.get('MC_SERVICE_HOST') or 'localhost'
... | #!/usr/bin/env python
from mcapi.mcapp import app, mcdb_connect
from mcapi import utils, access
from mcapi import objects, cache
from mcapi.user import account, usergroups, projects
from mcapi.globus import globus_service
from os import environ
import optparse
import signal
from mcapi import apikeydb
_HOST = environ.... |
Add getIndices() method to 2D arrays | export default function Array2 ({
fill,
size: [width, height]
}) {
const arr2 = []
for (let i = 0; i < width; i++) {
arr2.push(new Array(height).fill(fill))
}
// There should be a better way to include the indices . . .
arr2.forEach2 = (callback) => {
return arr2.forEach((row, i) =>
row.fo... | export default function Array2 ({
fill,
size: [width, height]
}) {
const arr2 = []
for (let i = 0; i < width; i++) {
arr2.push(new Array(height).fill(fill))
}
// There should be a better way to include the indices . . .
arr2.forEach2 = (callback) => {
return arr2.forEach((row, i) =>
row.fo... |
Remove leftovers from example config | package com.quiptiq.wurmrest;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import com.quiptiq.wurmrest.rmi.RmiProviderFactory;
import io.dropwizard.Configuration;
import com.fasterxml.jackson.annotation.Js... | package com.quiptiq.wurmrest;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import com.quiptiq.wurmrest.rmi.RmiProviderFactory;
import io.dropwizard.Configuration;
import com.fasterxml.jackson.annotation.Js... |
Add "String...args" into "public..." :maple_leaf: | public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
... | public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
... |
Remove extra space in help string
Extra spaces make the openstack-manuals tests fail with a niceness
error. This patch removes an extra space at the end of a help string.
Change-Id: I29bab90ea5a6f648c4539c7cd20cd9b2b63055c2 | # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
Update for other js file the linting | /* global $, alert, localStorage */
/* eslint-env jquery, browser */
'use strict'
var eq = {
item: {
detail: function () {
var elem = document.getElementById('item-detail-search')
var value = elem.getElementsByTagName('input')[0].value
window.location.href = [
'/action/eq/item-detail/... | 'use strict'
var eq = {
item: {
detail: function () {
var elem = document.getElementById('item-detail-search')
var value = elem.getElementsByTagName('input')[0].value
window.location.href = [
'/action/eq/item-detail/',
value.replace(/ /g, '+')
].join('')
return fal... |
Call onAny listeners in dispatcher context | "use strict";
const DiscordieError = require("./DiscordieError");
const Constants = require("../Constants");
const EventTypes = Object.keys(Constants.Events);
const events = require("events");
let lastEvent = null;
function validateEvent(eventType) {
if (EventTypes.indexOf(eventType) < 0)
throw new DiscordieE... | "use strict";
const DiscordieError = require("./DiscordieError");
const Constants = require("../Constants");
const EventTypes = Object.keys(Constants.Events);
const events = require("events");
let lastEvent = null;
function validateEvent(eventType) {
if (EventTypes.indexOf(eventType) < 0)
throw new DiscordieE... |
Fix wrong import for the test setup. | import 'Library/TestSetup';
import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import { LikeButton } from 'Components/LikeButton/LikeButton';
const onClickStub = sinon.spy();
const defaultProps = { storyId: 1, active: false, onClick: onClickStub };
const defaultComponent = <LikeBu... | import 'Utils/TestSetup';
import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import { LikeButton } from 'Components/LikeButton/LikeButton';
const onClickStub = sinon.spy();
const defaultProps = { storyId: 1, active: false, onClick: onClickStub };
const defaultComponent = <LikeButt... |
Update done() call to run(). | (function() {
'use strict';
var cli = require('casper').create().cli;
var parapsych = require(cli.raw.get('rootdir') + '/dist/parapsych').create(require);
parapsych.set('cli', cli).set('initUrl', '/').set('initSel', 'body');
describe('group 1', function() {
it('should pass --grep filter' , function() {
... | (function() {
'use strict';
var cli = require('casper').create().cli;
var parapsych = require(cli.raw.get('rootdir') + '/dist/parapsych').create(require);
parapsych.set('cli', cli)
.set('initUrl', '/')
.set('initSel', 'body');
describe('group 1', function() {
it('should pass --grep filter' , fu... |
Use build in relative path method | "use strict";
const vscode = require("vscode");
const analyser = require("./complexity-analyzer");
const reporter = require("./report-builder.js");
const config = require("./config");
const Output = require("./output-channel");
function buildReport(document) {
const channel = new Output();
const filePa... | "use strict";
const vscode = require("vscode");
const analyser = require("./complexity-analyzer");
const reporter = require("./report-builder.js");
const config = require("./config");
const Output = require("./output-channel");
function getFileRelativePath(document) {
const fileUri = document.fileName;
... |
Improve Iterable Conversion in For Directives
(gensrc): Improved Iterable Conversion for non-list non-range
expressions. | package dyvil.tools.gensrc.ast.expression;
import dyvil.collection.iterator.ArrayIterator;
import dyvil.collection.iterator.SingletonIterator;
import dyvil.source.position.SourcePosition;
import dyvil.tools.gensrc.ast.scope.Scope;
import dyvil.tools.parsing.ASTNode;
public interface Expression extends ASTNode
{
defa... | package dyvil.tools.gensrc.ast.expression;
import dyvil.tools.gensrc.ast.scope.Scope;
import dyvil.tools.parsing.ASTNode;
public interface Expression extends ASTNode
{
default boolean evaluateBoolean(Scope scope)
{
return Boolean.parseBoolean(this.evaluateString(scope));
}
default long evaluateInteger(Scope sc... |
Add a white space after left brackets | /**
* DocumentValidator
* Copyright (c) 2013-, Takahiko Ito, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your... | /**
* DocumentValidator
* Copyright (c) 2013-, Takahiko Ito, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your... |
Add custom toString() to SQLiteIndex | /*
* Copyright (C) 2013 Jerzy Chalupski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or a... | /*
* Copyright (C) 2013 Jerzy Chalupski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or a... |
Remove comma before 'and' in error messages | 'use strict';
const { toSentence } = require('underscore.string');
// Turn ['a', 'b', 'c'] into 'a, b or c'
const getWordsList = function (
words,
{
op = 'or',
quotes = false,
json = false,
} = {},
) {
if (words.length === 0) { return ''; }
const wordsA = jsonStringify(words, { json });
const... | 'use strict';
const { toSentence } = require('underscore.string');
// Turn ['a', 'b', 'c'] into 'a, b or c'
const getWordsList = function (
words,
{
op = 'or',
quotes = false,
json = false,
} = {},
) {
if (words.length === 0) { return ''; }
const wordsA = jsonStringify(words, { json });
const... |
Remove the for-loop in favor of mapping the array into event components | import Event from './event';
const Day = ({ events }) => {
const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ];
const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ];
const DAY = eve... | import Event from './event';
const Day = ({ events }) => {
let id = 0;
let eventList = [];
for (let e of events) {
eventList.push(<Event title={e.title} start_time={e.start_time} content={e.content} key={id}/>);
id++;
}
const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørda... |
Remove the "only" of the test file :( | 'use strict';
var Converter = require('..');
var fs = require('fs');
describe('Test JCAMP converter of GCMS', function () {
var result = Converter.convert(fs.readFileSync(__dirname + '/data/misc/gcms.jdx').toString());
var gcms=result.gcms;
it('Check content', function () {
gcms.should.keys(['... | 'use strict';
var Converter = require('..');
var fs = require('fs');
describe.only('Test JCAMP converter of GCMS', function () {
var result = Converter.convert(fs.readFileSync(__dirname + '/data/misc/gcms.jdx').toString());
var gcms=result.gcms;
it('Check content', function () {
gcms.should.ke... |
Update message/response test to use new API | const assert = require('assert');
const expect = require('chai').expect;
const Doorman = require('../lib/doorman');
const Service = require('../lib/service');
const EventEmitter = require('events').EventEmitter;
describe('Doorman', function () {
it('should expose a constructor', function () {
assert(Doorman in... | const assert = require('assert');
const expect = require('chai').expect;
const Doorman = require('../lib/doorman');
const Service = require('../lib/service');
const EventEmitter = require('events').EventEmitter;
describe('Doorman', function () {
it('should expose a constructor', function () {
assert(Doorman in... |
Remove a commented out, unused import | package types
import (
"time"
"github.com/joshheinrichs/geosource/server/types/fields"
)
type PostInfo struct {
Id string `json:"id" gorm:"column:p_postid"`
CreatorId string `json:"creator" gorm:"column:p_userid_creator"`
Channel string `json:"channel" gorm:"column:p_channelname"`
Title s... | package types
import (
"time"
"github.com/joshheinrichs/geosource/server/types/fields"
)
// "github.com/joshheinrichs/geosource/server/transactions"
type PostInfo struct {
Id string `json:"id" gorm:"column:p_postid"`
CreatorId string `json:"creator" gorm:"column:p_userid_creator"`
Channel string... |
Add test for same length, same letters, different letter instance counts
One possible solution to detecting an anagram might be to check to see if the words are the same length and that each letter from the first word is contained in the second word. This additional test would guard against that solution appearing to ... | var Anagram = require('./anagram');
describe('Anagram', function() {
it("no matches",function() {
var detector = new Anagram("diaper");
var matches = detector.match([ "hello", "world", "zombies", "pants"]);
expect(matches).toEqual([]);
});
xit("detects simple anagram",function() {
var detector ... | var Anagram = require('./anagram');
describe('Anagram', function() {
it("no matches",function() {
var detector = new Anagram("diaper");
var matches = detector.match([ "hello", "world", "zombies", "pants"]);
expect(matches).toEqual([]);
});
xit("detects simple anagram",function() {
var detector ... |
Change to a secret secret key | from .common import *
import dj_database_url
# Settings for production environment
DEBUG = False
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/projec... | from .common import *
import dj_database_url
# Settings for production environment
DEBUG = False
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/projec... |
Revert "Remove unnecessary and broken DELETE check."
This reverts commit 7906153b4718f34ed31c193a8e80b171e567209c.
Reverting commit accidentally commited straight to develop. | from django import forms
from go.router.view_definition import RouterViewDefinitionBase, EditRouterView
class KeywordForm(forms.Form):
keyword = forms.CharField()
target_endpoint = forms.CharField()
class BaseKeywordFormSet(forms.formsets.BaseFormSet):
@staticmethod
def initial_from_config(data):
... | from django import forms
from go.router.view_definition import RouterViewDefinitionBase, EditRouterView
class KeywordForm(forms.Form):
keyword = forms.CharField()
target_endpoint = forms.CharField()
class BaseKeywordFormSet(forms.formsets.BaseFormSet):
@staticmethod
def initial_from_config(data):
... |
Remove obsolete entry from eslint config. | module.exports = {
extends: [
"plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
"plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
"plugin:prettier/recommended" // Enables eslint-plugin-prettier a... | module.exports = {
extends: [
"plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
"plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
"plugin:prettier/recommended", // Enables eslint-plugin-prettier ... |
Remove crypto config from packagerOptions options to fix CI | 'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
const self = defaults.project.findAddonByName('ember-a11y-testing');
const autoImport = self.options.autoImport;
let app = new EmberAddon(defaults, {
autoImport,
});
/*
This build... | 'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
const self = defaults.project.findAddonByName('ember-a11y-testing');
const autoImport = self.options.autoImport;
let app = new EmberAddon(defaults, {
autoImport,
});
/*
This build... |
BAP-1027: Upgrade Symfony to version 2.3
- fix code style | <?php
namespace Oro\Bundle\DataAuditBundle\Entity\Repository;
use Gedmo\Loggable\Entity\Repository\LogEntryRepository;
use Gedmo\Tool\Wrapper\EntityWrapper;
class AuditRepository extends LogEntryRepository
{
public function getLogEntriesQueryBuilder($entity)
{
$wrapped = new EntityWrapper($entity... | <?php
namespace Oro\Bundle\DataAuditBundle\Entity\Repository;
use Gedmo\Loggable\Entity\Repository\LogEntryRepository;
use Gedmo\Tool\Wrapper\EntityWrapper;
class AuditRepository extends LogEntryRepository
{
public function getLogEntriesQueryBuilder($entity)
{
$wrapped = new EntityWrapper($entity... |
Change the text format for drawing a stroke. To use 5 digits but not 8 digits to present a point. | class TextCodec:
def __init__(self):
pass
def encodeStartPoint(self, p):
return "0{0[0]:02X}{0[1]:02X}".format(p)
def encodeEndPoint(self, p):
return "1{0[0]:02X}{0[1]:02X}".format(p)
def encodeControlPoint(self, p):
return "2{0[0]:02X}{0[1]:02X}".format(p)
def encodeStrokeExpression(self, pointExpress... | class TextCodec:
def __init__(self):
pass
def encodeStartPoint(self, p):
return "0000{0[0]:02X}{0[1]:02X}".format(p)
def encodeEndPoint(self, p):
return "0001{0[0]:02X}{0[1]:02X}".format(p)
def encodeControlPoint(self, p):
return "0002{0[0]:02X}{0[1]:02X}".format(p)
def encodeStrokeExpression(self, poi... |
Remove referencetree-related imports from the top level vytree package. | # vytree.__init__: package init file.
#
# Copyright (C) 2014 VyOS Development Group <maintainers@vyos.net>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# ver... | # vytree.__init__: package init file.
#
# Copyright (C) 2014 VyOS Development Group <maintainers@vyos.net>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# ver... |
Fix 64bit EUID conversion from String and comparing in Comparator | package com.rehivetech.beeeon;
import android.text.TextUtils;
import java.math.BigInteger;
import java.util.Comparator;
public class IdentifierComparator implements Comparator<IIdentifier> {
@Override
public int compare(IIdentifier lhs, IIdentifier rhs) {
return compareNumericIds(lhs, rhs);
}
public static i... | package com.rehivetech.beeeon;
import android.text.TextUtils;
import java.util.Comparator;
public class IdentifierComparator implements Comparator<IIdentifier> {
@Override
public int compare(IIdentifier lhs, IIdentifier rhs) {
return compareNumericIds(lhs, rhs);
}
public static int compareNumericIds(IIdentif... |
Use ellipsis character instead of three points | // In a real use case, the endpoint could point to another origin.
var LOG_ENDPOINT = 'report/logs';
// The code in `oninstall` and `onactive` force the service worker to
// control the clients ASAP.
self.oninstall = function(event) {
event.waitUntil(self.skipWaiting());
};
self.onactivate = function(event) {
eve... | // In a real use case, the endpoint could point to another origin.
var LOG_ENDPOINT = 'report/logs';
// The code in `oninstall` and `onactive` force the service worker to
// control the clients ASAP.
self.oninstall = function(event) {
event.waitUntil(self.skipWaiting());
};
self.onactivate = function(event) {
eve... |
Fix failing test on Python 3 | import click
from django.core.exceptions import ObjectDoesNotExist
class ModelInstance(click.ParamType):
def __init__(self, qs):
from django.db import models
if isinstance(qs, type) and issubclass(qs, models.Model):
qs = qs.objects.all()
self.qs = qs
self.name = '{}.{... | import click
from django.core.exceptions import ObjectDoesNotExist
class ModelInstance(click.ParamType):
def __init__(self, qs):
from django.db import models
if isinstance(qs, type) and issubclass(qs, models.Model):
qs = qs.objects.all()
self.qs = qs
self.name = '{}.{... |
Remove unnecessary full class qualification | package org.codeswarm.lipsum;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
/**
* A {@link Lipsum.ParagraphGenerator} implementation backed by an {@link STGroup}.
*/
class STGroupParagraphGenerator implements Lipsum.ParagraphGenerator {
interface TemplateNames {
int getMinIndex();
... | package org.codeswarm.lipsum;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
/**
* A {@link org.codeswarm.lipsum.Lipsum.ParagraphGenerator} implementation backed by an {@link STGroup}.
*/
class STGroupParagraphGenerator implements Lipsum.ParagraphGenerator {
interface TemplateNames {
... |
Use json naming standards instead of camelCase | from pprint import pprint
#[{u'accountId': 2,
#u'add': True,
#u'broadcastUri': u'vlan://untagged',
#u'firstIP': False,
#u'networkRate': 200,
#u'newNic': False,
#u'nicDevId': 1,
#u'oneToOneNat': False,
#u'publicIp': u'10.0.2.102',
#u'sourceNat': True,
#u'trafficType': u'Public',
#u'vifMacAddress': ... | from pprint import pprint
#[{u'accountId': 2,
#u'add': True,
#u'broadcastUri': u'vlan://untagged',
#u'firstIP': False,
#u'networkRate': 200,
#u'newNic': False,
#u'nicDevId': 1,
#u'oneToOneNat': False,
#u'publicIp': u'10.0.2.102',
#u'sourceNat': True,
#u'trafficType': u'Public',
#u'vifMacAddress': ... |
Add spacing to isNumeric function. | /**
* Utility function related to checking if a given value is numeric.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* 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... | /**
* Utility function related to checking if a given value is numeric.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* 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... |
Use empty test driver for test that doesn't need Mocha | var selftest = require('../tool-testing/selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("'meteor test --port' accepts/rejects proper values", function () {
var s = new Sandbox();
var run;
s.createApp("myapp", "standard-app");
s.cd("myapp");
s.set("")
var runAddPackage = s.run("add", "tmeas... | var selftest = require('../tool-testing/selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("'meteor test --port' accepts/rejects proper values", function () {
var s = new Sandbox();
var run;
s.createApp("myapp", "standard-app");
s.cd("myapp");
var runAddPackage = s.run("add", "meteortesting:moc... |
Write out the content of each file in a closure with module and exports defined | var http = require('http'),
fs = require('fs'),
util = require('./util')
// require.paths.unshift('.')
var modules = {},
port = 1234,
host = 'localhost'
var closureStart = '(function() {',
moduleDef = 'var module = {exports:{}}; var exports = module.exports;',
closureEnd = '\n})()'
moduleDef += 'var require =... | var http = require('http'),
fs = require('fs'),
util = require('./util')
// require.paths.unshift('.')
var modules = {},
port = 1234,
host = 'localhost'
var server = http.createServer(function(req, res) {
if (req.url.match(/\.js$/)) {
fs.readFile(req.url, function(err, content) {
if (err) { return res.end(... |
Fix it gau! oh godgp | window.onload = function() {
d3.json("examples/data/gitstats.json", function(data) {
data.forEach(function(d) {
d.date = new Date(d.date);
d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name;
});
var dataset = {data: data, metadata: {}};
var commitSVG = d3.select("#intro-chart");
... | window.onload = function() {
d3.json("../examples/data/gitstats.json", function(data) {
data.forEach(function(d) {
d.date = new Date(d.date);
d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name;
});
var dataset = {data: data, metadata: {}};
var commitSVG = d3.select("#intro-chart")... |
Add invoice pay and update methods | <?php
class Stripe_Invoice extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_s... | <?php
class Stripe_Invoice extends Stripe_ApiResource
{
public static function constructFrom($values, $apiKey=null)
{
$class = get_class();
return self::scopedConstructFrom($class, $values, $apiKey);
}
public static function retrieve($id, $apiKey=null)
{
$class = get_class();
return self::_s... |
Fix react error in NodeDetailsControls | const React = require('react');
const NodeControlButton = require('./node-control-button');
const NodeDetailsControls = React.createClass({
render: function() {
let spinnerClassName = 'fa fa-circle-o-notch fa-spin';
if (this.props.pending) {
spinnerClassName += ' node-details-controls-spinner';
}... | const React = require('react');
const NodeControlButton = require('./node-control-button');
const NodeDetailsControls = React.createClass({
render: function() {
let spinnerClassName = 'fa fa-circle-o-notch fa-spin';
if (this.props.pending) {
spinnerClassName += ' node-details-controls-spinner';
}... |
Remove duplicated lines in test | <?php
namespace Relay;
use ArrayObject;
use InvalidArgumentException;
use Traversable;
class RelayBuilderTest extends \PHPUnit\Framework\TestCase
{
protected $relayBuilder;
protected function setUp()
{
$this->relayBuilder = new RelayBuilder();
}
public function testArray()
{
... | <?php
namespace Relay;
use ArrayObject;
use InvalidArgumentException;
use Traversable;
class RelayBuilderTest extends \PHPUnit\Framework\TestCase
{
protected $relayBuilder;
protected function setUp()
{
$this->relayBuilder = new RelayBuilder();
}
public function testArray()
{
... |
Add a clip to the frameless example | """
===============================
Plotting a Map without any Axes
===============================
This examples shows you how to plot a Map without any annotations at all, i.e.
to save as an image.
"""
##############################################################################
# Start by importing the necessary m... | """
===============================
Plotting a Map without any Axes
===============================
This examples shows you how to plot a Map without any annotations at all, i.e.
to save as an image.
"""
##############################################################################
# Start by importing the necessary m... |
Print Preview: Hook up the cancel button.
BUG=57895
TEST=manual
Review URL: http://codereview.chromium.org/5151009
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@66822 0039d316-1c4b-4281-b951-d872f2087c98 | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
$('cancel-button').addEventListener('c... | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
chrome.send('getPrinters');
};
/**
*... |
Use call checker to ensure both writeFile calls go through before killing the mock | var should = require('should');
var sinon = require('sinon');
var tasks = require('../tasks.js');
var fs = require('fs');
var dataKeys = {
inProgress: ['toExec', 'resultsFile', 'startedAt', 'inProgress'],
success: ['toExec', 'resultsFile', 'startedAt', 'inProgress', 'finishedAt', 'stdout', 'stderr', 'success'],
... | var should = require('should');
var sinon = require('sinon');
var tasks = require('../tasks.js');
var fs = require('fs');
var dataKeys = {
inProgress: ['toExec', 'resultsFile', 'startedAt', 'inProgress'],
success: ['toExec', 'resultsFile', 'startedAt', 'inProgress', 'finishedAt', 'stdout', 'stderr', 'success'],
... |
Add support for data: Uri scheme to RCTImageView (e.g. base64-encoded images)
Summary: ImageRequestHelper was not handling data: scheme correctly, which resulted in images failing to load. This diff is fixing it by considering \"data:\" as a Uri resource, and piping it appropriately.
Reviewed By: sriramramani
Differ... | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package co... | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package co... |
Add better logging to see when wasm is loaded | //only exports browser api. use chloride module
//to get automatic fallbacks!
//load tweetnacl first, so that it works sync, and everything is there.
var exports = require('sodium-browserify-tweetnacl')
for(var k in exports) (function (k) {
if('function' == typeof exports[k])
//functions that wrap references to... |
//only exports browser api. use chloride module
//to get automatic fallbacks!
//load tweetnacl first, so that it works sync, and everything is there.
var exports = require('sodium-browserify-tweetnacl')
for(var k in exports) (function (k) {
if('function' == typeof exports[k])
//functions that wrap references t... |
Refactor and clean up for demo
Messages may be request scoped | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package eu.agilejava.mvc.prg;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.... | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package eu.agilejava.mvc.prg;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Name... |
Update docs on selection sort | import java.util.Arrays;
public class SelectionSort {
/**
* Selection Sort is an in-place comparison sort.
* Selection Sort has O(n^2) time complexity.
*/
public int[] selection_sort(int[] arr) {
int min, temp;
/* find the min element in the unsorted array */
for (int i = 0; i < arr.length; i++... | import java.util.Arrays;
public class SelectionSort {
/**
* Selection Sort is an in-place comparison sort.
* It has O(n^2) time complexity.
*/
public int[] selection_sort(int[] arr) {
int min, temp;
/* find the min element in the unsorted array */
for (int i = 0; i < arr.length; i++) {
/*... |
Fix import, use fileinput.iput as context, and fix its argument | #! /usr/bin/env python3
""" Helper functions to make our life easier.
Originally obtained from the 'pharm' repository, but modified.
"""
import fileinput
import json
import os.path
import sys
from dstruct.Sentence import Sentence
## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.p... | #! /usr/bin/env python3
""" Helper functions to make our life easier.
Originally obtained from the 'pharm' repository, but modified.
"""
import fileinput
import json
import os.path
from dstruct import Sentence
## BASE_DIR denotes the application directory
BASE_DIR, throwaway = os.path.split(os.path.realpath(__file_... |
Add missing api key in product picker.
Fixes #6185 | $.fn.productAutocomplete = function () {
'use strict';
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(','),
token: Spree.api_key
}, function (data) {
ca... | $.fn.productAutocomplete = function () {
'use strict';
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(',')
}, function (data) {
callback(data.products);
}... |
Establish different settings for minimal port | from weblab.admin.script import Creation
APACHE_CONF_NAME = 'apache.conf'
MIN_PORT = 14000
DEFAULT_DEPLOYMENT_SETTINGS = {
Creation.COORD_ENGINE: 'redis',
Creation.COORD_REDIS_DB: 0,
Creation.COORD_REDIS_PORT: 6379,
Creation.DB_ENGINE: 'mysql',
Creation.ADMIN_USER: 'CHANGE_ME', # --admin-user=admi... | from weblab.admin.script import Creation
APACHE_CONF_NAME = 'apache.conf'
MIN_PORT = 10000
DEFAULT_DEPLOYMENT_SETTINGS = {
Creation.COORD_ENGINE: 'redis',
Creation.COORD_REDIS_DB: 0,
Creation.COORD_REDIS_PORT: 6379,
Creation.DB_ENGINE: 'mysql',
Creation.ADMIN_USER: 'CHANGE_ME', # --admin-user=admi... |
Fix bad URL schema for list that would could direct URL with no ID not to always match |
angular.module('app')
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
// TODO: Enable this when server is properly configured
// $locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider
.state('index', {
url: '/',
templateUrl: 'partials/index.html',
... |
angular.module('app')
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
// TODO: Enable this when server is properly configured
// $locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider
.state('index', {
url: '/',
templateUrl: 'partials/index.html',
... |
Improve phone regex validation feedback | document.addEventListener('DOMContentLoaded', function () {
var phoneFormGroup = document.getElementById('phone-form-group')
var phone = document.getElementById('phone')
var message = document.getElementById('phoneLengthMessage')
var phoneRegex = /^[6, 8, 9]\d{7}$/
function checkPhone () {
if (phoneRegex... | document.addEventListener('DOMContentLoaded', function () {
var phoneFormGroup = document.getElementById('phone-form-group')
var phone = document.getElementById('phone')
var message = document.getElementById('phoneLengthMessage')
var phoneRegex = /^[6, 8, 9]\d{7}$/
function checkPhone () {
if (phoneRegex... |
Fix wrong login return page for tracker URLs | <?php
declare(strict_types = 1);
namespace Pages\Controllers\Mixed;
use Database\Objects\TrackerInfo;
use Generator;
use Pages\Controllers\AbstractHandlerController;
use Pages\Controllers\Handlers\OptionallyLoadTracker;
use Pages\Controllers\Handlers\RequireLoginState;
use Pages\IAction;
use Pages\Models\Mixed\LoginM... | <?php
declare(strict_types = 1);
namespace Pages\Controllers\Mixed;
use Database\Objects\TrackerInfo;
use Generator;
use Pages\Controllers\AbstractHandlerController;
use Pages\Controllers\Handlers\OptionallyLoadTracker;
use Pages\Controllers\Handlers\RequireLoginState;
use Pages\IAction;
use Pages\Models\Mixed\LoginM... |
Improve meetup's validation error messages | from django.db import models
from pizzaplace.models import PizzaPlace
from django.core.validators import RegexValidator
from meetup.services.meetup_api_lookup_agent import MeetupApiLookupAgent
from django.core.exceptions import ValidationError
from model_utils.models import TimeStampedModel
def validate_urlname(link):... | from django.db import models
from pizzaplace.models import PizzaPlace
from django.core.validators import RegexValidator
from meetup.services.meetup_api_lookup_agent import MeetupApiLookupAgent
from django.core.exceptions import ValidationError
def validate_urlname(link):
validator = RegexValidator(
regex='meetu... |
Change method 'alias' to 'bind' for provide facade | <?php
namespace AndrewNovikof\Objects;
use Illuminate\Support\ServiceProvider;
/**
* Class ObjectsServiceProvider
* @package Objects
*/
class ObjectsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
... | <?php
namespace AndrewNovikof\Objects;
use Illuminate\Support\ServiceProvider;
/**
* Class ObjectsServiceProvider
* @package Objects
*/
class ObjectsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
... |
Check user detail in test | # -*- coding: utf-8 -*-
import pytest
from .utils import get, versioned_reverse as reverse, assert_fields_exist
# === util methods ===
def get_list(api_client, version='v1'):
list_url = reverse('user-list', version=version)
return get(api_client, list_url)
def get_detail(api_client, detail_pk, version='v1')... | # -*- coding: utf-8 -*-
import pytest
from .utils import get, versioned_reverse as reverse, assert_fields_exist
# === util methods ===
def get_list(api_client, version='v1'):
list_url = reverse('user-list', version=version)
return get(api_client, list_url)
def assert_user_fields_exist(data, version='v1'):
... |
Reduce intermediate variables with merge function. | var merge = function(a, b){
var f = function(){};
f.prototype = a;
var c = new f();
for (var k in b) { if (b.hasOwnProperty(k)) {
c[k] = b[k];
}}
return c;
};
var defaultMappings = {
matchHost: '',
matchPath: '',
host: 'localhost',
port: 80
};
exports.resolve = function(mappings, request){
v... | var clone = function(o){
var f = function(){};
f.prototype = o;
return new f();
};
exports.resolve = function(mappings, request){
var host = (request.headers.host || '').split(':')[0];
var downstream;
for (var i = 0; i < mappings.length; i++) {
var m = mappings[i];
if (host.match(m.matchHost || ''... |
Improve default params handling on Middleware.response. | const res = response => Promise.resolve(response);
const rej = err => Promise.reject(err);
class Middleware {
constructor() {
this._req = [];
this._res = [];
}
request(fn) {
this._req.push(fn);
return this._req.length - 1;
}
response(fulfill = res, reject = rej) {
this._res.push({ fulfi... |
class Middleware {
constructor() {
this._req = [];
this._res = [];
}
request(fn) {
this._req.push(fn);
return this._req.length - 1;
}
response(fulfill, reject) {
fulfill || (fulfill = res => Promise.resolve(res));
reject || (reject = err => Promise.reject(err));
this._res.pus... |
Remove pytest-runner from install requirements, add numpy as test requirement | from setuptools import setup
version = "0.5.1"
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="arxiv",
version=version,
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
],
tests_require=[
"pytest",
"... | from setuptools import setup
version = "0.5.1"
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="arxiv",
version=version,
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
'pytest-runner',
],
tests_requi... |
Add UTC manipulation of dates for to and froms | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import moment from 'moment';
import { UIDatabase } from '../database';
import { FRIDGE_ACTIONS } from '../actions/FridgeActions';
const initialState = () => {
const fridges = UIDatabase.objects('Location');
return {
fridges,
selectedFridge... | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import moment from 'moment';
import { UIDatabase } from '../database';
import { FRIDGE_ACTIONS } from '../actions/FridgeActions';
const initialState = () => {
const fridges = UIDatabase.objects('Location');
return {
fridges,
selectedFridge... |
TASK: Exit value depending on the error number | <?php
namespace MStruebing\EditorconfigChecker;
use MStruebing\EditorconfigChecker\Cli\Cli;
use MStruebing\EditorconfigChecker\Cli\Logger;
$cliPath = dirname(__FILE__) . '/Cli/Cli.php';
$loggerPath = dirname(__FILE__) . '/Cli/Logger.php';
if (is_file($cliPath)) {
include_once $cliPath;
} else {
throw new \E... | <?php
namespace MStruebing\EditorconfigChecker;
use MStruebing\EditorconfigChecker\Cli\Cli;
use MStruebing\EditorconfigChecker\Cli\Logger;
$cliPath = dirname(__FILE__) . '/Cli/Cli.php';
$loggerPath = dirname(__FILE__) . '/Cli/Logger.php';
if (is_file($cliPath)) {
include_once $cliPath;
} else {
throw new \E... |
Add constructor to value encoders
We are adding this so we can extend constructors in subclasses, where needed | <?php
/*
* This file is part of the Active Collab Controller project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
declare(strict_types=1);
namespace ActiveCollab\Controller\ActionResultEncoder\ValueEncoder;
use Psr\Http\Message\StreamInterface;
use Slim\Http\Stream;
abstract class ValueEnc... | <?php
/*
* This file is part of the Active Collab Controller project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
declare(strict_types=1);
namespace ActiveCollab\Controller\ActionResultEncoder\ValueEncoder;
use Psr\Http\Message\StreamInterface;
use Slim\Http\Stream;
abstract class ValueEnc... |
Tidy up gulp jsdoc task | var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
livereload = require('gulp-livereload'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(
jsdoc(docsDestDir,
{
path: 'ink-doc... | var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
livereload = require('gulp-livereload'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(jsdoc.parser({
plugins: ['plugins/markdown']
}))
... |
Replace testing paremeters and implement Routing methods of the FOSJsBundle | $(document).ready(function() {
$('.crud-entity-delete').click(function() {
$('#entity-delete .btn-danger').attr('data-id', $(this).attr('data-id'));
$('#entity-delete .btn-danger').attr('data-entity', $(this).attr('data-entity'));
$('#entity-delete').modal();
return false;
});
... | $(document).ready(function() {
$('.crud-delete').click(function() {
$('#entity-delete .btn-danger').attr('data-id', $(this).attr('data-id'));
$('#entity-delete .btn-danger').attr('data-entity', $(this).attr('data-entity'));
$('#entity-delete').modal();
return false;
});
$('#e... |
Fix bad transposition of utility function in sflow | import struct, socket
def unpack_address(u):
addrtype = u.unpack_uint()
if addrtype == 1:
address = u.unpack_fopaque(4)
if addrtype == 2:
address = u.unpack_fopaque(16)
return address
class IPv4Address(object):
def __init__(self, addr_int):
self.addr_int = addr_int
... | import struct, socket
def unpack_address(u):
addrtype = u.unpack_uint()
if self.addrtype == 1:
self.address = u.unpack_fopaque(4)
if self.addrtype == 2:
self.address = u.unpack_fopaque(16)
return self.address
class IPv4Address(object):
def __init__(self, addr_int):
... |
Rename decorator equality_comparable to equalable | from .equals_builder import EqualsBuilder
from .hash_code_builder import HashCodeBuilder
__all__ = [
'hashable',
'equalable',
]
def hashable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls = equalable(cls, attributes, m... | from .equals_builder import EqualsBuilder
from .hash_code_builder import HashCodeBuilder
__all__ = [
'hashable',
'equality_comparable',
]
def hashable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls = equality_comparabl... |
Clarify that debugging has to be turned on for DB profiling to work.
git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@2619 653ae4dd-d31e-0410-96ef-6bf7bf53c507 |
<!-- footer -->
<div class="clear"></div>
</div>
<hr>
<p id="footer">
<small><?php Options::out('title'); _e(' is powered by'); ?> <a href="http://www.habariproject.org/" title="Habari">Habari</a> <?php _e('and a huge amount of'); ?>
<a href="http://en.wikipedia.org/wiki/Caffeine" title="<?php _e('Caffeine'); ?... |
<!-- footer -->
<div class="clear"></div>
</div>
<hr>
<p id="footer">
<small><?php Options::out('title'); _e(' is powered by'); ?> <a href="http://www.habariproject.org/" title="Habari">Habari</a> <?php _e('and a huge amount of'); ?>
<a href="http://en.wikipedia.org/wiki/Caffeine" title="<?php _e('Caffeine'); ?... |
Change bases of exception classes extending SpamListsError and ValueError
This commit removes SpamListsError and ValueError as direct base classes
of other exception classes (except SpamListsValueError), and replaces
them with SpamListsValueError. | # -*- coding: utf-8 -*-
'''
This module contains all classes of exceptions raised
by the library
'''
from __future__ import unicode_literals
class SpamListsError(Exception):
'''There was an error during testing a url or host'''
class SpamListsValueError(SpamListsError, ValueError):
'''An inapropriate value ... | # -*- coding: utf-8 -*-
'''
This module contains all classes of exceptions raised
by the library
'''
from __future__ import unicode_literals
class SpamListsError(Exception):
'''There was an error during testing a url or host'''
class SpamListsValueError(SpamListsError, ValueError):
'''An inapropriate value ... |
Add native type to boolean fields | <?php
/*
* This file is part of the Active Collab DatabaseStructure project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\DatabaseStructure\Field\Scalar;
use LogicException;
/**
* @package ActiveCollab\DatabaseStructure\Field\Scalar
*/
class BooleanField extends Fiel... | <?php
/*
* This file is part of the Active Collab DatabaseStructure project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\DatabaseStructure\Field\Scalar;
use LogicException;
/**
* @package ActiveCollab\DatabaseStructure\Field\Scalar
*/
class BooleanField extends Fiel... |
Revert "Fix broken test in PHP 5.4"
This reverts commit 60a6a6943c76a783f0251245b8a3919d86640f6b. | <?php
namespace Test;
// \HttpMessage
use Kambo\HttpMessage\Uri;
use Kambo\HttpMessage\Factories\String\UriFactory;
/**
* Unit test for the UriFactory object.
*
* @package Test
* @author Bohuslav Simek <bohuslav@simek.si>
* @license MIT
*/
class UriFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
... | <?php
namespace Test;
// \HttpMessage
use Kambo\HttpMessage\Uri;
use Kambo\HttpMessage\Factories\String\UriFactory;
/**
* Unit test for the UriFactory object.
*
* @package Test
* @author Bohuslav Simek <bohuslav@simek.si>
* @license MIT
*/
class UriFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
... |
Add DAG & non-DAG adjacency dicts | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _previsit():
pass
def _postvisit():
pass
def _dfs_explore():
pass
def check_dag():
"""Check Directed Acyclic Graph (DAG)."""
pass
def main():
# Graph adjacency dictionary for D... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _previsit():
pass
def _postvisit():
pass
def _dfs_explore():
pass
def check_dag():
"""Check Directed Acyclic Graph (DAG)."""
pass
def main():
# DAG.
dag_adj_d = {
'... |
Clean up route handling so it's more readable. | 'use strict';
const express = require('express');
const BodyParser = require('body-parser');
const Handlers = require('../util').Handlers;
const Err = require('../util').Err;
exports.attach = function (app, storage) {
app.get('/v1/health', require('./health'));
app.get('/v1/token/default', require('./token')(sto... | 'use strict';
const express = require('express');
const BodyParser = require('body-parser');
const Handlers = require('../util').Handlers;
const Err = require('../util').Err;
exports.attach = function (app, storage) {
app.get('/v1/health', require('./health'));
app.use('/v1/health', Handlers.allowed('GET'));
a... |
Improve thread safety around adding and removing IDataListener's
Previously deadlock was possible if a listener was running in the same
thread as a call attempting to add or remove listeners. As might be
commonly the case for the UI thread.
Also replaced the listeners List with a Set to prevent duplicate
listeners be... | /*-
* Copyright 2015, 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.... | /*-
* Copyright 2015, 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.... |
Fix bug on travis CI | import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
import configs from '../config/config';
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'test';
const config = configs[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize =... | import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
import configs from '../config/config';
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'development';
const config = configs[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequ... |
Mark internal classes final where possible | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\Php54;
/**
* @author Nicolas Grekas <p@tchwork.com>
... | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\Php54;
/**
* @author Nicolas Grekas <p@tchwork.com>
... |
Use the right step name for profiling | const _ = require('underscore');
module.exports = function dbConnSetup (pgConnection) {
return function dbConnSetupMiddleware (req, res, next) {
const { user } = res.locals;
pgConnection.setDBConn(user, res.locals, (err) => {
req.profiler.done('dbConnSetup');
if (err) {
... | const _ = require('underscore');
module.exports = function dbConnSetup (pgConnection) {
return function dbConnSetupMiddleware (req, res, next) {
const { user } = res.locals;
pgConnection.setDBConn(user, res.locals, (err) => {
req.profiler.done('setDBConn');
if (err) {
... |
Remove unused foundation JS components. | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... |
Put both the window URL and the test URL through an anchor.
Fixes an inconsistency in IE between a.href and window.location about whether default ports are included or not. | /*global define*/
define(function() {
"use strict";
var a;
/**
* Given a URL, determine whether that URL is considered cross-origin to the current page.
*
* @private
*/
var isCrossOriginUrl = function(url) {
if (typeof a === 'undefined') {
a = document.createEle... | /*global define*/
define(function() {
"use strict";
var a;
/**
* Given a URL, determine whether that URL is considered cross-origin to the current page.
*
* @private
*/
var isCrossOriginUrl = function(url) {
if (typeof a === 'undefined') {
a = document.createEle... |
Add Python3 classfier fo CheeseShop. | #!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
... | #!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
... |
Fix expose API host env | module.exports = {
/*
** Headers of the page
*/
head: {
title: 'client',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [{ rel: 'icon', type: 'i... | module.exports = {
/*
** Headers of the page
*/
head: {
title: 'client',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [{ rel: 'icon', type: 'i... |
Add check for OS - this gives errors on Mac as-is | <?php
/**
* PHP Command Line Tools
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*
* @author James Logsdon <dwarf@girsbrain.org>
* @copyright 2010 James Logsdom (http://girsbrain.org)
* @license http://www.opensource.org/licenses/mit-license.php... | <?php
/**
* PHP Command Line Tools
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*
* @author James Logsdon <dwarf@girsbrain.org>
* @copyright 2010 James Logsdom (http://girsbrain.org)
* @license http://www.opensource.org/licenses/mit-license.php... |
Fix an imports ordering problem | # coding: utf-8
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.template.response import TemplateResponse
from django.views.decorators.cache import cache_page... | # coding: utf-8
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.shortcuts import render
from django.views.decorators.cache import cache_page... |
Fix StatsRequest body type; add default values | """Query the datapath about its current state."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.foundation.basic_types import BinaryData, UBInt16
# Local imports
from pyof.v0x01.common.header import Header, Type
from pyof.v0x01.controller2switch.common import StatsT... | """Query the datapath about its current state."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.foundation.basic_types import ConstantTypeList, UBInt16
# Local imports
from pyof.v0x01.common.header import Header, Type
from pyof.v0x01.controller2switch.common import ... |
Refactor following storage's api backend change | # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_ha... | # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_ha... |
Move confirm call directly in the if statement | import { bind } from 'decko';
import React from 'react';
import { findDOMNode } from 'react-dom';
/**
* A modal dialog window.
*/
class Dialog extends React.Component {
componentDidMount () {
this.elDialog = findDOMNode(this.refs.dialog);
document.body.addEventListener('keydown', this.onEsc);
}
compo... | import { bind } from 'decko';
import React from 'react';
import { findDOMNode } from 'react-dom';
/**
* A modal dialog window.
*/
class Dialog extends React.Component {
componentDidMount () {
this.elDialog = findDOMNode(this.refs.dialog);
document.body.addEventListener('keydown', this.onEsc);
}
compo... |
Test for getting undefined/null values | var vows = require('vows'),
assert = require('assert'),
get = require('../src/get');
vows.describe('get()').addBatch({
'Getting': {
topic: function() {
return {
foo: 1,
undef: undefined,
nil: null
};
},
'an existing property returns the value': function(obj) {
... | var vows = require('vows'),
assert = require('assert'),
get = require('../src/get');
vows.describe('get()').addBatch({
'Getting': {
topic: function() {
return {
foo: 1
};
},
'an existing property returns the value': function(obj) {
assert.equal(get(obj, 'foo'), 1);
}... |
Add default options for import functionality | const path = require('path');
const logger = require('./logger');
const addMetadata = (res, filepath) => {
if (res.constructor === Array) {
return res.map(item => {
item.file = filepath;
return item;
});
} else {
res.file = filepath;
return res;
}
};
module.exports = {
import: (filePath, { strict =... | const path = require('path');
const logger = require('./logger');
const addMetadata = (res, filepath) => {
if (res.constructor === Array) {
return res.map(item => {
item.file = filepath;
return item;
});
} else {
res.file = filepath;
return res;
}
};
module.exports = {
import: (filePath, { strict =... |
Watch config.Source instead of config.Output
Fixes an issue which caused the watcher to not trigger re-builds, as it
was incorrectly watching the output folder. | // (c) 2012 Alexander Solovyov
// under terms of ISC license
package main
import (
"github.com/howeyc/fsnotify"
"os"
"path/filepath"
)
func Watcher(config *SiteConfig) (chan string, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
ch := make(chan string, 10)
go func() {
... | // (c) 2012 Alexander Solovyov
// under terms of ISC license
package main
import (
"github.com/howeyc/fsnotify"
"os"
"path/filepath"
)
func Watcher(config *SiteConfig) (chan string, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
ch := make(chan string, 10)
go func() {
... |
Add comments to explain what the script is doing on ingest | ## A quick script to fix the ridiculous format of the raw FAA download data (at least it's available though!)
import csv
# MASTER.txt is from https://www.faa.gov/licenses_certificates/aircraft_certification/aircraft_registry/releasable_aircraft_download/
with open("MASTER.txt") as orig_file:
orig_file_reader = cs... | ## A quick script to fix the ridiculous format of the raw FAA download data (at least it's available though!)
import csv
# MASTER.txt is from https://www.faa.gov/licenses_certificates/aircraft_certification/aircraft_registry/releasable_aircraft_download/
with open("MASTER.txt") as orig_file:
orig_file_reader = cs... |
Fix of the cosinue test for the negative rounding error. | <?php
use Litipk\BigNumbers\Decimal as Decimal;
/**
* @group cos
*/
class DecimalCosTest extends PHPUnit_Framework_TestCase
{
public function cosProvider() {
// Some values provided by Mathematica
return array(
array('1', '0.54030230586814', 14),
array('123.123', '-0.8248... | <?php
use Litipk\BigNumbers\Decimal as Decimal;
/**
* @group cos
*/
class DecimalCosTest extends PHPUnit_Framework_TestCase
{
public function cosProvider() {
// Some values provided by Mathematica
return array(
array('1', '0.54030230586814', 14),
array('123.123', '-0.8248... |
Add missing Google Analytics env vars | "use strict";
const isCi = require('is-ci');
const jwtSigningKey = process.env.jwtSigningKey ? new Buffer(process.env.jwtSigningKey, 'base64') : '' ;
const dbConfig = {
host: process.env.DB_HOST || '127.0.0.1',
port: process.env.DB_PORT || '5432',
database: process.env.DB_DATABASE || 'postgres',
username: pr... | "use strict";
const isCi = require('is-ci');
const jwtSigningKey = process.env.jwtSigningKey ? new Buffer(process.env.jwtSigningKey, 'base64') : '' ;
const dbConfig = {
host: process.env.DB_HOST || '127.0.0.1',
port: process.env.DB_PORT || '5432',
database: process.env.DB_DATABASE || 'postgres',
username: pr... |
Stop force clearing the dom when gelato is preparing it. | var Application = require('application');
module.exports = (function() {
function prepareDOM() {
document.body.appendChild(document.createElement('gelato-application'));
document.body.appendChild(document.createElement('gelato-dialogs'));
document.body.appendChild(document.createElement('g... | var Application = require('application');
module.exports = (function() {
function prepareDOM() {
document.body.innerHTML = '';
document.body.appendChild(document.createElement('gelato-application'));
document.body.appendChild(document.createElement('gelato-dialogs'));
document.body... |
Use standard toObject and fromObject methods
git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@64810 6b8eccd3-e8c5-4e7d-8186-e12b5326b719 | <?php
/**
* Clip operation attributes
*
* @package api
* @subpackage objects
*/
class KalturaClipAttributes extends KalturaOperationAttributes
{
/**
* Offset in milliseconds
* @var int
*/
public $offset;
/**
* Duration in milliseconds
* @var int
*/
public $duration;
public... | <?php
/**
* Clip operation attributes
*
* @package api
* @subpackage objects
*/
class KalturaClipAttributes extends KalturaOperationAttributes
{
/**
* Offset in milliseconds
* @var int
*/
public $offset;
/**
* Duration in milliseconds
* @var int
*/
public $duration;
public... |
Replace `cls` argument with `self`
Not sure if this was originally intended to be a `@classmethod` but it's now written and called as a method bound to an instance of the class. | from datetime import datetime, date
from sqlalchemy import Integer, UnicodeText, Float, BigInteger
from sqlalchemy import Boolean, Date, DateTime, Unicode
from sqlalchemy.types import TypeEngine
class Types(object):
"""A holder class for easy access to SQLAlchemy type names."""
integer = Integer
string =... | from datetime import datetime, date
from sqlalchemy import Integer, UnicodeText, Float, BigInteger
from sqlalchemy import Boolean, Date, DateTime, Unicode
from sqlalchemy.types import TypeEngine
class Types(object):
"""A holder class for easy access to SQLAlchemy type names."""
integer = Integer
string =... |
Test passes a seqJS.Seq, not String | /*global seqJS:true */
(function() {
/*
======== A Handy Little QUnit Reference ========
http://api.qunitjs.com/
Test methods:
module(name, {[setup][ ,teardown]})
test(name, callback)
expect(numberOfequalions)
stop(increment)
start(decrement)
Test equalions:
ok(v... | /*global seqJS:true */
(function() {
/*
======== A Handy Little QUnit Reference ========
http://api.qunitjs.com/
Test methods:
module(name, {[setup][ ,teardown]})
test(name, callback)
expect(numberOfequalions)
stop(increment)
start(decrement)
Test equalions:
ok(v... |
Remove PIL and docutils from requirements, easy_thumbnails requires it anyway | from distutils.core import setup
from setuptools import setup, find_packages
setup(name = "django-image-cropping",
version = "0.3.0",
description = "A reusable app for cropping images easily and non-destructively in Django",
long_description=open('README.rst').read(),
author = "jonasvp",
author_ema... | from distutils.core import setup
from setuptools import setup, find_packages
setup(name = "django-image-cropping",
version = "0.3.0",
description = "A reusable app for cropping images easily and non-destructively in Django",
long_description=open('README.rst').read(),
author = "jonasvp",
author_ema... |
Use tabs instead of spaces | <?php
function backTrace($backtrace)
{
foreach ($backtrace as $bt) {
$args = '';
foreach ($bt['args'] as $a) {
if ($args) {
$args .= ', ';
}
if (in_array($bt['function'], array('RawQuery', 'Query', 'FetchResult')) && !$args)
$args .= '"..."';
else
$args .= var_export($a, true);
}
$out... | <?php
function backTrace($backtrace)
{
foreach ($backtrace as $bt) {
$args = '';
foreach ($bt['args'] as $a) {
if ($args) {
$args .= ', ';
}
if (in_array($bt['function'], array('RawQuery', 'Query', 'FetchResult')) && !$args)
$args... |
Add avatar_url property to User. | # coding: utf-8
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from ._base import db
from ..utils.uploadsets import avatars
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
email = db.Co... | # coding: utf-8
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from ._base import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
email = db.Column(db.String(50), unique=True)
av... |
Correct static URL in JS | function hgvsValidation(element) {
if (element.val().length > 2) {
$('#result_' + element.attr('id')).html('<i>Please wait...</i>');
$.get(window.HGVS_URL, { 'code': element.val() }, function(data) {
result = data['parse_result'];
if (result == true) {
result_... | function hgvsValidation(element) {
if (element.val().length > 2) {
$('#result_' + element.attr('id')).html('<i>Please wait...</i>');
$.get(window.HGVS_URL, { 'code': element.val() }, function(data) {
result = data['parse_result'];
if (result == true) {
result_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.