text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Move dependencies into their own bundle to improve caching | var path = require('path')
module.exports = {
entry: {
app: './src/main.js',
vendors: [
'vue',
'vue-resource',
'vue-router',
],
},
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: '/themes/{{ name }}/dist/',
... | var path = require('path')
module.exports = {
entry: {
app: './src/main.js',
},
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: '/themes/{{ name }}/dist/',
filename: '[name].js',
},
resolve: {
extensions: ['', '.js', '.vue'],
alias: {
... |
[AllBundles] Fix doctrine common deprecations and resolve doctrine bundle v2 incompatibility | <?php
namespace Kunstmaan\PagePartBundle\Tests\Form;
use Kunstmaan\NodeBundle\Form\Type\URLChooserType;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Form\FormBuilder;
use Symfo... | <?php
namespace Kunstmaan\PagePartBundle\Tests\Form;
use Kunstmaan\NodeBundle\Form\Type\URLChooserType;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Form\FormBuilder;
use Symfo... |
ecs: Use `instanceof` checks when retrieving components. | /* exported withEntity */
function withEntity(Class) {
return class WithEntity extends Class {
constructor(...args) {
super(...args);
this.components = [];
}
addComponent(...components) {
components.forEach(component => {
if (this.hasComponent(component)) {
return;
... | /* exported withEntity */
function withEntity(Class) {
return class WithEntity extends Class {
constructor(...args) {
super(...args);
this.components = [];
}
addComponent(...components) {
components.forEach(component => {
if (this.hasComponent(component)) {
return;
... |
Handle sugar rest api version properly. | <?php
namespace BisonLab\SugarCrmBundle\Service;
/*
* Just a service object for the sugar7crm-wrapper class.
*/
class SugarWrapper
{
private $sugar;
private $options;
public function __construct($base_url, $username, $password, $platform = "sugar-wrapper")
{
if (!preg_match("/rest\/v[\d_... | <?php
namespace BisonLab\SugarCrmBundle\Service;
/*
* Just a service object for the sugar7crm-wrapper class.
*/
class SugarWrapper
{
private $sugar;
private $options;
public function __construct($base_url, $username, $password, $platform = "sugar-wrapper")
{
if (!preg_match("/rest\/v\d\d... |
Allow for URI with already existing query string | <?php
namespace Laravel\Passport\Http\Controllers;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
class DenyAuthorizationController
{
use RetrievesAuthRequestFromSession;
/**
* The response factory implementation.
*
* @var \Illuminat... | <?php
namespace Laravel\Passport\Http\Controllers;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
class DenyAuthorizationController
{
use RetrievesAuthRequestFromSession;
/**
* The response factory implementation.
*
* @var \Illuminat... |
Create person with last seen | var MissingPerson = require('../../app/models/missingPerson');
exports.create = function (req, res) {
var firstname = req.body.firstname;
var surname = req.body.surname;
var missingPerson = new MissingPerson();
if (firstname) {
missingPerson.forenames = firstname;
}
if (surname) {
... | var MissingPerson = require('../../app/models/missingPerson');
exports.create = function (req, res) {
var firstname = req.body.firstname;
var surname = req.body.surname;
var missingPerson = new MissingPerson();
if (firstname) {
missingPerson.forenames = firstname;
}
if (surname) {
... |
Test login with valid credentials |
"use strict";
describe('Login component', () => {
let element = undefined;
let $rootScope = undefined;
let $compile = undefined;
let mod = angular.module('tests.login', []).service('Authentication', function () {
this.check = false;
this.attempt = credentials => {
if (cred... |
"use strict";
describe('Login component', () => {
let element = undefined;
let $rootScope = undefined;
let $compile = undefined;
let tpl = angular.element(`
<monad-login>
<h1>logged in</h1>
</monad-login>
`);
let mod = angular.module('tests.login', []).service('Authentication', function (... |
Fix for using NAG Fortran 95, due to James Graham <jg307@cam.ac.uk>
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@2515 94b884b6-d6fd-0310-90d3-974f1d3f35e1 | import os
import sys
from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
class NAGFCompiler(FCompiler):
compiler_type = 'nag'
version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)'
executables = {
'version_cmd' : ["f95", "-V"],
... | import os
import sys
from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
class NAGFCompiler(FCompiler):
compiler_type = 'nag'
version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)'
executables = {
'version_cmd' : ["f95", "-V"],
... |
Allow absolute path on twig getPath function | <?php
namespace Victoire\Bundle\CoreBundle\Twig\Extension;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Victoire\Bundle\PageBundle\Helper\PageHelper;
/**
* class RoutingExtension
*/
class RoutingExtention extends RoutingExtension
{
priva... | <?php
namespace Victoire\Bundle\CoreBundle\Twig\Extension;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Victoire\Bundle\PageBundle\Helper\PageHelper;
/**
* class RoutingExtension
*/
class RoutingExtention extends RoutingExtension
{
priva... |
Bump the version number - 0.2.0-dev.
Signed-off-by: Lewis Gunsch <748e1641a368164906d4a0c0e3965345453dcc93@gunsch.ca> | import os
from distutils.core import setup
VERSION = '0.2.0-dev'
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
required = [
'Django >= 1.5.0',
]
setup(
name='madmin',
version=VERSION,
description="Virtual mail administration django app",
author="Lewis Gunsch",
... | import os
from distutils.core import setup
VERSION = '0.1.0'
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
required = [
'Django >= 1.5.0',
]
setup(
name='madmin',
version=VERSION,
description="Virtual mail administration django app",
author="Lewis Gunsch",
auth... |
Make jshint happy with new bind polyfill | if ( ! Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
var target = this;
if (typeof target !== "function") {
throw new TypeError("Function.prototype.bind called on incompatible " + target);
}
var args = Array.prototype.slice.cal... | if ( ! Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
var target = this;
if (typeof target != "function") {
throw new TypeError("Function.prototype.bind called on incompatible " + target);
}
var args = Array.prototype.slice.call... |
Use the cool new array syntax | <?php namespace STS\Tunneler;
use Illuminate\Support\ServiceProvider;
use STS\Tunneler\Console\TunnelerCommand;
use STS\Tunneler\Jobs\CreateTunnel;
class TunnelerServiceProvider extends ServiceProvider{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $de... | <?php namespace STS\Tunneler;
use Illuminate\Support\ServiceProvider;
use STS\Tunneler\Console\TunnelerCommand;
use STS\Tunneler\Jobs\CreateTunnel;
class TunnelerServiceProvider extends ServiceProvider{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $de... |
Fix a bug in redis queue | # -*- coding: utf-8 -*-
import redis
class RedisQueue(object):
"""Simple Queue with Redis Backend"""
def __init__(self, name, namespace='queue', **redis_kwargs):
"""The default connection parameters are: host='localhost', port=6379, db=0"""
self.db = redis.Redis(**redis_kwargs)
self.ke... | # -*- coding: utf-8 -*-
import redis
class RedisQueue(object):
"""Simple Queue with Redis Backend"""
def __init__(self, name, namespace='queue', **redis_kwargs):
"""The default connection parameters are: host='localhost', port=6379, db=0"""
self.db = redis.Redis(**redis_kwargs)
self.ke... |
Check gamerule before translating formattings | package com.ptsmods.morecommands.commands.server.elevated;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.ptsmods.morecommands.MoreCommands;
import com.ptsmods.morecommands.miscellaneous.Command;
import com.ptsmods.morecommands.miscellaneous.MoreGame... | package com.ptsmods.morecommands.commands.server.elevated;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.ptsmods.morecommands.MoreCommands;
import com.ptsmods.morecommands.miscellaneous.Command;
import net.minecraft.item.ItemStack;
import net.minecr... |
Add boleta xml generator tests | <?php
/**
* Created by PhpStorm.
* User: Giansalex
* Date: 16/07/2017
* Time: 22:54
*/
declare(strict_types=1);
namespace Tests\Greenter\Xml\Builder;
use Greenter\Data\Generator\BoletaStore;
use Greenter\Data\Generator\InvoiceFullStore;
use Greenter\Data\Generator\InvoiceStore;
use Greenter\Model\Sale\Invoice;
... | <?php
/**
* Created by PhpStorm.
* User: Giansalex
* Date: 16/07/2017
* Time: 22:54
*/
declare(strict_types=1);
namespace Tests\Greenter\Xml\Builder;
use Greenter\Data\Generator\InvoiceFullStore;
use Greenter\Data\Generator\InvoiceStore;
use Greenter\Model\Sale\Invoice;
use PHPUnit\Framework\TestCase;
/**
* C... |
Save and restore state of view on attach to presenter | package com.neoranga55.androidconfchangeloaders.presenters;
/**
* Created by neoranga on 28/03/2016.
*/
public class DemoPresenter implements DemoContract.UserActions<DemoContract.ViewActions> {
private DemoContract.ViewActions mViewActions;
private Thread mSlowTask;
private boolean isLoading;
priva... | package com.neoranga55.androidconfchangeloaders.presenters;
import android.os.AsyncTask;
/**
* Created by neoranga on 28/03/2016.
*/
public class DemoPresenter implements DemoContract.UserActions<DemoContract.ViewActions> {
private DemoContract.ViewActions mViewActions;
private Thread mSlowTask;
@Over... |
Enlarge the waiting before start count down | 'use strict';
(function () {
angular
.module('dailyMummApp')
.controller('NavbarDirectiveCtrl', NavbarDirectiveController);
NavbarDirectiveController.$inject = ['$scope', 'AuthService', '$state', '$timeout', 'CountDownService', 'CurrentOrderService'];
function NavbarDirectiveController($s... | 'use strict';
(function () {
angular
.module('dailyMummApp')
.controller('NavbarDirectiveCtrl', NavbarDirectiveController);
NavbarDirectiveController.$inject = ['$scope', 'AuthService', '$state', '$timeout', 'CountDownService', 'CurrentOrderService'];
function NavbarDirectiveController($s... |
Return title numbers in disc and track order, increment disc number if duplicated track number | from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of th... | from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._title_numbers = []
self._discs_and_tracks = {}
for title in self._titles:
# S... |
Allow disabling logging when Winston is not being used | var util = require('util');
var levels = [
'silly',
'input',
'verbose',
'prompt',
'debug',
'http',
'info',
'data',
'help',
'warn',
'error'
];
levels.forEach(function(level) {
exports[level] = function(msg) {
if (!exports.disabled) {
console.log(
... | var util = require('util');
var levels = [
'silly',
'input',
'verbose',
'prompt',
'debug',
'http',
'info',
'data',
'help',
'warn',
'error'
];
levels.forEach(function(level) {
exports[level] = function(msg) {
console.log(
level + ':',
util... |
Update return value order in normalize_signature docstring [skip ci] | from __future__ import print_function, division, absolute_import
from numba import types, typing
def is_signature(sig):
"""
Return whether *sig* is a potentially valid signature
specification (for user-facing APIs).
"""
return isinstance(sig, (str, tuple, typing.Signature))
def _parse_signature... | from __future__ import print_function, division, absolute_import
from numba import types, typing
def is_signature(sig):
"""
Return whether *sig* is a potentially valid signature
specification (for user-facing APIs).
"""
return isinstance(sig, (str, tuple, typing.Signature))
def _parse_signature... |
Allow adding new connection from connection picker | import Select from 'antd/lib/select';
import Icon from 'antd/lib/icon';
import React, { useContext, useState } from 'react';
import { ConnectionsContext } from '../connections/ConnectionsStore';
import ConnectionEditDrawer from '../connections/ConnectionEditDrawer';
const { Option } = Select;
function ConnectionDropd... | import Select from 'antd/lib/select';
import React from 'react';
import { ConnectionsContext } from '../connections/ConnectionsStore';
const { Option } = Select;
function ConnectionDropdown() {
return (
<ConnectionsContext.Consumer>
{context => (
<Select
showSearch
placeholder=... |
Remove trailing whitespace in line 31 | package seedu.ezdo.model.task;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import seedu.ezdo.model.todo.StartDate;
public class StartDateTest {
@Test
public void isValidStartDate() {
// invalid dates
assertFalse(StartDate.isV... | package seedu.ezdo.model.task;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import seedu.ezdo.model.todo.StartDate;
public class StartDateTest {
@Test
public void isValidStartDate() {
// invalid dates
assertFalse(StartDate.isV... |
Check if the cookie exists before accessing it. Little bit of refactoring also. | <?php namespace Hydrarulz\LaravelMixpanel;
use Illuminate\Support\Facades\Config;
use Mixpanel;
class LaravelMixpanel extends Mixpanel {
protected $token;
private static $_instance;
/**
* @param array $token
* @param array $options
*/
public function __construct($token, array $option... | <?php namespace Hydrarulz\LaravelMixpanel;
use Illuminate\Support\Facades\Config;
use Mixpanel;
class LaravelMixpanel extends Mixpanel {
protected $token;
private static $_instance;
/**
* @param array $token
* @param array $options
*/
public function __construct($token, array $option... |
Implement most of test class | /* *\
** SICU Stress Measurement System **
** Project P04 | C380 Team A **
** EBME 380: Biomedical Engineering Design Experience **
** ... | /* *\
** SICU Stress Measurement System **
** Project P04 | C380 Team A **
** EBME 380: Biomedical Engineering Design Experience **
** ... |
Move the babel task to the test task. | 'use strict';
const loadGruntTasks = require('load-grunt-tasks');
const rollupPluginBabel = require('rollup-plugin-babel');
module.exports = function register(grunt) {
loadGruntTasks(grunt);
grunt.initConfig({
eslint: {
all: ['lib', 'test'],
},
clean: {
all: ['dist', 'tmp'],
},
... | 'use strict';
const loadGruntTasks = require('load-grunt-tasks');
const rollupPluginBabel = require('rollup-plugin-babel');
module.exports = function register(grunt) {
loadGruntTasks(grunt);
grunt.initConfig({
eslint: {
all: ['lib', 'test'],
},
clean: {
all: ['dist', 'tmp'],
},
... |
Remove bson, datetime, and mongo
Current BSON fails to work
datetime can't be serialized by json_util
mongodb is not needed; just use JSON | #!/usr/bin/env python
#
# Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json
#
from argparse import ArgumentParser
from bs4 import BeautifulSoup
import json
parser = ArgumentParser(description='Convert Netscape bookmarks to JSON')
parser.add_argument(dest='filenames', metavar='filename', nargs='... | #!/usr/bin/env python
#
# Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json
#
from argparse import ArgumentParser
from bs4 import BeautifulSoup
from datetime import datetime, timezone
from bson import json_util
import json
parser = ArgumentParser(description='Convert Netscape bookmarks to JSON... |
Remove leftover `console.log` in `clever env import` | 'use strict';
const readline = require('readline');
const _ = require('lodash');
const Bacon = require('baconjs');
function parseLine (line) {
const p = line.split('=');
const key = p[0];
p.shift();
const value = p.join('=');
if (line.trim()[0] !== '#' && p.length > 0) {
return [key.trim(), value.trim(... | 'use strict';
const readline = require('readline');
const _ = require('lodash');
const Bacon = require('baconjs');
function parseLine (line) {
const p = line.split('=');
const key = p[0];
p.shift();
const value = p.join('=');
if (line.trim()[0] !== '#' && p.length > 0) {
return [key.trim(), value.trim(... |
Fix the issue of override url by mistake. | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from mezzanine.core.views import direct_to_template
admin.autodiscover()
# Must be defined before aut... | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from mezzanine.core.views import direct_to_template
admin.autodiscover()
# Must be defined before aut... |
Fix bug in round results property | package es.tid.smartsteps.dispersion;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
/**
*
* @author dmicol
*/
public abstract class Config {
public static final String DELIM... | package es.tid.smartsteps.dispersion;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
/**
*
* @author dmicol
*/
public abstract class Config {
public static final String DELIM... |
Update requirements to things that work | from setuptools import setup
setup(name='eventum',
version='0.2.6',
description='A content management system for event-driven Flask apps',
url='http://github.com/danrschlosser/eventum',
author='Dan Schlosser',
author_email='dan@schlosser.io',
license='MIT',
packages=['eventum'... | from setuptools import setup
setup(name='eventum',
version='0.2.6',
description='A content management system for event-driven Flask apps',
url='http://github.com/danrschlosser/eventum',
author='Dan Schlosser',
author_email='dan@schlosser.io',
license='MIT',
packages=['eventum'... |
Fix wrong model id key (1011) | <?php
declare(strict_types=1);
namespace Inowas\ModflowModel\Model\Command;
use Inowas\Common\Id\ModflowId;
use Inowas\Common\Id\UserId;
use Inowas\Common\Soilmodel\LayerId;
use Prooph\Common\Messaging\Command;
use Prooph\Common\Messaging\PayloadConstructable;
use Prooph\Common\Messaging\PayloadTrait;
class RemoveL... | <?php
declare(strict_types=1);
namespace Inowas\ModflowModel\Model\Command;
use Inowas\Common\Id\ModflowId;
use Inowas\Common\Id\UserId;
use Inowas\Common\Soilmodel\LayerId;
use Prooph\Common\Messaging\Command;
use Prooph\Common\Messaging\PayloadConstructable;
use Prooph\Common\Messaging\PayloadTrait;
class RemoveL... |
Fix init of local recognizer | import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
rl = RecognizerL... | import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
self.recognizer ... |
Remove locale related reassignment to global window object | import React from 'react';
import PropTypes from 'prop-types';
import getDisplayName from '../utils/getDisplayName';
import { localeShape } from '../constants/PropTypes';
export default Page => {
class WithLocale extends React.Component {
static displayName = getDisplayName('WithLocale', Page);
static propT... | import React from 'react';
import PropTypes from 'prop-types';
import getDisplayName from '../utils/getDisplayName';
import { localeShape } from '../constants/PropTypes';
export default Page => {
class WithLocale extends React.Component {
static displayName = getDisplayName('WithLocale', Page);
static propT... |
BAP-12468: Update ApplicationsHelper and ActionApplicationsHelper
- fix phpdoc | <?php
namespace Oro\Bundle\ActionBundle\Helper;
use Symfony\Component\Routing\RouterInterface;
class ApplicationsUrlHelper
{
/** @var ApplicationsHelper */
private $applicationsHelper;
/** @var RouterInterface */
private $router;
/**
* @param ApplicationsHelperInterface $applicationsHelper... | <?php
namespace Oro\Bundle\ActionBundle\Helper;
use Symfony\Component\Routing\RouterInterface;
class ApplicationsUrlHelper
{
/** @var ApplicationsHelper */
private $applicationsHelper;
/** @var RouterInterface */
private $router;
/**
* @param ApplicationsHelperInterface $applicationsHelper... |
Set period to 24 hours now that it works | """Updates atom feeds."""
import datetime
import time
import db
import tools
# Time in seconds between re-processing a domain.
PERIOD = 86400
if __name__ == '__main__':
while True:
try:
start = time.time()
# Pick the oldest domain.
with db.cursor... | """Updates atom feeds."""
import datetime
import time
import db
import tools
# Time in seconds between re-processing a domain.
PERIOD = 60#86400
if __name__ == '__main__':
while True:
try:
start = time.time()
# Pick the oldest domain.
with db.cur... |
Change the singleRun Karma option to true for Travis builds | module.exports = function karma(config) {
config.set({
frameworks: ['mocha'],
files: [
{ pattern: 'src/**/*.js', included: false },
'tests/**/*.js',
],
preprocessors: {
'tests/**/*.js': ['webpack', 'sourcemap'],
},
webpack: {
module: {
loaders: [
{
... | module.exports = function karma(config) {
config.set({
frameworks: ['mocha'],
files: [
{ pattern: 'src/**/*.js', included: false },
'tests/**/*.js',
],
preprocessors: {
'tests/**/*.js': ['webpack', 'sourcemap'],
},
webpack: {
module: {
loaders: [
{
... |
Fix condition, make sure not to include non-pivot relations | <?php
class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder
{
/**
* Eager load pivot relations.
*
* @param array $models
* @return void
*/
protected function loadPivotRelations($models)
{
$query = head($models)->pivot->newQuery()->with('unit');
$pivot... | <?php
class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder
{
/**
* Eager load pivot relations.
*
* @param array $models
* @return void
*/
protected function loadPivotRelations($models)
{
$query = head($models)->pivot->newQuery()->with('unit');
$pivot... |
Send userID if it exists | import React from 'react';
import './Rating.scss';
import { AuthCtx } from '../withUser';
class Rating extends React.Component {
constructor(props) {
super(props);
this.ratingVals = [
1, 2, 3, 4, 5
];
this.state = {
rating: 0,
hasRating: false,
}
}
componentDidMount() {
... | import React from 'react';
import './Rating.scss';
import { AuthCtx } from '../withUser';
class Rating extends React.Component {
constructor(props) {
super(props);
this.ratingVals = [
1, 2, 3, 4, 5
];
this.state = {
rating: 0,
hasRating: false,
}
}
componentDidMount() {
... |
Make the anchor working when edit a XML file | 'use strict';
/**
* @ngdoc directive
* @name waxeApp.directive:editor
* @description
* # editor
*/
angular.module('waxeApp')
.directive('editor', ['$interval', '$anchorScroll', '$location', 'Session', 'FileUtils', function ($interval, $anchorScroll, $location, Session, FileUtils) {
return {
... | 'use strict';
/**
* @ngdoc directive
* @name waxeApp.directive:editor
* @description
* # editor
*/
angular.module('waxeApp')
.directive('editor', ['$interval', 'Session', 'FileUtils', function ($interval, Session, FileUtils) {
return {
template: '<div></div>',
restrict: 'E',
... |
Handle zero-arguments case in bitcoinj-cli | package com.msgilligan.bitcoinj.cli;
import com.msgilligan.bitcoinj.rpc.JsonRPCException;
import java.io.IOException;
import java.util.List;
/**
* An attempt at cloning the bitcoin-cli tool, but using Java and bitcoinj
*
*/
public class BitcoinJCli extends CliCommand {
public final static String commandName =... | package com.msgilligan.bitcoinj.cli;
import com.msgilligan.bitcoinj.rpc.JsonRPCException;
import java.io.IOException;
import java.util.List;
/**
* An attempt at cloning the bitcoin-cli tool, but using Java and bitcoinj
*
*/
public class BitcoinJCli extends CliCommand {
public final static String commandName =... |
Fix import error when compiling without OpenSSL support | ####################################################################
#Dtool_funcToMethod(func, class)
#del func
#####################################################################
from panda3d import core
from .extension_native_helpers import Dtool_funcToMethod
"""
HTTPChannel-extensions module: contains me... | ####################################################################
#Dtool_funcToMethod(func, class)
#del func
#####################################################################
from panda3d.core import HTTPChannel
from .extension_native_helpers import Dtool_funcToMethod
"""
HTTPChannel-extensions module:... |
Update grunt for bin file | module.exports = function(grunt) {
var path = require('path');
grunt.initConfig({
clean: [
'dist'
],
jshint: {
all: {
src: [
'Gruntfile.js',
'lib/**/*.js'
]
},
options: {
jshintrc: '.jshintrc',
force: true
}
},
tr... | module.exports = function(grunt) {
var path = require('path');
grunt.initConfig({
clean: [
'dist'
],
transpile: {
app: {
type: 'cjs',
files: [{
expand: true,
src: ['bin/es6-module-packager', 'lib/**/*.js'],
dest: 'tmp/transpiled/'
}]
... |
Change development status from pre-alpha to alpha | import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
# import here, cause outside... | import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
# import here, cause outside... |
Disable automatic header numbering for now | function Structure()
{
this.outline = null;
}
Structure.prototype.numberHeadings = function()
{
var sectionNumbers = [0,0,0,0,0,0];
for (var child = document.body.firstChild; child != null; child = child.nextSibling) {
if (isHeadingElement(child)) {
var level = parseInt(child.nodeName.s... | function Structure()
{
this.outline = null;
}
Structure.prototype.numberHeadings = function()
{
var sectionNumbers = [0,0,0,0,0,0];
for (var child = document.body.firstChild; child != null; child = child.nextSibling) {
if (isHeadingElement(child)) {
var level = parseInt(child.nodeName.s... |
[Dns] Fix parse errors in resolver stub | <?php
namespace React\Dns;
use React\Socket\Connection;
class Resolver
{
public function resolve($domain, $callback)
{
$nameserver = '8.8.8.8';
$query = new Query($domain, 'A', 'IN');
$this->query($nameserver, $query, function (Message $response) use ($callback) {
$answer... | <?php
namespace React\Dns;
use React\Socket\Connection;
class Resolver
{
public function resolve($domain, $callback)
{
$nameserver = '8.8.8.8';
$query = new Query($domain, 'A', 'IN');
$this->query($nameserver, $query, function (Message $response) use ($callback) {
$answer... |
Make visible to interpreter "compositions" outside this package.
svn path=/spoofax/trunk/spoofax/org.spoofax.interpreter.adapter.ecj/; revision=16660 | /*
*
* Copyright (c) 2005, Karl Trygve Kalleberg <karltk@ii.uib.no>
*
* Licensed under the GNU General Public License, v2
*/
package org.spoofax.interpreter.library.ecj;
import org.spoofax.interpreter.library.AbstractStrategoOperatorRegistry;
public class ECJLibrary extends AbstractStrategoOperatorRegistry {
... | /*
*
* Copyright (c) 2005, Karl Trygve Kalleberg <karltk@ii.uib.no>
*
* Licensed under the GNU General Public License, v2
*/
package org.spoofax.interpreter.library.ecj;
import org.spoofax.interpreter.library.AbstractStrategoOperatorRegistry;
public class ECJLibrary extends AbstractStrategoOperatorRegistry {
... |
Adjust check to reject single-column entries | /**
* @class csv
* @module Parsers
*/
module.exports = (function() {
var FileParser = require('../interfaces/FileParser');
/**
* @method Parser
* @constructor
*/
function Parser(file, options) {
FileParser.apply(this, arguments);
if (options && options.separator) {
... | /**
* @class csv
* @module Parsers
*/
module.exports = (function() {
var FileParser = require('../interfaces/FileParser');
/**
* @method Parser
* @constructor
*/
function Parser(file, options) {
FileParser.apply(this, arguments);
if (options && options.separator) {
... |
Configure a title for the subscribe page | @extends('layout.master')
@section('title', trans('cachet.subscriber.subscribe'). " | ". $site_title))
@section('description', trans('cachet.meta.description.subscribe', ['app' => $site_title]))
@section('content')
<div class="pull-right">
<p><a class="btn btn-success btn-outline" href="{{ cachet_route('status-... | @extends('layout.master')
@section('description', trans('cachet.meta.description.subscribe', ['app' => $site_title]))
@section('content')
<div class="pull-right">
<p><a class="btn btn-success btn-outline" href="{{ cachet_route('status-page') }}"><i class="ion ion-home"></i></a></p>
</div>
<div class="clearfix"><... |
Add placeholders for new secondary repo details | """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
... | """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
... |
Fix doc styles in Firefox | import React from 'react';
import CodeBlock from './CodeBlock';
export default class StaticHTMLBlock {
static propTypes = {
html: React.PropTypes.string.isRequired
};
render() {
const { html } = this.props;
// Here goes a really hack-ish way to convert
// areas separated by Markdown <hr>s into ... | import React from 'react';
import CodeBlock from './CodeBlock';
export default class StaticHTMLBlock {
static propTypes = {
html: React.PropTypes.string.isRequired
};
render() {
const { html } = this.props;
// Here goes a really hack-ish way to convert
// areas separated by Markdown <hr>s into ... |
Work around a problem in later (currently unsupported) embers where Ember.computed.bool is not a function | import { run } from '@ember/runloop';
import Helper from '@ember/component/helper';
import { get, observer, computed } from '@ember/object';
import { inject as service } from '@ember/service';
export default Helper.extend({
moment: service(),
disableInterval: false,
globalAllowEmpty: computed('moment.__config__.... | import { run } from '@ember/runloop';
import Helper from '@ember/component/helper';
import { get, observer, computed } from '@ember/object';
import { inject as service } from '@ember/service';
export default Helper.extend({
moment: service(),
disableInterval: false,
globalAllowEmpty: computed.bool('moment.__conf... |
Add the repo name to the github package repo url
see https://github.com/freefair/gradle-plugins/issues/50#issuecomment-517961934 | package io.freefair.gradle.plugins.github;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin;
/**
* @author Lars Grefer
*/
public class GithubPackageRegistryMavenPublishPlugin implements Plug... | package io.freefair.gradle.plugins.github;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin;
/**
* @author Lars Grefer
*/
public class GithubPackageRegistryMavenPublishPlugin implements Plug... |
Fix a typo in the comparison string which caused the test to always fail. | <?php
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Relies on PHPUnit to test the functionality in ./Get_BasePathmapping.php.
Related custom constants are defined in ./phpunit.xml.
Example PHPUnit run command from this file's parent directory:
./vendor/... | <?php
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
/*
Relies on PHPUnit to test the functionality in ./Get_BasePathmapping.php.
Related custom constants are defined in ./phpunit.xml.
Example PHPUnit run command from this file's parent directory:
./vendor/... |
Add 2 more tests to cover cases where parent node isn't `computed` | describe('lib/rules/disallow-computedany', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowComputedAny: un... | describe('lib/rules/disallow-computedany', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowComputedAny: un... |
:bug: Abort clickoutside for null target | function getTest(el) {
if (Array.isArray(el)) {
return target => el.includes(target);
}
if (typeof el === 'function') {
return target => el(target);
}
return target => target === el;
}
export default function clickOutside(el, fn) {
const test = getTest(el);
function onClick... | function getTest(el) {
if (Array.isArray(el)) {
return target => el.includes(target);
}
if (typeof el === 'function') {
return target => el(target);
}
return target => target === el;
}
export default function clickOutside(el, fn) {
const test = getTest(el);
function onClick... |
Normalize check email step errors | 'use strict';
const AccountManager = require('../account-manager');
const {handleResponseData} = require('../utils');
module.exports = class CheckEmail {
constructor({name, retryStep} = {}) {
this.name = name;
this.retryStep = retryStep;
}
start(data) {
return AccountManager.checkEmail(data)
.t... | 'use strict';
const AccountManager = require('../account-manager');
const {handleResponseData} = require('../utils');
module.exports = class CheckEmail {
constructor({name, retryStep} = {}) {
this.name = name;
this.retryStep = retryStep;
}
start(data) {
return AccountManager.checkEmail(data)
.t... |
Revert "Assign quality values when checking MIME types"
This reverts commit b06842f3d5dea138f2962f91105926d889157773. | from __future__ import unicode_literals
from flask import Request
class AcceptRequest(Request):
_json_mimetypes = ['application/json',]
_html_mimetypes = ['text/html', 'application/xhtml+xml']
_xml_mimetypes = ['application/xml', 'text/xml']
_rss_mimetypes = ['application/rss+xml', 'application/rd... | from __future__ import unicode_literals
from flask import Request
from itertools import repeat, chain
class AcceptRequest(Request):
_json_mimetypes = ['application/json',]
_html_mimetypes = ['text/html', 'application/xhtml+xml']
_xml_mimetypes = ['application/xml', 'text/xml']
_rss_mimetypes = ['a... |
Add published year to title | (function (env) {
"use strict";
env.ddg_spice_arxiv = function(api_result){
if (!api_result) {
return Spice.failed('arxiv');
}
Spice.add({
id: "arxiv",
name: "Reference",
data: api_result,
meta: {
sourceName: ... | (function (env) {
"use strict";
env.ddg_spice_arxiv = function(api_result){
if (!api_result) {
return Spice.failed('arxiv');
}
Spice.add({
id: "arxiv",
name: "Reference",
data: api_result,
meta: {
sourceName: ... |
Update to reflect new create_app signature | from __future__ import print_function
from getpass import getpass
import readline
import sys
import annotator
from annotator.model import Consumer, User
if __name__ == '__main__':
r = raw_input("This program will perform initial setup of the annotation \n"
"store, and create the required admin ... | from __future__ import print_function
from getpass import getpass
import readline
import sys
import annotator
from annotator.model import Consumer, User
if __name__ == '__main__':
r = raw_input("This program will perform initial setup of the annotation \n"
"store, and create the required admin ... |
Change routeScript type to array (before object), and change the angular.foreach to navite javascript forEach | /**
* Created by Victor Avendano on 1/10/15.
* avenda@gmail.com
*/
'use strict';
(function(){
var mod = angular.module('routeScripts', ['ngRoute']);
mod.directive('routeScripts', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
lin... | /**
* Created by Victor Avendano on 1/10/15.
* avenda@gmail.com
*/
'use strict';
(function(){
var mod = angular.module('routeScripts', ['ngRoute']);
mod.directive('routeScripts', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
lin... |
Set user object in session | <?php
namespace Koddi\Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
class AuthController
{
public function getLogin(Application $app)
{
$username = $app['request']->server->get('PHP_AUTH_USER', false);
$password = $app['request']->server->get('PHP_AUTH_PW')... | <?php
namespace Koddi\Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
class AuthController
{
public function getLogin(Application $app)
{
$username = $app['request']->server->get('PHP_AUTH_USER', false);
$password = $app['request']->server->get('PHP_AUTH_PW')... |
Update package serviceprovider to support laravel 5.2 | <?php
namespace Benrowe\Laravel\Url;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
use Blade;
/**
* Url Service Provider
* Registers the service provider into the application IOC
*
* @package Benrowe\Laravel\Url
*/
class ServiceProvider extends LaravelServiceProvider
{
protected $defe... | <?php
/**
* This file is part of the laravel url package.
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace Benrowe\Laravel\Url;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
use Blade;
/**
* Url Ser... |
Fix employee form error about password hashing | from django import forms
from django.contrib import admin
from .models import Employee, Role
class UserCreationForm(forms.ModelForm):
class Meta:
model = Employee
fields = ('username', 'password',)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
... | from django.contrib import admin
from .models import Employee, Role
class RoleAdmin(admin.ModelAdmin):
list_display = ("name",)
class EmployeeAdmin(admin.ModelAdmin):
list_display = ("username", "first_name", "last_name", "email", 'level', 'score',)
fieldsets = (
(None, {'fields': ('username', '... |
Add support for y field of a pv | ''' Representation of an element
@param element_type: type of the element
@param length: length of the element
'''
import pkg_resources
from rml.exceptions import ConfigException
pkg_resources.require('cothread')
from cothread.catools import caget
class Element(object):
def __init__(self, element_type, length, **... | ''' Representation of an element
@param element_type: type of the element
@param length: length of the element
'''
import pkg_resources
from rml.exceptions import ConfigException
pkg_resources.require('cothread')
from cothread.catools import caget
class Element(object):
def __init__(self, element_type, length, **... |
Remove window param from self-exec main function | (function ($) {
'use strict';
var partner = 'YW5kcm9pZC12M3M',
build_url = function (url, params) {
return url + '?' + $.param(params);
},
methods = {
searchMovie: function (qparam, ajaxOptions) {
return this.each(function () {
... | (function (window, $) {
'use strict';
var partner = 'YW5kcm9pZC12M3M',
build_url = function (url, params) {
return url + '?' + $.param(params);
},
methods = {
searchMovie: function (qparam, ajaxOptions) {
return this.each(function () {
... |
Move things around on the settings controller | <?hh
class SettingsController extends BaseController {
public static function getPath(): string {
return '/settings';
}
public static function getConfig(): ControllerConfig {
return (new ControllerConfig())
->setUserRoles(array(UserRole::Superuser));
}
public static function get(): :xhp {
... | <?hh
class SettingsController extends BaseController {
public static function getPath(): string {
return '/settings';
}
public static function getConfig(): ControllerConfig {
return (new ControllerConfig())
->setUserRoles(array(UserRole::Superuser));
}
public static function get(): :xhp {
... |
Add "Table Header" (tblHeader) support for table rows (repeat row on each page, as needed). | <?php
/**
* This file is part of the PHP Open Doc library.
*
* @author Jason Morriss <lifo101@gmail.com>
* @since 1.0
*
*/
namespace PHPDOC\Document\Writer\Word2007\Formatter;
use PHPDOC\Element\ElementInterface,
PHPDOC\Document\Writer\Word2007\Translator,
PHPDOC\Document\Writer\Exception\SaveException
... | <?php
/**
* This file is part of the PHP Open Doc library.
*
* @author Jason Morriss <lifo101@gmail.com>
* @since 1.0
*
*/
namespace PHPDOC\Document\Writer\Word2007\Formatter;
use PHPDOC\Element\ElementInterface,
PHPDOC\Document\Writer\Word2007\Translator,
PHPDOC\Document\Writer\Exception\SaveException
... |
Add legacy slug to embedded Party on memberships | from rest_framework import serializers
from parties.models import Party, PartyDescription, PartyEmblem
class PartyEmblemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PartyEmblem
fields = (
"image",
"description",
"date_approved",
... | from rest_framework import serializers
from parties.models import Party, PartyDescription, PartyEmblem
class PartyEmblemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PartyEmblem
fields = (
"image",
"description",
"date_approved",
... |
Update visitor strongCoupling unit test | <?php
namespace Solidifier;
use Solidifier\Analyzers\FakeAnalyzer;
class ConfigurationHandlerTest extends \PHPUnit_Framework_TestCase
{
private
$analyzer;
protected function setUp()
{
$this->analyzer = new FakeAnalyzer();
}
private function getVisitorTypes()
{
... | <?php
namespace Solidifier;
use Solidifier\Analyzers\FakeAnalyzer;
class ConfigurationHandlerTest extends \PHPUnit_Framework_TestCase
{
private
$analyzer;
protected function setUp()
{
$this->analyzer = new FakeAnalyzer();
}
private function getVisitorTypes()
{
... |
Make the FetchedValue marked as for_update
SQLAlchemy is currently unable to determine between a FetchedValue
inside of a server_default and one inside of a server_onupdate
causing the one in server_onupdate to override the func.now()
in server_default.
See: http://www.sqlalchemy.org/trac/ticket/2631 | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.... |
Convert file to string before sending downstream. | 'use strict';
var PluginError = require('plugin-error'),
through = require('through2'),
inlineCss = require('inline-css');
module.exports = function (opt) {
return through.obj(function (file, enc, cb) {
var self = this,
_opt = JSON.parse(JSON.stringify(opt || {}));
// 'url' op... | 'use strict';
var PluginError = require('plugin-error'),
through = require('through2'),
inlineCss = require('inline-css');
module.exports = function (opt) {
return through.obj(function (file, enc, cb) {
var self = this,
_opt = JSON.parse(JSON.stringify(opt || {}));
// 'url' op... |
[casspy] Change to console command prompt | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Cassoundra: admin-commands
~~~~~~~~~~
Module to handle special commands to control the bot once it is already running.
Created by Joshua Prince, 2017
"""
import discord
from casspy import cassoundra
async def process_input(loop):
while True:
command ... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Cassoundra: admin-commands
~~~~~~~~~~
Module to handle special commands to control the bot once it is already running.
Created by Joshua Prince, 2017
"""
import discord
from casspy import cassoundra
async def process_input(loop):
while True:
command ... |
Use tarball to match current version | import os
from setuptools import setup, find_packages
from wagtailmenus import __version__
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setu... | import os
from setuptools import setup, find_packages
from wagtailmenus import __version__
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setu... |
Use `ifError` assertion instead of `equal`. | 'use strict';
var grunt = require('grunt');
/**
* Constructs a test case.
*
* @param {string} file The `package.json` file to be tested.
* @param {boolean} valid Flag indicating whether the test is
* expected to pass.
* @param {Array} [args] ... | 'use strict';
var grunt = require('grunt');
/**
* Constructs a test case.
*
* @param {string} file The `package.json` file to be tested.
* @param {boolean} valid Flag indicating whether the test is
* expected to pass.
* @param {Array} [args] ... |
Change to nameId for the userlogin test | <?php
namespace AppBundle\Tests\Connections;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* @file
* Project: orcid
* File: RepositoryTest.php
*/
class UserTest extends KernelTestCase
{
/**
* @var \AppBundle\Security\User
*/
private $user;
private $container;
public funct... | <?php
namespace AppBundle\Tests\Connections;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* @file
* Project: orcid
* File: RepositoryTest.php
*/
class UserTest extends KernelTestCase
{
/**
* @var \AppBundle\Security\User
*/
private $user;
private $container;
public funct... |
Use more precise RegExp for mixin scan | <?php
namespace Jade\Lexer;
/**
* Class Jade\Lexer\MixinScanner.
*/
abstract class MixinScanner extends CaseScanner
{
/**
* @return object
*/
protected function scanCall()
{
if (preg_match('/^\+(\w[-\w]*)/', $this->input, $matches)) {
$this->consume($matches[0]);
... | <?php
namespace Jade\Lexer;
/**
* Class Jade\Lexer\MixinScanner.
*/
abstract class MixinScanner extends CaseScanner
{
/**
* @return object
*/
protected function scanCall()
{
if (preg_match('/^\+(\w[-\w]*)/', $this->input, $matches)) {
$this->consume($matches[0]);
... |
Make UnionFind.unite return whether the operation was successful |
class UnionFind(object):
"""A collection of distjoint sets."""
def __init__(self, n = 0):
"""Creates a collection of n disjoint unit sets."""
self.p = [-1]*n
self.leaders = set( i for i in range(n) )
def find(self, x):
"""Return the identifier of a representative element f... |
class UnionFind(object):
"""A collection of distjoint sets."""
def __init__(self, n = 0):
"""Creates a collection of n disjoint unit sets."""
self.p = [-1]*n
self.leaders = set( i for i in range(n) )
def find(self, x):
"""Return the identifier of a representative element f... |
Fix email not being sent | <?php
namespace App\Mail;
use App\User;
use App\Contact;
use App\Reminder;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class UserReminded extends Mailable
{
use Queueable, SerializesModels;
protected $reminder... | <?php
namespace App\Mail;
use App\User;
use App\Contact;
use App\Reminder;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class UserReminded extends Mailable
{
use Queueable, SerializesModels;
protected $reminder... |
Fix windows compiler not finding common.hpp | #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=nat... | #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=nat... |
Return error if user is not logged in | <?php
namespace fennecweb\ajax\details;
use \PDO as PDO;
/**
* Web Service.
* Returns a project according to the project ID.
*/
class Projects extends \fennecweb\WebService
{
/**
* @param $querydata[]
* @returns Array $result
* <code>
* array('project_id': {biomfile});
* </code>
*/
... | <?php
namespace fennecweb\ajax\details;
use \PDO as PDO;
/**
* Web Service.
* Returns a project according to the project ID.
*/
class Projects extends \fennecweb\WebService
{
/**
* @param $querydata[]
* @returns Array $result
* <code>
* array('project_id': {biomfile});
* </code>
*/
... |
Improve performance (set minimongo debug to false) | import minimongo from 'minimongo-cache';
process.nextTick = setImmediate;
const db = new minimongo();
db.debug = false;
export default {
_endpoint: null,
_options: null,
ddp: null,
subscriptions: {},
db: db,
calls: [],
hasBeenConnected: false,
getUrl() {
return this._endpoint.substring(0, this._e... | import minimongo from 'minimongo-cache';
process.nextTick = setImmediate;
export default {
_endpoint: null,
_options: null,
ddp: null,
subscriptions: {},
db: new minimongo(),
calls: [],
hasBeenConnected: false,
getUrl() {
return this._endpoint.substring(0, this._endpoint.indexOf('/websocket'));
... |
Fix map partner SQL request | package org.lagonette.app.room.statement;
public abstract class MapPartnerStatement
extends Statement {
// TODO Why only 87 partners returned ??
public static final String SQL =
"SELECT partner.id, " +
"partner.latitude, " +
"partner.longitude, " +
... | package org.lagonette.app.room.statement;
public abstract class MapPartnerStatement
extends Statement {
// TODO Why only 87 partners returned ??
public static final String SQL =
"SELECT partner.id, " +
"partner.latitude, " +
"partner.longitude, " +
... |
Add public visibility to constructors | <?php
namespace Kunstmaan\DashboardBundle\Widget;
use Doctrine\Common\Annotations\AnnotationReader;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DashboardWidget
{
... | <?php
namespace Kunstmaan\DashboardBundle\Widget;
use Doctrine\Common\Annotations\AnnotationReader;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DashboardWidget
{
... |
Fix text wrapping on Attendee report descriptive text | package org.kumoricon.site.report.attendees;
import com.vaadin.navigator.View;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import org.kumoricon.site.report.ReportVi... | package org.kumoricon.site.report.attendees;
import com.vaadin.navigator.View;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import org.kumoricon.site.report.ReportVi... |
Use preserved games for opening move selection | import random
import pdb
from defines import *
class OpeningsMover(object):
def __init__(self, o_mgr, game):
self.o_mgr = o_mgr
self.game = game
def get_a_good_move(self):
wins = 0
losses = 0
totals = []
colour = self.game.to_move_colour()
max_rating_f... | import random
import pdb
from defines import *
class OpeningsMover(object):
def __init__(self, o_mgr, game):
self.o_mgr = o_mgr
self.game = game
def get_a_good_move(self):
wins = 0
losses = 0
totals = []
colour = self.game.to_move_colour()
max_rating_f... |
Remove logging code from Error Controller. | <?php
class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
$errors = $this->_getParam('error_handler');
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHand... | <?php
class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
$errors = $this->_getParam('error_handler');
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHand... |
Optimize Performance for long lines (use mb_strcut() instead of pred_split()) | <?php
/*
* This file is part of the eluceo/iCal package.
*
* (c) Markus Poerschke <markus@eluceo.de>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Eluceo\iCal\Util;
class ComponentUtil
{
/**
* Folds a single line.
*
... | <?php
/*
* This file is part of the eluceo/iCal package.
*
* (c) Markus Poerschke <markus@eluceo.de>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Eluceo\iCal\Util;
class ComponentUtil
{
/**
* Folds a single line.
*
... |
Add processData and contentType properties to ajax call | // For testing
if (typeof module !== 'undefined') {
$ = require('jquery');
gebo = require('../config').gebo;
FormData = require('./__mocks__/FormData');
}
/**
* Send a request to the gebo. The message can be sent
* as FormData or JSON.
*
* @param object
* @param FormData - optional
... | // For testing
if (typeof module !== 'undefined') {
$ = require('jquery');
gebo = require('../config').gebo;
FormData = require('./__mocks__/FormData');
}
/**
* Send a request to the gebo. The message can be sent
* as FormData or JSON.
*
* @param object
* @param FormData - optional
... |
Fix more CSRF issues on login after 401s | (function() {
'use strict';
angular
.module('sentryApp')
.factory('authExpiredInterceptor', authExpiredInterceptor);
authExpiredInterceptor.$inject = ['$rootScope', '$q', '$injector'];
function authExpiredInterceptor($rootScope, $q, $injector) {
var service = {
res... | (function() {
'use strict';
angular
.module('sentryApp')
.factory('authExpiredInterceptor', authExpiredInterceptor);
authExpiredInterceptor.$inject = ['$rootScope', '$q', '$injector'];
function authExpiredInterceptor($rootScope, $q, $injector) {
var service = {
res... |
Use componentController to load controller | import <%= upCaseName %>Module from './<%= name %>'
import <%= upCaseName %>Controller from './<%= name %>.controller';
import <%= upCaseName %>Component from './<%= name %>.component';
import <%= upCaseName %>Template from './<%= name %>.html';
const { module } = angular.mock;
describe('<%= upCaseName %>', () => {
... | import <%= upCaseName %>Module from './<%= name %>'
import <%= upCaseName %>Controller from './<%= name %>.controller';
import <%= upCaseName %>Component from './<%= name %>.component';
import <%= upCaseName %>Template from './<%= name %>.html';
const { module } = angular.mock;
describe('<%= upCaseName %>', () => {
... |
Set sensitivity of e-mail backend to 2, so notifications with 1 aren't mailed. | from django.conf import settings
from django.core.mail import EmailMessage
from notification.backends.base import NotificationBackend
class EmailBackend(NotificationBackend):
sensitivity = 2
slug = u'email'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def email_for_user(self, rec... | from django.conf import settings
from django.core.mail import EmailMessage
from notification.backends.base import NotificationBackend
class EmailBackend(NotificationBackend):
slug = u'email'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def email_for_user(self, recipient):
ret... |
Support for RPC to work from chrome ext itself.
Normally our RPC was just for the web site to the bg context but I found
a need to use it in the boot stage. | /* global chrome, sauce */
(function() {
'use strict';
const hooks = {};
function addHook(system, op, callback) {
const sysTable = hooks[system] || (hooks[system] = {});
sysTable[op] = callback;
}
addHook('storage', 'set', sauce.storage.set);
addHook('storage', 'get', sauce.s... | /* global chrome, sauce */
(function() {
'use strict';
const hooks = {};
function addHook(system, op, callback) {
const sysTable = hooks[system] || (hooks[system] = {});
sysTable[op] = callback;
}
addHook('storage', 'set', sauce.storage.set);
addHook('storage', 'get', sauce.s... |
Use notification ID in syncWithoutDetaching | <?php
namespace App\Http\Controllers\Mship;
use Auth;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Session;
use Redirect;
class Notification extends \App\Http\Controllers\BaseController
{
protected $redirectTo = 'mship/notification/list';
public function postAcknowledge($notification)
{... | <?php
namespace App\Http\Controllers\Mship;
use Auth;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Session;
use Redirect;
class Notification extends \App\Http\Controllers\BaseController
{
protected $redirectTo = 'mship/notification/list';
public function postAcknowledge($notification)
{... |
Remove config handling from threadmanager (was unused) | import Queue
import signal
import threading
import time
class ThreadManager():
"""Knows how to manage dem threads"""
quit = False
quitting = False
threads = []
def __init__(self, threads=[]):
"""Program entry point"""
self.threads = threads
self.register_signal_handlers()
... | import Queue
import signal
import threading
import time
class ThreadManager():
"""Knows how to manage dem threads"""
quit = False
quitting = False
threads = []
def __init__(self, queue=Queue.Queue(), threads=[], config={}):
"""Program entry point"""
# Set up queue
self.qu... |
Add failing tests for type equality | from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
# @skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Un... | from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
@skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Unio... |
Make all modals buttons default to dismiss the modal | /**
* Adds a marionette region to a bootstrap modal
*
* Copyright 2015 Ethan Smith
*/
var Backbone = require('backbone'),
Marionette = require('backbone.marionette'),
RegionModalLayout = require('./RegionModalLayout.js'),
ModalButtonView = require('./ModalButtonView.js'),
_ = require('underscore');... | /**
* Adds a marionette region to a bootstrap modal
*
* Copyright 2015 Ethan Smith
*/
var Backbone = require('backbone'),
Marionette = require('backbone.marionette'),
RegionModalLayout = require('./RegionModalLayout.js'),
ModalButtonView = require('./ModalButtonView.js'),
_ = require('underscore');... |
Make it possible to display no error message by setting attr errorMsg to false | angular.module('mwUI.Form')
.config(function (mwValidationMessagesProvider) {
mwValidationMessagesProvider.registerValidator(
'customValidation',
'mwErrorMessages.invalidInput'
);
})
.directive('mwCustomErrorValidator', function (mwValidationMessages, i18n) {
return {
require: 'ngMo... | angular.module('mwUI.Form')
.config(function(mwValidationMessagesProvider){
mwValidationMessagesProvider.registerValidator(
'customValidation',
'mwErrorMessages.invalidInput'
);
})
.directive('mwCustomErrorValidator', function (mwValidationMessages, i18n) {
return {
require: 'ngMode... |
Fix the bug where a mob can't be put back to 0 | import Ember from 'ember';
import _ from 'lodash/lodash';
import steps from '../ressources/ocre-quest';
export default Ember.Component.extend({
progress: '',
stepIndex: 0,
target: 0,
onChange: () => {},
actions: {
update(item, delta) {
let progress = this.get('progress');
... | import Ember from 'ember';
import _ from 'lodash/lodash';
import steps from '../ressources/ocre-quest';
export default Ember.Component.extend({
progress: '',
stepIndex: 0,
target: 0,
onChange: () => {},
actions: {
update(item, delta) {
let progress = this.get('progress');
... |
Use correct m2m join table name in LatestCommentsFeed
git-svn-id: http://code.djangoproject.com/svn/django/trunk@9089 bcc190cf-cafb-0310-a4f2-bffc1f526a37
--HG--
extra : convert_revision : 9ea8b1f1f4ccc068b460e76127f288742d25088e | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
... | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
... |
Use the latest openstax-accounts (0.10.0) | # -*- coding: utf-8 -*-
import sys
from setuptools import setup, find_packages
IS_PY3 = sys.version_info > (3,)
install_requires = (
'cnx-archive',
'cnx-epub',
'jinja2',
'openstax-accounts>=0.10.0',
'psycopg2',
'pyramid>=1.5',
'pyramid_multiauth',
)
tests_require = [
'webtest',
... | # -*- coding: utf-8 -*-
import sys
from setuptools import setup, find_packages
IS_PY3 = sys.version_info > (3,)
install_requires = (
'cnx-archive',
'cnx-epub',
'jinja2',
'openstax-accounts>=0.8',
'psycopg2',
'pyramid>=1.5',
'pyramid_multiauth',
)
tests_require = [
'webtest',
]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.