text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Fix parsing of taskWarrior's output
I don't know for older versions, but the latest stable release already
have '[' and ']' when doing an export. This lead to raising an exception
because it makes a nested list and you try to access it using a string
rather than an integer | # -*- coding: utf-8 -*-
"""
Display currently active (started) taskwarrior tasks.
Configuration parameters:
- cache_timeout : how often we refresh this module in seconds (5s default)
Requires
- task
@author James Smith http://jazmit.github.io/
@license BSD
"""
# import your useful libs here
from time import... | # -*- coding: utf-8 -*-
"""
Display currently active (started) taskwarrior tasks.
Configuration parameters:
- cache_timeout : how often we refresh this module in seconds (5s default)
Requires
- task
@author James Smith http://jazmit.github.io/
@license BSD
"""
# import your useful libs here
from time import... |
Modify url for mentor search get request | app.controller('SearchController', ['$http', function($http) {
console.log('SearchController running');
var self = this;
self.mentors = [];
self.newSearch = {
first_name: null,
last_name: null,
email: null,
company: null,
job_title: null,
zip: null,
race: null,
sex: null,
ori... | app.controller('SearchController', ['$http', function($http) {
console.log('SearchController running');
var self = this;
self.mentors = [];
self.newSearch = {
first_name: null,
last_name: null,
email: null,
company: null,
job_title: null,
zip: null,
race: null,
sex: null,
ori... |
Include district in updated e-mail. | import {
Email,
Box,
Item,
Span,
A,
renderEmail
} from 'react-html-email'
import React from 'react'
import ReactMarkdown from 'react-markdown'
import feeFactory from '../../shared/fee/feeFactory.js'
export function html(values) {
const participantsList = value... | import {
Email,
Box,
Item,
Span,
A,
renderEmail
} from 'react-html-email'
import React from 'react'
import ReactMarkdown from 'react-markdown'
import feeFactory from '../../shared/fee/feeFactory.js'
export function html(values) {
const participantsList = value... |
Upgrade pyflakes from 0.7.3 to 0.8 | from setuptools import setup
setup(
name='tangled',
version='0.1a8.dev0',
description='Tangled namespace and utilities',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled/tags',
author='Wyatt Baldwin',
au... | from setuptools import setup
setup(
name='tangled',
version='0.1a8.dev0',
description='Tangled namespace and utilities',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled/tags',
author='Wyatt Baldwin',
au... |
Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite. | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)... | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)... |
Switch triggerUnti lfunction (deprecated) to trigger function | <?php
namespace Detail\Apigility\Rest\Resource;
use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
use ZF\Rest\Resource as BaseResource;
use Detail\Apigility\Exception;
class Resource extends BaseResource
{
public function patchMultiple($ids, $data)
{
if (!is_array($ids)) {
... | <?php
namespace Detail\Apigility\Rest\Resource;
use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
use ZF\Rest\Resource as BaseResource;
use Detail\Apigility\Exception;
class Resource extends BaseResource
{
public function patchMultiple($ids, $data)
{
if (!is_array($ids)) {
... |
Fix core logging when no message on channel | from __future__ import unicode_literals
import logging
import time
from .message import Message
from .utils import name_that_thing
logger = logging.getLogger('django.channels')
class Worker(object):
"""
A "worker" process that continually looks for available messages to run
and runs their consumers.
... | from __future__ import unicode_literals
import logging
import time
from .message import Message
from .utils import name_that_thing
logger = logging.getLogger('django.channels')
class Worker(object):
"""
A "worker" process that continually looks for available messages to run
and runs their consumers.
... |
Support variables with - and _ symbols | import * as postcss from 'postcss';
import * as _ from 'underscore';
export default postcss.plugin('postcss-themeize', (options = {}) => {
const themesOptions = options.themes || {};
const themesConfig = _.reduce(themesOptions, (memo, config, theme) => {
_.each(config, (value, rule) => {
me... | import * as postcss from 'postcss';
import * as _ from 'underscore';
export default postcss.plugin('postcss-themeize', (options = {}) => {
const themesOptions = options.themes || {};
const themesConfig = _.reduce(themesOptions, (memo, config, theme) => {
_.each(config, (value, rule) => {
me... |
Add sound level to influx | # coding=utf-8
from local_settings import *
from utils import SensorConsumerBase
import redis
import datetime
import sys
class DustNode(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "indoor_air_quality")
def run(self):
self.subscribe("dust-node-pubsub", self.pubsu... | # coding=utf-8
from local_settings import *
from utils import SensorConsumerBase
import redis
import datetime
import sys
class DustNode(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "indoor_air_quality")
def run(self):
self.subscribe("dust-node-pubsub", self.pubsu... |
Allow spaces in template variables | JSONEditor.defaults.templates["default"] = function() {
return {
compile: function(template) {
var matches = template.match(/{{\s*([a-zA-Z0-9\-_ \.]+)\s*}}/g);
var l = matches.length;
// Shortcut if the template contains no variables
if(!l) return function() { return template; };
/... | JSONEditor.defaults.templates["default"] = function() {
return {
compile: function(template) {
var matches = template.match(/{{\s*([a-zA-Z0-9\-_\.]+)\s*}}/g);
var l = matches.length;
// Shortcut if the template contains no variables
if(!l) return function() { return template; };
//... |
Modify function that calculate the expected signature | import logging
import hashlib
import hmac
import json
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from app.models import SocialNetworkApp
logger = logging.getLogger(__name__)
def _get_facebook_app():
apps = SocialNetworkApp.objects.all()
f... | import logging
import hashlib
import json
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from app.models import SocialNetworkApp
logger = logging.getLogger(__name__)
def _get_facebook_app():
apps = SocialNetworkApp.objects.all()
for app in ap... |
Raise an error when a symbol cannot be found | class Environment:
def __init__(self, par=None, bnd=None):
if bnd:
self.binds = bnd
else:
self.binds = {}
self.parent = par
if par:
self.level = self.parent.level + 1
else:
self.level = 0
def get(self,... | class Environment:
def __init__(self, par=None, bnd=None):
if bnd:
self.binds = bnd
else:
self.binds = {}
self.parent = par
if par:
self.level = self.parent.level + 1
else:
self.level = 0
def get(self,... |
Add ref for file upload dropZone | import { h, Component } from 'preact';
import Dropzone from 'react-dropzone';
import style from './style';
export default class FileUpload extends Component {
constructor(props) {
super(props);
this.dropzoneRef = null;
this.state = {
isFileSelected: false,
file: false,
};
this.handl... | import { h, Component } from 'preact';
import Dropzone from 'react-dropzone';
import style from './style';
export default class FileUpload extends Component {
constructor(props) {
super(props);
this.state = {
isFileSelected: false,
file: false,
};
this.handleFileDrop = this.handleFileDr... |
Throw an appropriate AuthenticateException when a chat-api authentication error code is encountered. | <?php
namespace MessageBird\Common;
use MessageBird\Exceptions;
/**
* Class ResponseError
*
* @package MessageBird\Common
*/
class ResponseError
{
const SUCCESS = 1;
const REQUEST_NOT_ALLOWED = 2;
const MISSING_PARAMS = 9;
const INVALID_PARAMS = 10;
const NOT_FOUND = 20;
const NOT_EN... | <?php
namespace MessageBird\Common;
use MessageBird\Exceptions;
/**
* Class ResponseError
*
* @package MessageBird\Common
*/
class ResponseError
{
const SUCCESS = 1;
const REQUEST_NOT_ALLOWED = 2;
const MISSING_PARAMS = 9;
const INVALID_PARAMS = 10;
const NOT_FOUND = 20;
const NOT_EN... |
[CFG] Rename 'format' route to 'accept' | <?php
return [
'name_prefix' => 'aura.demo.',
'routes' => [
'home' => [
'path' => '/',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'index',
],
],
'hello' => [
'path' => '/hello',
... | <?php
return [
'name_prefix' => 'aura.demo.',
'routes' => [
'home' => [
'path' => '/',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'index',
],
],
'hello' => [
'path' => '/hello',
... |
Fix bind of the switches and increase perf with the DOM | function RenderClass(element) {
var _private = this;
_private.el = null;
this.update = function (data) {
if (_private.el === null) { return; }
for (var container of data) {
var isChecked = (container.state === 'Up')
var newLine = document.getElementById('template').cloneNode(true);
va... | function RenderClass(element) {
var _private = this;
_private.el = null;
this.update = function (data) {
if (_private.el === null) { return; }
for (var container of data) {
newLine = document.getElementById('template').cloneNode(true);
newLine.innerHTML = newLine.innerHTML
.repla... |
Fix issue when a private match is found multiple times | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Processor functions
"""
def conflict_prefer_longer(matches):
"""
Remove shorter matches if they conflicts with longer ones
:param matches:
:type matches: rebulk.match.Matches
:param context:
:type context:
:return:
:rtype: list[rebulk.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Processor functions
"""
def conflict_prefer_longer(matches):
"""
Remove shorter matches if they conflicts with longer ones
:param matches:
:type matches: rebulk.match.Matches
:param context:
:type context:
:return:
:rtype: list[rebulk.... |
Update repo URL for Jazzband ownership transfer | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-ical',
version='1.5',
description="iCal feeds for Django based on Django's syndication feed "
"framework.",
long_description=(open('README.rst').read() + '\n' +
open('CHANGES.rst... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-ical',
version='1.5',
description="iCal feeds for Django based on Django's syndication feed "
"framework.",
long_description=(open('README.rst').read() + '\n' +
open('CHANGES.rst... |
[FrameworkBundle][5.4] Remove fileLinkFormat property from DebugHandlersListener | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Symfony\... | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Symfony\... |
Change KAFKA_BROKER parameter, added a send producer | import json
from get_tmdb import GetTMDB
from kafka import KafkaConsumer, KafkaProducer
try:
from GLOBALS import KAFKA_BROKER, TMDB_API
except ImportError:
print('Get it somewhere else')
class CollectTMDB(object):
def __init__(self, ):
self.tmdb = GetTMDB(TMDB_API)
self.producer = KafkaP... | import json
from get_tmdb import GetTMDB
from kafka import KafkaConsumer
try:
from GLOBALS import KAFKA_BROKER, TMDB_API
except ImportError:
print('Get it somewhere else')
class CollectTMDB(object):
def __init__(self, ):
self.tmdb = GetTMDB(TMDB_API)
self.consumer = KafkaConsumer(group_i... |
Make it work for node <= 5 | 'use strict';
var path = require('path');
module.exports = class BowerResolvePlugin {
constructor(options) {
this.options = options;
}
apply(resolver) {
resolver.plugin('existing-directory', function (request, callback) {
if (request.path !== request.descriptionFileRoot) {
... | var path = require('path');
module.exports = class BowerResolvePlugin {
constructor(options) {
this.options = options;
}
apply(resolver) {
resolver.plugin('existing-directory', function (request, callback) {
if (request.path !== request.descriptionFileRoot) {
re... |
Use PHP5.3 safe syntax in rename_keys | <?php
/**
* @package Garp\Functional
* @author Harmen Janssen <harmen@grrr.nl>
* @license https://github.com/grrr-amsterdam/garp-functional/blob/master/LICENSE.md BSD-3-Clause
*/
namespace Garp\Functional;
/**
* Rename keys in an array.
*
* @param mixed $transformMap
* @param mixed $collection
* @return... | <?php
/**
* @package Garp\Functional
* @author Harmen Janssen <harmen@grrr.nl>
* @license https://github.com/grrr-amsterdam/garp-functional/blob/master/LICENSE.md BSD-3-Clause
*/
namespace Garp\Functional;
/**
* Rename keys in an array.
*
* @param mixed $transformMap
* @param mixed $collection
* @return... |
Update test results using new return type | """Data transformation utilities test cases."""
import unittest
from datagrid_gtk3.utils.transformations import degree_decimal_str_transform
class DegreeDecimalStrTransformTest(unittest.TestCase):
"""Degree decimal string transformation test case."""
def test_no_basestring(self):
"""AssertionError... | """Data transformation utilities test cases."""
import unittest
from datagrid_gtk3.utils.transformations import degree_decimal_str_transform
class DegreeDecimalStrTransformTest(unittest.TestCase):
"""Degree decimal string transformation test case."""
def test_no_basestring(self):
"""AssertionError... |
Replace api key with env vars | module.exports = {
siteMetadata: {
siteUrl: 'https://chocolate-free.com/',
title: 'Chocolate Free',
},
plugins: [
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: process.env.CHOCOLATE_FREE_CF_SPACE,
accessToken: process.env.CHOCOLATE_FREE_CF_TOKEN
},
},... | module.exports = {
siteMetadata: {
siteUrl: 'https://chocolate-free.com/',
title: 'Chocolate Free',
},
plugins: [
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: '0w6gaytm0wfv',
accessToken: 'c9414fe612e8c31f402182354c5263f9c6b1f0c611ae5597585cb78692dc2493',
... |
Add a representation of GraphView object | from octopus.dispatcher.model import TaskNode, FolderNode, TaskGroup
from octopus.dispatcher import rules
import logging
logger = logging.getLogger("dispatcher")
class RuleError(rules.RuleError):
'''Base class for GraphViewBuilder related exceptions.'''
pass
class TaskNodeHasNoChildrenError(RuleError):
... | from octopus.dispatcher.model import TaskNode, FolderNode, TaskGroup
from octopus.dispatcher import rules
import logging
logger = logging.getLogger("dispatcher")
class RuleError(rules.RuleError):
'''Base class for GraphViewBuilder related exceptions.'''
pass
class TaskNodeHasNoChildrenError(RuleError):
... |
Update the function header declaration
So that it looks not that horrible. | function c_a(a, b) {
"use strict";
var c, d, obj;
obj = {
"difference": [],
"same_elements": []
};
function trim(a) {
var i = a.length;
while (i >= 0) {
if (a[i] === "_*deleted*_") {
a.splice(i, 1);
}
i -= 1;
... | var c_a = function (a, b) {
"use strict";
var c, d, obj;
obj = {
"difference": [],
"same_elements": []
};
function trim(a) {
var i = a.length;
while (i >= 0) {
if (a[i] === "_*deleted*_") {
a.splice(i, 1);
}
i -= 1;
... |
Fix URL trailing slash bug in teams endpoint | """Defines the URL routes for the Team API."""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
TeamsListView,
TeamsDetailView,
TopicDetailView,
TopicListView,
MembershipListView,
MembershipDetailView
)
TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+... | """Defines the URL routes for the Team API."""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
TeamsListView,
TeamsDetailView,
TopicDetailView,
TopicListView,
MembershipListView,
MembershipDetailView
)
TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+... |
Fix get gpg key from database | from glob import glob
import os
from .credential import Credential
from .crypt import create_gpg, load_gpg
class Database(object):
def __init__(self, path, gpg):
self.path = path
self.gpg = gpg
@classmethod
def create(cls, path, passphrase, gpg_bin="gpg"):
gpg = create_gpg(gpg_b... | from glob import glob
import os
from .credential import Credential
from .crypt import create_gpg, load_gpg
class Database(object):
def __init__(self, path, gpg):
self.path = path
self.gpg = gpg
@classmethod
def create(cls, path, passphrase, gpg_bin="gpg"):
gpg = create_gpg(gpg_b... |
Load box2d library in JNI | package org.cocos2dx.breakout;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import android.os.Bundle;
import android.widget.EditText;
public class BreakoutCocos2Dx extends Cocos2dxActivity{
private Cocos2dxGLSurfaceView mGLView;
protected void onCreate(Bundle ... | package org.cocos2dx.breakout;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import android.os.Bundle;
import android.widget.EditText;
public class BreakoutCocos2Dx extends Cocos2dxActivity{
private Cocos2dxGLSurfaceView mGLView;
protected void onCreate(Bundle ... |
Fix error when no content-length is sent. | export default class FileLoader {
// This returns ArrayBuffer
static load (url, on_progress = () => {
}) {
return new Promise((resolve, reject) => {
fetch(url).then(async (response) => {
// Handle HTTP error
if (response.status === 404) {
reject('NOT_FOUND')
} else if (... | export default class FileLoader {
// This returns ArrayBuffer
static load (url, on_progress = () => {
}) {
return new Promise((resolve, reject) => {
fetch(url).then(async (response) => {
// Handle HTTP error
if (response.status === 404) {
reject('NOT_FOUND')
} else if (... |
Add prefixes for Android >= 4.0 | const options = require('./options');
const autoprefixer = require('autoprefixer');
module.exports = {
resolve: {
modules: [
options.paths.root,
options.paths.resolve('node_modules')
],
alias: {
src: 'src',
directives: 'src/directives',
... | const options = require('./options');
const autoprefixer = require('autoprefixer');
module.exports = {
resolve: {
modules: [
options.paths.root,
options.paths.resolve('node_modules')
],
alias: {
src: 'src',
directives: 'src/directives',
... |
Make sure we're sorting results | import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
exp... | import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
exp... |
Use application sourceLanguage in default migrate | <?php
use yii\db\Migration;
use lav45\translate\LocaleHelperTrait;
class m151220_112320_lang extends Migration
{
use LocaleHelperTrait;
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-... | <?php
use yii\db\Migration;
class m151220_112320_lang extends Migration
{
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
... |
Make the party set JS generator output keys in a predictable order
This makes it easier to check with "git diff" if there have been any
changes. | import json
from os.path import dirname, join, realpath
from django.conf import settings
from django.core.management.base import BaseCommand
from candidates.election_specific import AREA_POST_DATA
from candidates.popit import get_all_posts
class Command(BaseCommand):
def handle(self, **options):
repo_ro... | import json
from os.path import dirname, join, realpath
from django.conf import settings
from django.core.management.base import BaseCommand
from candidates.election_specific import AREA_POST_DATA
from candidates.popit import get_all_posts
class Command(BaseCommand):
def handle(self, **options):
repo_ro... |
Change to form handling now persists realtionship between associations | <?php
namespace Test\TestTwoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Test\TestTwoBundle\Entity\All;
use Test\TestTwoBundle\Form\AllType;
use Test\TestStoreBundle\Entity\User;
use Test... | <?php
namespace Test\TestTwoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Test\TestTwoBundle\Entity\All;
use Test\TestTwoBundle\Form\AllType;
use Test\TestStoreBundle\Entity\User;
use Test... |
Fix after parameter for reddit api | 'use strict';
angular.module('repicbro.services')
.factory('PostsManager', function ($rootScope, Posts) {
var posts = [],
current = null,
index = 0,
latest = '',
updating = false;
var broadcastCurrentUpdate = function (current) {
$rootScope.$broadcast('PostsManager.Cur... | 'use strict';
angular.module('repicbro.services')
.factory('PostsManager', function ($rootScope, Posts) {
var posts = [],
current = null,
index = 0,
latest = '',
updating = false;
var broadcastCurrentUpdate = function (current) {
$rootScope.$broadcast('PostsManager.Cur... |
Move extension requirement logic into PHPUnit phpDoc annotation | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ... | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ... |
Fix for spaces in user queries | <?php
namespace Scriptotek\Alma\Users;
use Scriptotek\Alma\ResourceList;
class Users extends ResourceList
{
protected $resourceName = User::class;
/**
* Iterates over all users matching the given query.
* Handles continuation.
*/
public function search($query, $full = false, $batchSize = ... | <?php
namespace Scriptotek\Alma\Users;
use Scriptotek\Alma\ResourceList;
class Users extends ResourceList
{
protected $resourceName = User::class;
/**
* Iterates over all users matching the given query.
* Handles continuation.
*/
public function search($query, $full = false, $batchSize = ... |
Add views in Pynuts init | """__init__ file for Pynuts."""
import flask
from flask.ext.sqlalchemy import SQLAlchemy
import document
import view
class Pynuts(flask.Flask):
"""Create the Pynuts class.
:param import_name: Flask application name
:param config: Flask application configuration
:param reflect: Create models with da... | """__init__ file for Pynuts."""
import flask
from flask.ext.sqlalchemy import SQLAlchemy
import document
import view
class Pynuts(flask.Flask):
"""Create the Pynuts class.
:param import_name: Flask application name
:param config: Flask application configuration
:param reflect: Create models with da... |
Deploy Travis CI build 720 to GitHub | #!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
LONG_DESCRIPTION = "<placeholder>"
else:
LONG_DESCRIPTION = README + '\n' + CH... | #!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
LONG_DESCRIPTION = "<file not found>"
else:
LONG_DESCRIPTION = README + '\n' +... |
Make form update existing instance if uid matches | from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
... | from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
... |
Revert "Revert "Make migration SQLite compatible""
This reverts commit b16016994f20945a8a2bbb63b9cb920d856ab66f. | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(... |
Make the clusters member final | package me.prettyprint.cassandra.service;
import java.util.HashMap;
import java.util.Map;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
public class ClusterFactory {
private static final Map<String, Cluster> clusters = new HashMap<String, Cluster>();
public static Cluster get(String clus... | package me.prettyprint.cassandra.service;
import java.util.HashMap;
import java.util.Map;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
public class ClusterFactory {
private static Map<String, Cluster> clusters = new HashMap<String, Cluster>();
public static Cluster get(String clusterNam... |
Make the bot to save memory by sending events as soon as it reads through the corresponding lines of the input file. | """
Spamhaus XBL list handler.
Maintainer: Sauli Pahlman <sauli@codenomicon.com>
"""
import idiokit
from abusehelper.core import cymruwhois, bot, events
class SpamhausXblBot(bot.PollingBot):
xbl_filepath = bot.Param("Filename of Spamhaus XBL file")
@idiokit.stream
def poll(self):
skip_chars = [... | """
Spamhaus XBL list handler.
Maintainer: Sauli Pahlman <sauli@codenomicon.com>
"""
import idiokit
from abusehelper.core import cymruwhois, bot, events
class SpamhausXblBot(bot.PollingBot):
xbl_filepath = bot.Param("Filename of Spamhaus XBL file")
@idiokit.stream
def poll(self):
skip_chars = [... |
Use git diff instead of git diff-index | import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const ... | import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const ... |
Print rancher-compose command to help debug/confirmation | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_pa... | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_pa... |
Add exception type for script_fields related errors | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
... |
Trim slashes from base URL. | <?php
namespace Orbt\ResourceMirror;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Main service for materializing services.
*/
class ResourceMirror
{
/**
* Event dispatcher.
* @var EventDispatcherInterface
*/
protected $dispatcher;
/**
* Mirror base URL.
... | <?php
namespace Orbt\ResourceMirror;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Main service for materializing services.
*/
class ResourceMirror
{
/**
* Event dispatcher.
* @var EventDispatcherInterface
*/
protected $dispatcher;
/**
* Mirror base URL.
... |
Add optional plugin build options
Adds a `--plugins` CLI option Grunt build command which is a comma separated list of plugins that will be included in the build. | module.exports = function(grunt) {
var _ = grunt.util._;
var plugins = (grunt.option('plugins') || '').split(',');
var gruntConfig = {
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: '\n'
},
dist: {
... | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: '\n'
},
dist: {
src: [
'vendor/**/*.js',
'template/_header.js',... |
Fix up syntax error in JS from my merge/port upto V8 - oops :( | (function () {
function CreateNotifyController(
$scope,
contentResource,
navigationService,
angularHelper) {
var vm = this;
var currentForm;
vm.notifyOptions = [];
vm.save = save;
vm.cancel = cancel;
vm.message = {
name: $sc... | (function () {
function CreateNotifyController(
$scope,
contentResource,
navigationService,
angularHelper) {
var vm = this;
var currentForm;
vm.notifyOptions = [];
vm.save = save;
vm.cancel = cancel;
vm.message = {
name: $sc... |
Fix default not being used in getSettings | // Requires
var Q = require('q');
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
function setup(options, imports, register) {
var workspace = imports.workspace;
var logger = imports.logger.namespace("settings");
var settings = {};
// Return settings
var ge... | // Requires
var Q = require('q');
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
function setup(options, imports, register) {
var workspace = imports.workspace;
var logger = imports.logger.namespace("settings");
var settings = {};
// Return settings
var ge... |
Update "X-Molotov-Agent" header for Molotov version 1.2.2. | chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":3,\"app_version_name\":\"1.2.2\",\"type\":\"desktop\",\"electron_version\":\"1.4.12\",\"os\":\"Unknown\",\"... | chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":2,\"app_version_name\":\"1.0.0\",\"type\":\"desktop\",\"os\":\"\",\"os_version\":\"\",\"manufacturer\":\"\"... |
Fix deleting all webhooks for a list | <?php namespace JohnRivs\Wunderlist;
trait Webhook {
/**
* Show all the webhooks for a list.
*
* @param array $attributes
* @return array
*/
public function getWebhooks(array $attributes = [])
{
$this->requires(['list_id'], $attributes);
return $thi... | <?php namespace JohnRivs\Wunderlist;
trait Webhook {
/**
* Show all the webhooks for a list.
*
* @param array $attributes
* @return array
*/
public function getWebhooks(array $attributes = [])
{
$this->requires(['list_id'], $attributes);
return $thi... |
Hide button to delete the first form of the formset | // django-dynamic-formset fixes for bootstrap 3
(function($) {
$(document).ready(function(){
function fixDeleteRow ($deleteClickable) {
// Move .delete-row link immediately after the form input
var $deleteClickableList = $deleteClickable.parent();
var $formInputField = $... | // django-dynamic-formset fixes for bootstrap 3
(function($) {
$(document).ready(function(){
function fixDeleteRow ($deleteClickable) {
// Move .delete-row link immediately after the form input
var $deleteClickableList = $deleteClickable.parent();
var $formInputField = $... |
Fix typo which causes memory leak. | define([
'jquery',
'var/eventStorage',
'prototype/var/EmojioneArea'
],
function($, eventStorage, EmojioneArea) {
EmojioneArea.prototype.off = function(events, handler) {
if (events) {
var id = this.id;
$.each(events.toLowerCase().replace(/_/g, '.').split(' '), function(i,... | define([
'jquery',
'var/eventStorage',
'prototype/var/EmojioneArea'
],
function($, eventStorage, EmojioneArea) {
EmojioneArea.prototype.off = function(events, handler) {
if (events) {
var id = this.id;
$.each(events.toLowerCase().replace(/_/g, '.').split(' '), function(i,... |
Fix for different types with the same value giving the same hash, such as "1" and 1 | /*
* Hashcode.js 1.0.0
* https://github.com/stuartbannerman/hashcode
*
* Copyright 2013 Stuart Bannerman (me@stuartbannerman.com)
* Released under the MIT license
*
* Date: 07-04-2013
*/
(function(window)
{
window.Hashcode = (function()
{
// Hashes a string
var hash = funct... | /*
* Hashcode.js 1.0.0
* https://github.com/stuartbannerman/hashcode
*
* Copyright 2013 Stuart Bannerman (me@stuartbannerman.com)
* Released under the MIT license
*
* Date: 07-04-2013
*/
(function(window)
{
window.Hashcode = (function()
{
// Hashes a string
var hash = funct... |
Support a range of redis client versions | import os
import re
from setuptools import (
find_packages,
setup,
)
version_re = re.compile(r"__version__\s*=\s*['\"](.*?)['\"]")
def get_version():
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, 'curator/__init__.py')) as initf:
for line in initf:
... | import os
import re
from setuptools import (
find_packages,
setup,
)
version_re = re.compile(r"__version__\s*=\s*['\"](.*?)['\"]")
def get_version():
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, 'curator/__init__.py')) as initf:
for line in initf:
... |
Add styles for code blocks | import React from "react";
import { graphql, Link } from "gatsby";
import Layout from "../app/layout";
import "prismjs/themes/prism-solarizedlight.css";
import "./blog-post.scss";
export const BLOG_POST_QUERY = graphql`
query BlogPostTemplate($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
... | import React from "react";
import { graphql, Link } from "gatsby";
import Layout from "../app/layout";
import "./blog-post.scss";
export const BLOG_POST_QUERY = graphql`
query BlogPostTemplate($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
id
excerpt
html
fields {
... |
Use vendor and product id for udev rules | #!/usr/bin/env python3
import os
import requests
from select import select
from sys import exit, stderr
from time import sleep
WRITE_BYTES = [0x0 for b in range(0, 8)]
WRITE_BYTES[0] = 0x08
WRITE_BYTES[7] = 0x02
CLOSED = 0x15
OPEN = 0x17
DOWN = 0x16
def main():
fd_id = os.open('/dev/big_red_button', os.O_RDWR|os... | #!/usr/bin/env python3
import os
from select import select
from sys import exit, stderr
from time import sleep
WRITE_BYTES = [0x0 for b in range(0, 8)]
WRITE_BYTES[0] = 0x08
WRITE_BYTES[7] = 0x02
CLOSED = 0x15
OPEN = 0x17
DOWN = 0x16
def main():
fd_id = os.open('/dev/big_red_button', os.O_RDWR|os.O_NONBLOCK)
... |
refact(checkbox): Move cssClass from label to div | package lt.inventi.wicket.component.bootstrap.form;
import org.apache.wicket.util.string.AppendingStringBuffer;
abstract class ChoiceUtils {
public enum InputPosition {
BEFORE_LABEL, AFTER_LABEL
}
private ChoiceUtils() {
// static utils
}
static void moveInputInsideLabel(Appendi... | package lt.inventi.wicket.component.bootstrap.form;
import org.apache.wicket.util.string.AppendingStringBuffer;
abstract class ChoiceUtils {
public enum InputPosition {
BEFORE_LABEL, AFTER_LABEL
}
private ChoiceUtils() {
// static utils
}
static void moveInputInsideLabel(Appendi... |
Fix to target events (not all card effects) | const DrawCard = require('../../drawcard.js');
const EventRegistrar = require('../../eventregistrar.js');
const { CardTypes, Players } = require('../../Constants');
class MagnificentTriumph extends DrawCard {
setupCardAbilities(ability) {
this.duelWinnersThisConflict = [];
this.eventRegistrar = new... | const DrawCard = require('../../drawcard.js');
const EventRegistrar = require('../../eventregistrar.js');
const { CardTypes, Players } = require('../../Constants');
class MagnificentTriumph extends DrawCard {
setupCardAbilities(ability) {
this.duelWinnersThisConflict = [];
this.eventRegistrar = new... |
Simplify Eidos reader, use Eidos JSON String call | import json
from indra.java_vm import autoclass, JavaException
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings are done with the same
in... | from indra.java_vm import autoclass, JavaException
from .scala_utils import get_python_json
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings ... |
Revert "Fix url for default user image" | define('app/views/user_menu', ['app/views/templated', 'md5'],
/**
* User Menu View
*
* @returns Class
*/
function (TemplatedView) {
'user strict';
return TemplatedView.extend({
/**
* Properties
*/
isNotCore: !IS_CORE,
... | define('app/views/user_menu', ['app/views/templated', 'md5'],
/**
* User Menu View
*
* @returns Class
*/
function (TemplatedView) {
'user strict';
return TemplatedView.extend({
/**
* Properties
*/
isNotCore: !IS_CORE,
... |
Fix test covering pip 1.5.2 error handling. | # coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
... | # coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
... |
Reformat string representation of Credentials | import os
class Credential(object):
def __init__(self, name, login, password, comments):
self.name = name
self.login = login
self.password = password
self.comments = comments
def save(self, database_path):
credential_path = os.path.join(database_path, self.name)
... | import os
class Credential(object):
def __init__(self, name, login, password, comments):
self.name = name
self.login = login
self.password = password
self.comments = comments
def save(self, database_path):
credential_path = os.path.join(database_path, self.name)
... |
Fix translation typo message info folders | import React from 'react';
import { c } from 'ttag';
import { Loader, Alert, PrimaryButton, useFolders, useModals } from 'react-components';
import FolderTreeViewList from './FolderTreeViewList';
import EditLabelModal from './modals/Edit';
function LabelsSection() {
const [folders, loadingFolders] = useFolders();... | import React from 'react';
import { c } from 'ttag';
import { Loader, Alert, PrimaryButton, useFolders, useModals } from 'react-components';
import FolderTreeViewList from './FolderTreeViewList';
import EditLabelModal from './modals/Edit';
function LabelsSection() {
const [folders, loadingFolders] = useFolders();... |
Set require debug to be the same as debug. | from .base import * # noqa
DEBUG = True
REQUIRE_DEBUG = DEBUG
INTERNAL_IPS = INTERNAL_IPS + ('', )
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'app_kdl_dev',
'USER': 'app_kdl',
'PASSWORD': '',
'HOST': ''
},
}
LOGGING_LEVEL =... | from .base import * # noqa
DEBUG = True
INTERNAL_IPS = INTERNAL_IPS + ('', )
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'app_kdl_dev',
'USER': 'app_kdl',
'PASSWORD': '',
'HOST': ''
},
}
LOGGING_LEVEL = logging.DEBUG
LOGGIN... |
Set default sales tax rates | <?php
namespace Freeagent\Invoice;
/**
* Class InvoiceItem
*
* @package Freeagent\Invoice
*/
class InvoiceItem
{
/**
* @var string
*/
public $item_type;
/**
* @var int
*/
public $quantity;
/**
* @var float
*/
public $price;
/**
* @var string
*/... | <?php
namespace Freeagent\Invoice;
/**
* Class InvoiceItem
*
* @package Freeagent\Invoice
*/
class InvoiceItem
{
/**
* @var string
*/
public $item_type;
/**
* @var int
*/
public $quantity;
/**
* @var float
*/
public $price;
/**
* @var string
*/... |
Change triggerEvent possible value to mouseover for consistency | (function($){
$.fn.seAccordion = function(options) {
var defaults = {
header: 'h1',
content: 'div',
speed: 'slow',
easing: 'swing',
singleOpen: true,
allowAllClosed: false,
triggerEvent: 'click'
};
var params... | (function($){
$.fn.seAccordion = function(options) {
var defaults = {
header: 'h1',
content: 'div',
speed: 'slow',
easing: 'swing',
singleOpen: true,
allowAllClosed: false,
triggerEvent: 'click'
};
var params... |
Convert maxmind raw result to UTF-8 | <?php
namespace Maxmind\MinFraud;
class MinFraudResponse
{
private $isCurlSuccessful;
private $rawResult;
/**
* @param bool $isCurlSuccessful
* @param string $result
*/
public function __construct($isCurlSuccessful, $result)
{
$this->isCurlSuccessful = $isCurlSuccessful;
... | <?php
namespace Maxmind\MinFraud;
class MinFraudResponse
{
private $isCurlSuccessful;
private $rawResult;
/**
* @param bool $isCurlSuccessful
* @param string $result
*/
public function __construct($isCurlSuccessful, $result)
{
$this->isCurlSuccessful = $isCurlSuccessful;
... |
Create sentinel rounds on Session creation | from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from .models import (
Performance,
Session,
)
@receiver(post_save, sender=Session)
def session_post_save(sender, instance=None, created=False, raw=False, **kwargs):
"""Create sentinels."""
if not raw:
... | from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from .models import (
Performance,
Session,
)
@receiver(post_save, sender=Performance)
def performance_post_save(sender, instance=None, created=False, raw=False, **kwargs):
"""Create sentinels."""
if not raw... |
Fix selector for update credit card form | $(function() {
$("#credit-card input, #credit-card select").attr("disabled", false);
$("form:has(#credit-card)").submit(function() {
var form = this;
$("#user_submit").attr("disabled", true);
$("#credit-card input, #credit-card select").attr("name", "");
$("#credit-card-errors").hide();
if (!$... | $(function() {
$("#credit-card input, #credit-card select").attr("disabled", false);
$("#new_user, .edit_user").submit(function() {
var form = this;
$("#user_submit").attr("disabled", true);
$("#credit-card input, #credit-card select").attr("name", "");
$("#credit-card-errors").hide();
if (!$(... |
Refactor formatting of save name. | import os
import matplotlib.pyplot as plt
def save_all_figs(directory='./', fmt=None, default_name='untitled%i'):
"""Save all open figures.
Each figure is saved with the title of the plot, if possible.
Parameters
------------
directory : str
Path where figures are saved.
fmt : str, l... | import os
import matplotlib.pyplot as plt
def save_all_figs(directory='./', fmt=None, default_name='untitled%i'):
"""Save all open figures.
Each figure is saved with the title of the plot, if possible.
Parameters
------------
directory : str
Path where figures are saved.
fmt : str, l... |
Add title to the site | <!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstr... | <!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstr... |
Tag parser now instruct the issue as related to metadata | package alien4cloud.tosca.parser.impl.advanced;
import java.util.List;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import alien4cloud.model.common.Tag;
import alien4cloud.tosca.parser.Pa... | package alien4cloud.tosca.parser.impl.advanced;
import java.util.List;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import alien4cloud.model.common.Tag;
import alien4cloud.tosca.parser.Pa... |
Send state when dispatched 'JUMP_TO_STATE' | export default function createDevToolsStore(onDispatch) {
const initialState = {
actionsById: {},
computedStates: [],
currentStateIndex: -1,
monitorState: {},
nextActionId: 0,
skippedActionIds: [],
stagedActionIds: []
};
let currentState = [];
let listeners = [];
let initiated = fa... | export default function createDevToolsStore(onDispatch) {
const initialState = {
actionsById: {},
computedStates: [],
currentStateIndex: -1,
monitorState: {},
nextActionId: 0,
skippedActionIds: [],
stagedActionIds: []
};
let currentState = [];
let listeners = [];
let initiated = fa... |
Create key if not exists. | <?php
namespace App\Http\Services;
use App\Hospital;
use Illuminate\Database\Eloquent\Collection;
use App\Key;
class KeyService
{
public function generateKey(): string
{
return chr(mt_rand(ord( 'a' ), ord( 'z' ))) . substr(md5(time()), 1);
}
public function saveKey(string $key): ?Key
{ ... | <?php
namespace App\Http\Services;
use App\Hospital;
use Illuminate\Database\Eloquent\Collection;
use App\Key;
class KeyService
{
public function generateKey(): string
{
return chr(mt_rand(ord( 'a' ), ord( 'z' ))) . substr(md5(time()), 1);
}
public function saveKey(string $key): ?Key
{ ... |
Move 'me' check outside of author lookup | from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.api.auth import get_current_user
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self, author_id):
i... | from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.api.auth import get_current_user
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self, author_id):
i... |
Add dummy attribute to drawable node | package gui;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
/**
* Created by TUDelft SID on 17-5-2017.
*/
public class DrawableNode {
private static final int ARC_SIZE = 10;
private static GraphicsContext gc;
private int id;
private double xCoordinate;
private dou... | package gui;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
/**
* Created by TUDelft SID on 17-5-2017.
*/
public class DrawableNode {
private static final int ARC_SIZE = 10;
private static GraphicsContext gc;
private int id;
private double xCoordinate;
private dou... |
Test reaching end of stack |
/*
* composable-middleware
* https://github.com/randymized/composable-middleware
*
* Copyright (c) 2013 Randy McLaughlin
* Licensed under the MIT license.
*/
'use strict';
module.exports= function composable_middleware(components) {
var stack= [];
function middleware(req,res,out) {
var layer= 0;
v... |
/*
* composable-middleware
* https://github.com/randymized/composable-middleware
*
* Copyright (c) 2013 Randy McLaughlin
* Licensed under the MIT license.
*/
'use strict';
module.exports= function composable_middleware(components) {
var stack= [];
function middleware(req,res,out) {
var layer= 0;
v... |
Update header of beatmapset discussion votes | {{--
Copyright (c) ppy Pty Ltd <contact@ppy.sh>.
This file is part of osu!web. osu!web is distributed with the hope of
attracting more community contributions to the core ecosystem of osu!.
osu!web is free software: you can redistribute it and/or modify
it under the terms of the Affero GNU General... | {{--
Copyright (c) ppy Pty Ltd <contact@ppy.sh>.
This file is part of osu!web. osu!web is distributed with the hope of
attracting more community contributions to the core ecosystem of osu!.
osu!web is free software: you can redistribute it and/or modify
it under the terms of the Affero GNU General... |
Fix code error in template | import ATV from 'atvjs';
// templates
import listTemplate from './templates/list.jade';
let myPageStyles = `
.text-bold {
font-weight: bold;
}
.text-white {
color: rgb(255, 255, 255);
}
`;
App.onLaunch = function (options) {
var demoPage = ATV.Page.create({
name: 'demo',
style: myPageStyle... | import ATV from 'atvjs';
// templates
import listTemplate from './templates/list.jade';
let myPageStyles = `
.text-bold {
font-weight: bold;
}
.text-white {
color: rgb(255, 255, 255);
}
`;
App.onLaunch = function (options) {
var demoPage = ATV.Page.create({
name: 'demo',
style: myPageStyle... |
Allow adding extra form-data to FileUpload component | define([
'require',
'../inheritance',
'../component',
'../event',
'../view',
'../collections',
'../network',
'!fileupload.css',
'!fileupload.html'
],function(require,inheritance,component,event,element,collections,network){
var factory = component.ComponentFactory(require,{
... | define([
'require',
'../inheritance',
'../component',
'../event',
'../view',
'../collections',
'../network',
'!fileupload.css',
'!fileupload.html'
],function(require,inheritance,component,event,element,collections,network){
var factory = component.ComponentFactory(require,{
... |
Add a function to write a sequence of nodes into a file | from graph import Graph
class Writer:
'''
Write a graph or a list of nodes into a file.
'''
def write_blossom_iv(self, graph, file_location):
'''
Write a graph to a file, use the blossom IV format
@type: graph: graph
@param: graph: graph that should be written to file
... | from graph import Graph
class Writer:
'''
Write a graph into file.
'''
def write_blossom_iv(self, graph, file_location):
'''
Write a graph to a file, use the blossom IV format
@type: graph: graph
@param: graph: graph that should be written to file
@type: file_l... |
Change anonymous response transformation function to a reusable named function
- This function always does the same, but was implemented twice (duplicate
code is eeevil!).
- In addition, fixed a bug causing the function to fail when the server
response is not successful. | (function() {
'use strict';
angular.module('app.feature.weather').factory('_owmWeatherFactory', [
'$log', '$resource', 'WEATHER_SETTINGS',
function($log, $resource, weatherSettings) {
var owmSettings = weatherSettings.OPEN_WEATHER_MAP;
var _dateTimeReviver = function(key, value) {
if (... | (function() {
'use strict';
angular.module('app.feature.weather').factory('_owmWeatherFactory', [
'$log', '$resource', 'WEATHER_SETTINGS',
function($log, $resource, weatherSettings) {
var owmSettings = weatherSettings.OPEN_WEATHER_MAP;
var _dateTimeReviver = function(key, value) {
if (... |
Add test for round tripping via chronicle indexed. | package vanilla.java.echo;
import net.openhft.affinity.AffinityLock;
import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ChronicleQueueBuilder;
import net.openhft.chronicle.ExcerptAppender;
import net.openhft.chronicle.ExcerptTailer;
import java.io.IOException;
public class QueueServerMain {
pub... | package vanilla.java.echo;
import net.openhft.affinity.AffinityLock;
import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ChronicleQueueBuilder;
import net.openhft.chronicle.ExcerptAppender;
import net.openhft.chronicle.ExcerptTailer;
import java.io.IOException;
public class QueueServerMain {
pub... |
Test PrintReport with a real stream | import sys
import unittest
from mock import MagicMock
from chainer import testing
from chainer.training import extensions
class TestPrintReport(unittest.TestCase):
def _setup(self, stream=None, delete_flush=False):
self.logreport = MagicMock(spec=extensions.LogReport(
['epoch'], trigger=(1, ... | import sys
import unittest
from mock import MagicMock
from chainer import testing
from chainer.training import extensions
class TestPrintReport(unittest.TestCase):
def _setup(self, delete_flush=False):
self.logreport = MagicMock(spec=extensions.LogReport(
['epoch'], trigger=(1, 'iteration'), ... |
Add tabId to test-app serverInfo | if (Meteor.isClient) {
var Info = new Mongo.Collection("info");
var Counter = new Mongo.Collection("counter");
Template.hello.onCreated(function () {
Meteor.subscribe("info");
Meteor.subscribe("counter");
});
Template.hello.helpers({
counter: function () {
if (!Template.instance().subscr... | if (Meteor.isClient) {
var Info = new Mongo.Collection("info");
var Counter = new Mongo.Collection("counter");
Template.hello.onCreated(function () {
Meteor.subscribe("info");
Meteor.subscribe("counter");
});
Template.hello.helpers({
counter: function () {
if (!Template.instance().subscr... |
Fix for os.path.join with model_id, was breaking on non-string model_id values. | import os
import requests
class LumidatumClient(object):
def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'):
self.authentication_token = authentication_token
self.model_id = str(model_id)
self.host_address = host_address
def getRecommen... | import os
import requests
class LumidatumClient(object):
def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'):
self.authentication_token = authentication_token
self.model_id = model_id
self.host_address = host_address
def getRecommendatio... |
Change variable name consistently to pool_config | # pylint: disable=W0401
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.oracle.base import *
from django.db.backends.oracle.base import DatabaseWrapper as DjDatabaseWrapper
import cx_Oracle
class DatabaseWrapper(DjDatabaseWrapper):
def __init__(self, *args, **kwargs):
sup... | # pylint: disable=W0401
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.oracle.base import *
from django.db.backends.oracle.base import DatabaseWrapper as DjDatabaseWrapper
import cx_Oracle
class DatabaseWrapper(DjDatabaseWrapper):
def __init__(self, *args, **kwargs):
sup... |
Update to use Session helper
Session no longer available with $request | <?php
/**
* Part of the CSCMS package by Coder Studios.
*
* NOTICE OF LICENSE
*
* Licensed under the terms of the MIT license https://opensource.org/licenses/MIT
*
* @package CSCMS
* @version 1.0.0
* @author Coder Studios Ltd
* @license MIT https://opensource.org/licenses/MIT
* @copyright (c) 2... | <?php
/**
* Part of the CSCMS package by Coder Studios.
*
* NOTICE OF LICENSE
*
* Licensed under the terms of the MIT license https://opensource.org/licenses/MIT
*
* @package CSCMS
* @version 1.0.0
* @author Coder Studios Ltd
* @license MIT https://opensource.org/licenses/MIT
* @copyright (c) 2... |
Allow user-override of pcp config variable like PCP_TMP_DIR.
This is implemented in the same way that the PCP C code does - if
the same-named environment variable is set, use its value (and no
extra checking added). | package com.custardsource.parfait.dxm;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.google.common.io.Closeables;
public class PcpConfig {
private final static String pcpC... | package com.custardsource.parfait.dxm;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.google.common.io.Closeables;
public class PcpConfig {
private final static String pcpC... |
Fix expected PDF E2E warning count | package org.dita.dost;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.nio.file.Paths;
import static org.dita.dost.AbstractIntegrationTest.Transtype.*;
public class EndToEndTest extends AbstractIntegrationTest {
@Test
public void xhtml() throws Throwable {
builder()... | package org.dita.dost;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.nio.file.Paths;
import static org.dita.dost.AbstractIntegrationTest.Transtype.*;
public class EndToEndTest extends AbstractIntegrationTest {
@Test
public void xhtml() throws Throwable {
builder()... |
Add validation state to story title component | import _ from 'lodash';
import React from 'react/addons';
const TITLE_ATTRS = {
who: {
title: "As an",
placeholder: "e.g. an accountant"
},
what: {
title: "I Want",
placeholder: "e.g. Quickbooks integration"
},
why: {
title: "so that",
placeholder: "e.g. I don't have to import CSV's d... | import React from 'react/addons';
let AddItemStoryTitle = React.createClass({
propTypes: {
who: React.PropTypes.object.isRequired,
what: React.PropTypes.object.isRequired,
why: React.PropTypes.object.isRequired
},
render() {
return (
<div className="form-group story-title">
<div c... |
Use proper divider for advisors selector buttons on mobile | <div class="box">
<div class="box-header with-border">
<h3 class="box-title"><i class="fa fa-question-circle"></i> Consult advisor</h3>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.production... | <div class="box">
<div class="box-header with-border">
<h3 class="box-title"><i class="fa fa-question-circle"></i> Consult advisor</h3>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.production... |
Rename edit prop and add default value | import React from 'react';
import SchemaForm from './SchemaForm';
import SchemaFormUtil from '../utils/SchemaFormUtil';
const METHODS_TO_BIND = [
'handleFormChange',
'validateForm'
];
class JobForm extends SchemaForm {
constructor() {
super();
METHODS_TO_BIND.forEach((method) => {
this[method] =... | import React from 'react';
import SchemaForm from './SchemaForm';
import SchemaFormUtil from '../utils/SchemaFormUtil';
const METHODS_TO_BIND = [
'handleFormChange',
'validateForm'
];
class JobForm extends SchemaForm {
constructor() {
super();
METHODS_TO_BIND.forEach((method) => {
this[method] =... |
Fix error in UT because of problem with merge conflicts | <?php
namespace Smartbox\Integration\FrameworkBundle\Tools\Evaluator;
use Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
class CustomExpressionLan... | <?php
namespace Smartbox\Integration\FrameworkBundle\Tools\Evaluator;
use Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
class CustomExpressionLan... |
Use the right port number
I find this makes all the difference... | import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.js';
import gulp from 'gulp';
import gutil from 'gulp-util';
import webpack from 'webpack';
gulp.task('default', ['webpack-dev-server']);
gulp.task('build', ['webpack:build']);
gulp.task('webpack:build', callback => {
const myC... | import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.js';
import gulp from 'gulp';
import gutil from 'gulp-util';
import webpack from 'webpack';
gulp.task('default', ['webpack-dev-server']);
gulp.task('build', ['webpack:build']);
gulp.task('webpack:build', callback => {
const myC... |
Add get_filter_set_kwargs for instanciating FilterSet with additional arguments | from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
... | from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
... |
Fix detecting if timings are enabled | package com.github.games647.lagmonitor.command.timing;
import com.github.games647.lagmonitor.LagMonitor;
import com.github.games647.lagmonitor.command.LagCommand;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public abstract class TimingCommand ext... | package com.github.games647.lagmonitor.command.timing;
import com.github.games647.lagmonitor.LagMonitor;
import com.github.games647.lagmonitor.command.LagCommand;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public abstract class TimingCommand ext... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.