text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add explicit comments in test using reserved binding name | /*jshint -W030 */
var gremlin = require('../');
describe('Bindings', function() {
it('should support bindings with client.execute()', function(done) {
var client = gremlin.createClient();
client.execute('g.v(x)', { x: 1 }, function(err, result) {
(err === null).should.be.true;
result.length.shou... | /*jshint -W030 */
var gremlin = require('../');
describe('Bindings', function() {
it('should support bindings with client.execute()', function(done) {
var client = gremlin.createClient();
client.execute('g.v(x)', { x: 1 }, function(err, result) {
(err === null).should.be.true;
result.length.shou... |
Allow DB migrations source path customization | package buildlog
import (
"fmt"
"log"
"os"
"github.com/mattes/migrate"
"github.com/mattes/migrate/database/postgres"
_ "github.com/mattes/migrate/source/file"
)
type migrationLogger struct {
}
func (m migrationLogger) Verbose() bool {
return false
}
func (m migrationLogger) Printf(format string, v ...interf... | package buildlog
import (
"fmt"
"log"
"github.com/mattes/migrate"
"github.com/mattes/migrate/database/postgres"
_ "github.com/mattes/migrate/source/file"
)
type migrationLogger struct {
}
func (m migrationLogger) Verbose() bool {
return false
}
func (m migrationLogger) Printf(format string, v ...interface{})... |
Fix codestyle by adding a space between string concatenation | <?php
namespace Frisbee\Controller;
use Frisbee\Bootstrap\BootstrapInterface;
use Frisbee\Exception\Flingable;
abstract class AbstractController extends Flingable implements ControllerInterface
{
/**
* @var BootstrapInterface
*/
private $bootstrap;
/**
* @var string
*/
protected ... | <?php
namespace Frisbee\Controller;
use Frisbee\Bootstrap\BootstrapInterface;
use Frisbee\Exception\Flingable;
abstract class AbstractController extends Flingable implements ControllerInterface
{
/**
* @var BootstrapInterface
*/
private $bootstrap;
/**
* @var string
*/
protected ... |
Add compatibility to old uuid key | import has from 'lodash/has';
import isPlainObject from 'lodash/isPlainObject';
import isArray from 'lodash/isArray';
const UUID_KEY_PATTERN = /__.+uuid__/i;
const OLD_KEY = 'zent-design-uuid';
export default function stripUUID(value) {
if (isPlainObject(value)) {
// eslint-disable-next-line
for (const key ... | import has from 'lodash/has';
import isPlainObject from 'lodash/isPlainObject';
import isArray from 'lodash/isArray';
const UUID_KEY_PATTERN = /__.+uuid__/i;
export default function stripUUID(value) {
if (isPlainObject(value)) {
// eslint-disable-next-line
for (const key in value) {
if (has(value, key... |
Fix export collections with sub-collections | function collectionToBookmarkHtml(collection) {
var html = addHeader();
html += "<DL><p>";
html += transformCollection(collection);
html += "</DL><p>";
return html;
}
function collectionsToBookmarkHtml(collections) {
var html = addHeader();
html += "<DL><p>";
$.each(collections, fun... | function collectionToBookmarkHtml(collection) {
var html = addHeader();
html += "<DL><p>";
html += transformCollection(collection);
html += "</DL><p>";
return html;
}
function collectionsToBookmarkHtml(collections) {
var html = addHeader();
html += "<DL><p>";
$.each(collections, fun... |
Resolve XXE vulnerability in XML validation | package manage.validations;
import org.everit.json.schema.FormatValidator;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import jav... | package manage.validations;
import org.everit.json.schema.FormatValidator;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Optional;
public class ... |
Return sorted values for scores | """
Blueprint implementing the API wrapper.
:author: 2013, Pascal Hartig <phartig@weluse.de>
:license: BSD
"""
import json
from flask import Blueprint, request, abort
from .utils import JSONError
from .calc import calculate_scores
api = Blueprint('api', __name__, url_prefix='/v1')
class ScoresResponse(object):
... | """
Blueprint implementing the API wrapper.
:author: 2013, Pascal Hartig <phartig@weluse.de>
:license: BSD
"""
import json
from flask import Blueprint, request, abort
from .utils import JSONError
from .calc import calculate_scores
api = Blueprint('api', __name__, url_prefix='/v1')
class ScoresResponse(object):
... |
Fix wrong display fullName in sophancong gird. | /**
* Created by dungvn3000 on 4/4/14.
*/
Ext.define('sunerp.component.NhanVienCb', {
extend: 'sunerp.component.Combobox',
alias: 'widget.nhanviencb',
gird: null,
valueField: 'maNv',
displayField: 'fullName',
inject: ['userService'],
config: {
userService: null
},
initComp... | /**
* Created by dungvn3000 on 4/4/14.
*/
Ext.define('sunerp.component.NhanVienCb', {
extend: 'sunerp.component.Combobox',
alias: 'widget.nhanviencb',
gird: null,
valueField: 'maNv',
displayField: 'fullName',
inject: ['userService'],
config: {
userService: null
},
initComp... |
Allow reading word list from stdin. | import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
... | import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
... |
Fix parse_requirements call for new pip version. | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
i... | #!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
... |
FIX Неправильно обрабатывались юзеры без дисплейнейма | registerAction(function (node) {
if (!settings["fixNames"]) return;
node = node || document.body;
toArray(node.querySelectorAll(".content > .l_profile, .lbody > .l_profile, .name > .l_profile, .foaf > .l_profile"))
.forEach(function (node) {
var login = node.getAttribute("href").substr(... | registerAction(function (node) {
if (!settings["fixNames"]) return;
node = node || document.body;
toArray(node.querySelectorAll(".content > .l_profile, .lbody > .l_profile, .name > .l_profile, .foaf > .l_profile"))
.forEach(function (node) {
var login = node.getAttribute("href").substr(... |
Change ticker font scale factor to 0.7 | Dashboard.TickerWidget = Dashboard.Widget.extend({
sourceData: "",
templateName: 'ticker_widget',
classNames: ['widget', 'widget-ticker'],
widgetView: function() {
var widget = this;
return this._super().reopen({
didInsertElement: function() {
var scaleFactor = 0.7;
var widgetHeig... | Dashboard.TickerWidget = Dashboard.Widget.extend({
sourceData: "",
templateName: 'ticker_widget',
classNames: ['widget', 'widget-ticker'],
widgetView: function() {
var widget = this;
return this._super().reopen({
didInsertElement: function() {
var scaleFactor = 0.5;
var scaleSourc... |
Comment out rush warning and job score on job event detail | <?php $job = $item->assocObject;?>
<?php $id = 'job_evt_'.$job->ID.$item->ID;?>
<div id="<?php echo $id;?>">
<div class="pad"><?php
$job = $item->getAssocObject();
?>
<?php /* js: hide rush warning
<?php if($job->RUSH){?>
<span class="warning">RUSH</span>
<?php } ?>
*/ ?>
<a href="<?php echo CHtml::nor... | <?php $job = $item->assocObject;?>
<?php $id = 'job_evt_'.$job->ID.$item->ID;?>
<div id="<?php echo $id;?>">
<div class="pad"><?php
$job = $item->getAssocObject();
?>
<?php if($job->RUSH){?>
<span class="warning">RUSH</span>
<?php } ?>
<a href="<?php echo CHtml::normalizeUrl(array('job/view', 'id'=>$job... |
Make lexer argument optional and guess content if not provided | // Pygments wrapper for golang. Pygments is a syntax highlighter
package pygments
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
)
var (
bin = "pygmentize"
)
func Binary(path string) {
bin = path
}
func Which() string {
return bin
}
func Highlight(code string, lexer string, format string, enc string) str... | // Pygments wrapper for golang. Pygments is a syntax highlighter
package pygments
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
)
var (
bin = "pygmentize"
)
func Binary(path string) {
bin = path
}
func Which() string {
return bin
}
func Highlight(code string, lexer string, format string, enc string) str... |
Remove underlines that indicate privacy | const buildRequest = function (url, method, responseType, headers) {
const internalHeaders = headers || {};
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.responseType = responseType;
req.open(method.toUpperCase(), url);
Object.keys(internalHeaders).forEach((header... | const buildRequest = function (url, method, responseType, headers) {
const internalHeaders = headers || {};
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.responseType = responseType;
req.open(method.toUpperCase(), url);
Object.keys(internalHeaders).forEach((header... |
Store songs, artists, and albums as objects
Add 'favorite' bool as property of each object | 'use strict';
/* Controllers */
angular.module('myApp.controllers', [])
.controller('HomeController', ['$scope', function($scope) {
$scope.allMusic = [];
$scope.albums = [];
$scope.artists = [];
$scope.songs = [];
$scope.metadata = {song: '', artist: '', album: ''};
$scope.saveMusic = fun... | 'use strict';
/* Controllers */
angular.module('myApp.controllers', [])
.controller('HomeController', ['$scope', function($scope) {
$scope.allMusic = [];
$scope.albums = [];
$scope.artists = [];
$scope.songs = [];
$scope.metadata = {song: '', artist: '', album: ''};
$scope.saveMusic = fun... |
Change menu text from edit/delete datasource -> manage datasources | /*
* Copyright 2014 Codenvy, S.A.
*
* 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 ... | /*
* Copyright 2014 Codenvy, S.A.
*
* 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 ... |
Fix redirects causing duplicate setup method calls
Triggering a transition from the beforeModel method in the application route will cause the beforeModel method to be called again on the next transition. Moving the transition call to the redirect method fixes this. | import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { isPresent } from '@ember/utils';
export default class ApplicationRoute extends Route {
@service('remotestorage') storage;
@service localData;
@service logger;
@service... | import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { isPresent } from '@ember/utils';
export default class ApplicationRoute extends Route {
@service('remotestorage') storage;
@service localData;
@service logger;
@service... |
Allow PeriodicRefresher to be force-refreshed | import {autobind} from 'core-decorators';
const refreshMapPerUniqueId = new WeakMap();
export default class PeriodicRefresher {
refresh() {
this._callback();
}
static getRefreshMap(uniqueId) {
let refreshMap = refreshMapPerUniqueId.get(uniqueId);
if (!refreshMap) {
refreshMap = new Map();
... | import {autobind} from 'core-decorators';
const refreshMapPerUniqueId = new WeakMap();
export default class PeriodicRefresher {
static getRefreshMap(uniqueId) {
let refreshMap = refreshMapPerUniqueId.get(uniqueId);
if (!refreshMap) {
refreshMap = new Map();
refreshMapPerUniqueId.set(uniqueId, re... |
Revert "Added a validation into the parser"
This reverts commit 36a90ec21a9be5e5534017360051be49f3a0c2a9. | const {
UtilsParsingError,
UtilsRuntimeError,
} = require('./UtilsErrors');
const {
RequestRuntimeError,
} = require('../../Request/RequestErrors');
function currencyConvertParse(json) {
try {
json = json['util:CurrencyConversion'].map(curr => ({
from: curr.From,
to: curr.To,
rate: parseF... | const {
UtilsParsingError,
UtilsRuntimeError,
} = require('./UtilsErrors');
const {
RequestRuntimeError,
} = require('../../Request/RequestErrors');
function currencyConvertParse(json) {
try {
json = json['util:CurrencyConversion'].map(curr => ({
from: curr.From,
to: curr.To,
rate: parseF... |
Swap seeding positions of known/test user. | <?php
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use eien\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
User::create([
'name' => 'amatsuka',
... | <?php
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use eien\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
foreach (range(1, 9) as $inx) {
User::crea... |
Remove loading of requirements from pip-requires | from setuptools import setup, find_packages
requirements = ['virtualenv', 'pyparsing==1.5.7', 'pydot==1.0.2']
desc = ''
with open('README.rst') as f:
desc = f.read()
setup(
name='packmap',
version='0.0.1',
description=('PackMap discovers all dependencies for a specific'
'Python packa... | from setuptools import setup, find_packages
# Dirty requirements loads
requirements = []
with open('pip-requires') as f:
requirements = f.read().splitlines()
desc = ''
with open('README.rst') as f:
desc = f.read()
setup(
name='packmap',
version='0.0.1',
description=('PackMap discovers all depende... |
Use brighter colors in contextual Graphite graphs | // TODO: This is not a real model or controller
App.Graphs = Ember.Controller.extend({
graph: function(emberId, entityName, entityType, numSeries) {
entityName = entityName.replace(/\./g, '-');
var url = ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityTy... | // TODO: This is not a real model or controller
App.Graphs = Ember.Controller.extend({
graph: function(emberId, entityName, entityType, numSeries) {
entityName = entityName.replace(/\./g, '-');
var url = ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityTy... |
Add background color for Toolbar
Fix #90 | import React from 'react'
import { inject, observer } from 'mobx-react'
import Toolbar from './Toolbar'
import ToolbarIndicator from './ToolbarIndicator'
@inject('userStore')
@observer
export default class ToolbarWrapper extends React.Component {
render () {
const {
lazyHideToolbar, showToolbar
} = thi... | import React from 'react'
import { inject, observer } from 'mobx-react'
import Toolbar from './Toolbar'
import ToolbarIndicator from './ToolbarIndicator'
@inject('userStore')
@observer
export default class ToolbarWrapper extends React.Component {
render () {
const {
lazyHideToolbar, showToolbar
} = thi... |
Load intl packages from correct location
This path changed in the last major version to remove `dist`. | export async function loadPolyfills() {
await Promise.all([
intlPluralRules(),
intlRelativeTimeFormat(),
]);
}
async function intlPluralRules() {
if ('Intl' in window && 'PluralRules' in Intl) {
return;
}
await import('@formatjs/intl-pluralrules/polyfill');
await Promise.all([
import('@for... | export async function loadPolyfills() {
await Promise.all([
intlPluralRules(),
intlRelativeTimeFormat(),
]);
}
async function intlPluralRules() {
if ('Intl' in window && 'PluralRules' in Intl) {
return;
}
await import('@formatjs/intl-pluralrules/polyfill');
await Promise.all([
import('@for... |
Add a logfile for tutorial01 | package main
import (
"fmt"
"hge"
)
var h *hge.HGE
func FrameFunc() int {
if h.Input_GetKeyState(hge.K_ESCAPE) {
return 1
}
return 0
}
func main() {
h = hge.Create(hge.VERSION)
defer h.Release()
h.System_SetState(hge.LOGFILE, "tutorial01.log")
h.System_SetState(hge.FRAMEFUNC, FrameFunc)
h.System_SetSt... | package main
import (
"fmt"
"hge"
)
var h *hge.HGE
func FrameFunc() int {
if h.Input_GetKeyState(hge.K_ESCAPE) {
return 1
}
return 0
}
func main() {
h = hge.Create(hge.VERSION)
defer h.Release()
h.System_SetState(hge.FRAMEFUNC, FrameFunc)
h.System_SetState(hge.TITLE, "HGE Tutorial 01 - Minimal HGE appl... |
Fix accidental context menu opening in Windows | import $ from 'jquery'
export default function GameScene(display) {
return function (container) {
let handler = () => false
$(window).on('touchstart', handler)
showCanvas(display, container)
return {
teardown() {
$(window).off('touchstart', handler)
},
}
}
}
function showCa... | import $ from 'jquery'
export default function GameScene(display) {
return function (container) {
let handler = () => false
$(window).on('touchstart', handler)
showCanvas(display, container)
return {
teardown() {
$(window).off('touchstart', handler)
},
}
}
}
function showCa... |
Use mocha style reporting for tests | var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ 'PhantomJS' ], // use PhantomJS for now (@gordyd - I'm using a VM)
singleRun: true,
frameworks: [ 'mocha', 'sinon' ], // Mocha is our testing framework of choice
files: [
'tests.webpack.js' //just lo... | var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ 'PhantomJS' ], // use PhantomJS for now (@gordyd - I'm using a VM)
singleRun: true,
frameworks: [ 'mocha', 'sinon' ], // Mocha is our testing framework of choice
files: [
'tests.webpack.js' //just lo... |
Make class serializable so that it'll work with the session stuff | /*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* Unless required by app... | /*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* Unless required by app... |
Change PyPI development status from pre-alpha to beta. | #!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cr... | #!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cr... |
Fix check for cls attribute
* If resolved_view has a cls attribute then view should already be a
class. | import warnings
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLTestMixin(object):
def assert_url_matches_view(self, view, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly ... | import warnings
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLTestMixin(object):
def assert_url_matches_view(self, view, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly ... |
Update to ensure backwards compatibility for Laravel 5.8 and below | <?php
namespace Coreplex\Meta\Managers;
use Illuminate\Support\Manager;
use Coreplex\Meta\Eloquent\Repository as EloquentRepository;
class Store extends Manager
{
public function createEloquentDriver()
{
return new EloquentRepository;
}
/**
* Get the default authentication driver name.
... | <?php
namespace Coreplex\Meta\Managers;
use Illuminate\Support\Manager;
use Coreplex\Meta\Eloquent\Repository as EloquentRepository;
class Store extends Manager
{
public function createEloquentDriver()
{
return new EloquentRepository;
}
/**
* Get the default authentication driver name.
... |
Fix the flex on panels with buttons | import React from "react";
class IntroWithButton extends React.Component {
static displayName = "Panel.IntroWithButton";
static propTypes = {
children: React.PropTypes.node.isRequired
};
render() {
let children = React.Children.toArray(this.props.children);
let intro;
let button;
if(chil... | import React from "react";
class IntroWithButton extends React.Component {
static displayName = "Panel.IntroWithButton";
static propTypes = {
children: React.PropTypes.node.isRequired
};
render() {
let children = React.Children.toArray(this.props.children);
let intro;
let button;
if(chil... |
BAP-4210: Add EntityExtendBundle dumper extension to generate activity association entities. Refactoring | <?php
namespace Oro\Bundle\EntityExtendBundle\Tools;
use Oro\Bundle\EntityConfigBundle\Config\ConfigInterface;
abstract class MultipleAssociationExtendConfigDumperExtension extends AbstractAssociationExtendConfigDumperExtension
{
/**
* {@inheritdoc}
*/
protected function getAssociationType()
{
... | <?php
namespace Oro\Bundle\EntityExtendBundle\Tools;
use Oro\Bundle\EntityConfigBundle\Config\ConfigInterface;
abstract class MultipleAssociationExtendConfigDumperExtension extends AbstractAssociationExtendConfigDumperExtension
{
/**
* {@inheritdoc}
*/
protected function getAssociationType()
{
... |
Fix stale environment header vhost metadata
*Really* closes
https://github.com/aptible/dashboard.aptible.com/issues/496 by binding
the computed vhost metadata to the parent environment. | import Ember from 'ember';
export default Ember.Component.extend({
tagName: '',
maxVisibleDomainNames: 1,
displayVhostNames: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames').join(', ');
}),
showVhostTooltip: Ember.computed('model.vhostNames', function() {
return t... | import Ember from 'ember';
export default Ember.Component.extend({
tagName: '',
maxVisibleDomainNames: 1,
displayVhostNames: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames').join(', ');
}),
showVhostTooltip: Ember.computed('model.vhostNames', function() {
return t... |
Use Vary header by default | package core
import "net/http"
type handlersStack []func(*Context)
var handlers handlersStack
// Use adds a handler to the handlers stack.
func Use(h func(*Context)) {
handlers = append(handlers, h)
}
func (h handlersStack) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Init a new context for the request... | package core
import "net/http"
type handlersStack []func(*Context)
var handlers handlersStack
// Use adds a handler to the handlers stack.
func Use(h func(*Context)) {
handlers = append(handlers, h)
}
func (h handlersStack) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Init a new context for the request... |
Refactor to reuse test case initialization code | /* global describe it beforeEach */
'use strict'
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
require('sinon-as-promised')
chai.use(chaiAsPromised)
chai.use(sinonCh... | /* global describe it */
'use strict'
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
require('sinon-as-promised')
chai.use(chaiAsPromised)
chai.use(sinonChai)
const ... |
Fix cookie not being parsed on load.
If you have to stringify your object before saving, and you add that,
to the `_cookies` cache, then you'll return that on `load` after setting
it with `save`.
While if the value is already set, the script correctly parses the cookie
values and what you load is returned as an objec... | var cookie = require('cookie');
var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : '');
for (var key in _cookies) {
try {
_cookies[key] = JSON.parse(_cookies[key]);
} catch(e) {
// Not serialized object
}
}
function load(name) {
return _cookies[name];
}
function save(n... | var cookie = require('cookie');
var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : '');
for (var key in _cookies) {
try {
_cookies[key] = JSON.parse(_cookies[key]);
} catch(e) {
// Not serialized object
}
}
function load(name) {
return _cookies[name];
}
function save(n... |
Fix path for custom plugin | /* jshint node: true */
'use strict';
const Funnel = require('broccoli-funnel');
const path = require('path');
const mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-cli-bootstrap-datetimepicker',
included: function(app) {
this._super.included(app);
// Import unminified css ... | /* jshint node: true */
'use strict';
const Funnel = require('broccoli-funnel');
const path = require('path');
const mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-cli-bootstrap-datetimepicker',
included: function(app) {
this._super.included(app);
// Import unminified css ... |
Redux: Create our own createStore and fix typo | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// import {createStore} from 'redux';
// ReactDOM.render(<App />, document.getElementById('app'));
const counter = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
... | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// import {createStore} from 'redux';
// ReactDOM.render(<App />, document.getElementById('app'));
const counter = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
... |
Test all methods are found by factory reparceler. | package pl.mg6.testsupport;
import junit.framework.TestCase;
import java.util.List;
import pl.mg6.testsupport.data.Simple;
import pl.mg6.testsupport.factory.SimpleFactory;
public class FactoryReparcelerTestCase extends TestCase {
private final FactoryReparceler reparceler = new FactoryReparceler();
public... | package pl.mg6.testsupport;
import junit.framework.TestCase;
import java.util.List;
import pl.mg6.testsupport.data.Simple;
import pl.mg6.testsupport.factory.SimpleFactory;
public class FactoryReparcelerTestCase extends TestCase {
private final FactoryReparceler reparceler = new FactoryReparceler();
public... |
Handle no latest event (fixes GH-1727) | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api import client
from sentry.api.base import DocSection
from sentry.api.bases.group import GroupEndpoint
class GroupEventsLatestEndpoint(GroupEndpoint):
doc_section = DocSection.EVENTS
def get(self, request, gr... | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api import client
from sentry.api.base import DocSection
from sentry.api.bases.group import GroupEndpoint
class GroupEventsLatestEndpoint(GroupEndpoint):
doc_section = DocSection.EVENTS
def get(self, request, gr... |
Add a test case for instanceof expressions | // fails
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// NAME_NOT_FOUND
// TYPE_MISMATCH
package java.util;
// import java.lang.*;
import java.io.File;
import java.io.JFile; // fails
class A extends Object {
String fname = "filename";
File file = new java.io.File(fname);
JFile jfile = new JFile... | // fails
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// NAME_NOT_FOUND
// TYPE_MISMATCH
package java.util;
// import java.lang.*;
import java.io.File;
import java.io.JFile; // fails
class A extends Object {
String fname = "filename";
File file = new java.io.File(fname);
JFile jfile = new JFile... |
Fix request logger for use cases when childLogger middleware was not
used. | var uuid = require('node-uuid');
var bunyan = require('bunyan');
module.exports = function(loggerInstance) {
if (!loggerInstance) {
var opts = {
stream: process.stdout,
serializers: {
req: bunyan.stdSerializers.req
}
};
loggerInstance = bunyan.createLogger(opts);
}
ret... | var uuid = require('node-uuid');
var bunyan = require('bunyan');
module.exports = function(loggerInstance) {
if (!loggerInstance) {
var opts = {
stream: process.stdout,
serializers: {
req: bunyan.stdSerializers.req
}
};
loggerInstance = bunyan.createLogger(opts);
}
ret... |
Include trailing slash in URL. | package tempredis
import "fmt"
// Config is a key-value map of Redis config settings.
type Config map[string]string
// Host returns the host for a Redis server configured with this Config as
// "host:port".
func (c Config) Host() string {
bind, ok := c["bind"]
if !ok {
bind = "127.0.0.1"
}
port, ok := c["port... | package tempredis
import "fmt"
// Config is a key-value map of Redis config settings.
type Config map[string]string
// Host returns the host for a Redis server configured with this Config as
// "host:port".
func (c Config) Host() string {
bind, ok := c["bind"]
if !ok {
bind = "127.0.0.1"
}
port, ok := c["port... |
Fix and add terminate to set Content-Type and Accept header | <?php
namespace Stack;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
class JsonRequest implements HttpKernelInterface, TerminableInterface
{
private $app;
... | <?php
namespace Stack;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class JsonRequest implements HttpKernelInterface
{
private $app;
private $contentTypes = array('application/json');
public function __construct(HttpKernelInterface $app, array $cont... |
Replace definition of missing constant PREG_BAD_UTF8_OFFSET_ERROR in HHVM by not using it at all | <?php
namespace Gobie\Regex\Drivers\Pcre;
use Gobie\Regex\RegexException;
class PcreRegexException extends RegexException
{
public static $messages = array(
PREG_INTERNAL_ERROR => 'Internal error',
PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted',
PREG_RECURSION_LIMIT... | <?php
namespace Gobie\Regex\Drivers\Pcre;
use Gobie\Regex\RegexException;
// hhvm fix
if (!\defined('PREG_BAD_UTF8_OFFSET_ERROR')) {
\define('PREG_BAD_UTF8_OFFSET_ERROR', 5);
};
class PcreRegexException extends RegexException
{
public static $messages = array(
PREG_INTERNAL_ERROR => 'Interna... |
Add Sponsor component to home page | import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Theme from '../../../config/theme';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import UpIcon from 'material-ui/svg-icons/navigation/arrow-upward';
import Header from '../Header';
import News f... | import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Theme from '../../../config/theme';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import UpIcon from 'material-ui/svg-icons/navigation/arrow-upward';
import Header from '../Header';
import News f... |
Add Python 3.6 to classifiers | #!/usr/bin/env python
from setuptools import setup
setup(
name="exec-wrappers",
version='1.0.3',
author="Guilherme Quentel Melo",
author_email="gqmelo@gmail.com",
url="https://github.com/gqmelo/exec-wrappers",
license="MIT",
classifiers=[
"Development Status :: 5 - Production/Stabl... | #!/usr/bin/env python
from setuptools import setup
setup(
name="exec-wrappers",
version='1.0.3',
author="Guilherme Quentel Melo",
author_email="gqmelo@gmail.com",
url="https://github.com/gqmelo/exec-wrappers",
license="MIT",
classifiers=[
"Development Status :: 5 - Production/Stabl... |
Use of 'Else' for Stop Executing After Occuring Error | var registerAction = require('../logic/account/registerAction')
var userChecker = require('../logic/account/userChecker')
exports.register = {
name: "register",
description: "Register a User",
run: function (api, data, next) {
var payload = JSON.parse(JSON.stringify(data.connection.rawConnection.params.body... | var registerAction = require('../logic/account/registerAction')
var userChecker = require('../logic/account/userChecker')
exports.register = {
name: "register",
description: "Register a User",
run: function(api, data, next) {
var payload = JSON.parse(JSON.stringify(data.connection.rawConnection.params.... |
Use sorted on the set to parametrize tests so that pytest-xdist works | import numpy
import cupy
import scipy.special
import cupyx.scipy.special
from cupy import testing
import pytest
scipy_ufuncs = {
f
for f in scipy.special.__all__
if isinstance(getattr(scipy.special, f), numpy.ufunc)
}
cupyx_scipy_ufuncs = {
f
for f in dir(cupyx.scipy.special)
if isinstance(get... | import numpy
import cupy
import scipy.special
import cupyx.scipy.special
from cupy import testing
import pytest
scipy_ufuncs = {
f
for f in scipy.special.__all__
if isinstance(getattr(scipy.special, f), numpy.ufunc)
}
cupyx_scipy_ufuncs = {
f
for f in dir(cupyx.scipy.special)
if isinstance(get... |
perf(mapboxgl): Disable interactivity on the mapbox gl layer since it is handled by leaflet | import L from 'leaflet'
import {} from 'mapbox-gl-leaflet'
import {GridLayer, withLeaflet} from 'react-leaflet'
const accessToken = process.env.MAPBOX_ACCESS_TOKEN
const attribution = `© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong... | import L from 'leaflet'
import {} from 'mapbox-gl-leaflet'
import {GridLayer, withLeaflet} from 'react-leaflet'
const accessToken = process.env.MAPBOX_ACCESS_TOKEN
const attribution = `© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong... |
Add a private constructor to hide the implicit public one
Add a private constructor to hide the implicit public one on
OpenConfigComparatorFactory.
Change-Id: Id24e1b3bb8c59e0eaed71093acd4443e75ac50db
Signed-off-by: Claudio D. Gasparini <3480fb4575078d890be8aed0007cb1d8785aa579@cisco.com> | /*
* Copyright (c) 2015 Cisco Systems, Inc. and others. 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 (c) 2015 Cisco Systems, Inc. and others. 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... |
REmove unused dependency on jsEncode | /** MIT License (c) copyright 2010-2013 B Cavalier & J Hann */
/**
* curl json! cram plugin
*/
define(function () {
return {
compile: function (pluginId, resId, req, io, config) {
var absId;
absId = pluginId + '!' + resId;
io.read(
resId,
function (source) {
if (config.strictJSONParse) {... | /** MIT License (c) copyright 2010-2013 B Cavalier & J Hann */
/**
* curl json! cram plugin
*/
define(['./jsEncode'], function (jsEncode) {
return {
compile: function (pluginId, resId, req, io, config) {
var absId;
absId = pluginId + '!' + resId;
io.read(
resId,
function (source) {
if (c... |
Rework HOME fixture so it doesn't leave os.environ corrupted | import functools
import os.path
import shutil
import sys
import tempfile
import pytest
@pytest.fixture(scope="function")
def HOME(tmpdir):
old_home = os.environ['HOME']
try:
home = os.path.join(tmpdir, 'john')
os.mkdir(home)
# NOTE: homely._utils makes use of os.environ['HOME'], so w... | import functools
import os.path
import shutil
import sys
import tempfile
import pytest
@pytest.fixture(scope="function")
def HOME(tmpdir):
home = os.path.join(tmpdir, 'john')
os.mkdir(home)
# NOTE: homely._utils makes use of os.environ['HOME'], so we need to
# destroy any homely modules that may have... |
Remove unused functions from the Mode base object | # The purpose of this file is to provide base classes with the needed functions
# already defined; this allows us to guarantee that any exceptions raised
# during function calls are a problem with the module and not just that the
# particular function isn't defined.
from txircd.utils import now
class Module(object):
... | # The purpose of this file is to provide base classes with the needed functions
# already defined; this allows us to guarantee that any exceptions raised
# during function calls are a problem with the module and not just that the
# particular function isn't defined.
from txircd.utils import now
class Module(object):
... |
Remove the machine id from state when the machine is deleted | package triton
import (
"fmt"
"time"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
)
// StepDeleteMachine deletes the machine with the ID specified in state["machine"]
type StepDeleteMachine struct{}
func (s *StepDeleteMachine) Run(state multistep.StateBag) multistep.StepAction {
driver... | package triton
import (
"fmt"
"time"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
)
// StepDeleteMachine deletes the machine with the ID specified in state["machine"]
type StepDeleteMachine struct{}
func (s *StepDeleteMachine) Run(state multistep.StateBag) multistep.StepAction {
driver... |
Fix multiselect user/group field when retrieving results from a report | from .base import MultiSelectField
from swimlane.core.resources.usergroup import UserGroup
class UserGroupField(MultiSelectField):
"""Manages getting/setting users from record User/Group fields"""
field_type = 'Core.Models.Fields.UserGroupField, Core'
supported_types = [UserGroup]
def set_swimlane(... | from .base import MultiSelectField
from swimlane.core.resources.usergroup import UserGroup
class UserGroupField(MultiSelectField):
"""Manages getting/setting users from record User/Group fields"""
field_type = 'Core.Models.Fields.UserGroupField, Core'
supported_types = [UserGroup]
def cast_to_pytho... |
Update to indicate the ARN is used | package main
import (
"os"
"github.com/remind101/empire/pkg/heroku"
)
var cmdCertAttach = &Command{
Run: runCertAttach,
Usage: "cert-attach <aws_cert_arn>",
NeedsApp: true,
Category: "certs",
Short: "attach a certificate to an app",
Long: `
Attaches an SSL certificate to an applications web proces... | package main
import (
"os"
"github.com/remind101/empire/pkg/heroku"
)
var cmdCertAttach = &Command{
Run: runCertAttach,
Usage: "cert-attach <aws_cert_name>",
NeedsApp: true,
Category: "certs",
Short: "attach a certificate to an app",
Long: `
Attaches an SSL certificate to an applications web proce... |
Add placeholders for user notification | import React from 'react';
import './TicTacToe.scss';
import { connect } from 'react-redux';
import ticTacToeActions from 'actions/tictactoe';
import GameBoard from './components/GameBoard';
const mapStateToProps = (state) => {
return {
playerTurn: state.tictactoe.playerTurn
};
};
class TicTacToe... | import React from 'react';
import './TicTacToe.scss';
import { connect } from 'react-redux';
import ticTacToeActions from 'actions/tictactoe';
import GameBoard from './components/GameBoard';
const mapStateToProps = (state) => {
return {
playerTurn: state.tictactoe.playerTurn
};
};
class TicTacToe... |
Change tag name from pjax to psxhr | <?php
if (isset($_GET['get-date'])) {
echo uniqid();
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
<title></title>
</head>
<body>
<div psxhr="true" psxhr-href="<?= $_SERVER['PHP_SELF']; ?>?get-date=true" psxhr-time="1000" psxhr-response="text" psxhr-... | <?php
if (isset($_GET['get-date'])) {
echo uniqid();
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
<title></title>
</head>
<body>
<div pjax="true" pjax-href="<?= $_SERVER['PHP_SELF']; ?>?get-date=true" pjax-time="1000" pjax-response="text" pjax-event... |
Fix url attribute on share serializer :) | from bioshareX.models import ShareLog, Share, Tag, ShareStats
from rest_framework import serializers
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class UserSerializer(serializers.ModelSerializer):
class Meta:
fields=('first_name','last_name','email','username','id... | from bioshareX.models import ShareLog, Share, Tag, ShareStats
from rest_framework import serializers
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class UserSerializer(serializers.ModelSerializer):
class Meta:
fields=('first_name','last_name','email','username','id... |
Fix duplicate `graphql` package bug by checking for local installation
See https://github.com/graphql/graphiql/issues/58 for more info | const axios = require('axios')
const path = require('path')
let GraphQL
try {
// do to GraphQL schema issue [see](https://github.com/graphql/graphiql/issues/58)
GraphQL = require(path.join(process.cwd(), './node_modules/graphql'))
} catch (e) {
// fallback if graphql is not installed locally
GraphQL = require(... | const axios = require('axios')
const { graphql } = require('graphql')
const { correctURL, encode, DEFAULT_CONFIG } = require('./util')
function Gest (schema, config = {}) {
const { baseURL, headers, timeout } = Object.assign(DEFAULT_CONFIG, config)
return function (query) {
if (baseURL) {
const instance... |
Modify the picture plugin slightly | from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/pi... | from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/pi... |
Change font-awesome css file to compile | var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
gulp.task('default',['sass'], function() {
});
gulp.task("sass", function () {
gulp.src("./sass/*.scss")
.pipe(sass({outputStyle: 'expanded'}).on('error', sass.logEr... | var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
gulp.task('default',['sass'], function() {
});
gulp.task("sass", function () {
gulp.src("./sass/*.scss")
.pipe(sass({outputStyle: 'expanded'}).on('error', sass.logEr... |
Fix unhandled promise rejection error reporting to Sentry | import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import './static/bootstrap/css/bootstrap.css';
import App from './Main/App';
import ErrorBoundary from './Main/ErrorBoundary';
import { unregister } from './registerServiceWorker';
function i... | import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import './static/bootstrap/css/bootstrap.css';
import App from './Main/App';
import ErrorBoundary from './Main/ErrorBoundary';
import { unregister } from './registerServiceWorker';
function i... |
Add method to create a normal user | from mailu import manager, db
from mailu.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, p... | from mailu import manager, db
from mailu.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, p... |
Fix missing name on password field | <div class="app-user app-user-login">
<h2>Connexion</h2>
<div class="login-form">
<form id="Connexion" method="post" action="<?php echo Config::get('config.base'); ?>/user/login">
<div>
<label for="email">Email</label><input name="email" id="email" type="text" required /><br/>
<label for="... | <div class="app-user app-user-login">
<h2>Connexion</h2>
<div class="login-form">
<form id="Connexion" method="post" action="<?php echo Config::get('config.base'); ?>/user/login">
<div>
<label for="email">Email</label><input name="email" id="email" type="text" required /><br/>
<label for="... |
Allow saving to a file that does not already exist again. |
import tkFileDialog
import joincsv
import os.path
import sys
if __name__ == '__main__':
filetypes=[("Spreadsheets", "*.csv"),
("Spreadsheets", "*.xls"),
("Spreadsheets", "*.xlsx")]
if len(sys.argv) == 2:
input_filename = sys.argv[1]
else:
input_filename =... |
import tkFileDialog
import joincsv
import os.path
import sys
if __name__ == '__main__':
filetypes=[("Spreadsheets", "*.csv"),
("Spreadsheets", "*.xls"),
("Spreadsheets", "*.xlsx")]
if len(sys.argv) == 2:
input_filename = sys.argv[1]
else:
input_filename =... |
Add the ability to specify snippets on a per-invocation basis. | 'use strict';
/*****
* Vain
*
* A view-first templating engine for Node.js.
*****/
var jsdom = require('jsdom'),
$ = require('jquery')(jsdom.jsdom().createWindow()),
snippetRegistry = {};
/**
* Register a snippet in the snippet registry.
**/
exports.registerSnippet = function(snippetName, snippetFn) {
s... | 'use strict';
/*****
* Vain
*
* A view-first templating engine for Node.js.
*****/
var jsdom = require('jsdom'),
$ = require('jquery')(jsdom.jsdom().createWindow()),
snippetRegistry = {};
/**
* Register a snippet in the snippet registry.
**/
exports.registerSnippet = function(snippetName, snippetFn) {
s... |
Remove @NotNull annotation to name field. | package com.zyeeda.framework.entities.base;
import javax.validation.constraints.NotNull;
@javax.persistence.MappedSuperclass
public class SimpleDomainEntity extends DomainEntity {
private static final long serialVersionUID = -2200108673372668900L;
private String name;
private String description;
... | package com.zyeeda.framework.entities.base;
import javax.validation.constraints.NotNull;
@javax.persistence.MappedSuperclass
public class SimpleDomainEntity extends DomainEntity {
private static final long serialVersionUID = -2200108673372668900L;
private String name;
private String description;
... |
Add results to LoadSessionServlet model.
Each reservation may contain many results. Since clients may
be depending on these results we will want to keep them
constant when loading sessions from the CMS. This means that
results must be included in the model that is used to update
the reservation.
Change-Id: I8318b3866... | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... |
Switch to using block chainer | """ Test a pipeline with repeated FFTs and inverse FFTs """
from timeit import default_timer as timer
import numpy as np
import bifrost as bf
from bifrost import pipeline as bfp
from bifrost import blocks as blocks
from bifrost_benchmarks import PipelineBenchmarker
class GPUFFTBenchmarker(PipelineBenchmarker):
"""... | """ Test a pipeline with repeated FFTs and inverse FFTs """
from timeit import default_timer as timer
import numpy as np
import bifrost as bf
from bifrost import pipeline as bfp
from bifrost import blocks as blocks
from bifrost_benchmarks import PipelineBenchmarker
class GPUFFTBenchmarker(PipelineBenchmarker):
"""... |
Add pubish action helper for influxdb | #-*- coding:utf-8 -*-
import sys
import logging
from influxdb import InfluxDBClient as OriginalInfluxDBClient
class InfluxDBClient(OriginalInfluxDBClient):
def Publish(self, measurement, tags):
return InfluxDBPublish(self, measurement, tags)
class InfluxDBPublish(object):
def __init__(self, influxd... | #-*- coding:utf-8 -*-
import sys
import logging
from influxdb import InfluxDBClient
class InfluxDBPublish(object):
def __init__(self, influxdb, measurement, tags):
assert(isinstance(influxdb, InfluxDBClient))
self.influxdb = influxdb
self.tags = tags
self.measurement = measurement... |
Add confirmation to user password validation. | <?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Hash;
class User extends Authenticatable
{
static $rules = [
'name' => 'required|max:255',
'email' => 'required|email',
'password' => 'required|confirmed|min:8|max:255'
];
protected $fillable = ['name', 'email', 'passwor... | <?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Hash;
class User extends Authenticatable
{
static $rules = [
'name' => 'required|max:255',
'email' => 'required|email',
'password' => 'required|min:8|max:255'
];
protected $fillable = ['name', 'email', 'password'];
prot... |
Support HTML5's input type 'tel' | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import CharField
from django.core.exceptions import ValidationError
from phonenumber_field.validators import validate_international_phonenumber
from phonenumber_field.phonen... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import CharField
from django.core.exceptions import ValidationError
from phonenumber_field.validators import validate_international_phonenumber
from phonenumber_field.phonen... |
Install now drops and recreates the database | process.env.NODE_CONFIG_DIR="../config/";
var mysql = require("promise-mysql");
var config = require("config");
var fs = require("fs");
var connection;
mysql.createConnection({
host: config.get("database.host"),
user: config.get("database.username"),
password: config.get("database.password"),
... | process.env.NODE_CONFIG_DIR="../config/";
var mysql = require("promise-mysql");
var config = require("config");
var fs = require("fs");
var connection;
mysql.createConnection({
host: config.get("database.host"),
user: config.get("database.username"),
password: config.get("database.password"),
... |
Remove unnecessary call to loadTasks. | /*
* grunt-check-pages
* https://github.com/DavidAnson/grunt-check-pages
*
* Copyright (c) 2014 David Anson
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
// Linting
jshint: {
all: [
'Gruntfile.js',
... | /*
* grunt-check-pages
* https://github.com/DavidAnson/grunt-check-pages
*
* Copyright (c) 2014 David Anson
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
// Linting
jshint: {
all: [
'Gruntfile.js',
... |
Fix typo causing strangeness in transition to photo-card schema mode | import { task } from 'ember-concurrency';
import { tracked } from '@glimmer/tracking';
import BaseIsolatedLayoutComponent from '../base-isolated-layout';
export default class PhotoCardIsolatedComponent extends BaseIsolatedLayoutComponent {
@tracked bylineName;
@tracked bylineImageURL;
constructor(...args) {
... | import { task } from 'ember-concurrency';
import { tracked } from '@glimmer/tracking';
import BaseIsolatedLayoutComponent from '../base-isolated-layout';
export default class PhotoCardIsolatedComponent extends BaseIsolatedLayoutComponent {
@tracked bylineName;
@tracked bylineImageURL;
constructor(...args) {
... |
Add debug logging to elm-format | from __future__ import print_function
import subprocess
import re
import sublime, sublime_plugin
class ElmFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = "elm-format {} --yes".format(self.view.file_name())
p = subprocess.Popen(command, stdout=subprocess.PIPE, sterr=subprocess.PIPE, she... | import subprocess
import re
import sublime, sublime_plugin
class ElmFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = "elm-format {} --yes".format(self.view.file_name())
p = subprocess.Popen(command, shell=True)
class ElmFormatOnSave(sublime_plugin.EventListener):
def on_pre_save(self,... |
[Biography] Fix case where artist blurb was null and RN couldn't render | /* @flow */
'use strict';
import Relay from 'react-relay';
import React from 'react-native';
const { View, Text, Dimensions } = React;
import removeMarkdown from 'remove-markdown';
import Headline from '../text/headline';
import SerifText from '../text/serif';
const sideMargin = Dimensions.get('window').width > 700... | /* @flow */
'use strict';
import Relay from 'react-relay';
import React from 'react-native';
const { View, Text, Dimensions } = React;
import removeMarkdown from 'remove-markdown';
import Headline from '../text/headline';
import SerifText from '../text/serif';
const sideMargin = Dimensions.get('window').width > 700... |
Check that ImagePaths aren't empty in testing | package talks
import (
"fmt"
"testing"
assert "github.com/stretchr/testify/require"
)
func TestCompile(t *testing.T) {
talk, err := Compile("../content", "../content/talks-drafts", "paradise-lost.yaml", true)
assert.NoError(t, err)
assert.Equal(t, true, talk.Draft)
assert.NotEmpty(t, talk.Intro)
assert.NotE... | package talks
import (
"fmt"
"testing"
assert "github.com/stretchr/testify/require"
)
func TestCompile(t *testing.T) {
talk, err := Compile("../content", "../content/talks-drafts", "paradise-lost.yaml", true)
assert.NoError(t, err)
assert.Equal(t, true, talk.Draft)
assert.NotEmpty(t, talk.Intro)
assert.NotE... |
Change the comment of InterleavingMethod.evaluate | class InterleavingMethod(object):
'''
Interleaving
'''
def interleave(self, k, a, b):
'''
k: the maximum length of resultant interleaving
a: a list of document IDs
b: a list of document IDs
Return an instance of Ranking
'''
raise NotImplementedErr... | class InterleavingMethod(object):
'''
Interleaving
'''
def interleave(self, k, a, b):
'''
k: the maximum length of resultant interleaving
a: a list of document IDs
b: a list of document IDs
Return an instance of Ranking
'''
raise NotImplementedErr... |
Change package name in tests | import pytest
from curryer import curry
class TestCurry:
def test_curry_as_decorator(self):
"""Ensure that currypy.curry can be used as a decorator"""
@curry
def func():
pass
assert func.curried is False
def test_curry_refuses_None(self):
"""Ensure that c... | import pytest
from currypy import curry
class TestCurry:
def test_curry_as_decorator(self):
"""Ensure that currypy.curry can be used as a decorator"""
@curry
def func():
pass
assert func.curried is False
def test_curry_refuses_None(self):
"""Ensure that c... |
Move variable declaration up a level to ensure it exists later | import React from 'react'
import { prefixLink } from './gatsby-helpers'
let stylesStr
if (process.env.NODE_ENV === `production`) {
try {
stylesStr = require(`!raw!public/styles.css`)
} catch (e) {
// ignore
}
}
const htmlStyles = (args = {}) => {
if (process.env.NODE_ENV === `production`) {
if (ar... | import React from 'react'
import { prefixLink } from './gatsby-helpers'
if (process.env.NODE_ENV === `production`) {
let stylesStr
try {
stylesStr = require(`!raw!public/styles.css`)
} catch (e) {
// ignore
}
}
const htmlStyles = (args = {}) => {
if (process.env.NODE_ENV === `production`) {
if (... |
Update UserRegistrationForm to be connected to an existing OSF user. | from __future__ import absolute_import
from django import forms
from django.db.models import Q
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
... | from __future__ import absolute_import
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import Group
from osf.models.user import OSFUser
from admin.common_auth.models import AdminProfile
cl... |
Add GET location by ID route. | const express = require('express');
const router = express.Router();
const authController = require('./authController');
const locationsController = require('./locationsController');
const locationTypeController = require('./locationTypeController');
const happyHoursController = require('./happyHoursController');
ro... | const express = require('express');
const router = express.Router();
const authController = require('./authController');
const locationsController = require('./locationsController');
const locationTypeController = require('./locationTypeController');
const happyHoursController = require('./happyHoursController');
ro... |
Fix Wholeness of the World to be max 1 per round | const DrawCard = require('../../drawcard.js');
class WholenessOfTheWorld extends DrawCard {
setupCardAbilities(ability) {
this.wouldInterrupt({
title: 'Keep a claimed ring',
when: {
onReturnRing: (event, context) => event.ring.claimedBy === context.player.name
... | const DrawCard = require('../../drawcard.js');
class WholenessOfTheWorld extends DrawCard {
setupCardAbilities() {
this.wouldInterrupt({
title: 'Keep a claimed ring',
when: {
onReturnRing: (event, context) => event.ring.claimedBy === context.player.name
}... |
Set return with config SentinelBootstraper instance | <?php
if (!function_exists('auth')) {
function auth()
{
return sentinel();
}
}
if (!function_exists('sentinel')) {
function sentinel()
{
$config = new Library\Sentinel\SentinelBootstrapper(__DIR__.'/../config/sentinel.php');
return Cartalyst\Sentinel\Native\Facades\Sentine... | <?php
if (!function_exists('auth')) {
function auth()
{
return sentinel();
}
}
if (!function_exists('sentinel')) {
function sentinel()
{
return Cartalyst\Sentinel\Native\Facades\Sentinel::instance()->getSentinel();
}
}
if (!function_exists('user')) {
function user($user = ... |
Fix displaying quotes in followups list | angular.module('codebrag.common.directives')
.directive('reactionMessageSummary', function($filter) {
return {
restrict: 'E',
template: '<span ng-bind-html-unsafe="reactionMessage"></span>',
replace: true,
scope: {
reaction: '='
}... | angular.module('codebrag.common.directives')
.directive('reactionMessageSummary', function() {
return {
restrict: 'E',
template: '<span>{{reactionMessage | truncate:50}}</span>',
replace: true,
scope: {
reaction: '='
},
... |
Fix media deletion issues and media model implicit binding | <?php
declare(strict_types=1);
use Cortex\Foundation\Http\Middleware\Clockwork;
use Illuminate\Database\Eloquent\Relations\Relation;
return function () {
// Bind route models and constrains
Route::pattern('locale', '[a-z]{2}');
Route::pattern('media', '[a-zA-Z0-9-_]+');
Route::pattern('accessarea', '... | <?php
declare(strict_types=1);
use Cortex\Foundation\Http\Middleware\Clockwork;
use Illuminate\Database\Eloquent\Relations\Relation;
return function () {
// Bind route models and constrains
Route::pattern('locale', '[a-z]{2}');
Route::pattern('accessarea', '[a-zA-Z0-9-_]+');
Route::model('media', con... |
Make helper functions full `@deploy`s so they support global pyinfra kwargs. | from pyinfra.api import deploy
from .configure import configure_kubeconfig, configure_kubernetes_component
from .install import install_kubernetes
@deploy('Deploy Kubernetes master')
def deploy_kubernetes_master(
state, host,
etcd_nodes,
):
# Install server components
install_kubernetes(components=(
... | from .configure import configure_kubeconfig, configure_kubernetes_component
from .install import install_kubernetes
def deploy_kubernetes_master(etcd_nodes):
# Install server components
install_kubernetes(components=(
'kube-apiserver', 'kube-scheduler', 'kube-controller-manager',
))
# Configu... |
Use double quotes instead of single ones. | var gulp = require("gulp");
var tasks = [];
// Browserify
var browserify = require("browserify");
var vinylSourceStream = require("vinyl-source-stream");
var makeBrowserify = function(source, destination, output) {
gulp.task(output+"-browserify", function() {
bundler = browserify(source);
bundler.transform(... | var gulp = require('gulp');
var tasks = [];
// Browserify
var browserify = require('browserify');
var vinylSourceStream = require('vinyl-source-stream');
var makeBrowserify = function(source, destination, output) {
gulp.task(output+"-browserify", function() {
bundler = browserify(source);
bundler.transform(... |
Replace function that IE11 does not support
https://bugzilla.redhat.com/show_bug.cgi?id=1448104 | //= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requ... | //= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requ... |
Update default CONDA_NPY to 18 | from __future__ import print_function, division, absolute_import
import os
import sys
from os.path import abspath, expanduser, join
import conda.config as cc
CONDA_PY = int(os.getenv('CONDA_PY', cc.default_python.replace('.', '')))
CONDA_NPY = int(os.getenv('CONDA_NPY', 18))
PY3K = int(bool(CONDA_PY >= 30))
if cc.... | from __future__ import print_function, division, absolute_import
import os
import sys
from os.path import abspath, expanduser, join
import conda.config as cc
CONDA_PY = int(os.getenv('CONDA_PY', cc.default_python.replace('.', '')))
CONDA_NPY = int(os.getenv('CONDA_NPY', 17))
PY3K = int(bool(CONDA_PY >= 30))
if cc.... |
Update solution to be consistent | def my_init(shape=(5, 5, 3, 3), dtype=None):
array = np.zeros(shape=shape)
array[2, 2] = np.eye(3)
return array
conv_strides_same = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="same", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
conv_strides_va... |
def my_init(shape, dtype=None):
array = np.zeros(shape=(5,5,3,3))
array[2,2] = np.eye(3)
return array
inp = Input((None, None, 3), dtype="float32")
x = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="same", kernel_initializer=my_init)(inp)
conv_strides_same = Model(inputs=inp, output... |
Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded.
PiperOrigin-RevId: 413779472 | # Lint as: python3
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | # Lint as: python3
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
Update blueprint to prepare for publishing. | module.exports = {
normalizeEntityName: function() {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
},
afterInstall: function() {
return this.addBowerPackagesToProject([
{ name: 'qunit', target: '~1.20... | module.exports = {
normalizeEntityName: function() {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
},
afterInstall: function() {
return this.addBowerPackagesToProject([
{ name: 'qunit', target: '~1.19... |
Check props before calling function | // main.js
(function() {
'use strict';
var React = require('react');
var d3 = require('d3');
var Whiteboard = React.createClass({
svg: null,
propTypes: {
width: React.PropTypes.number,
height: React.PropTypes.number,
listener: React.PropTypes.func
},
componentDidMount: func... | // main.js
(function() {
'use strict';
var React = require('react');
var d3 = require('d3');
var Whiteboard = React.createClass({
svg: null,
propTypes: {
width: React.PropTypes.number,
height: React.PropTypes.number,
listener: React.PropTypes.func
},
componentDidMount: func... |
Use only 1byte on setValue | package com.uxxu.konashi.lib.action;
import android.bluetooth.BluetoothGattService;
import com.uxxu.konashi.lib.KonashiUUID;
import com.uxxu.konashi.lib.KonashiUtils;
import com.uxxu.konashi.lib.store.UartStore;
import com.uxxu.konashi.lib.util.UartUtils;
import java.util.UUID;
/**
* Created by e10dokup on 2015/09... | package com.uxxu.konashi.lib.action;
import android.bluetooth.BluetoothGattService;
import com.uxxu.konashi.lib.KonashiUUID;
import com.uxxu.konashi.lib.KonashiUtils;
import com.uxxu.konashi.lib.store.UartStore;
import com.uxxu.konashi.lib.util.UartUtils;
import java.util.UUID;
/**
* Created by e10dokup on 2015/09... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.