text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Add auth flow onEnter states | angular.module('smartCampUZApp', ['ui.router', 'base64', 'angular-jwt'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
//starter screen
.state('starter', {
url: "/starter",
templateUrl: "templates/starter.html",
... | angular.module('smartCampUZApp', ['ui.router', 'base64', 'angular-jwt'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
//starter screen
.state('starter', {
url: "/starter",
templateUrl: "templates/starter.html",
... |
Declare vars before using it
If there are not tests, then an exception occurs:
```
PHP Notice: Undefined variable: methods in PROJECT/vendor/jolicode/asynit/src/Parser/TestsFinder.php on line 56
PHP Fatal error: Uncaught TypeError: Return value of Asynit\Parser\TestsFinder::doFindTests() must be of the type arr... | <?php
namespace Asynit\Parser;
use Asynit\Test;
use Asynit\TestCase;
use Symfony\Component\Finder\Finder;
class TestsFinder
{
public function findTests(string $path): array
{
if (\is_file($path)) {
return $this->doFindTests([$path]);
}
$finder = Finder::create()
... | <?php
namespace Asynit\Parser;
use Asynit\Test;
use Asynit\TestCase;
use Symfony\Component\Finder\Finder;
class TestsFinder
{
public function findTests(string $path): array
{
if (\is_file($path)) {
return $this->doFindTests([$path]);
}
$finder = Finder::create()
... |
Use the HTMLParser module instead of htmllib | import plugin
import urllib2
import logging
import re
from httplib import HTTPException
import HTMLParser
class Plugin(plugin.baseplugin):
def __init__(self, bot):
self._regex = re.compile("(https?://.+)\s?")
self._ua = "Mozilla/5.0 (X11; Linux x86_64; rv:2.0b8) Gecko/20100101 Firefox/4.0b8"
... | import plugin
import urllib2
import logging
import re
from httplib import HTTPException
from htmllib import HTMLParser
class Plugin(plugin.baseplugin):
def __init__(self, bot):
self._regex = re.compile("(https?://.+)\s?")
self._ua = "Mozilla/5.0 (X11; Linux x86_64; rv:2.0b8) Gecko/20100101 Firefox... |
Fix lecturerService being spelled wrong for logging out | (function() {
'use strict';
angular
.module('lecturer')
.factory('lecturerFactory', lecturerFactory);
/* @ngInject */
function lecturerFactory(lecturerService, $location) {
var username = '';
var observerCallbacks = [];
var Login = false;
var se... | (function() {
'use strict';
angular
.module('lecturer')
.factory('lecturerFactory', lecturerFactory);
/* @ngInject */
function lecturerFactory(lecturerService, $location) {
var username = '';
var observerCallbacks = [];
var Login = false;
var se... |
Use PickleSerializer to serialize test sessions.
Use PickleSerializer so that we can serialize datetimes in sessions
(this is necessary to set expired sessions in automated tests). See
https://docs.djangoproject.com/en/2.0/topics/http/sessions/#write-your-own-serializer. | import datetime
from importlib import import_module
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from session_cleanup.tasks import cleanup
class CleanupTest(TestCase):
@override_settings(SESSION_ENGINE="django... | import datetime
from importlib import import_module
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from session_cleanup.tasks import cleanup
class CleanupTest(TestCase):
@override_settings(SESSION_ENGINE="django... |
Add delete example in CURL job | """A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name_... | """A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name_... |
Fix use of userID instead of id | var Blog = React.createClass({
navigate: function(interval) {
alert(interval)
},
navBtn: function(forwards) {
return (
<div className={"ui " + (forwards?"right":"left") + " floated segment basic"}>
<button className="circular ui button" onClick={()=>this.navigate(... | var Blog = React.createClass({
navigate: function(interval) {
alert(interval)
},
navBtn: function(forwards) {
return (
<div className={"ui " + (forwards?"right":"left") + " floated segment basic"}>
<button className="circular ui button" onClick={()=>this.navigate(... |
Use i_latest_revision to ensure we get the latest revision. | """Name output plugin
"""
import optparse
from pyang import plugin
def pyang_plugin_init():
plugin.register_plugin(NamePlugin())
class NamePlugin(plugin.PyangPlugin):
def add_output_format(self, fmts):
self.multiple_modules = True
fmts['name'] = self
def add_opts(self, optparser):
... | """Name output plugin
"""
import optparse
from pyang import plugin
def pyang_plugin_init():
plugin.register_plugin(NamePlugin())
class NamePlugin(plugin.PyangPlugin):
def add_output_format(self, fmts):
self.multiple_modules = True
fmts['name'] = self
def add_opts(self, optparser):
... |
Use BSA's API to get URL of latest prescribing data | import os
import requests
from django.conf import settings
from django.core.management import BaseCommand
from openprescribing.utils import mkdir_p
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("year", type=int)
parser.add_argument("month", type=int)
def ... | import os
import requests
from bs4 import BeautifulSoup
from django.conf import settings
from django.core.management import BaseCommand
from openprescribing.utils import mkdir_p
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("year", type=int)
parser.add_argumen... |
Remove hard exits and event logging from buildInfo example | <?php
use Jmikola\React\MongoDB\Connection;
use Jmikola\React\MongoDB\ConnectionFactory;
use Jmikola\React\MongoDB\Protocol\Query;
use Jmikola\React\MongoDB\Protocol\Reply;
require __DIR__ . '/../vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$factory = new ConnectionFactory($loop);
$connection = ... | <?php
use Jmikola\React\MongoDB\Connection;
use Jmikola\React\MongoDB\ConnectionFactory;
use Jmikola\React\MongoDB\Protocol\Query;
use Jmikola\React\MongoDB\Protocol\Reply;
require __DIR__ . '/../vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$factory = new ConnectionFactory($loop);
$connection = ... |
Remove a not-too-useful comment hating on Django Pipelines | require('js-yaml');
var path = require('path');
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-jst');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-karma');
grunt.initConfig({
paths: require('js_paths.yml'),
mochaTest: {
jsbox_apps: {
src: ['<%=... | require('js-yaml');
var path = require('path');
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-jst');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-karma');
grunt.initConfig({
paths: require('js_paths.yml'),
mochaTest: {
jsbox_apps: {
src: ['<%=... |
Remove reference to old UUIDfield in django migration | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
import uuid
from django.db.models import UUIDField
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name=... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
import uuid
try:
from django.db.models import UUIDField
except ImportError:
from django_dbq.fields import UUIDField
class Migration(migrations.Migration):
dependencies = [
... |
Test for HOST_NAME or HOSTNAME env var | from cla_public.config.common import *
DEBUG = os.environ.get('SET_DEBUG', False) == 'True'
SECRET_KEY = os.environ['SECRET_KEY']
# TODO - change this to True when serving over HTTPS
SESSION_COOKIE_SECURE = os.environ.get('CLA_ENV', '') in ['prod', 'staging']
HOST_NAME = os.environ.get('HOST_NAME') or os.environ.g... | from cla_public.config.common import *
DEBUG = os.environ.get('SET_DEBUG', False) == 'True'
SECRET_KEY = os.environ['SECRET_KEY']
# TODO - change this to True when serving over HTTPS
SESSION_COOKIE_SECURE = os.environ.get('CLA_ENV', '') in ['prod', 'staging']
HOST_NAME = os.environ['HOST_NAME']
BACKEND_API = {
... |
Fix python 3 use of iteritems | import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in iter(d.items()):
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
... | import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
... |
Switch capmetrics script to etl function. | #!/usr/bin/env python3
import os
from setuptools import setup, find_packages
def get_readme():
return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
author="Julio Gonzalez Altamirano",
author_email='devjga@gmail.com',
classifiers=[
'Intended Audience :: Developers',... | #!/usr/bin/env python3
import os
from setuptools import setup, find_packages
def get_readme():
return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
author="Julio Gonzalez Altamirano",
author_email='devjga@gmail.com',
classifiers=[
'Intended Audience :: Developers',... |
Remove deprecated usage of TreeBuilder on Symfony 4 | <?php
/*
* This file is part of the EzCoreExtraBundle package.
*
* (c) Jérôme Vieilledent <jerome@vieilledent.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Lolautruche\EzCoreExtraBundle\DependencyInjection;
use e... | <?php
/*
* This file is part of the EzCoreExtraBundle package.
*
* (c) Jérôme Vieilledent <jerome@vieilledent.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Lolautruche\EzCoreExtraBundle\DependencyInjection;
use e... |
Use pyaccess as the package name. | from setuptools import setup, Extension
import numpy as np
import os
extension_name = '_pyaccess'
extension_version = '.1'
include_dirs = [
'ann_1.1.2/include',
'sparsehash-2.0.2/src',
np.get_include(),
'.'
]
library_dirs = [
'ann_1.1.2/lib',
'contraction_hierarchies'
]
packages = ['pyaccess']... | from setuptools import setup, Extension
import numpy as np
import os
extension_name = '_pyaccess'
extension_version = '.1'
include_dirs = [
'ann_1.1.2/include',
'sparsehash-2.0.2/src',
np.get_include(),
'.'
]
library_dirs = [
'ann_1.1.2/lib',
'contraction_hierarchies'
]
packages = ['pyaccess']... |
Fix incorrect global comment in include path script | #!/usr/bin/env python3
"""
Parses .vscode/.cmaketools.json to obtain a list of include paths.
These can then be subsequently pasted into .vscode/c_cpp_properties.json
to make intellisense work. This is script exists purely for convenience
and only needs to be used when the include paths change (e.g. when a new
depende... | #!/usr/bin/env python3
"""
Deploys the website to a target directory supplied as an argument.
"""
import json
import os
import sys
def iterate_over(dict_or_list, result):
"""
Iterates recursively over nested lists and dictionaries
keeping track of all "path" values with the key "includePath"
within n... |
Remove unnecessary explicit index check. | // Place your library's code here
//
// If you add additional files, be sure to
// load them in order in ./wrapper.js
//
import _ from 'underscore';
import moment from 'moment';
var ConsecutiveSegments = {
// Segment an array of events by scale
group(segments, scale='weeks') {
if (_.isEmpty(segments)) { retu... | // Place your library's code here
//
// If you add additional files, be sure to
// load them in order in ./wrapper.js
//
import _ from 'underscore';
import moment from 'moment';
var ConsecutiveSegments = {
// Segment an array of events by scale
group(segments, scale='weeks') {
if (_.isEmpty(segments)) { retu... |
Change artifact location to suite CircleCI | module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-mocha-istanbul");
var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output";
var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts";
grunt.initConfig({
moc... | module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-mocha-istanbul");
var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output";
var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts";
grunt.initConfig({
moc... |
Change compile CLI entry point name to urbansim_compile. | from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='urbansim',
version='0.2dev',
description='Tool for modeling metropolitan real estate markets',
author='Synthicity',
author_email='ffoti@berkeley.edu',
license='AGPL',
u... | from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='urbansim',
version='0.2dev',
description='Tool for modeling metropolitan real estate markets',
author='Synthicity',
author_email='ffoti@berkeley.edu',
license='AGPL',
u... |
Fix sort order for refreshed movies list | import {Meteor} from 'meteor/meteor';
import {autorun, toJS} from 'mobx';
import Movies from '../../api/documents/documents'
export default class Mongo2Mobx {
constructor(store) {
this.moviesSubscription = null;
this.moviesObserver = null;
let moviesDataSync = autorun(() => {
le... | import {Meteor} from 'meteor/meteor';
import {autorun, toJS} from 'mobx';
import Movies from '../../api/documents/documents'
export default class Mongo2Mobx {
constructor(store) {
this.moviesSubscription = null;
this.moviesObserver = null;
let moviesDataSync = autorun(() => {
le... |
Remove entry point for parse payload documentation | from setuptools import setup, find_packages
setup(
name='zeit.push',
version='1.21.0.dev0',
author='gocept, Zeit Online',
author_email='zon-backend@zeit.de',
url='http://www.zeit.de/',
description="Sending push notifications through various providers",
packages=find_packages('src'),
pa... | from setuptools import setup, find_packages
setup(
name='zeit.push',
version='1.21.0.dev0',
author='gocept, Zeit Online',
author_email='zon-backend@zeit.de',
url='http://www.zeit.de/',
description="Sending push notifications through various providers",
packages=find_packages('src'),
pa... |
Handle fields without validation objects attached | import Ember from 'ember';
import layout from '../templates/components/smd-form';
export default Ember.Component.extend({
// Services
toaster: Ember.inject.service('smd-toaster'),
// Attributes
layout,
tagName: 'form',
model: null,
errorMessage: 'Please correct the errors in the form',
// Computed
ch... | import Ember from 'ember';
import layout from '../templates/components/smd-form';
export default Ember.Component.extend({
// Services
toaster: Ember.inject.service('smd-toaster'),
// Attributes
layout,
tagName: 'form',
model: null,
errorMessage: 'Please correct the errors in the form',
// Computed
ch... |
Remove trailing newlines from test cases | import unittest
from BKKCrypt import BKKCrypt
import urllib.request
class TestEncodeStrings(unittest.TestCase):
def test_simple_strings(self):
self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin')
self.assertEqual(BKKCrypt('hunter2'), 'hunter2')
self.assertEqual(BKKCrypt('password'), 'pas... | import unittest
from BKKCrypt import BKKCrypt
import urllib.request
class TestEncodeStrings(unittest.TestCase):
def test_simple_strings(self):
self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin')
self.assertEqual(BKKCrypt('hunter2'), 'hunter2')
self.assertEqual(BKKCrypt('password'), 'pas... |
Allow get specs to everyone | <?php
namespace Application\Controller\Api;
use Zend\Db\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
class SpecController extends AbstractRestfulController
{
/**
* @var TableGateway
*/
private $table;
public funct... | <?php
namespace Application\Controller\Api;
use Zend\Db\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
class SpecController extends AbstractRestfulController
{
/**
* @var TableGateway
*/
private $table;
public funct... |
Make current request available to `ListingPage`s item methods
This is an awful hack. Hopefully we can find a better way.
See ICEKit ticket #154 in Assembla | from django.conf.urls import patterns, url
from django.http import Http404
from django.template.response import TemplateResponse
from fluent_pages.extensions import page_type_pool
from icekit.page_types.layout_page.admin import LayoutPageAdmin
from icekit.plugins import ICEkitFluentContentsPagePlugin
class ListingPa... | from django.conf.urls import patterns, url
from django.http import Http404
from django.template.response import TemplateResponse
from fluent_pages.extensions import page_type_pool
from icekit.page_types.layout_page.admin import LayoutPageAdmin
from icekit.plugins import ICEkitFluentContentsPagePlugin
class ListingPa... |
Update shortcut keys for new signature | $(document).ready(function() {
$(document).keyup(function(e) {
var tag = e.target.tagName.toLowerCase();
if (tag != 'input' && tag != 'textarea' && tag != 'select' && !e.ctrlKey) {
if (e.keyCode==78 || e.keyCode==77) {
$('.nav-menu-icon').trigger('click');
} e... | $(document).ready(function() {
$(document).keyup(function(e) {
var tag = e.target.tagName.toLowerCase();
if (tag != 'input' && tag != 'textarea' && tag != 'select' && !e.ctrlKey) {
if (e.keyCode==78 || e.keyCode==77) {
$('.nav-menu-icon').trigger('click');
} e... |
telemetry: Fix an import path in the Android screen recorder
Review URL: https://codereview.chromium.org/1301613004
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#343960} | # Copyright 2013 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.
import os
import subprocess
from telemetry.core import util
from telemetry.internal.platform import profiler
from telemetry.internal.backends.chrome import ... | # Copyright 2013 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.
import os
import subprocess
from telemetry.internal.platform import profiler
from telemetry.internal import util
from telemetry.internal.backends.chrome imp... |
Change default baud rate to 230400 to match cantranslator. | """A virtual serial port data source."""
from __future__ import absolute_import
import logging
from .base import BytestreamDataSource, DataSourceError
LOG = logging.getLogger(__name__)
try:
import serial
except ImportError:
LOG.debug("serial library not installed, can't use serial interface")
class Serial... | """A virtual serial port data source."""
from __future__ import absolute_import
import logging
from .base import BytestreamDataSource, DataSourceError
LOG = logging.getLogger(__name__)
try:
import serial
except ImportError:
LOG.debug("serial library not installed, can't use serial interface")
class Serial... |
Drop support for EOL Python 2.6 and 3.3 | #!/usr/bin/env python
import os
from setuptools import setup
ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR)
requirements = [
'six >= 1.4.0',
]
version = None
exec(open('dockerpycreds/version.py').read())
with open('./test-requirements.txt') as test_reqs_txt:
test_requirements = [... | #!/usr/bin/env python
import os
from setuptools import setup
ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR)
requirements = [
'six >= 1.4.0',
]
version = None
exec(open('dockerpycreds/version.py').read())
with open('./test-requirements.txt') as test_reqs_txt:
test_requirements = [... |
Add support for `skipNested` field option.
+ The `skip` option removes `N` elements from the top-level list.
This works fine for a simple list but does not work for nested lists,
e.g. for `Classification` which is a list of hierarchies.
+ Now `skipNested` wiill remove `N` items from the second-level
(nested) lis... | (function () {
'use strict';
define(
[
'lodash',
'knockout',
'util/safelyParseJson'
],
function (_, ko, parse) {
var idField = 'object_id';
return function (result, fields) {
result = ko.unwrap(result);
... | (function () {
'use strict';
define(
[
'lodash',
'knockout',
'util/safelyParseJson'
],
function (_, ko, parse) {
var idField = 'object_id';
return function (result, fields) {
result = ko.unwrap(result);
... |
Add forgotten fields to Location schema | module.exports = function(config) {
['MONGO_URL', 'MONGO_USERNAME', 'MONGO_PASSWORD'].forEach(function(envvar) {
if (config[envvar] === undefined) {
throw new Error('Mongo is missing ' + envvar);
}
});
var mongoose = require('mongoose');
var db = mongoose.connection;
var schemas = {};
var e... | module.exports = function(config) {
['MONGO_URL', 'MONGO_USERNAME', 'MONGO_PASSWORD'].forEach(function(envvar) {
if (config[envvar] === undefined) {
throw new Error('Mongo is missing ' + envvar);
}
});
var mongoose = require('mongoose');
var db = mongoose.connection;
var schemas = {};
var e... |
Add import option to nav | <nav class="navigation -white -floating">
<a class="navigation__logo" href="/"><span>DoSomething.org</span></a>
<div class="navigation__menu">
@if (Auth::user())
<ul class="navigation__primary">
<li>
<a href="/campaigns">
<strong cl... | <nav class="navigation -white -floating">
<a class="navigation__logo" href="/"><span>DoSomething.org</span></a>
<div class="navigation__menu">
@if (Auth::user())
<ul class="navigation__primary">
<li>
<a href="/campaigns">
<strong cl... |
Fix typo GYP_DEF_target_arch v GPP_DEF_target_arch
BUG=
Review URL: https://codereview.chromium.org/218623005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@260590 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2013 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.
"""A module to add gyp support to cr."""
import cr
import os
GYP_DEFINE_PREFIX = 'GYP_DEF_'
class GypPrepareOut(cr.PrepareOut):
"""A prepare action that... | # Copyright 2013 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.
"""A module to add gyp support to cr."""
import cr
import os
GYP_DEFINE_PREFIX = 'GYP_DEF_'
class GypPrepareOut(cr.PrepareOut):
"""A prepare action that... |
Add post process stage for stray mixin calls | # -*- coding: utf8 -*-
"""
.. module:: lesscpy.plib.deferred
:synopsis: Deferred mixin call.
Copyright (c)
See LICENSE for details.
.. moduleauthor:: Jóhann T. Maríusson <jtm@robot.is>
"""
from .node import Node
class Deferred(Node):
def __init__(self, mixin, args):
"""This node represents... | # -*- coding: utf8 -*-
"""
.. module:: lesscpy.plib.deferred
:synopsis: Deferred mixin call.
Copyright (c)
See LICENSE for details.
.. moduleauthor:: Jóhann T. Maríusson <jtm@robot.is>
"""
from .node import Node
class Deferred(Node):
def __init__(self, mixin, args):
"""This node represents... |
Set up login component to log the user in correctly, need to set up an alert to the user | import React, {Component} from 'react';
import loginUser from '../../utils/loginUser';
class Home extends Component {
handleSubmit(event) {
event.preventDefault();
loginUser({
email: document.getElementById('email').value,
password: document.getElementById('passwor... | import React, {Component} from 'react';
class Home extends Component {
handleSubmit(event) {
event.preventDefault();
signupUser({
email: document.getElementById('email').value,
password: document.getElementById('password').value
});
}
render() {... |
Set locale on first request | <?php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleListener implements EventSubscriberInterface
{
/**
* @var string
*/
private $d... | <?php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleListener implements EventSubscriberInterface
{
/**
* @var string
*/
private $d... |
Fix typo in variable name | ## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep... | ## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep... |
Fix internal server error at url /account/recover
Fixed a 500 error at /account/recover when trying to reset password on the
login page.
Testing Done:
Verified that the server no longer returns a 500 error when loading the form.
Reviewed at https://reviews.reviewboard.org/r/5431/ | from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
ur... | from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
ur... |
Work better with identified Ably client
This avoids warnings when using an Ably "Realtime" client instance
that uses "identified" authentication. | // TODO:
// - end-to-end test
// - extract update code, inject it as a function?
function createAblyHandler(options) {
var ably = options.ably
var operations = options.operations
var fetchOperation = options.fetchOperation
return function (operation, variables, cacheConfig, observer) {
var channelName, chan... | // TODO:
// - end-to-end test
// - extract update code, inject it as a function?
function createAblyHandler(options) {
var ably = options.ably
var operations = options.operations
var fetchOperation = options.fetchOperation
return function (operation, variables, cacheConfig, observer) {
var channelName, chan... |
Check whether user already exists before creating it. | var bcrypt = require('bcrypt'),
db = require('./db');
module.exports = {
/**
* Insert user supplied in `user` propety.
* `password` field required for bcrypt to work.
* Checks that `username` is unique.
*/
insert: function(options, callback) {
var users = db.coll('users'),
... | var bcrypt = require('bcrypt'),
db = require('./db');
module.exports = {
insert: function(options, callback) {
var users = db.coll('users'),
data = options.user,
password = options.password;
bcrypt.hash(password, 10, function(err, hash) {
if (err) {
... |
Improve example to showcase forceLogin | import React, { Component } from 'react';
import TwitterLogin from 'react-twitter-auth/lib/react-twitter-auth-component.js';
class App extends Component {
constructor() {
super();
this.onFailed = this.onFailed.bind(this);
this.onSuccess = this.onSuccess.bind(this);
}
onSuccess(response) {
resp... | import React, { Component } from 'react';
import TwitterLogin from 'react-twitter-auth/lib/react-twitter-auth-component.js';
class App extends Component {
constructor() {
super();
this.onFailed = this.onFailed.bind(this);
this.onSuccess = this.onSuccess.bind(this);
}
onSuccess(response) {
resp... |
Fix - Common list on press function | import React from 'react';
import {
View,
ScrollView,
Image,
TouchableHighlight,
Text
} from 'react-native';
import styles from './styles';
const nextImage = require('assets/next.png');
function onPress(data) {
if (data && data.functionOnPress) {
data.functionOnPress(data.url);
}
}
function List(pr... | import React from 'react';
import {
View,
ScrollView,
Image,
TouchableHighlight,
Text
} from 'react-native';
import styles from './styles';
const nextImage = require('assets/next.png');
function List(props) {
return (
<ScrollView>
{ props.content.map((data, key) => (
<TouchableHighlight
... |
Set minCloudCover to zero if it's absent from scene query | export default (app) => {
class SceneService {
constructor($resource) {
'ngInject';
this.Scene = $resource(
'/api/scenes/:id/', {
id: '@properties.id'
}, {
query: {
method: 'GET',
... | export default (app) => {
class SceneService {
constructor($resource) {
'ngInject';
this.Scene = $resource(
'/api/scenes/:id/', {
id: '@properties.id'
}, {
query: {
method: 'GET',
... |
Allow to pass in OkHttpClient from application.
+ Interceptors must now be defined within the application! | package info.metadude.java.library.brockman;
import com.squareup.moshi.Moshi;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import info.metadude.java.library.brockman.adapters.StreamAdapter;
import info.metadude.java.library.brockman.adapters.StreamTypeAdapter;
import info.metadude.j... | package info.metadude.java.library.brockman;
import com.squareup.moshi.Moshi;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import info.metadude.java.library.brockman.adapters.StreamAdapter;
import info.metadude.java.library.brockman.adapters.StreamTypeAdapter;
import info.metadude.j... |
Fix camera entity picture 401 | import Polymer from '../polymer';
import hass from '../util/home-assistant-js-instance';
const { moreInfoActions } = hass;
const UPDATE_INTERVAL = 10000; // ms
export default new Polymer({
is: 'ha-camera-card',
properties: {
stateObj: {
type: Object,
observer: 'updateCameraFeedSrc',
},
... | import Polymer from '../polymer';
import hass from '../util/home-assistant-js-instance';
const { moreInfoActions } = hass;
const UPDATE_INTERVAL = 10000; // ms
export default new Polymer({
is: 'ha-camera-card',
properties: {
stateObj: {
type: Object,
observer: 'updateCameraFeedSrc',
},
... |
Split auth test into success and failure | package core.auth;
import controllers.routes;
import static org.junit.Assert.*;
import org.junit.*;
import java.util.*;
import play.mvc.*;
import play.libs.*;
import play.test.*;
import static play.test.Helpers.*;
import com.avaje.ebean.Ebean;
import com.google.common.collect.ImmutableMap;
import java.util.List;
pub... | package core.auth;
import controllers.routes;
import static org.junit.Assert.*;
import org.junit.*;
import java.util.*;
import play.mvc.*;
import play.libs.*;
import play.test.*;
import static play.test.Helpers.*;
import com.avaje.ebean.Ebean;
import com.google.common.collect.ImmutableMap;
import java.util.List;
pub... |
11804: Use async/await for ajax request | // Handles getting info about bulk media thresholds
ELMO.Views.ExportCsvView = class ExportCsvView extends ELMO.Views.ApplicationView {
get events() {
return {
'click #response_csv_export_options_download_media': 'calculateMediaSize'
};
}
initialize(params) {
$(".calculating-info").hide();
... | // Handles getting info about bulk media thresholds
ELMO.Views.ExportCsvView = class ExportCsvView extends ELMO.Views.ApplicationView {
get events() {
return {
'click #response_csv_export_options_download_media': 'calculateMediaSize'
};
}
initialize(params) {
$(".calculating-info").hide();
... |
Fix get_current_context typo in docstring | from threading import local
_local = local()
def get_current_context(silent=False):
"""Returns the current click context. This can be used as a way to
access the current context object from anywhere. This is a more implicit
alternative to the :func:`pass_context` decorator. This function is
prima... | from threading import local
_local = local()
def get_current_context(silent=False):
"""Returns the current click context. This can be used as a way to
access the current context object from anywhere. This is a more implicit
alternative to the :func:`pass_context` decorator. This function is
prima... |
CRM-2894: Modify sync email body. Sync at once. | <?php
namespace Oro\Bundle\EmailBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Oro\Bundle\EmailBundle\Cache\EmailCacheManag... | <?php
namespace Oro\Bundle\EmailBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Oro\Bundle\EmailBundle\Cache\EmailCacheManag... |
Add delay to field focus to ensure it will work | import React, {Component} from 'react'
import Icon from 'react-fa'
import {EditorState, Editor, ContentState} from 'draft-js'
export class Input extends Component{
state = {editorState: EditorState.createWithContent(ContentState.createFromText(''))}
componentDidMount() {
if (this.props.isFirst) {
setT... | import React, {Component} from 'react'
import Icon from 'react-fa'
import {EditorState, Editor, ContentState} from 'draft-js'
export class Input extends Component{
state = {editorState: EditorState.createWithContent(ContentState.createFromText(''))}
componentDidMount() {
if (this.props.isFirst) {
// t... |
Fix retro compatibility in dynamodb model | const smash = require("../../smash.js");
const Console = require("./console.js");
const logger = smash.logger("DynamodbModel");
const DYNAMODB_TABLE_SUFFIX = "dynamodb.tableSuffix";
const UNDERSCORE = "_";
class DynamodbModel extends Console {// FIX ME remove extends console in next major, only for compatibility
c... | const smash = require("../../smash.js");
const logger = smash.logger("DynamodbModel");
const DYNAMODB_TABLE_SUFFIX = "dynamodb.tableSuffix";
const UNDERSCORE = "_";
class DynamodbModel {
constructor(table, env = null) {
if (this.constructor === DynamodbModel) {
throw new Error("DynamodbModel is... |
Add todo for no expectations defined case | package com.github.liucijus.jinsist.expectations;
import com.github.liucijus.jinsist.matchers.Arguments;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class OrderedExpectations implements Expectations {
private List<Expectation> expectations = new ArrayList<>();
p... | package com.github.liucijus.jinsist.expectations;
import com.github.liucijus.jinsist.matchers.Arguments;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class OrderedExpectations implements Expectations {
private List<Expectation> expectations = new ArrayList<>();
p... |
Fix for client mock api (specify page_context by documentation) | <?php
namespace OpsWay\ZohoBooks\Tests\Api;
use OpsWay\ZohoBooks\Api\BaseApi;
use OpsWay\ZohoBooks\Client;
use PHPUnit\Framework\TestCase;
class BaseApiTest extends TestCase
{
const ORG_ID = 1;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $client;
/**
* @var BaseApi
... | <?php
namespace OpsWay\ZohoBooks\Tests\Api;
use OpsWay\ZohoBooks\Api\BaseApi;
use OpsWay\ZohoBooks\Client;
use PHPUnit\Framework\TestCase;
class BaseApiTest extends TestCase
{
const ORG_ID = 1;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $client;
/**
* @var BaseApi
... |
Add whitespace to version spec? | # -*- coding: utf-8 -*-
from os import path
from setuptools import find_packages, setup
README_rst = path.join(path.abspath(path.dirname(__file__)), 'README.rst')
with open(README_rst, 'r') as f:
long_description = f.read()
setup(
name="pyee",
vcversioner={},
packages=find_packages(),
setup_req... | # -*- coding: utf-8 -*-
from os import path
from setuptools import find_packages, setup
README_rst = path.join(path.abspath(path.dirname(__file__)), 'README.rst')
with open(README_rst, 'r') as f:
long_description = f.read()
setup(
name="pyee",
vcversioner={},
packages=find_packages(),
setup_req... |
Add a MAPPING table to remove duplicated loop logic | import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def send(self, data):
sent = 0
for alert in data['alerts']:
for label, klass in... | import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
def send(self, data):
sent = 0
for alert in data['alerts']:
if 'project' in alert['labels']:
logger.debug('Checking for projects')
... |
Remove hash & path on dev webpack css module names
This will make bok-choy testing easier. | /* eslint-env node */
'use strict';
var Merge = require('webpack-merge');
var path = require('path');
var webpack = require('webpack');
var commonConfig = require('./webpack.common.config.js');
module.exports = Merge.smart(commonConfig, {
output: {
filename: '[name].js'
},
devtool: 'source-map',... | /* eslint-env node */
'use strict';
var Merge = require('webpack-merge');
var path = require('path');
var webpack = require('webpack');
var commonConfig = require('./webpack.common.config.js');
module.exports = Merge.smart(commonConfig, {
output: {
filename: '[name].js'
},
devtool: 'source-map',... |
Fix wrong phpdoc type name | <?php
/**
* We made this code.
* By pH7 (Pierre-Henry SORIA).
*/
namespace PFBC\Validation;
use PH7\ExistsCoreModel;
use PH7\Framework\Security\Ban\Ban;
class BankAccount extends \PFBC\Validation
{
protected $sTable;
/**
* Constructor of class.
*
* @param string $sTable
*/
public... | <?php
/**
* We made this code.
* By pH7 (Pierre-Henry SORIA).
*/
namespace PFBC\Validation;
use PH7\ExistsCoreModel;
use PH7\Framework\Security\Ban\Ban;
class BankAccount extends \PFBC\Validation
{
protected $sTable;
/**
* Constructor of class.
*
* @param $sTable Default 'Affiliates'
... |
:art: Fix mixins-before-declaration rule to work with latest gonzales | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'mixins-before-declarations',
'defaults': {
'exclude': [
'breakpoint',
'mq'
]
},
'detect': function (ast, parser) {
var result = [],
error;
ast.traverseByType('include', function (node, i, parent... | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'mixins-before-declarations',
'defaults': {
'exclude': [
'breakpoint',
'mq'
]
},
'detect': function (ast, parser) {
var result = [],
error;
ast.traverseByType('include', function (node, i, parent... |
Improve regexp to match result from babel
Babel does convert commonjs require calls from
var bar = require('bar');
bar.foo('test');
into
_bar2.default.foo('test')
therefore this regexp need to consider _ and 2.default as optional | <?php
class Kwf_Assets_Util_Trl
{
//returns replacement used for js trl strings
//used by Kwf_Assets_Dependency_File_Js and Kwf_Assets_CommonJs_Underscore_TemplateDependency
public static function getJsReplacement($trlElement)
{
$b = $trlElement['before'];
$fn = substr($b, 0, strpos($b, ... | <?php
class Kwf_Assets_Util_Trl
{
//returns replacement used for js trl strings
//used by Kwf_Assets_Dependency_File_Js and Kwf_Assets_CommonJs_Underscore_TemplateDependency
public static function getJsReplacement($trlElement)
{
$b = $trlElement['before'];
$fn = substr($b, 0, strpos($b, ... |
Fix no labeled statement error | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import TableRow from './TableRow/index.js'
import Button from '../../Components/Button/index.js'
export default class Table extends Component {
static propTypes = {
tableName: PropTypes.string,
columnTypes: PropTypes.object.isRequir... | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import TableRow from './TableRow/index.js'
import Button from '../../Components/Button/index.js'
export default class Table extends Component {
static propTypes = {
tableName: PropTypes.string,
columnTypes: PropTypes.object.isRequir... |
Add maxlengthIndicator to text area fields | import Ember from 'ember';
const formObject = Ember.Object.create({
"schema": {
"type": "object",
"properties": {
"activity": {
"type": "string",
"title": "What were you doing yesterday at 10am/7pm?",
"maxLength": 75
},
... | import Ember from 'ember';
const formObject = {
"schema": {
"type": "object",
"properties": {
"activity": {
"type": "string",
"title": "What were you doing yesterday at 10am/7pm?",
"maxLength": 75
},
"location": {
... |
Upgrade for improved sequencing mechanism | 'use strict';
module.exports = {
requestProvider: {
parent: 'danf:dependencyInjection.contextProvider',
properties: {
interface: 'danf:http.request'
}
},
responseProvider: {
parent: 'danf:dependencyInjection.contextProvider',
properties: {
int... | 'use strict';
module.exports = {
requestProvider: {
parent: 'danf:dependencyInjection.contextProvider',
properties: {
interface: 'danf:http.request'
}
},
responseProvider: {
parent: 'danf:dependencyInjection.contextProvider',
properties: {
int... |
Clean up the definition loader | <?php namespace Watson\Industrie;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class DefinitionLoader {
/**
* Locations to search for model definitions.
*
* @var array
*/
protected $directories = [
'app/spec/factories',
'app/tests/factories',
'spe... | <?php namespace Watson\Industrie;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class DefinitionLoader {
/**
* Locations to search for model definitions.
*
* @var array
*/
protected $directories = [
'app/spec/factories',
'app/tests/factories',
'spe... |
Fix missing cls variable and add some docstring info | # -*- coding: utf-8 -*-
# Import Python Libs
import shutil
import subprocess
import tempfile
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
class GitModuleTest(integration.ModuleCase):
'''
Integration tests for ... | # -*- coding: utf-8 -*-
import shutil
import subprocess
import tempfile
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
class GitModuleTest(integration.ModuleCase):
@classmethod
def setUpClass(cls):
from ... |
Fix team permissions backend not pulling out manager_permissions
Something like
request.user.has_perm('reviews.can_manage_%s' % proposal.kind.section.slug)
Will aways return false as the backend does a lookup of team membership
(member or manager) but only grabs the 'permissions' and not the
'manager_permissions' fie... | from django.db.models import Q
from .models import Team
class TeamPermissionsBackend(object):
def authenticate(self, username=None, password=None):
return None
def get_team_permissions(self, user_obj, obj=None):
"""
Returns a set of permission strings that this user has through his/... | from django.db.models import Q
from .models import Team
class TeamPermissionsBackend(object):
def authenticate(self, username=None, password=None):
return None
def get_team_permissions(self, user_obj, obj=None):
"""
Returns a set of permission strings that this user has through his/... |
Fix broken locale copying mechanism | const fs = require('fs-extra');
const path = require('path');
const { createFilePath } = require('gatsby-source-filesystem');
exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
const { createNodeField } = boundActionCreators;
if (node.internal.type === 'MarkdownRemark') {
const slug = create... | const fs = require('fs-extra');
const path = require('path');
const { createFilePath } = require('gatsby-source-filesystem');
exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
const { createNodeField } = boundActionCreators;
if (node.internal.type === 'MarkdownRemark') {
const slug = create... |
Restructure major projects for spring evals 👷 | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... |
Set up loggers after the configuration file is loaded | # coding: utf-8
###################################################################
# Copyright (c) 2016-2020 European Synchrotron Radiation Facility #
# #
# Author: Marius Retegan #
# ... | # coding: utf-8
###################################################################
# Copyright (c) 2016-2020 European Synchrotron Radiation Facility #
# #
# Author: Marius Retegan #
# ... |
Convert snapshot date to format complying with ISO 8601 | var PHRAGILE = PHRAGILE || {};
(function (PHRAGILE) {
/**
* Same as Graph but also renders graph areas under the line.
* ProgressGraph will be limited to dates <= today.
* @param {Object[]} data
* @param {string} cssID - Its CSS identifier (used as class or id)
* @param {string} label - De... | var PHRAGILE = PHRAGILE || {};
(function (PHRAGILE) {
/**
* Same as Graph but also renders graph areas under the line.
* ProgressGraph will be limited to dates <= today.
* @param {Object[]} data
* @param {string} cssID - Its CSS identifier (used as class or id)
* @param {string} label - De... |
Add new engagement to household only if one not created | export default (state = [], action) => {
switch (action.type) {
case "FETCH_HOUSEHOLDS_SUCCESS": {
return action.households
}
case "ADD_HOUSEHOLD_SUCCESS": {
return [...state, action.household]
}
case "CREATE_NOTE_SUCCESS": {
return state.map(
h =>
h.id === pars... | export default (state = [], action) => {
switch (action.type) {
case "FETCH_HOUSEHOLDS_SUCCESS": {
return action.households
}
case "ADD_HOUSEHOLD_SUCCESS": {
return [...state, action.household]
}
case "CREATE_NOTE_SUCCESS": {
return state.map(
h =>
h.id === pars... |
Use TextReporter when in cli mode. | <?php
require_once('simpletest/unit_tester.php');
require_once('simpletest/reporter.php');
require_once(dirname(__FILE__).'/acceptance_test.php');
require_once(dirname(__FILE__).'/annotation_test.php');
require_once(dirname(__FILE__).'/constrained_annotation_test.php');
require_once(... | <?php
require_once('simpletest/unit_tester.php');
require_once('simpletest/reporter.php');
require_once(dirname(__FILE__).'/acceptance_test.php');
require_once(dirname(__FILE__).'/annotation_test.php');
require_once(dirname(__FILE__).'/constrained_annotation_test.php');
require_once(... |
Set default database migration setting to 'safe' | /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#/documentation/concepts/ORM
*/
module.exports.models = {
/*******************************... | /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#/documentation/concepts/ORM
*/
module.exports.models = {
/*******************************... |
Switch to getting the API key from the URL instead of a config file.
Allows other people to get their anki calendar if they want. |
from __future__ import absolute_import
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
class WaniKaniView(View):
def get(self, request, **kwargs):
client = WaniKani(kwargs['api_key... | from __future__ import absolute_import
import os
import logging
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani')
with open(CONFI... |
Fix handling of errors that are not the Error | var domain = require('domain');
var _ = require('lodash');
module.exports = function (app, templateVarService, appUtil) {
return {
setup: function () {
app.use(function (req, res) {
templateVarService.setupLocals(req, res);
res.status(404).render('not-found');
... | var domain = require('domain');
module.exports = function (app, templateVarService, appUtil) {
return {
setup: function () {
app.use(function (req, res) {
templateVarService.setupLocals(req, res);
res.status(404).render('not-found');
});
a... |
Trim pasted URL before submitting.
Closes #14 | function(context) {
var app = $$(this).app;
var url = $("#pasted_url").val();
if (url.length > 0) {
idPos = url.indexOf("id=");
if (idPos > -1) {
url = url.substr(idPos + 3);
}
lastSlash = url.lastIndexOf("/");
if (lastSlash > -1) {
url = url.substr(lastSlash + 1);
}
ampPos... | function(context) {
var app = $$(this).app;
var url = $("#pasted_url").val();
if (url.length > 0) {
idPos = url.indexOf("id=");
if (idPos > -1) {
url = url.substr(idPos + 3);
}
lastSlash = url.lastIndexOf("/");
if (lastSlash > -1) {
url = url.substr(lastSlash + 1);
}
ampPos... |
Tweak for when SQS message is missing the eTag from a bucket notification. | from boto.sqs.message import Message
import json
from s3_notification_info import S3NotificationInfo
class S3SQSMessage(Message):
def __init__(self, queue=None, body='', xml_attrs=None):
Message.__init__(self, queue, body)
self.payload = None
self.notification_type = 'S3Info'
def even... | from boto.sqs.message import Message
import json
from s3_notification_info import S3NotificationInfo
class S3SQSMessage(Message):
def __init__(self, queue=None, body='', xml_attrs=None):
Message.__init__(self, queue, body)
self.payload = None
self.notification_type = 'S3Info'
def even... |
Use HTTPS URLs for MaxMind resources | from ooni.settings import config
from ooni.utils import unzip, gunzip
from ooni.deckgen.processors import citizenlab_test_lists
from ooni.deckgen.processors import namebench_dns_servers
config.read_config_file()
__version__ = "0.0.1"
inputs = {
"namebench-dns-servers.csv": {
"url": "https://namebench.go... | from ooni.settings import config
from ooni.utils import unzip, gunzip
from ooni.deckgen.processors import citizenlab_test_lists
from ooni.deckgen.processors import namebench_dns_servers
config.read_config_file()
__version__ = "0.0.1"
inputs = {
"namebench-dns-servers.csv": {
"url": "https://namebench.go... |
Add license to the packaging | try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='fabtools',
version='0.1',
description='Tools for writing awesome Fabric files',
author='Ronan Amicel',
a... | try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='fabtools',
version='0.1',
description='Tools for writing awesome Fabric files',
author='Ronan Amicel',
a... |
Use the sync version of unlink to try to resolve spurious Travis failures
Travis can fail random tests with:
Error: ENOENT: no such file or directory, rename 'spec-db/users.db~' -> 'spec-db/users.db'
at Error (native)
This isn't due to double `unlink()` calls (else the operation would be "unlink"
and not "rena... | /*
* Helper class for cleaning nedb state
*/
"use strict";
var Promise = require("bluebird");
var fs = require("fs");
/**
* Reset the database, wiping all data.
* @param {String} databaseUri : The database URI to wipe all data from.
* @return {Promise} Which is resolved when the database has been cleared.
*/
mod... | /*
* Helper class for cleaning nedb state
*/
"use strict";
var Promise = require("bluebird");
var fs = require("fs");
/**
* Reset the database, wiping all data.
* @param {String} databaseUri : The database URI to wipe all data from.
* @return {Promise} Which is resolved when the database has been cleared.
*/
mod... |
Update to newer Asserts to eliminate deprecation warning | package io.hawt.keystore;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
/**
*
*/
public class KeystoreServiceTest {
@Test
public void test() throws IOException {
KeystoreService service = new KeystoreService();
SecurityProviderDTO info = service.get... | package io.hawt.keystore;
import org.junit.Test;
import java.io.IOException;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
*
*/
public class KeystoreServiceTest {
@Test
public void test() throws IOException {
KeystoreService service = ne... |
Fix multiple bugs in download block | <div class="felix-item-title felix-item-title felix-item-title-generic">
<h3>Download the latest <i>Felix</i></h3>
</div>
<br>
<?php
$link = new ArchiveLink();
$issue = $link->getLatestForPublication(1);
if($issue):
try {
// prime issue
$issue->getThumbnailURL();... | <div class="felix-item-title felix-item-title felix-item-title-generic">
<h3>Download the latest <i>Felix</i></h3>
</div>
<br>
<?php
$link = new ArchiveLink();
$issue = $link->getLatestForPublication(1);
if($issue):
try {
// prime issue
$issue->getThumbnailURL();... |
Debug print each health check | # -*- coding: utf-8 -*-
import requests
class Healthcheck:
def __init__(self):
pass
def _result(self, site, health, response=None, message=None):
result = {
"name": site["name"],
"health": health
}
if message:
result["message"] = message
... | # -*- coding: utf-8 -*-
import requests
class Healthcheck:
def __init__(self):
pass
def _result(self, site, health, response=None, message=None):
result = {
"name": site["name"],
"health": health
}
if message:
result["message"] = message
... |
Call CourseInstructorPanel only when having instructors | var CourseCardContentPanel = {
render: function (c_section, fetched_eval) {
var eval_data = (fetched_eval? WSData.iasystem_data(): null);
var index = c_section.index;
// Determine if we have valid eval data for the section
var has_valid_eval = (eval_data && eval_data.secti... | var CourseCardContentPanel = {
render: function (c_section, fetched_eval) {
var eval_data = (fetched_eval? WSData.iasystem_data(): null);
var index = c_section.index;
// Determine if we have valid eval data for the section
var has_valid_eval = (eval_data && eval_data.secti... |
Fix base url for swagger | <?php
namespace OParl\Website\Api\Controllers;
use function Swagger\scan;
/**
* @SWG\Swagger(
* schemes={"https"},
* host=SWAGGER_API_HOST,
* basePath="/api/",
* @SWG\Info(
* title="OParl Developer Platform API",
* description="Meta information concerning the OParl ecosystem",
... | <?php
namespace OParl\Website\Api\Controllers;
use function Swagger\scan;
/**
* @SWG\Swagger(
* schemes={"https"},
* host="dev.oparl.org",
* basePath="/api/",
* @SWG\Info(
* title="OParl Developer Platform API",
* description="Meta information concerning the OParl ecosystem",
... |
Use same versions as requirements.pip to prevent unexpected upgrades of dependencies | # -*- coding: utf-8 -*-
"""
pyxform - Python library that converts XLSForms to XForms.
"""
from setuptools import find_packages, setup
REQUIRES = [
"xlrd==1.2.0",
"unicodecsv==0.14.1",
"formencode==1.3.1",
"unittest2==1.1.0",
'functools32==3.2.3.post2 ; python_version < "3.2"',
]
setup(
name="... | # -*- coding: utf-8 -*-
"""
pyxform - Python library that converts XLSForms to XForms.
"""
from setuptools import find_packages, setup
REQUIRES = [
"xlrd>=1.1.0",
"unicodecsv>=0.14.1",
"formencode",
"unittest2",
'functools32==3.2.3.post2 ; python_version < "3.2"',
]
setup(
name="pyxform",
... |
Add pytest to surveymonkey dependencies | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
requirements = [
'furl==0.5.6',
'six==1.10.0',
'pytest==3.0.3'
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='sur... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
requirements = [
'furl==0.5.6',
'six==1.10.0'
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='surveymonkey',
versi... |
Remove through field check, as we now check the entire through chain | <?php
namespace AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations;
class AssociationStubMonomorphic extends AssociationStubBase
{
/**
* @param \AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubBase $otherStub
*
* @return bool
*/
public function isCompa... | <?php
namespace AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations;
class AssociationStubMonomorphic extends AssociationStubBase
{
/**
* @param \AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubBase $otherStub
*
* @return bool
*/
public function isCompa... |
Disable Postgres cache by default | /**
* Base class for Postgres repositories
* @module arpen/repositories/postgres
*/
const path = require('path');
const BaseRepository = require('./base');
/**
* Repository base class
*/
class PostgresRepository extends BaseRepository {
/**
* Create repository
* @param {App} app ... | /**
* Base class for Postgres repositories
* @module arpen/repositories/postgres
*/
const path = require('path');
const BaseRepository = require('./base');
/**
* Repository base class
*/
class PostgresRepository extends BaseRepository {
/**
* Create repository
* @param {App} app ... |
Improve selection of the Recipe | package com.sb.elsinore.html;
import com.sb.elsinore.BrewServer;
import org.rendersnake.HtmlCanvas;
import org.rendersnake.Renderable;
import java.io.IOException;
import java.util.ArrayList;
import static org.rendersnake.HtmlAttributesFactory.id;
import static org.rendersnake.HtmlAttributesFactory.name;
import stati... | package com.sb.elsinore.html;
import com.sb.elsinore.BrewServer;
import org.rendersnake.HtmlCanvas;
import org.rendersnake.Renderable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import static org.rendersnake.HtmlAttributesFactory.id;
import static org.rendersnake.HtmlAttributesFact... |
Handle non-existent files in the database. | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... |
Remove active flag from all options before setting current.
Rapidly changing presets could result in multiple options selected
simultaneously. | function updateColor(input) {
var value = input.val();
console.log("Updating to " + value + ".\n");
input.data('updating', true);
$.post("/pixel/" + input.attr('id'), { color: value, immediate: "false" })
.always(function () {
input.data('updating', false);
var next_value = input.... | function updateColor(input) {
var value = input.val();
console.log("Updating to " + value + ".\n");
input.data('updating', true);
$.post("/pixel/" + input.attr('id'), { color: value, immediate: "false" })
.always(function () {
input.data('updating', false);
var next_value = input.... |
Add all versions of conversion doctests | import pytest
def pytest_collection_modifyitems(config, items):
try:
import pandas
except ImportError:
pandas = None
try:
import cesium
except ImportError:
cesium = None
if pandas is None:
skip_marker = pytest.mark.skip(reason="pandas not installed!")
... | import pytest
def pytest_collection_modifyitems(config, items):
try:
import pandas
except ImportError:
pandas = None
try:
import cesium
except ImportError:
cesium = None
if pandas is None:
skip_marker = pytest.mark.skip(reason="pandas not installed!")
... |
Define the attributes that aren't mass assignable | <?php
namespace App\Models\Items;
use Illuminate\Database\Eloquent\Model;
class Vehicle extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'vehicles';
/**
* The primary key column.
*
* @var string
*/
protected $pri... | <?php
namespace App\Models\Items;
use Illuminate\Database\Eloquent\Model;
class Vehicle extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'vehicles';
/**
* The primary key column.
*
* @var string
*/
protected $pri... |
Fix simple typo: occured -> occurred | # -*- coding: utf-8 -*-
import os
import sys
from contextlib import contextmanager
from click._compat import isatty
WIN = sys.platform.startswith("win")
env = os.environ
@contextmanager
def raw_mode():
"""
Enables terminal raw mode during the context.
Note: Currently noop for Windows systems.
Usag... | # -*- coding: utf-8 -*-
import os
import sys
from contextlib import contextmanager
from click._compat import isatty
WIN = sys.platform.startswith("win")
env = os.environ
@contextmanager
def raw_mode():
"""
Enables terminal raw mode during the context.
Note: Currently noop for Windows systems.
Usag... |
Include exempt groups in search | import { inject as service } from '@ember/service';
import Controller from '@ember/controller';
import { task, timeout } from 'ember-concurrency';
export default Controller.extend({
flashMessages: service(),
searchGroup: task(function* (term){
yield timeout(600);
let kindOptions = {
'Chorus': 32,
... | import { inject as service } from '@ember/service';
import Controller from '@ember/controller';
import { task, timeout } from 'ember-concurrency';
export default Controller.extend({
flashMessages: service(),
searchGroup: task(function* (term){
yield timeout(600);
let kindOptions = {
'Chorus': 32,
... |
HBO: Add options argument to get() | class Hbo():
def handle(self, url):
return "hbo.com" in url
def get(self, options, url):
parse = urlparse(url)
try:
other = parse[5]
except KeyError:
log.error("Something wrong with that url")
sys.exit(2)
match = re.search("^/(.*).html... | class Hbo():
def handle(self, url):
return "hbo.com" in url
def get(self, url):
parse = urlparse(url)
try:
other = parse[5]
except KeyError:
log.error("Something wrong with that url")
sys.exit(2)
match = re.search("^/(.*).html", other)... |
Increase results to 25 per page to make page look nicer | from django.views.generic import ListView, DetailView
from .forms import OrganisationSearchForm
from .models import Organisation
from .search_indexes import OrganisationIndex
from .search_utils import SearchPaginator
class OrganisationSearchView(ListView):
template_name = 'justizgelder/search.html'
paginate_... | from django.views.generic import ListView, DetailView
from .forms import OrganisationSearchForm
from .models import Organisation
from .search_indexes import OrganisationIndex
from .search_utils import SearchPaginator
class OrganisationSearchView(ListView):
template_name = 'justizgelder/search.html'
paginate_... |
Add created field to DataPoint model | import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
created = models.DateTimeField(aut... | import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_le... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.