text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Allow original exception to be provided if necessary
git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1329661 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: 91e8c0fd7a04cfa172a34abfb5d0296d040843c0 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
Update user model with confirmed and confirmed_at | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... |
FIX : Attribute map (TI) | <?php
namespace DoL\LdapBundle\Tests\Hydrator;
use FOS\UserBundle\Model\UserManagerInterface;
use DoL\LdapBundle\Hydrator\LegacyHydrator;
use DoL\LdapBundle\Tests\TestUser;
class LegacyHydratorTest extends AbstractHydratorTestCase
{
protected function setUp()
{
parent::setUp();
/** @var User... | <?php
namespace DoL\LdapBundle\Tests\Hydrator;
use FOS\UserBundle\Model\UserManagerInterface;
use DoL\LdapBundle\Hydrator\LegacyHydrator;
use DoL\LdapBundle\Tests\TestUser;
class LegacyHydratorTest extends AbstractHydratorTestCase
{
protected function setUp()
{
parent::setUp();
/** @var User... |
Prepend the tester name in the composite item name formatter | package se.fnord.katydid.internal;
import se.fnord.katydid.ComparisonStatus;
import se.fnord.katydid.DataTester;
import se.fnord.katydid.TestingContext;
import java.nio.ByteBuffer;
import static java.lang.Math.max;
public abstract class CompositeTester extends AbstractTester {
private final DataTester[] values;
... | package se.fnord.katydid.internal;
import se.fnord.katydid.ComparisonStatus;
import se.fnord.katydid.DataTester;
import se.fnord.katydid.TestingContext;
import java.nio.ByteBuffer;
import static java.lang.Math.max;
public abstract class CompositeTester extends AbstractTester {
private final DataTester[] values;
... |
Replace void 0 with undefined | /* eslint import/no-extraneous-dependencies: [2, { "devDependencies": true }] */
import expect from 'expect';
import { map, toUpper } from 'ramda';
import React from 'react';
import { shallow } from 'enzyme';
import createElement, { mapElementPropsWith } from './createElement';
describe('createElement', () => {
i... | /* eslint import/no-extraneous-dependencies: [2, { "devDependencies": true }] */
import expect from 'expect';
import { map, toUpper } from 'ramda';
import React from 'react';
import { shallow } from 'enzyme';
import createElement, { mapElementPropsWith } from './createElement';
describe('createElement', () => {
i... |
Switch console to use tracing-develop | import logging
logging.basicConfig(level=logging.DEBUG)
import mdk_tracing
import time
import quark
# tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None)
tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None)
def goodHandler(result):
# loggi... | import logging
logging.basicConfig(level=logging.DEBUG)
import mdk_tracing
import time
import quark
tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None)
# tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None)
def goodHandler(result):
# loggi... |
Change return type of getView() and getPresenter() for Dialogs. | package com.philliphsu.bottomsheetpickers.view.numberpad;
import com.philliphsu.bottomsheetpickers.view.LocaleModel;
public class NumberPadTimePickerDialogPresenterTest extends NumberPadTimePickerPresenterTest {
@Override
INumberPadTimePicker.DialogView getView(int mode) {
return (INumberPadTimePicke... | package com.philliphsu.bottomsheetpickers.view.numberpad;
import com.philliphsu.bottomsheetpickers.view.LocaleModel;
public class NumberPadTimePickerDialogPresenterTest extends NumberPadTimePickerPresenterTest {
@Override
Class<? extends INumberPadTimePicker.DialogView> getViewClass() {
return INumber... |
Store the rotation matrix corresponding to the orientation in the item. | """Provide the class Image corresponding to an IdxItem.
"""
import os.path
import re
from PySide import QtGui
class ImageNotFoundError(Exception):
pass
class Image(object):
def __init__(self, basedir, item):
self.item = item
self.fileName = os.path.join(basedir, item.filename)
self... | """Provide the class Image corresponding to an IdxItem.
"""
import os.path
import re
from PySide import QtGui
class ImageNotFoundError(Exception):
pass
class Image(object):
def __init__(self, basedir, item):
self.item = item
self.fileName = os.path.join(basedir, item.filename)
self... |
Remove redundant lookup from field type process | <?php
namespace Statamic\Addons\LinkOgData;
use Statamic\Extend\Fieldtype;
class LinkOgDataFieldtype extends Fieldtype
{
/**
* The blank/default value
*
* @return array
*/
public function blank()
{
return [
'url' => null
];
}
/**
* Pre-process... | <?php
namespace Statamic\Addons\LinkOgData;
use Statamic\Extend\Fieldtype;
class LinkOgDataFieldtype extends Fieldtype
{
protected function init()
{
$this->linkogdata = new LinkOgData;
}
/**
* The blank/default value
*
* @return array
*/
public function blank()
{
... |
Add coverage as a testing requirement | #!/usr/bin/env python
from setuptools import setup, find_packages
VERSION = '0.4.2'
def readme():
with open('README.rst') as f:
return f.read()
setup(
name='django-backupdb',
version=VERSION,
description='Management commands for backing up and restoring databases in Django.',
long_des... | #!/usr/bin/env python
from setuptools import setup, find_packages
VERSION = '0.4.2'
def readme():
with open('README.rst') as f:
return f.read()
setup(
name='django-backupdb',
version=VERSION,
description='Management commands for backing up and restoring databases in Django.',
long_des... |
Add the -v flag to work with linux nc | # (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import os
import pytest
from .common import INSTANCE, HOST
from datadog_checks.dev import docker_run, get_here, run_command
from datadog_checks.dev.conditions import CheckCommandOutput
@pytest.fixture(scope='se... | # (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import os
import pytest
from .common import INSTANCE, HOST
from datadog_checks.dev import docker_run, get_here, run_command
from datadog_checks.dev.conditions import CheckCommandOutput
@pytest.fixture(scope='se... |
Correct endpoints for mocking data | import { expect, isFSA, hasStreamMetadata } from '../spec_helper'
import * as subject from '../../src/actions/onboarding'
describe('actions', () => {
it('#loadChannels returns the expected action', () => {
const action = subject.loadChannels()
expect(isFSA(action)).to.be.true
expect(hasStreamMetadata(act... | import { expect, isFSA, hasStreamMetadata } from '../spec_helper'
import * as subject from '../../src/actions/onboarding'
describe('actions', () => {
it('#loadChannels returns the expected action', () => {
const action = subject.loadChannels()
expect(isFSA(action)).to.be.true
expect(hasStreamMetadata(act... |
Update method creation syntax to ES6 LookAction.js iamtienng | L.LockAction = L.EditAction.extend({
initialize(map, overlay, options) {
var edit = overlay.editing;
var use;
var tooltip;
if (edit instanceof L.DistortableImage.Edit) {
L.DistortableImage.action_map.u = '_unlock';
L.DistortableImage.action_map.l = '_lock';
tooltip = overlay.options... | L.LockAction = L.EditAction.extend({
initialize: function(map, overlay, options) {
var edit = overlay.editing;
var use;
var tooltip;
if (edit instanceof L.DistortableImage.Edit) {
L.DistortableImage.action_map.u = '_unlock';
L.DistortableImage.action_map.l = '_lock';
tooltip = overl... |
Add condition to replace Translation extension | <?php
/*
* This file is part of the Cocorico package.
*
* (c) Cocolabs SAS <contact@cocolabs.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cocorico\CoreBundle\DependencyInjection\Compiler;
use Cocorico\CoreBundle... | <?php
/*
* This file is part of the Cocorico package.
*
* (c) Cocolabs SAS <contact@cocolabs.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cocorico\CoreBundle\DependencyInjection\Compiler;
use Cocorico\CoreBundle... |
Check if verification is enabled | package org.jboss.aerogear.unifiedpush.service.impl;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.enterprise.inject.Alternative;
import javax.inject.Inject;
import org.jboss.aerogear.unifiedpush.api.Installation;
import org.jboss.aerogear.unifiedpush.api.Variant;
import org.jboss.aerogear.u... | package org.jboss.aerogear.unifiedpush.service.impl;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.enterprise.inject.Alternative;
import javax.inject.Inject;
import org.jboss.aerogear.unifiedpush.api.Installation;
import org.jboss.aerogear.unifiedpush.api.Variant;
import org.jboss.aerogear.u... |
Put new sentence in Javadoc on new line | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... |
Remove unused call to 'bestOrder' | import { polygonCentroid, distance } from "./math.js";
// With 8 or fewer shapes, find the best permutation
// Skip if array is huge (9+ shapes)
export default function(start, end) {
let distances = start.map(p1 => end.map(p2 => squaredDistance(p1, p2)));
if (start.length > 8) {
return start.map((d, i) => i);
... | import { polygonCentroid, distance } from "./math.js";
// With 8 or fewer shapes, find the best permutation
// Skip if array is huge (9+ shapes)
export default function(start, end) {
let distances = start.map(p1 => end.map(p2 => squaredDistance(p1, p2))),
order = bestOrder(start, end, distances);
if (start.le... |
Remove operation specific to Volley | package com.insa.rocketlyonandroid.utils;
import android.app.Activity;
import android.support.v4.app.Fragment;
import butterknife.ButterKnife;
import trikita.log.Log;
/* With this Base Class, we can access to parent activity of fragment very easily */
public abstract class BaseFragment extends Fragment {
protect... | package com.insa.rocketlyonandroid.utils;
import android.app.Activity;
import android.support.v4.app.Fragment;
import butterknife.ButterKnife;
import trikita.log.Log;
/* With this Base Class, we can access to parent activity of fragment very easily */
public abstract class BaseFragment extends Fragment {
protect... |
[Python] Fix the sample python plugin.
PyGI doesn't handle default values for introspected methods,
so we need to specify all the arguments for pack_start() | # -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:
import gobject
from gi.repository import Peas
from gi.repository import Gtk
LABEL_STRING="Python Says Hello!"
class PythonHelloPlugin(gobject.GObject, Peas.Activatable):
__gtype_name__ = 'PythonHelloPlugin'
def do_activate(self, window):
print "Pytho... | # -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:
import gobject
from gi.repository import Peas
from gi.repository import Gtk
LABEL_STRING="Python Says Hello!"
class PythonHelloPlugin(gobject.GObject, Peas.Activatable):
__gtype_name__ = 'PythonHelloPlugin'
def do_activate(self, window):
print "Pytho... |
Use most recent Ubuntu AMI to minimize the cloud instance spin-up time (=> less system updates to apply at startup) | package org.lamport.tla.toolbox.jcloud;
public class EC2CloudTLCInstanceParameters extends CloudTLCInstanceParameters {
@Override
public String getOwnerId() {
// ubuntu official
return "owner-id=owner-id=099720109477;state=available;image-type=machine";
}
@Override
public String getCloudProvier() {
return... | package org.lamport.tla.toolbox.jcloud;
public class EC2CloudTLCInstanceParameters extends CloudTLCInstanceParameters {
@Override
public String getOwnerId() {
// ubuntu official
return "owner-id=owner-id=099720109477;state=available;image-type=machine";
}
@Override
public String getCloudProvier() {
return... |
Fix lib/raczlib build for CGO_ENABLED=0 | // Copyright 2019 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | // Copyright 2019 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
Change canceling icon to 'spinning orange' | import JobStatus from 'girder_plugins/jobs/JobStatus';
JobStatus.registerStatus({
WORKER_FETCHING_INPUT: {
value: 820,
text: 'Fetching input',
icon: 'icon-download',
color: '#89d2e2'
},
WORKER_CONVERTING_INPUT: {
value: 821,
text: 'Converting input',
... | import JobStatus from 'girder_plugins/jobs/JobStatus';
JobStatus.registerStatus({
WORKER_FETCHING_INPUT: {
value: 820,
text: 'Fetching input',
icon: 'icon-download',
color: '#89d2e2'
},
WORKER_CONVERTING_INPUT: {
value: 821,
text: 'Converting input',
... |
Reduce number of tweets to reduce CPU compuation time of the unoptimised models | from flask import Blueprint, request, render_template
from ..load import processing_results, api
import string
import tweepy
twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static')
ascii_chars = set(string.printable)
ascii_chars.remove(' ')
ascii_chars.add('...')
def takeo... | from flask import Blueprint, request, render_template
from ..load import processing_results, api
import string
import tweepy
twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static')
ascii_chars = set(string.printable)
ascii_chars.remove(' ')
ascii_chars.add('...')
def takeo... |
Use service client factory method for resource group command | from msrest import Serializer
from ..commands import command, description
from ._command_creation import get_service_client
from .._profile import Profile
@command('resource group list')
@description('List resource groups')
# TODO: waiting on Python Azure SDK bug fixes
# @option('--tag-name -g <tagName>', L('the resou... | from msrest import Serializer
from ..commands import command, description
from .._profile import Profile
@command('resource group list')
@description('List resource groups')
# TODO: waiting on Python Azure SDK bug fixes
# @option('--tag-name -g <tagName>', L('the resource group's tag name'))
# @option('--tag-value -g ... |
Include subfolders of `demo` and `test` folders for linting | 'use strict';
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var htmlExtract = require('gulp-html-extract');
var stylelint = require('gulp-stylelint');
gulp.task('lint', ['lint:js', 'lint:html', 'lint:css']);
gulp.task('lint:js', function() {
return gulp.src([
'*.js',
'test/**/*.js'
])
... | 'use strict';
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var htmlExtract = require('gulp-html-extract');
var stylelint = require('gulp-stylelint');
gulp.task('lint', ['lint:js', 'lint:html', 'lint:css']);
gulp.task('lint:js', function() {
return gulp.src([
'*.js',
'test/*.js'
])
.... |
Improve signal handling in balancer | package main
import (
"fmt"
"os"
"os/exec"
"os/signal"
"syscall"
"github.com/squaremo/ambergreen/balancer"
"github.com/squaremo/ambergreen/balancer/fatal"
)
func iptables(args []string) ([]byte, error) {
return exec.Command("iptables", args...).CombinedOutput()
}
func main() {
// Catch some signals for whc... | package main
import (
"fmt"
"os"
"os/exec"
"os/signal"
"syscall"
"github.com/squaremo/ambergreen/balancer"
"github.com/squaremo/ambergreen/balancer/fatal"
)
func iptables(args []string) ([]byte, error) {
return exec.Command("iptables", args...).CombinedOutput()
}
func main() {
exitCode := 0
defer os.Exit(... |
Fix test case for challenge2 | package challenge2
import "testing"
func TestCase1(t *testing.T) {
cases := []struct {
in int
want bool
}{
{120, false},
{166, true},
{141, true},
{79, false},
{26, true},
{158, true},
{174, false},
{141, true},
{169, true},
{129, true},
{199, false},
{27, false},
{57, true},
{183,... | package challenge2
import "testing"
func TestCase1(t *testing.T) {
cases := []struct {
in int
want bool
}{
{120, false},
{166, true},
{141, true},
{79, false},
{26, true},
{158, true},
{174, false},
{141, true},
{169, true},
{129, false},
{199, false},
{27, false},
{57, true},
{183... |
Fix deprecated twig filter syntax | <?php
namespace Liip\ImagineBundle\Templating;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
class ImagineExtension extends \Twig_Extension
{
/**
* @var CacheManager
*/
private $cacheManager;
/**
* Constructor.
*
* @param CacheManager $cacheManager
*/
public functi... | <?php
namespace Liip\ImagineBundle\Templating;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
class ImagineExtension extends \Twig_Extension
{
/**
* @var CacheManager
*/
private $cacheManager;
/**
* Constructor.
*
* @param CacheManager $cacheManager
*/
public functi... |
changed: Enable `referers` as parameter of GenerateSecuredAPIKey | package algoliasearch
func checkGenerateSecuredAPIKey(params Map) error {
if err := checkQuery(params,
"restrictIndices",
"restrictSources",
"userToken",
"validUntil",
"referers",
); err != nil {
return err
}
for k, v := range params {
switch k {
case "restrictIndices", "restrictSources", "userTok... | package algoliasearch
func checkGenerateSecuredAPIKey(params Map) error {
if err := checkQuery(params,
"restrictIndices",
"restrictSources",
"userToken",
"validUntil",
); err != nil {
return err
}
for k, v := range params {
switch k {
case "restrictIndices", "restrictSources", "userToken":
if _, ... |
Make button list more fault tolerant | // ==UserScript==
// @name Selfish Youtube
// @namespace https://github.com/ASzc/selfish-youtube
// @description On the watch page, remove the share panel.
// @include http://youtube.com/watch*
// @include http://*.youtube.com/watch*
// @include https... | // ==UserScript==
// @name Selfish Youtube
// @namespace https://github.com/ASzc/selfish-youtube
// @description On the watch page, remove the share panel.
// @include http://youtube.com/watch*
// @include http://*.youtube.com/watch*
// @include https... |
Make differential.querydiffs more liberal about arguments
Summary:
Fixes T12092. D17164 made `DiffQuery` more strict about arguments using modern conventions, but `differential.querydiffs` uses bizarre ancient conventions.
Give it more modern conventions instead.
Test Plan: Made a `querydiffs` call with only revisio... | <?php
final class DifferentialQueryDiffsConduitAPIMethod
extends DifferentialConduitAPIMethod {
public function getAPIMethodName() {
return 'differential.querydiffs';
}
public function getMethodDescription() {
return pht('Query differential diffs which match certain criteria.');
}
protected func... | <?php
final class DifferentialQueryDiffsConduitAPIMethod
extends DifferentialConduitAPIMethod {
public function getAPIMethodName() {
return 'differential.querydiffs';
}
public function getMethodDescription() {
return pht('Query differential diffs which match certain criteria.');
}
protected func... |
Fix the __file__ is not defined bug | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Dependencies:
- bidi.algorithm
- arabic_reshaper
Dependencies installation:
pip install python-bidi arabic_reshape
"""
import os
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bid... | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Dependencies:
- bidi.algorithm
- arabic_reshaper
Dependencies installation:
pip install python-bidi arabic_reshape
"""
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshape... |
Set USE_TZ in test settings | """
Test Django settings
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'chatterbot.ext.django_chatterbot',
'tests_django',
]
CHATTERB... | """
Test Django settings
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'chatterbot.ext.django_chatterbot',
'tests_django',
]
CHATTERB... |
Raise pypeSyntaxError in pype test | from pytest import raises
from pype.lexer import lexer
from pype.pipeline import Pipeline
example_error_ppl='test/samples/example_error.ppl'
example0_ppl='test/samples/example0.ppl'
example0_token='test/samples/example0.tokens'
example1_ppl='test/samples/example1.ppl'
example1_token='test/samples/example1.tokens'
def... | from pype.lexer import lexer
from pype.pipeline import Pipeline
example_error_ppl='test/samples/example_error.ppl'
example0_ppl='test/samples/example0.ppl'
example0_token='test/samples/example0.tokens'
example1_ppl='test/samples/example1.ppl'
example1_token='test/samples/example1.tokens'
def test_lexer():
lexer.i... |
Correct pytest setup and teardown | import pytest
from tests import base
from buildercore import cfngen, project
import logging
LOG = logging.getLogger(__name__)
logging.disable(logging.NOTSET) # re-enables logging during integration testing
# Depends on talking to AWS.
class TestValidationFixtures(base.BaseCase):
def test_validation(self):
... | import pytest
from tests import base
from buildercore import cfngen, project
import logging
LOG = logging.getLogger(__name__)
logging.disable(logging.NOTSET) # re-enables logging during integration testing
# Depends on talking to AWS.
class TestValidationFixtures(base.BaseCase):
def test_validation(self):
... |
Tag version 0.5 with bytes/text fix | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.5',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[... | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.4',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[... |
Revert to original solution for vcf type determination | package com.hartwig.healthchecks.nesbit.extractor;
import com.hartwig.healthchecks.nesbit.model.VCFType;
import org.jetbrains.annotations.NotNull;
final class VCFExtractorFunctions {
private static final int ALT_INDEX = 4;
private static final int REF_INDEX = 3;
private static final String MULTIPLE_ALTS... | package com.hartwig.healthchecks.nesbit.extractor;
import com.hartwig.healthchecks.nesbit.model.VCFType;
import org.jetbrains.annotations.NotNull;
final class VCFExtractorFunctions {
private static final int ALT_INDEX = 4;
private static final int REF_INDEX = 3;
private static final String MULTIPLE_ALTS... |
Delete commented out loaddata command.
git-svn-id: d73fdb991549f9d1a0affa567d55bb0fdbd453f3@8436 f04a3889-0f81-4131-97fb-bc517d1f583d | from fabric.api import local, run
from fabric.colors import green
from fabric.contrib import django
from fabric.decorators import task
@task
def run_tests(test='src'):
django.settings_module('texas_choropleth.settings.test')
local('./src/manage.py test {0}'.format(test))
def build():
print(green("[ Inst... | from fabric.api import local, run
from fabric.colors import green
from fabric.contrib import django
from fabric.decorators import task
@task
def run_tests(test='src'):
django.settings_module('texas_choropleth.settings.test')
local('./src/manage.py test {0}'.format(test))
def build():
print(green("[ Inst... |
Fix typo in POST request | /* eslint-env jquery */
start();
function start () {
'use strict';
$(document).ready(() => {
$('form').submit(event => {
event.preventDefault();
const username = $('#username').val();
const password = $('#password').val();
const loginObj = {
username,
password
};
... | /* eslint-env jquery */
start();
function start () {
'use strict';
$(document).ready(() => {
$('form').submit(event => {
event.preventDefault();
const username = $('#username').val();
const password = $('#password').val();
const loginObj = {
username,
password
};
... |
Split call into two lines | package beaform.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import beaform.gui.debug.DebugUtilities;
/**
* This class represents the main panel where all views will work in.
*
* @author Steven Post
*
*/
public class MainPanel extends ... | package beaform.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import beaform.gui.debug.DebugUtilities;
/**
* This class represents the main panel where all views will work in.
*
* @author Steven Post
*
*/
public class MainPanel extends ... |
Fix the counter concatenating when updating donation amount
animate counter when donated | Template.logo.helpers({
logoUrl: function(){
return Settings.get("logoUrl");
},
// Add total counter
totalDonation: function() {
$('span.total-counter').text('');
var collection = 0;
var posts = Posts.find().fetch();
for (i = 0; i < posts.length; i++) {
collection += posts[i].Dona... | Template.logo.helpers({
logoUrl: function(){
return Settings.get("logoUrl");
},
// Add total counter
totalDonation: function() {
var collection = 0;
var posts = Posts.find().fetch();
for (i = 0; i < posts.length; i++) {
// debugger;
collection += posts[i].Donations;
};
/... |
Set command reducer memo to undefined | import {Command} from '@grid/core/command';
import {noop} from '../utility';
export class Composite {
static func(list, reduce = noop, memo = null) {
return (...args) => {
for (const f of list) {
memo = reduce(memo, f(...args));
}
return memo;
};
}
static command(list) {
return new Command({
... | import {Command} from '@grid/core/command';
import {noop} from '../utility';
export class Composite {
static func(list, reduce = noop, memo = null) {
return (...args) => {
for (const f of list) {
memo = reduce(memo, f(...args));
}
return memo;
};
}
static command(list) {
return new Command({
... |
Trim email address before submitting to API. | (function (window, document, $) {
var app = window.devsite;
app.pages.signup = function () {
var $btn = $('.notify-btn');
$btn.on('click', function() {
$btn.addClass('disabled');
$.post('/api/developer-plus/coming-soon', {
email: $('input[name="email"]').val().trim()
}, function(... | (function (window, document, $) {
var app = window.devsite;
app.pages.signup = function () {
var $btn = $('.notify-btn');
$btn.on('click', function() {
$btn.addClass('disabled');
$.post('/api/developer-plus/coming-soon', {
email: $('input[name="email"]').val()
}, function(data, s... |
Fix test after JUnit upgrade | package patterns.document;
import java.util.HashMap;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import org.junit.Assert;
import org.junit.Test;
public class CarTest {
private static final double DELTA = 0.000001;
private static final double PRICE = 100.0;
p... | package patterns.document;
import java.util.HashMap;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import org.junit.Test;
import org.junit.Assert;
public class CarTest {
private static final double PRICE = 100.0;
private static final String MODEL = "Audi";
p... |
Fix schema version for api demo | <?php
return [
'itemsPerPage' => 100,
'rootURL' => 'api/oparl/v1/',
'modelNamespace' => 'OParl\\Server\\Model\\',
'transformers' => [
'serializer' => OParl\Server\API\Serializer::class,
'namespace' => 'OParl\\Server\\API\\Transformers',
'classPattern' => '[:modelNa... | <?php
return [
'itemsPerPage' => 100,
'rootURL' => 'api/oparl/v1/',
'modelNamespace' => 'OParl\\Server\\Model\\',
'transformers' => [
'serializer' => OParl\Server\API\Serializer::class,
'namespace' => 'OParl\\Server\\API\\Transformers',
'classPattern' => '[:modelNa... |
Remove a comment that wasn't needed anymore. | $(function () {
$(".boundBoxSize").on("click", function () {
var currentValue = $(this).val();
var grnsightContainerClass = "grnsight-container " + currentValue;
if (!$(".grnsight-container").hasClass(currentValue)) {
$(".grnsight-container").attr("class", grnsightContainerClass);
$("#reloa... | $(function () {
$(".boundBoxSize").on("click", function () {
var currentValue = $(this).val();
var grnsightContainerClass = "grnsight-container " + currentValue;
if (!$(".grnsight-container").hasClass(currentValue)) {
$(".grnsight-container").attr("class", grnsightContainerClass);
$("#reloa... |
Change project factory default values | import factory
from django.contrib.auth.models import User
from accounts.tests.factories import UserFactory
from .. import models
class OrganizationFactory(factory.DjangoModelFactory):
"""Organization factory"""
FACTORY_FOR = models.Organization
name = factory.Sequence(lambda n: 'organization {}'.format(... | import factory
from django.contrib.auth.models import User
from accounts.tests.factories import UserFactory
from .. import models
class OrganizationFactory(factory.DjangoModelFactory):
"""Organization factory"""
FACTORY_FOR = models.Organization
name = factory.Sequence(lambda n: 'organization {}'.format(... |
Revert to returning the exportUrl as String since a relative href is not a valid Java URL. | /**
* Copyright (C) 2009-2016 Simonsoft Nordic AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | /**
* Copyright (C) 2009-2016 Simonsoft Nordic AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... |
FIX visibility of forecast button
Default value for cutoff date is end date of previous fiscal year | # Copyright 2016-2019 Akretion France
# Copyright 2018-2019 Camptocamp
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Account Invoice Start End Dates",
"version": "13.0.1.0.0",
"category": "Accounting & Finance",
"li... | # Copyright 2016-2019 Akretion France
# Copyright 2018-2019 Camptocamp
# @author: Alexis de Lattre <alexis.delattre@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Account Invoice Start End Dates",
"version": "13.0.1.0.0",
"category": "Accounting & Finance",
"li... |
Add maxlength to argument form title and abstract | from colander import Length
from deform import Form
from deform.widget import TextAreaWidget, TextInputWidget
from ekklesia_portal.helper.contract import Schema, string_property
from ekklesia_portal.helper.translation import _
TITLE_MAXLENGTH = 80
ABSTRACT_MAXLENGTH = 160
class ArgumentSchema(Schema):
title = s... | from colander import Length
from deform import Form
from deform.widget import TextAreaWidget
from ekklesia_portal.helper.contract import Schema, string_property
from ekklesia_portal.helper.translation import _
class ArgumentSchema(Schema):
title = string_property(title=_('title'), validator=Length(min=5, max=80))... |
Add solution to problem 20 | /*
* Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable ... | /*
* Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable ... |
Change to keys and values functions from map for labels and visits and countries | 'use strict';
dataDashboard.controller('MainCtrl', ['$scope', 'Traffic', function ($scope, Traffic) {
var getAllTraffic = function() {
Traffic.getTraffic()
.then(function(data) {
if (data) {
$scope.trafficList = data;
// console.log($scope.trafficList);
$... | 'use strict';
dataDashboard.controller('MainCtrl', ['$scope', 'Traffic', function ($scope, Traffic) {
var getAllTraffic = function() {
Traffic.getTraffic()
.then(function(data) {
if (data) {
$scope.trafficList = data;
// console.log($scope.trafficList);
$... |
Bump to 2.0 to get past old django-compress | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
setup(
name='django-compress',
version='2.0.0',
description='A Django app for compressing CSS and JS',
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
setup(
name='django-compress',
version='1.0.0',
description='A Django app for compressing CSS and JS',
... |
Increase size of `password` column | # -*- coding: utf-8 -*-
import sys
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
SQLALCHEMY_DATABASE_URI = 'sqlite:///accounts.db'
Base = declarative_base()
def db_connect():
"""
Performs database connection using... | # -*- coding: utf-8 -*-
import sys
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
SQLALCHEMY_DATABASE_URI = 'sqlite:///accounts.db'
Base = declarative_base()
def db_connect():
"""
Performs database connection using... |
Change cucumber test tag to not run by default | /**
* Copyright Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | /**
* Copyright Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
Add comments explaining prediction data structure | # Based on modeprediction.py
import emission.core.wrapper.wrapperbase as ecwb
# The "prediction" data structure is a list of label possibilities, each one consisting of a set of labels and a probability:
# [
# {"labels": {"labeltype1": "labelvalue1", "labeltype2": "labelvalue2"}, "p": 0.61},
# {"labels": {"label... | # Based on modeprediction.py
import emission.core.wrapper.wrapperbase as ecwb
class Labelprediction(ecwb.WrapperBase):
props = {"trip_id": ecwb.WrapperBase.Access.WORM, # the trip that this is part of
"prediction": ecwb.WrapperBase.Access.WORM, # What we predict
"start_ts": ecwb.Wrapp... |
Fix indent, PEP-8 style and remove dup import. | from django.views.generic import RedirectView
from django.views.generic.detail import SingleObjectMixin
from django.contrib.auth import login, authenticate
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
class BaseAuthView(SingleObjectMixin, RedirectView):
def get_... | from django.views.generic import RedirectView
from django.views.generic.detail import SingleObjectMixin
from django.contrib.auth import login, authenticate, login
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
class BaseAuthView(SingleObjectMixin, RedirectView):
d... |
Add plt to rio_insp locals. |
import code
import collections
import logging
import sys
import matplotlib.pyplot as plt
import numpy
import rasterio
logger = logging.getLogger('rasterio')
Stats = collections.namedtuple('Stats', ['min', 'max', 'mean'])
def main(banner, dataset):
def show(source, cmap='gray'):
"""Show a raster usin... |
import code
import collections
import logging
import sys
import numpy
import rasterio
logger = logging.getLogger('rasterio')
Stats = collections.namedtuple('Stats', ['min', 'max', 'mean'])
def main(banner, dataset):
def show(source, cmap='gray'):
"""Show a raster using matplotlib.
The raste... |
Replace YAML parse function to parseFile | <?php
namespace Misantron\Silex\Provider\Adapter;
use Misantron\Silex\Provider\ConfigAdapter;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Parser;
/**
* Class YamlConfigAdapter
* @package Misantron\Silex\Provider\Adapter
*/
class YamlConfigAdapter extends ConfigAdapter
{
/*... | <?php
namespace Misantron\Silex\Provider\Adapter;
use Misantron\Silex\Provider\ConfigAdapter;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Parser;
/**
* Class YamlConfigAdapter
* @package Misantron\Silex\Provider\Adapter
*/
class YamlConfigAdapter extends ConfigAdapter
{
/*... |
Update graphic settings before renderer is created | import { isWebGLSupported } from './core/utils';
import CanvasRenderer from './core/renderers/canvas/CanvasRenderer';
import WebGLRenderer from './core/renderers/webgl/WebGLRenderer';
import settings from './core/settings';
import { SCALE_MODES } from './core/const';
export default class VisualServer {
constructo... | import { isWebGLSupported } from './core/utils';
import CanvasRenderer from './core/renderers/canvas/CanvasRenderer';
import WebGLRenderer from './core/renderers/webgl/WebGLRenderer';
import settings from './core/settings';
import { SCALE_MODES } from './core/const';
export default class VisualServer {
constructo... |
Make committing with case-insensitive username possible | <?php
/* Libre.fm -- a free network service for sharing your music listening habits
Copyright (C) 2009 Libre.fm Project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either ver... | <?php
/* Libre.fm -- a free network service for sharing your music listening habits
Copyright (C) 2009 Libre.fm Project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either ver... |
Fix a floating point issue | var exports = {};
exports.simplePrint = function(video) {
return `**${video.title}**`;
};
exports.prettyPrint = function(video) {
viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return `**${video.title}** by **${video.author}** *(${viewCount} views)*`;
};
exports.prettyPrintWithUser = funct... | var exports = {};
exports.simplePrint = function(video) {
return `**${video.title}**`;
};
exports.prettyPrint = function(video) {
viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return `**${video.title}** by **${video.author}** *(${viewCount} views)*`;
};
exports.prettyPrintWithUser = funct... |
Test that framebuffer can't be bound after deletion. | from nose.tools import *
from scikits.gpu.fbo import *
from pyglet.gl import *
class TestFramebuffer(object):
def create(self, x, y, colours, dtype):
fbo = Framebuffer(x, y, bands=colours, dtype=dtype)
fbo.bind()
fbo.unbind()
fbo.delete()
def test_creation(self):
fbo =... | from nose.tools import *
from scikits.gpu.fbo import *
from pyglet.gl import *
class TestFramebuffer(object):
def create(self, x, y, colours, dtype):
fbo = Framebuffer(x, y, bands=colours, dtype=dtype)
fbo.bind()
fbo.unbind()
fbo.delete()
def test_creation(self):
fbo =... |
Check for existence before removal | var mongoose = require('mongoose');
var Table = require('./Table');
var TableSchema = Table.schema;
var Schema = mongoose.Schema;
var handleError = function(err){
if (err){
console.log(err);
return;
}
}
var TableQueueSchema = new Schema({
queue : {type: [TableSchema], defa... | var mongoose = require('mongoose');
var Table = require('./Table');
var TableSchema = Table.schema;
var Schema = mongoose.Schema;
var handleError = function(err){
if (err){
console.log(err);
return;
}
}
var TableQueueSchema = new Schema({
queue : {type: [TableSchema], defa... |
Update URL for bel2rdf service | import requests
import json
import time
ndex_base_url = 'http://bel2rdf.bigmech.ndexbio.org'
#ndex_base_url = 'http://52.37.175.128'
def send_request(url_suffix, params):
res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
res_json = get_result(res)
return res_json
def get_result(res... | import requests
import json
import time
ndex_base_url = 'http://general.bigmech.ndexbio.org:8082'
#ndex_base_url = 'http://52.37.175.128'
def send_request(url_suffix, params):
res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
res_json = get_result(res)
return res_json
def get_resul... |
Add method to reset the LogMonitor i.e. forget any previously logged
messages. | /**
================================================================================
Project: Procter and Gamble - Skelmersdale.
$HeadURL$
$Author$
$Revision$
$Date$
$Log$
============================== (c) Swisslog(UK) Ltd, 2005 ======================
*/
package io.cloudracer;
import static org.... | /**
================================================================================
Project: Procter and Gamble - Skelmersdale.
$HeadURL$
$Author$
$Revision$
$Date$
$Log$
============================== (c) Swisslog(UK) Ltd, 2005 ======================
*/
package io.cloudracer;
import static org.... |
Add support for a setup phase which is not recorded. | package net.openhft.chronicle.wire;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
/**
* Created by peter on 17/05/2017.
*/
public class TextMethodTesterTest {
@Test
public void run() throws IOException {
TextMethodTester test = new TextMethodTester... | package net.openhft.chronicle.wire;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
/**
* Created by peter on 17/05/2017.
*/
public class TextMethodTesterTest {
@Test
public void run() throws IOException {
TextMethodTester test = new TextMethodTester... |
Add identifiers function and create an array of identifiers and their number of times they appear | const esprima = require('esprima');
var source = 'answer = 42; hola = 5; isCold = "Si"; answer = 50;';
const tokens = esprima.tokenize(source);
//console.log(tokens);
var identificadores = tokens.filter(function (el) {
return (el.type === "Identifier");
});
console.log("El código es: ");
console.log(source);
//c... | const esprima = require('esprima');
var source = 'answer = 42; hola = 5; isCold = "Si"; answer = 50;';
const tokens = esprima.tokenize(source);
//console.log(tokens);
var identificadores = tokens.filter(function (el) {
return (el.type === "Identifier");
});
console.log("El código es: ");
console.log(source);
//con... |
Fix logging so it doesn't erase the file | from threading import Thread
from Queue import Queue
from twisted.python import log
import time
import Mailbox, Web
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", "-v", help="output logs to std out, not the file",
action="store_true")
args = parser.pa... | from threading import Thread
from Queue import Queue
from twisted.python import log
import time
import Mailbox, Web
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", "-v", help="output logs to std out, not the file",
action="store_true")
args = parser.pa... |
Fix the location path of OpenIPSL | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"... | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"... |
Fix arguments to diff method | # -*- coding: utf-8 -*-
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
class DB(object):
"""Facade for the low level DB operations"""
def __init__(self, dsn, schema=None):
self.engine = create_engine(dsn)
self.... | # -*- coding: utf-8 -*-
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
class DB(object):
"""Facade for the low level DB operations"""
def __init__(self, dsn, schema=None):
self.engine = create_engine(dsn)
self.... |
Update the PyPI version to 0.2.7 | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.7',
packages=['todoist', 'todoist.managers'],
author='Doist Team'... | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.6',
packages=['todoist', 'todoist.managers'],
author='Doist Team'... |
Change visibility from protected to public | <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Customizer\Layout\Settings;
use GrottoPress\Jentil\Setups\Customizer\Layout\Layout;
use GrottoPress\Jentil\utilities\ThemeMods\Layout as LayoutMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;
abstract class AbstractSetting... | <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Customizer\Layout\Settings;
use GrottoPress\Jentil\Setups\Customizer\Layout\Layout;
use GrottoPress\Jentil\utilities\ThemeMods\Layout as LayoutMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;
abstract class AbstractSetting... |
Remove extraneous currency field from transfer schedules. | package co.omise.models.schedules;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TransferScheduling {
private String recipient;
private long amount;
@JsonProperty("percentage_of_balance")
private float percentageOfBalance;
public String getRecipient() {
return recipie... | package co.omise.models.schedules;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TransferScheduling {
private String recipient;
private long amount;
private String currency;
@JsonProperty("percentage_of_balance")
private float percentageOfBalance;
public String getRecipie... |
Update user details API call | from social.backends.oauth import BaseOAuth2
class HastexoOAuth2(BaseOAuth2):
"""Hastexo OAuth2 authentication backend"""
name = 'hastexo'
AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/'
ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/'
ACCESS_TOKEN_METHOD = 'POST'
SCOPE_SE... | from social.backends.oauth import BaseOAuth2
class HastexoOAuth2(BaseOAuth2):
"""Hastexo OAuth2 authentication backend"""
name = 'hastexo'
AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/'
ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/'
ACCESS_TOKEN_METHOD = 'POST'
SCOPE_SE... |
Fix python debugging on Windows. | from __future__ import print_function
import sys
import os
import time
import socket
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('--launch-adapter')
parser.add_argument('--lldb')
parser.add_argument('--wait-port')
args = parser.parse_args()
if args.launch_adapter:
lld... | from __future__ import print_function
import sys
import os
import time
import socket
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('--launch-adapter')
parser.add_argument('--lldb')
parser.add_argument('--wait-port')
args = parser.parse_args()
if args.launch_adapter:
lld... |
Reset term state and change default search term. | import React, {Component} from 'react';
import {connect} from 'react-redux';
import {searchVideos} from '../actions/index';
import {bindActionCreators} from 'redux';
class SearchBar extends Component{
constructor(props){
super(props);
this.state = { term: ''};
}
handleOnChange(term){
this.setState({term});... | import React, {Component} from 'react';
import {connect} from 'react-redux';
import {searchVideos} from '../actions/index';
import {bindActionCreators} from 'redux';
class SearchBar extends Component{
constructor(props){
super(props);
this.state = { term: 'Basketball'};
}
handleOnChange(term){
this.setStat... |
Enable consistent-hashing policy for Collector
Change-Id: I7ed6747b6c3ef95d8fed0c62e786c7039fb510a6
Fixes-Bug: #1600368 | import string
template = string.Template("""
[DEFAULTS]
zk_server_ip=$__contrail_zk_server_ip__
zk_server_port=$__contrail_zk_server_port__
listen_ip_addr=$__contrail_listen_ip_addr__
listen_port=$__contrail_listen_port__
log_local=$__contrail_log_local__
log_file=$__contrail_log_file__
cassandra_server_list=$__contra... | import string
template = string.Template("""
[DEFAULTS]
zk_server_ip=$__contrail_zk_server_ip__
zk_server_port=$__contrail_zk_server_port__
listen_ip_addr=$__contrail_listen_ip_addr__
listen_port=$__contrail_listen_port__
log_local=$__contrail_log_local__
log_file=$__contrail_log_file__
cassandra_server_list=$__contra... |
Return Status 422 on bad JSON content | import json
import os
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **template_args):
self.response.write(self.jinja2.render_templa... | import json
import os
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **template_args):
self.response.write(self.jinja2.render_templa... |
BAP-9940: Create controller DELETE list action
- fix cs | <?php
namespace Oro\Bundle\ApiBundle\Processor;
use Oro\Component\ChainProcessor\ProcessorBag;
use Oro\Bundle\ApiBundle\Provider\ConfigProvider;
use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext;
use Oro\Bundle\ApiBundle\Provider\MetadataProvider;
class DeleteListProcessor extends RequestActionProcess... | <?php
namespace Oro\Bundle\ApiBundle\Processor;
use Oro\Bundle\ApiBundle\Provider\ConfigProvider;
use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext;
use Oro\Bundle\ApiBundle\Provider\MetadataProvider;
use Oro\Component\ChainProcessor\ProcessorBag;
class DeleteListProcessor extends RequestActionProcesso... |
Set the relation name for the list of greetings. | package hello.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.hateoas.core.Relation;
... | package hello.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
public class Greeting {
@Id
@GeneratedV... |
Order planets by distance form their star. | from django.views.generic import ListView, DetailView
from .models import Planet, SolarSystem
class SystemMixin(object):
model = SolarSystem
def get_queryset(self):
return super(SystemMixin, self).get_queryset().filter(radius__isnull=False)
class PlanetMixin(object):
model = Planet
def get_... | from django.views.generic import ListView, DetailView
from .models import Planet, SolarSystem
class SystemMixin(object):
model = SolarSystem
def get_queryset(self):
return super(SystemMixin, self).get_queryset().filter(radius__isnull=False)
class PlanetMixin(object):
model = Planet
def get_... |
Change the cursor over cast list items. | // @flow
import React from 'react';
import PropTypes from 'prop-types';
import { red500 } from 'material-ui/styles/colors';
import { ListItem } from 'material-ui/List';
import Avatar from 'material-ui/Avatar';
class CastListItem extends React.Component {
static propTypes = {
role: PropTypes.string.isReq... | // @flow
import React from 'react';
import PropTypes from 'prop-types';
import { red500 } from 'material-ui/styles/colors';
import { ListItem } from 'material-ui/List';
import Avatar from 'material-ui/Avatar';
class CastListItem extends React.Component {
static propTypes = {
role: PropTypes.string.isReq... |
Refactor minor details for editCommand | package seedu.jimi.logic.commands;
import seedu.jimi.model.task.FloatingTask;
/**
*
* @author zexuan
*
* Edits an existing task/event in Jimi.
*/
public class EditCommand extends Command{
public static final String COMMAND_WORD = "edit";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edi... | package seedu.jimi.logic.commands;
import seedu.jimi.model.task.FloatingTask;
/**
*
* @author zexuan
*
* Edits an existing task/event in Jimi.
*/
public class EditCommand extends Command{
public static final String COMMAND_WORD = "add";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edit... |
Add email field to login status. | package com.google.sps.servlets;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.sps.utilities.CommonUtils;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.... | package com.google.sps.servlets;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.sps.utilities.CommonUtils;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.... |
Comment out block to make linter happy | import assert from 'assert'
const TYPE_TO_PREFIXES = {
municipality: 'K',
borough: 'B',
county: 'F',
commerceRegion: 'N'
}
// we might need this reverse mapping at some point later
//const PREFIX_TO_TYPE = Object.keys(TYPE_TO_PREFIXES).reduce((acc, key) => {
// acc[TYPE_TO_PREFIXES[key]] = key
// return acc
... | import assert from 'assert'
const TYPE_TO_PREFIXES = {
municipality: 'K',
borough: 'B',
county: 'F',
commerceRegion: 'N'
}
const PREFIX_TO_TYPE = Object.keys(TYPE_TO_PREFIXES).reduce((acc, key) => {
acc[TYPE_TO_PREFIXES[key]] = key
return acc
}, {})
const REGION_TYPE_TO_ID_FIELD_MAPPING = {
municipality... |
Add stub for pulling player_stats including a new base_url for MySportsFeed | import json
import csv
import requests
import secret
base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings f... | import json
import csv
from collections import namedtuple
from player_class import Players
def main():
filename = get_data_file()
data = load_file(filename)
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Imp... |
Use lastSeen instead of clients in list | #! /usr/bin/env node
'use strict';
const unifi = require('./lib/unifi');
const domoticz = require('./lib/domoticz');
const config = require('./lib/config');
let configArgIndex = process.argv.findIndex(arg => {
return arg === '-c';
});
if (configArgIndex) {
config.init(process.argv[configArgIndex + 1]);
}
domoti... | #! /usr/bin/env node
'use strict';
const unifi = require('./lib/unifi');
const domoticz = require('./lib/domoticz');
const config = require('./lib/config');
let configArgIndex = process.argv.findIndex(arg => {
return arg === '-c';
});
if (configArgIndex) {
config.init(process.argv[configArgIndex + 1]);
}
domoti... |
Remove String annotations, use Field instead | <?php
namespace Saxulum\Tests\DoctrineMongoDbOdm\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* @ODM\Document
*/
class Page
{
/**
* @var string
* @ODM\Id
*/
protected $id;
/**
* @var string
* @ODM\Field(type="string")
*/
protected $title;
/*... | <?php
namespace Saxulum\Tests\DoctrineMongoDbOdm\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* @ODM\Document
*/
class Page
{
/**
* @var string
* @ODM\Id
*/
protected $id;
/**
* @var string
* @ODM\String
*/
protected $title;
/**
* @var ... |
Change `type` prop to `theme` | const React = require('react');
const classNames = require('classnames');
class Button extends React.Component {
render() {
const {
className,
children,
theme,
...props
} = this.props;
const buttonClassNames = classNames({
btn: true,
'btn-sm': this.props.size === 'sma... | const React = require('react');
const classNames = require('classnames');
class Button extends React.Component {
render() {
const {
className,
children,
type,
...props
} = this.props;
const buttonClassNames = classNames({
btn: true,
'btn-sm': this.props.size === 'smal... |
Add blank line between HexFormat chunks. | package uk.ac.cam.gpe21.droidssl.mitm;
import uk.ac.cam.gpe21.droidssl.mitm.util.HexFormat;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public final class IoCopyRunnable implements Runnable {
private final InputStream in;
private final OutputStream out;
public IoCopyRunna... | package uk.ac.cam.gpe21.droidssl.mitm;
import uk.ac.cam.gpe21.droidssl.mitm.util.HexFormat;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public final class IoCopyRunnable implements Runnable {
private final InputStream in;
private final OutputStream out;
public IoCopyRunna... |
[Telemetry] Increase Kraken timeout to allow it to pass on Android.
BUG=163680
TEST=tools/perf/run_multipage_benchmarks --browser=android-content-shell kraken tools/perf/page_sets/kraken.json
Review URL: https://chromiumcodereview.appspot.com/11519015
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@172374 0039... | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry import multi_page_benchmark
from telemetry import util
def _Mean(l):
return float(sum(l)) / len(l) if len(l) > 0 else 0.0
class Kraken... | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry import multi_page_benchmark
from telemetry import util
def _Mean(l):
return float(sum(l)) / len(l) if len(l) > 0 else 0.0
class Kraken... |
Fix typo in name of variable | #!/usr/bin/env python3
import os
from datetime import timedelta
_BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__))
DEFAULT_SERVICE_PORT = 34000
SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml')
DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs')
TOKEN_VALID_TIME = timed... | #!/usr/bin/env python3
import os
from datetime import timedelta
_BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__))
DEFAULT_SERVICE_PORT = 34000
SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml')
DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs')
TOKEN_VALID_TIME = timed... |
Set config contained a bug after refactoring | import argparse
import logging.config
from intexration import settings
from intexration.server import Server
# Logger
logging.config.fileConfig(settings.LOGGING_FILE)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-host', help='Change the hostname')
parser.add_argument('-port', help=... | import argparse
import logging.config
import os
from intexration import settings
from intexration.server import Server
# Logger
logging.config.fileConfig(settings.LOGGING_FILE)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-host', help='Change the hostname')
parser.add_argument('-po... |
[FIX] Return Ayah's pk instead of number | from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = ... | from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = ... |
Add delete old sessions command | from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
"""
>>> def clean(count):
... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
... s.delete()
... if str(idx).endswith('000'): print idx
... p... | from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
"""
>>> def clean(count):
... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
... s.delete()
... if str(idx).endswith('000'): print idx
... p... |
Update expected value on test | import markdown
from mdx_embedly import EmbedlyExtension
def test_embedly():
s = "[https://github.com/yymm:embed]"
expected = """
<p>
<a class="embedly-card" href="https://github.com/yymm">embed.ly</a>
<script async src="//cdn.embedly.com/widgets/platform.js" charset="UTF-8"></script>
</p>
""".strip()
... | import markdown
from mdx_embedly import EmbedlyExtension
def test_embedly():
s = "[https://github.com/yymm:embed]"
expected = """
<p>
<a class="embedly-card" href="https://github.com/yymm">embed.ly</a>
<script async src="//cdn.embedly.com/widgets/platform.js"charset="UTF-8"></script>
</p>
""".strip()
... |
Delete auto generated comments.
Comment out the entire file. | package com.biotronisis.pettplant.type;
//public enum EntrainmentMode {
// oldMEDITATE(0),
// oldSLEEP(1),
// oldSTAY_AWAKE(2);
// Run/Stop button values
// public static final String RUN = "Run";
// public static final String STOP = "Stop";
// Pause/Resume button values
// public static final Str... | package com.biotronisis.pettplant.type;
/**
* Created by john on 6/16/15.
*/
public enum EntrainmentMode {
oldMEDITATE(0),
oldSLEEP(1),
oldSTAY_AWAKE(2);
// Run/Stop button values
// public static final String RUN = "Run";
// public static final String STOP = "Stop";
// Pause/Resume button valu... |
Fix shell script reference - note to self add to other hooks | <?php
include 'config.php';
list($algo, $hash) = explode('=', $_SERVER["HTTP_X_HUB_SIGNATURE"], 2);
$payload = file_get_contents('php://input');
$payloadHash = hash_hmac($algo, $payload, $secret);
if ($hash !== $payloadHash) {
http_response_code(401);
echo "Bad secret";
exit;
}
$data = json_decode($pay... | <?php
include 'config.php';
list($algo, $hash) = explode('=', $_SERVER["HTTP_X_HUB_SIGNATURE"], 2);
$payload = file_get_contents('php://input');
$payloadHash = hash_hmac($algo, $payload, $secret);
if ($hash !== $payloadHash) {
http_response_code(401);
echo "Bad secret";
exit;
}
$data = json_decode($pay... |
Use AttachUser middleware before verifyAdmin. | const userController = require('../controllers/user');
const authenticationMiddleware = require('../middleware/authentication');
const express = require('express');
const router = express.Router();
// GET all users
router.get(
'/', // route
authenticationMiddleware.validateAuthentication, // isAuthenticated mid... | const userController = require('../controllers/user');
const authenticationMiddleware = require('../middleware/authentication');
const express = require('express');
const router = express.Router();
// GET all users
router.get(
'/', // route
authenticationMiddleware.validateAuthentication, // isAuthenticated mid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.