text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Add NetBandwith & CPUUsage in Container struct | package dockerguard
type DockerInfo struct {
// Infos from docker api /version
APIVersion string `json:"ApiVersion"`
Arch string `json:"Arch"`
Experimental bool `json:"Experimental"`
GitCommit string `json:"GitCommit"`
GoVersion string `json:"GoVersion"`
KernelVersion string `json:"Kernel... | package dockerguard
type DockerInfo struct {
// Infos from docker api /version
APIVersion string `json:"ApiVersion"`
Arch string `json:"Arch"`
Experimental bool `json:"Experimental"`
GitCommit string `json:"GitCommit"`
GoVersion string `json:"GoVersion"`
KernelVersion string `json:"Kernel... |
Clear command default answer changed to no | <?php
/*
* This file is part of the Subway package.
*
* (c) Eymen Gunay <eymen@egunay.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Subway\Command;
use Subway\Factory;
use Symfony\Component\Console\Input\InputIn... | <?php
/*
* This file is part of the Subway package.
*
* (c) Eymen Gunay <eymen@egunay.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Subway\Command;
use Subway\Factory;
use Symfony\Component\Console\Input\InputIn... |
Add stopwatch as auth protected route | import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Switch
} from 'react-router-dom';
import MonthDetail from './components/pages/History/MonthDetail';
import HomePage from './components/pages/Home';
import SignupPage from './components/pages/Signup';
import LoginPage from '.... | import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Switch
} from 'react-router-dom';
import MonthDetail from './components/pages/History/MonthDetail';
import HomePage from './components/pages/Home';
import SignupPage from './components/pages/Signup';
import LoginPage from '.... |
Print out errors to log. | #!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError(RuntimeError):
def _... | #!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError(RuntimeError):
def _... |
Fix try-except-finally statement for python 2.4 support | # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.l... | # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.l... |
CRM-1648: Adjust EmailType form type to use email templates selector
- update unit tests | <?php
namespace Oro\Bundle\EmailBundle\Tests\Unit\Form\Model;
use Oro\Bundle\EmailBundle\Entity\EmailTemplate;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Oro\Bundle\EmailBundle\Form\Model\Email;
class EmailTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider propertiesDataProvider
... | <?php
namespace Oro\Bundle\EmailBundle\Tests\Unit\Form\Model;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Oro\Bundle\EmailBundle\Form\Model\Email;
class EmailTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider propertiesDataProvider
* @param string $property
* @param mixed... |
Fix LIST command crashing (again) on certain input | from twisted.words.protocols import irc
from txircd.modbase import Mode
class SecretMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "NAMES":
return data
remove = []
for chan in data["targetchan"]:
if "s" in chan.mode and chan.name not in user.channe... | from twisted.words.protocols import irc
from txircd.modbase import Mode
class SecretMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "NAMES":
return data
remove = []
for chan in data["targetchan"]:
if "s" in chan.mode and chan.name not in user.channe... |
Fix directory creation by view assistant creator | <?php
namespace Knp\RadBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
class AssistantController extends Controller
{
public function missingViewAction($viewName, $viewParams)
{
$viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);
$viewBody = $this->ren... | <?php
namespace Knp\RadBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
class AssistantController extends Controller
{
public function missingViewAction($viewName, $viewParams)
{
$viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);
$viewBody = $this->ren... |
Fix of loading chosen options on Lead timeline filter without need to refresh the page | <?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
?>
<!-- filter form -->
<form action="" class="panel" id="timeline-filters">
<div class="fo... | <?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
?>
<!-- filter form -->
<form action="" class="panel" id="timeline-filters">
<div class="fo... |
Add valueAttr to the application module | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
option... | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
option... |
Mark runserver as a plumbing command | """Command-line utilities for HTTP service subsystem."""
import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(BaseCommand):
"""
Run a debug server.
**This is for debug, local use only, not production.**
Th... | """Command-line utilities for HTTP service subsystem."""
import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(BaseCommand):
"""
Run a debug server.
**This is for debug, local use only, not production.**
Th... |
Change the constraints for dateTime class | package seedu.emeraldo.model.task;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
/**
* Represents a Task's date and time in Emeraldo.
* Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)}
*/
public class DateTime {
public static final String MESSAGE_ADDRESS_C... | package seedu.emeraldo.model.task;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
/**
* Represents a Task's date and time in Emeraldo.
* Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)}
*/
public class DateTime {
public static final String MESSAGE_ADDRESS_C... |
Update jwtauth service provider @ fix namespace error. | <?php namespace JwtAuth;
use ReflectionClass;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
class JwtAuthServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
... | <?php namespace JwtAuth;
use Illuminate\Support\ServiceProvider;
class JwtAuthServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @retur... |
Remove any leading '*.' that may be present in the suffix list. | package org.bouncycastle.test.est.examples;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
class SuffixList
{
static Set<String> loadSuffixes(String file)
... | package org.bouncycastle.test.est.examples;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
class SuffixList
{
static Set<String> loadSuffixes(String file)
... |
Change module.exports to export default | import { isFunction } from 'lodash';
import { setHeader } from 'focus-core/application';
const cartridgeBehaviour = {
/**
* Updates the cartridge using the cartridgeConfiguration.
*/
_registerCartridge(props = this.props) {
const cartridgeConfiguration = this.cartridgeConfiguration || props.... | import { isFunction } from 'lodash';
import { setHeader } from 'focus-core/application';
module.exports = {
/**
* Updates the cartridge using the cartridgeConfiguration.
*/
_registerCartridge(props = this.props) {
const cartridgeConfiguration = this.cartridgeConfiguration || props.cartridgeC... |
Make sure `multi` returns a promise | 'use strict';
var Pipeline = require('./pipeline');
var utils = require('./utils');
exports.addTransactionSupport = function (redis) {
redis.pipeline = function () {
var pipeline = new Pipeline(this);
return pipeline;
};
var multi = redis.multi;
redis.multi = function (options) {
if (options && o... | 'use strict';
var Pipeline = require('./pipeline');
var utils = require('./utils');
exports.addTransactionSupport = function (redis) {
redis.pipeline = function () {
var pipeline = new Pipeline(this);
return pipeline;
};
var multi = redis.multi;
redis.multi = function (options) {
if (options && o... |
Fix log for grunt tasks | (function() {
'use strict';
var yeoman = require('yeoman-generator'),
scaffold = {};
module.exports = yeoman.generators.Base.extend({
constructor: function() {
yeoman.generators.Base.apply(this, arguments);
this.option('skip-welcome');
this.argument(... | (function() {
'use strict';
var yeoman = require('yeoman-generator'),
scaffold = {};
module.exports = yeoman.generators.Base.extend({
constructor: function() {
yeoman.generators.Base.apply(this, arguments);
this.option('skip-welcome');
this.argument(... |
Return instead of throw the exception | <?php
declare(strict_types = 1);
namespace Speicher210\Estimote;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use JMS\Serializer\SerializerInterface;
use Speicher210\Estimote\Exception\ApiException;
use Speicher210\Estimote\Exception\ApiKeyInvalidException;
/**
* Abstract resource.
*/
abstract... | <?php
namespace Speicher210\Estimote;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use JMS\Serializer\SerializerInterface;
use Speicher210\Estimote\Exception\ApiException;
use Speicher210\Estimote\Exception\ApiKeyInvalidException;
use Speicher210\Estimote\Model\Beacon as BeaconModel;
/**
* Abstr... |
Use the `web` middleware group by default in the web config | <?php
return [
/*
|--------------------------------------------------------------------------
| User Model
|--------------------------------------------------------------------------
|
| Set your eloquent model for your users.
|
*/
'user' => App\User::class,
/*
|---------... | <?php
return [
/*
|--------------------------------------------------------------------------
| User Model
|--------------------------------------------------------------------------
|
| Set your eloquent model for your users.
|
*/
'user' => App\User::class,
/*
|---------... |
Revise elif to if due to continue | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def valid_parentheses(s):
"""Balance parentheses in a string."""
open_close_d = {
'(': ')',
'[': ']',
'{': '}'
}
# Use stack to collect open parentheses.
stack = []... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def valid_parentheses(s):
"""Balance parentheses in a string."""
open_close_d = {
'(': ')',
'[': ']',
'{': '}'
}
# Use stack to collect open parentheses.
stack = []... |
Allow shared container to store empty, but not null values. | <?php
/**
*
*/
namespace Mvc5\Resolver;
use RuntimeException;
trait Initializer
{
/**
* @var array
*/
protected $pending = [];
/**
* @param string $name
* @param callable $callback
* @param array $args
* @return callable|null|object
*/
protected abstract function... | <?php
/**
*
*/
namespace Mvc5\Resolver;
use RuntimeException;
trait Initializer
{
/**
* @var array
*/
protected $pending = [];
/**
* @param string $name
* @param callable $callback
* @param array $args
* @return callable|null|object
*/
protected abstract function... |
Fix condition for when keys for self can be generated | import { ADDRESS_STATUS, ADDRESS_TYPE, MEMBER_PRIVATE, RECEIVE_ADDRESS } from 'proton-shared/lib/constants';
const { TYPE_ORIGINAL, TYPE_CUSTOM_DOMAIN, TYPE_PREMIUM } = ADDRESS_TYPE;
const { READABLE } = MEMBER_PRIVATE;
export const getStatus = ({ address: { Status, Receive, DomainID, HasKeys }, i }) => {
const i... | import { ADDRESS_STATUS, ADDRESS_TYPE, MEMBER_PRIVATE, RECEIVE_ADDRESS } from 'proton-shared/lib/constants';
const { TYPE_ORIGINAL, TYPE_CUSTOM_DOMAIN, TYPE_PREMIUM } = ADDRESS_TYPE;
const { READABLE, UNREADABLE } = MEMBER_PRIVATE;
export const getStatus = ({ address: { Status, Receive, DomainID, HasKeys }, i }) => {... |
Fix typo in parameter name. | <?php
namespace Slim\Middleware;
/**
* HTTP Basic Authentication
*
* Provides HTTP Basic Authentication on given routes
*
* @package Slim
* @author Mika Tuupola <tuupola@appelsiini.net>
*/
class HttpBasicAuth extends \Slim\Middleware {
public $options;
public function __construct($options = nu... | <?php
namespace Slim\Middleware;
/**
* HTTP Basic Authentication
*
* Provides HTTP Basic Authentication on given routes
*
* @package Slim
* @author Mika Tuupola <tuupola@appelsiini.net>
*/
class HttpBasicAuth extends \Slim\Middleware {
public $options;
public function __construct($options = nu... |
Change username to osf uid | from .apps import OsfOauth2AdapterConfig
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class OSFAccount(ProviderAccount):
def to_str(self):
# default ... reserved word... | from .apps import OsfOauth2AdapterConfig
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class OSFAccount(ProviderAccount):
def to_str(self):
# default ... reserved word... |
Revert "Swallow proxy exception from requests"
This reverts commit 8d9ccbb2bbde7c2f8dbe60b90f730d87b924d86e. | """
Some code to manage the Amazon Certificate Service.
"""
import logging
import boto3
import botocore
class DiscoACM(object):
"""
A class to manage the Amazon Certificate Service
"""
def __init__(self, connection=None):
self._acm = connection
@property
def acm(self):
"""
... | """
Some code to manage the Amazon Certificate Service.
"""
import logging
import boto3
import botocore
class DiscoACM(object):
"""
A class to manage the Amazon Certificate Service
"""
def __init__(self, connection=None):
self._acm = connection
@property
def acm(self):
"""
... |
Convert time to JS format
JS uses ms instead of s provided by the API. | var async = require('async');
var pingdom = require('./pingdom');
function checks(config, limit, done) {
var api = pingdom(config);
api.checks(function(err, checks) {
if(err) return console.error(err);
async.map(checks, function(check, cb) {
api.results(function(err, results) {
... | var async = require('async');
var pingdom = require('./pingdom');
function checks(config, limit, done) {
var api = pingdom(config);
api.checks(function(err, checks) {
if(err) return console.error(err);
async.map(checks, function(check, cb) {
api.results(function(err, results) {
... |
Tweak layout of export component | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
const exampleQuery = (slug) => `query {
organization(slug: "${slug}") {
auditEvents(first: 500) {
edges {
node {
type
occurredAt
actor {
name
}... | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
const exampleQuery = (slug) => `query {
organization(slug: "${slug}") {
auditEvents(first: 500) {
edges {
node {
type
occurredAt
actor {
name
}... |
Fix SVG load with spaces in filename | var server = require('webserver').create(),
fs = require('fs');
var serverUrl = '127.0.0.1:8888';
var workingDirectory = fs.workingDirectory.replace(/\//g, fs.separator);
function create() {
var serverCreated = server.listen(serverUrl, function (request, response) {
var cleanedUrl = decodeURIComponent... | var server = require('webserver').create(),
fs = require('fs');
var serverUrl = '127.0.0.1:8888';
var workingDirectory = fs.workingDirectory.replace(/\//g, fs.separator);
function create() {
var serverCreated = server.listen(serverUrl, function (request, response) {
var cleanedUrl = request.url
... |
Make the SSH configuration more resilient.
If you don't have certain values specified in your ~/.ssh/config, use
the defaults instead of erroring out. | # -*- coding: utf-8 -*-
__author__ = 'John Moylan'
import sys
from paramiko import SSHClient, SSHConfig, AutoAddPolicy
from pyvarnish.settings import SSH_CONFIG
class Varnish_admin():
def __init__(self, server=''):
self.server = server
self.conf = {
'hostname': server,
... | # -*- coding: utf-8 -*-
__author__ = 'John Moylan'
import sys
from paramiko import SSHClient, SSHConfig, AutoAddPolicy
from pyvarnish.settings import SSH_CONFIG
class Varnish_admin():
def __init__(self, server=''):
self.server = server
self.conf = self.config()
def config(self):
s... |
Allow MarkdownDirectory events to specify author. | from been.core import DirectorySource, source_registry
from hashlib import sha1
import re
import unicodedata
import time
import markdown
# slugify from Django source (BSD license)
def slugify(value):
value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-... | from been.core import DirectorySource, source_registry
from hashlib import sha1
import re
import unicodedata
import time
import markdown
# slugify from Django source (BSD license)
def slugify(value):
value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-... |
Add response logging for upload of image | package xyz.igorgee.shapejs;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okht... | package xyz.igorgee.shapejs;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public clas... |
Allow specific migrations to be run | """
Run all migrations
"""
import imp
import os
import re
import sys
from os.path import join
import logging
from backdrop.core.database import Database
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
config_... | """
Run all migrations
"""
import imp
import os
import sys
import pymongo
from os.path import join
import logging
from backdrop.core.database import Database
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
co... |
Use Buffer.from() instead of new Buffer()
new Buffer() is now deprecated | /*
* Whitespace-JS / utils.js
* copyright (c) 2016 Susisu
*/
"use strict";
function end() {
module.exports = Object.freeze({
SPACE,
TAB,
LF,
intToWhitespace,
labelToWhitespace
});
}
const SPACE = " ";
const TAB = "\t";
const LF = "\n";
function intToWhitespac... | /*
* Whitespace-JS / utils.js
* copyright (c) 2016 Susisu
*/
"use strict";
function end() {
module.exports = Object.freeze({
SPACE,
TAB,
LF,
intToWhitespace,
labelToWhitespace
});
}
const SPACE = " ";
const TAB = "\t";
const LF = "\n";
function intToWhitespac... |
Load a schedule on start | 'use strict';
var fs = require('fs');
var Mustache = require('mustache');
import * as schedule from './schedule/schedule.js';
function readForm() {
return {
school: schedule.schools['Globala gymnasiet'],
id: document.getElementById('select-id').value,
week: 38,
width: 600,
... | 'use strict';
var fs = require('fs');
var Mustache = require('mustache');
import * as schedule from './schedule/schedule.js';
function readForm() {
return {
school: schedule.schools['Globala gymnasiet'],
id: document.getElementById('select-id').value,
week: 38,
width: 600,
... |
Fix typo in upgrade script
git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@1647 af82e41b-90c4-0310-8c96-b1721e28e2e2 | import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
... | import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
... |
Add new properties to ignore due to matrix.org protocol changes | package com.dmytrobilokha.disturber.network.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The matrix Joined Room DTO
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class JoinedRoomDto {
@JsonProperty(value = "unread_notific... | package com.dmytrobilokha.disturber.network.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The matrix Joined Room DTO
*/
public class JoinedRoomDto {
@JsonProperty(value = "unread_notifications", required = true)
private UnreadNotificationCountsDto unreadNotificationCounts;
@JsonPrope... |
Add test for transfer control disable otp | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
http... | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
http... |
Fix the inclusion of the TODO.rst file. | import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='utinypass',
version='0.1.0',
description='Parse and split PEM files painlessly.',
... | import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='utinypass',
version='0.1.0',
description='Parse and split PEM files painlessly.',
... |
Fix redirect after delete element | <?php
namespace OuterEdge\Layout\Controller\Adminhtml\Elements;
use Magento\Backend\App\Action;
class Delete extends \Magento\Backend\App\Action
{
/**
* @param Action\Context $context
*/
public function __construct(Action\Context $context)
{
parent::__construct($context);
}
/*... | <?php
namespace OuterEdge\Layout\Controller\Adminhtml\Elements;
use Magento\Backend\App\Action;
class Delete extends \Magento\Backend\App\Action
{
/**
* @param Action\Context $context
*/
public function __construct(Action\Context $context)
{
parent::__construct($context);
}
/*... |
Add missing SVN eol-style property to text files. | import sys, unittest
from ctypes import *
structures = []
byteswapped_structures = []
if sys.byteorder == "little":
SwappedStructure = BigEndianStructure
else:
SwappedStructure = LittleEndianStructure
for typ in [c_short, c_int, c_long, c_longlong,
c_float, c_double,
c_ushort, c_uint... | import sys, unittest
from ctypes import *
structures = []
byteswapped_structures = []
if sys.byteorder == "little":
SwappedStructure = BigEndianStructure
else:
SwappedStructure = LittleEndianStructure
for typ in [c_short, c_int, c_long, c_longlong,
c_float, c_double,
c_... |
Move includes dir and copy all files by default
Partial fix for #4 | var Async = require('async'),
Fs = require('fs'),
Glob = require('glob'),
Path = require('path'),
RawSource = require('webpack-core/lib/RawSource');
module.exports = function(options) {
this.options = options;
};
module.exports.prototype.apply = function(compiler) {
var options = this.options;
c... | var Async = require('async'),
Fs = require('fs'),
Glob = require('glob'),
Path = require('path'),
RawSource = require('webpack-core/lib/RawSource');
module.exports = function(options) {
this.options = options;
};
module.exports.prototype.apply = function(compiler) {
var options = this.options;
c... |
Fix the drag'n drop when entering a fipe. | (function() {
App.Views.Fipe = Backbone.View.extend({
events: {
// Classic file selection
'click .upload a' : 'browseFiles',
'change input[type="file"]' : 'selectFiles',
// Drag'n drop
'dragover .widget' : 'dragOver',
... | (function() {
App.Views.Fipe = Backbone.View.extend({
events: {
// Classic file selection
'click .upload a' : 'browseFiles',
'change input[type="file"]' : 'enterTheFipe',
// Drag'n drop
'dragover .widget' : 'dragOver',
... |
Raise exception on not found ticker | import requests
from bs4 import BeautifulSoup
try:
from urllib.parse import urlparse
except ImportError:
from urllib2 import urlparse
urlparse = urlparse.urlparse
try:
ConnectionError
except NameError:
ConnectionError = ValueError
YAHOO_ENDPOINT = "http://finance.yahoo.com/q/pr?s={}"
CLEARBIT_ENDP... | import requests
from bs4 import BeautifulSoup
try:
from urllib.parse import urlparse
except ImportError:
from urllib2 import urlparse
urlparse = urlparse.urlparse
try:
ConnectionError
except NameError:
ConnectionError = ValueError
YAHOO_ENDPOINT = "http://finance.yahoo.com/q/pr?s={}"
CLEARBIT_ENDP... |
Add alert and logout when no login details given
Former-commit-id: 78b396c1adfca2470a9e0f44a36e91513779f424 | /**
* Generic error handler method for ajax responses.
* Apply your specific requirements for an error response and then call this method to take care of the rest.
* @param response
*/
function handleApiError(response) {
if (!response || response.status === 200)
return;
if (response.status === 403... | /**
* Generic error handler method for ajax responses.
* Apply your specific requirements for an error response and then call this method to take care of the rest.
* @param response
*/
function handleApiError(response) {
if (!response || response.status === 200)
return;
if (response.status === 403... |
Move datatype editor to the right | import React, { PropTypes } from 'react'
import {
changeDatatypeName, changeDatatypeParam
} from '../actions/response-format'
import DatatypePicker from './datatype-picker';
import NumericDatatypeEditor from './numeric-datatype-editor';
import TextDatatypeEditor from './text-datatype-editor';
import DateDatatypeEdi... | import React, { PropTypes } from 'react'
import {
changeDatatypeName, changeDatatypeParam
} from '../actions/response-format'
import DatatypePicker from './datatype-picker';
import NumericDatatypeEditor from './numeric-datatype-editor';
import TextDatatypeEditor from './text-datatype-editor';
import DateDatatypeEdi... |
Switch basic app back to using perspective camera | window.addEvent("domready", function() {
var BasicApp = new Class({
Extends: App,
initialize: function(element, options) {
this.parent(element, options);
this.renderer = new BasicRenderer('basic-renderer-vert',
'basic-renderer-fra... | window.addEvent("domready", function() {
var BasicApp = new Class({
Extends: App,
initialize: function(element, options) {
this.parent(element, options);
this.renderer = new BasicRenderer('basic-renderer-vert',
'basic-renderer-fra... |
Remove the convenience functions, reorganize around the SQLAlchemy class | from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class... | from __future__ import unicode_literals
import os
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
@property... |
Use token in github hook | <?php
namespace Criterion\UI\Controller;
class HookController
{
public function github(\Silex\Application $app)
{
$query_token = $app['request']->query->get('token');
$token = new \Criterion\Model\Token($query_token);
if ( ! $token->exists)
{
return $app->abort(404... | <?php
namespace Criterion\UI\Controller;
class HookController
{
public function github(\Silex\Application $app)
{
$payload = json_decode($app['request']->get('payload'), true);
if ( ! isset($payload['repository']['url']))
{
return $app->json(array(
'success' ... |
[FEATURE] Update user links in angular to get resources. | 'use strict';
angular.module('publicApp')
.controller('UsersCtrl', ['$scope', '$http', '$location', '$route', '$routeParams', 'UserService', function ($scope, $http, $location, $route, $routeParams, $user) {
$scope.user = $user;
if ($user.isLogged) {
if (($user.id == $routeParams.id) || $user.admin) {
... | 'use strict';
angular.module('publicApp')
.controller('UsersCtrl', ['$scope', '$http', '$location', '$route', '$routeParams', 'UserService', function ($scope, $http, $location, $route, $routeParams, $user) {
$scope.user = $user;
if ($user.isLogged) {
if (($user.id == $routeParams.id) || $user.admin) {
... |
Stop relying on `ts-node` from the global scope | const childProcess = require("child_process");
const fs = require("fs");
if (process.argv.length !== 3) {
throw new Error("Requires the base path as argument.");
}
const basePath = process.argv[2];
if (!basePath.match(/[\\\/]$/)) {
throw new Error("Path must end with a slash - any slash will do.");
}
else if ... | const childProcess = require("child_process");
const fs = require("fs");
if (process.argv.length !== 3) {
throw new Error("Requires the base path as argument.");
}
const basePath = process.argv[2];
if (!basePath.match(/[\\\/]$/)) {
throw new Error("Path must end with a slash - any slash will do.");
}
else if ... |
Return the parameter for channel mode +l as a list
This fixes a bug where every digit was handled as a separate parameter, causing
"MODE #channel +l 10" to turn into "MODE #channel +ll 1 0" | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "Lim... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "Lim... |
Use AutoVersionClient to fix client incompatibity issues
Fixes #35 | # -*- coding: utf-8 -*-
import docker
import os
import sys
import requests
DEFAULT_TIMEOUT_SECONDS = 600
def docker_client():
# Default timeout 10 minutes
try:
timeout = int(os.getenv('DOCKER_TIMEOUT', 600))
except ValueError as e:
print("Provided timeout value: %s cannot be parsed as i... | # -*- coding: utf-8 -*-
import docker
import os
import sys
import requests
DEFAULT_TIMEOUT_SECONDS = 600
def docker_client():
# Default timeout 10 minutes
try:
timeout = int(os.getenv('DOCKER_TIMEOUT', 600))
except ValueError as e:
print("Provided timeout value: %s cannot be parsed as i... |
Add check to ensure hook exists before deleting it | <?php
namespace BrainMaestro\GitHooks;
class Hook
{
private static $hooks;
/**
* Add valid git hooks.
*/
public static function add($hook, $script)
{
$filename = ".git/hooks/{$hook}";
if (array_key_exists($hook, self::getHooks())) {
file_put_contents($fi... | <?php
namespace BrainMaestro\GitHooks;
class Hook
{
private static $hooks;
/**
* Add valid git hooks.
*/
public static function add($hook, $script)
{
if (array_key_exists($hook, self::getHooks())) {
$filename = ".git/hooks/{$hook}";
file_put_contents($filenam... |
Move $locale closer to usage | <?php
namespace App\Handlers\Events;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\NewBooking;
use Notifynder;
use Log;
use Mail;
use App;
class SendBookingNotification
{
/**
* Create the event handler.
*
* @return void
*/
public funct... | <?php
namespace App\Handlers\Events;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\NewBooking;
use Notifynder;
use Log;
use Mail;
use App;
class SendBookingNotification
{
/**
* Create the event handler.
*
* @return void
*/
public funct... |
Remove hard coded experiment description. Remove done field and add status field since that is what we get from the backend. | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: ... | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: ... |
Check for all exceptions to main method | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import sys
import argparse
import tmux_wrapper as tmux
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def load_session_presets():
try:
file_path = os.environ["TM_SESSIONS"]
except KeyError:... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import sys
import argparse
import tmux_wrapper as tmux
__version__ = 1.0
__description__ = "A tmux wrapper featuring shortcuts and session presets."
def load_session_presets():
try:
file_path = os.environ["TM_SESSIONS"]
except KeyError:... |
Change delegate to make it safer
Up till now the delegate would've failed without any error if there was no response or if the middleware it was supposed to trigger was null (end of stack) | <?php
declare(strict_types=1);
namespace Onion\Framework\Http\Middleware;
use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message;
final class Delegate implements DelegateInterface
{
/**
* @var ServerMiddlewareInterface
*/
protected ... | <?php
declare(strict_types=1);
namespace Onion\Framework\Http\Middleware;
use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message;
final class Delegate implements DelegateInterface
{
/**
* @var ServerMiddlewareInterface
*/
protected ... |
Add legacy support for i18n and backbone | //Generator http://patorjk.com/software/taag/#p=display&h=1&f=Banner4&t=Focus-COMPONENTS
import './style';
import translation from 'focus-core/translation';
import history from 'focus-core/history';
const infos = require(`${__PACKAGE_JSON_PATH__}/package.json`);
import components from './components';
import behaviour... | //Generator http://patorjk.com/software/taag/#p=display&h=1&f=Banner4&t=Focus-COMPONENTS
import './style';
const infos = require(`${__PACKAGE_JSON_PATH__}/package.json`);
import components from './components';
import behaviours from './behaviours';
/**
* Display information data for Focus-COMPONENTS
*/
const infosFn =... |
Fix regex when no date is specified in the url, thx @kashike | $(function() {
var moving = false;
var availableDays = JSON.parse($('#available-log-days').text());
var $dateInput = $('#log-date');
$dateInput.datepicker({
format: "yyyy/mm/dd",
endDate: "today",
todayBtn: "linked",
language: "en-GB",
orientation: "top right",
... | $(function() {
var moving = false;
var availableDays = JSON.parse($('#available-log-days').text());
var $dateInput = $('#log-date');
$dateInput.datepicker({
format: "yyyy/mm/dd",
endDate: "today",
todayBtn: "linked",
language: "en-GB",
orientation: "top right",
... |
Use filter macro for request validation
StringifiedTrytesArray(Type) filter macro was
introduced in #243. Becasue of this, no request
filter test case is needed, hence the macro is
covered already in other test cases. | # coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from typing import Iterable, List, Optional
import filters as f
from iota import Transaction, TransactionHash
from iota.commands.core import GetTrytesCommand
from iota.commands import FilterCommand, RequestFilter
... | # coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from typing import Iterable, List, Optional
import filters as f
from iota import Transaction, TransactionHash
from iota.commands.core import GetTrytesCommand
from iota.commands import FilterCommand, RequestFilter
... |
Prepare the analyzer base config values before opening the config dialog (setting default values) | 'use strict';
import _ from 'lodash/core';
import ConfigurationEditController from './config.edit.controller';
import configurationEditTpl from './config.edit.modal.html';
export default class OrganizationConfigsController {
constructor($log, $uibModal, AnalyzerService, NotificationService) {
'ngInject';
t... | 'use strict';
import _ from 'lodash/core';
import ConfigurationEditController from './config.edit.controller';
import configurationEditTpl from './config.edit.modal.html';
export default class OrganizationConfigsController {
constructor($log, $uibModal, AnalyzerService, NotificationService) {
'ngInject';
t... |
Update grunt watch to include sass | module.exports = function(grunt) {
grunt.initConfig({
coffee: {
compile: {
options: {
bare: false,
join: true
},
files: {
'blitz.js': ['lib/blitz.coffee'],
'test/blitz_test.js': ['test/blitz_test.coffee']
}
}
},
uglify: {... | module.exports = function(grunt) {
grunt.initConfig({
coffee: {
compile: {
options: {
bare: false,
join: true
},
files: {
'blitz.js': ['lib/blitz.coffee'],
'test/blitz_test.js': ['test/blitz_test.coffee']
}
}
},
uglify: {... |
Add api and model to packages | from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
... | from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
... |
Fix bug that can happen when configuration file doesn't exist | var Promise = require('../utils/promise');
var validateConfig = require('./validateConfig');
var CONFIG_FILES = require('../constants/configFiles');
/**
Parse configuration from "book.json" or "book.js"
@param {Book} book
@return {Promise<Book>}
*/
function parseConfig(book) {
var fs = book.getFS();
... | var Promise = require('../utils/promise');
var validateConfig = require('./validateConfig');
var CONFIG_FILES = require('../constants/configFiles');
/**
Parse configuration from "book.json" or "book.js"
@param {Book} book
@return {Promise<Book>}
*/
function parseConfig(book) {
var fs = book.getFS();
... |
Fix the manager methods for deferred/non_deferred | from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)... | from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)... |
feat: Remove label and just show checkbox | import React from 'react';
import PropTypes from 'prop-types';
import { RadioGroup, Radio, Checkbox } from '@blueprintjs/core';
import { NotificationTypes } from 'enums';
const NotificationsPanel = ({
notificationType,
onSettingsChange,
setNotificationType,
continuousMode,
setContinuousMode
}) => (
<div c... | import React from 'react';
import PropTypes from 'prop-types';
import { RadioGroup, Radio, Checkbox } from '@blueprintjs/core';
import { NotificationTypes } from 'enums';
const NotificationsPanel = ({
notificationType,
onSettingsChange,
setNotificationType,
continuousMode,
setContinuousMode
}) => (
<div c... |
Fix incorrect issue ref in test | package com.fasterxml.jackson.dataformat.xml.misc;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.XmlTestBase;
// test(s) for [dataformat-xml#169]
public class EmptyPolymorphicTest extends XmlTestBase
{
static class Da... | package com.fasterxml.jackson.dataformat.xml.misc;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.XmlTestBase;
// test(s) for [dataformat-xml#111]
public class EmptyPolymorphicTest extends XmlTestBase
{
static class Da... |
Refactor view widget Twig extension. | <?php declare(strict_types=1);
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace... | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\AdminBundle\Twig\... |
Add hyperlink to spendings in search view | @extends('layout')
@section('body')
<h1>Search</h1>
<form method="GET" class="tight">
<div class="row spacing-top-large">
<div class="column">
<input type="text" name="query" />
</div>
<div class="column tight">
<input type="submit" va... | @extends('layout')
@section('body')
<h1>Search</h1>
<form method="GET" class="tight">
<div class="row spacing-top-large">
<div class="column">
<input type="text" name="query" />
</div>
<div class="column tight">
<input type="submit" va... |
Store timestamp also in articles | var MongoClient = require("mongodb").MongoClient;
var config = require("./config.json");
var dbConnection = null;
function getDB() {
return new Promise(function(resolve, reject) {
if (!dbConnection) {
var mongoServerUri = 'mongodb://' +
config.mongodb.user + ':' + config.mongod... | var MongoClient = require("mongodb").MongoClient;
var config = require("./config.json");
var dbConnection = null;
function getDB() {
return new Promise(function(resolve, reject) {
if (!dbConnection) {
var mongoServerUri = 'mongodb://' +
config.mongodb.user + ':' + config.mongod... |
Remove the topic and time from the pandas index so they are included in the json output again. | """Serializers for the use with rest-pandas"""
from rest_framework import serializers
from .models import MQTTMessage
import re
import copy
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = MQTTMessage
fields = ['id', 'time_recorded', 'topic', 'payload']
pandas_in... | """Serializers for the use with rest-pandas"""
from rest_framework import serializers
from .models import MQTTMessage
import re
import copy
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = MQTTMessage
fields = ['id', 'time_recorded', 'topic', 'payload']
pandas_in... |
FIX password reset method that was not resetting the password | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, models
from odoo.addons.auth_signup.models.res_partner import now
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, models
_logger = logging.getLogger(__name__)
class ResUsers(models.Model):
_inherit = 'res.users'
@api.multi
def action_reset_password(self):
create_mode = boo... |
FIX Ensure file is written after FileSize is set | <?php
/**
* Post upgrade, update filesizes for assets uploaded prior to FileSize capture
*
* @author marcus
*/
class UpdateFileSizeTask extends BuildTask
{
public function run($request)
{
$number = $request->getVar('number');
if (!$number) {
$number = 50;
}
... | <?php
/**
* Post upgrade, update filesizes for assets uploaded prior to FileSize capture
*
* @author marcus
*/
class UpdateFileSizeTask extends BuildTask
{
public function run($request)
{
$number = $request->getVar('number');
if (!$number) {
$number = 50;
}
... |
Return xls as type for application/vnd.ms-excel. | (function(module) {
module.directive("displayFileContents", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: "E",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,... | (function(module) {
module.directive("displayFileContents", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: "E",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,... |
Remove unnecessary parsing of body -- it's already an object. | var http = require('http');
var r = require('request');
var config = require('./config.json');
var doneUrl;
var userUrl;
http.createServer(function(request, response) {
if (!isEvent(request)) return;
r.post({
url: doneUrl
}, function(error, response, body) {
if (error !== null) {
... | var http = require('http');
var r = require('request');
var config = require('./config.json');
var doneUrl;
var userUrl;
http.createServer(function(request, response) {
if (!isEvent(request)) return;
r.post({
url: doneUrl
}, function(error, response, body) {
if (error !== null) {
... |
III-2522: Fix language factory method test | <?php
namespace CultuurNet\UDB3;
use CultuurNet\UDB3\Model\ValueObject\Translation\Language as Udb3ModelLanguage;
use InvalidArgumentException;
use PHPUnit_Framework_TestCase;
class LanguageTest extends PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_requires_an_iso_639_1_code()
... | <?php
namespace CultuurNet\UDB3;
use InvalidArgumentException;
use PHPUnit_Framework_TestCase;
class LanguageTest extends PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_requires_an_iso_639_1_code()
{
$language = new Language('en');
$this->assertEquals('en', $lan... |
Extend AbstractArezTest otherwise invariant checking state is not controlled and thus some tests may fail | package org.realityforge.arez;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class DisposableTest
extends AbstractArezTest
{
static class TestDisposable
implements Disposable
{
private boolean _disposed;
@Override
public void dispose()
{
_disposed = tru... | package org.realityforge.arez;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class DisposableTest
{
static class TestDisposable
implements Disposable
{
private boolean _disposed;
@Override
public void dispose()
{
_disposed = true;
}
@Override
... |
Correct THE stupid mistake. Now we have a string! | package framework.util;
import framework.util.RingBuffer;
import framework.generators.Generator;
/**
* Models a guitar string using the Karplus-Strong algorithm.
*/
public class GuitarString {
/**
* Create a GuitarString of the given frequency.
* @param f the frequency
*/
public GuitarString... | package framework.util;
import framework.util.RingBuffer;
import framework.generators.Generator;
/**
* Models a guitar string using the Karplus-Strong algorithm.
*/
public class GuitarString {
/**
* Create a GuitarString of the given frequency.
* @param f the frequency
*/
public GuitarString... |
Change querying param to variable | import React, { useEffect, useState } from "react";
import classes from "./SelectCompetition.module.css";
import CompetitionCard from "../../components/CompetitionCard/CompetitionCard";
import LinkButton from "../../components/UI/LinkButton/LinkButton";
const SelectCompetition = (props) => {
const userId = 123;
co... | import React, { useEffect, useState } from "react";
import classes from "./SelectCompetition.module.css";
import CompetitionCard from "../../components/CompetitionCard/CompetitionCard";
import LinkButton from "../../components/UI/LinkButton/LinkButton";
const SelectCompetition = (props) => {
const userId = 123;
co... |
Add test for fellow model | from django.test import TestCase
from .models import Fellow, Event
class FellowTestCase(TestCase):
def setUp(self):
fellows = (
{
"forenames": "A",
"surname": "C",
"affiliation": "King's College",
"research_area... | from django.test import TestCase
from .models import Event
class EventTestCase(TestCase):
def setUp(self):
events = (
{
"fellow": 1,
"category": "O",
"name": "CW16",
"url": "http://www.software.ac.uk/cw16",
... |
Set web middleware to get token | <?php
namespace Asvae\ApiTester\Providers;
use Illuminate\Routing\Router;
class RouteServiceProvider extends \Illuminate\Foundation\Support\Providers\RouteServiceProvider
{
/**
* Define the routes for the application.
*
* Module
* ├ Http
* │ └ routes.php
* │
* └ Providers
... | <?php
namespace Asvae\ApiTester\Providers;
use Illuminate\Routing\Router;
class RouteServiceProvider extends \Illuminate\Foundation\Support\Providers\RouteServiceProvider
{
/**
* Define the routes for the application.
*
* Module
* ├ Http
* │ └ routes.php
* │
* └ Providers
... |
Fix mistake in geocoder reverse method | <?php
namespace Ivory\GoogleMapBundle\Model\Services\Geocoding;
use Geocoder\Geocoder as BaseGeocoder;
/**
* Geocoder which describes a google map geocoder
*
* @see http://code.google.com/apis/maps/documentation/javascript/reference.html#Geocoder
* @author GeLo <geloen.eric@gmail.com>
*/
class Geocoder extends ... | <?php
namespace Ivory\GoogleMapBundle\Model\Services\Geocoding;
use Geocoder\Geocoder as BaseGeocoder;
/**
* Geocoder which describes a google map geocoder
*
* @see http://code.google.com/apis/maps/documentation/javascript/reference.html#Geocoder
* @author GeLo <geloen.eric@gmail.com>
*/
class Geocoder extends ... |
Remove line break in tweets | 'use strict';
if (process.env.NODE_ENV === 'production') {
var Twit = Npm.require('twit');
var twitter = new Twit({
consumer_key: process.env.TWIT_KEY,
consumer_secret: process.env.TWIT_SECRET,
access_token: process.env.TWIT_TOKEN,
access_token_secret: process.env.TWIT_TOKE... | 'use strict';
if (process.env.NODE_ENV === 'production') {
var Twit = Npm.require('twit');
var twitter = new Twit({
consumer_key: process.env.TWIT_KEY,
consumer_secret: process.env.TWIT_SECRET,
access_token: process.env.TWIT_TOKEN,
access_token_secret: process.env.TWIT_TOKE... |
Add vibration when time runs out. | (function () {
'use strict';
function WordCtrl(Term, Session, $location, $route, $scope) {
var time,
soundEffect = new Audio('/mp3/bike.mp3');
$scope.word = 'tralala';
$scope.started = false;
$scope.term = Term.get({
discipline: $route.current.params.dis... | (function () {
'use strict';
function WordCtrl(Term, Session, $location, $route, $scope) {
var time;
$scope.word = 'tralala';
$scope.started = false;
$scope.term = Term.get({
discipline: $route.current.params.discipline,
language: $route.current.params.l... |
Fix bug of session data being stored with an extra `values` key | 'use strict';
export default {
setup,
};
/**
* Module dependencies.
*/
import SequelizeStore from 'koa-generic-session-sequelize';
// import convert from 'koa-convert';
import session from 'koa-generic-session';
/**
* Prepares session middleware and methods without attaching to the stack
*
* @param {Object} ... | 'use strict';
export default {
setup,
};
/**
* Module dependencies.
*/
import SequelizeStore from 'koa-generic-session-sequelize';
// import convert from 'koa-convert';
import session from 'koa-generic-session';
/**
* Prepares session middleware and methods without attaching to the stack
*
* @param {Object} ... |
Fix endpoint for clone operation | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
... | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
... |
Fix logging, add a sleep to molify Google's rate limit. | """Geocode Contact objects."""
import sys
import time
from geopy import geocoders
from django.core.management.base import BaseCommand, CommandError
from portal import models
class Command(BaseCommand):
"""Set lat/long fields on contacts with a street address,
currently just using Google's geocoder."""
... | """Geocode Contact objects."""
import sys
from geopy import geocoders
from django.core.management.base import BaseCommand, CommandError
from portal import models
class Command(BaseCommand):
"""Set lat/long fields on contacts with a street address,
currently just using Google's geocoder."""
def handle(... |
Add type safety to the url parameters | <?php
namespace Backend\Modules\ContentBlocks\Api;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlock;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlockRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoun... | <?php
namespace Backend\Modules\ContentBlocks\Api;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlock;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlockRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoun... |
Add identifier relation popout to grants and projects | <div class="related-grants-and-projects">
<h4>Related Grants and Projects</h4>
<ul class="list-unstyled">
@foreach($related['grants_projects']['docs'] as $col)
<li>
<i class="fa fa-flask icon-portal"></i>
<small>{{ $col['display_relationship'] }}</small>
... | <div class="related-grants-and-projects">
<h4>Related Grants and Projects</h4>
<ul class="list-unstyled">
@foreach($related['grants_projects']['docs'] as $col)
<li>
<i class="fa fa-flask icon-portal"></i>
<small>{{ $col['display_relationship'] }}</small>
... |
Correct scroll on menu click | function generateMenu(nodes) {
let output = [];
nodes.forEach((node) => {
output.push(generateMenuFromNode(node));
});
return output.join('');
}
function generateMenuFromNode(node) {
if (node.children !== undefined && node.children.length > 0) {
let output = [
`<ul class... | function generateMenu(nodes) {
let output = [];
nodes.forEach((node) => {
output.push(generateMenuFromNode(node));
});
return output.join('');
}
function generateMenuFromNode(node) {
if (node.children !== undefined && node.children.length > 0) {
let output = [
`<ul class... |
Call parent constructor on response object
Signed-off-by: Roeland Jago Douma <982d370f7dc34a05b4abe8788f899578d515262d@famdouma.nl> | <?php
/**
* Audio Player
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the LICENSE.md file.
*
* @author Marcel Scherello <audioplayer@scherello.de>
* @author Olivier Paroz <galleryapps@oparoz.com>
* @copyright 2016-2019 Marcel Scherello
*/
namespace OCA\audioplaye... | <?php
/**
* Audio Player
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the LICENSE.md file.
*
* @author Marcel Scherello <audioplayer@scherello.de>
* @author Olivier Paroz <galleryapps@oparoz.com>
* @copyright 2016-2019 Marcel Scherello
*/
namespace OCA\audioplaye... |
Add compact and delete stubs | import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localhost', port=2379):
self.channel = grpc.insecure_channel('{host}:{port}'.format(
host=host, port=port)
)
self.kvstub = etcdrpc... | import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localhost', port=2379):
self.channel = grpc.insecure_channel('{host}:{port}'.format(
host=host, port=port)
)
self.kvstub = etcdrpc... |
Throw RuntimeException if getResourceName() fails | package com.xtremelabs.robolectric.res;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
public class ResourceExtractor {
private Map<String, Integer> resourceStringToId = new HashMap<String, Integer>();
private Map<Integer, String> resourceIdT... | package com.xtremelabs.robolectric.res;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
public class ResourceExtractor {
private Map<String, Integer> resourceStringToId = new HashMap<String, Integer>();
private Map<Integer, String> resourceIdT... |
Add methods to work with retrieving bytes from ByteBuffer. | package com.sibilantsolutions.iptools.util;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public abstract class Convert
{
private Convert() {} //Prevent instantiation.
static public int byteToNum( byte b )
{
return b & 0xFF;
}
static public int getByte( ByteBuffer bb )
{... | package com.sibilantsolutions.iptools.util;
import java.nio.ByteOrder;
public abstract class Convert
{
private Convert() {} //Prevent instantiation.
static public long toNum( byte[] bytes, int offset, int length )
{
return toNum( bytes, offset, length, ByteOrder.BIG_ENDIAN );
}
stati... |
ENH: Add very basic tests for codata and constants. |
import warnings
import codata
import constants
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = fin... |
import warnings
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = find('qwertyuiop', disp=False)
... |
Update webpack settings for v2 | var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: path.join(__dirname, 'webapp', 'src'),
entry: {
main: './index.js'
},
output: {
path: path.join(__dirname, 'app', 'assets'),
filename: '[name].[hash].js',
publ... | var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: path.join(__dirname, 'webapp', 'src'),
entry: {
main: './index.js'
},
output: {
path: path.join(__dirname, 'app', 'assets'),
filename: '[name].[hash].js',
publ... |
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command. | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loa... | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loa... |
Stop auto fetching if view no more visible | /*global window: true */
define(
[
'text!templates/repoList.html',
'underscore',
'jquery',
'backbone'
],
function (template, _, $, Backbone) {
"use strict";
return Backbone.View.extend({
tagName: 'ul',
className: 'repos unstyled',
... | /*global window: true */
define(
[
'text!templates/repoList.html',
'underscore',
'jquery',
'backbone'
],
function (template, _, $, Backbone) {
"use strict";
return Backbone.View.extend({
tagName: 'ul',
className: 'repos unstyled',
... |
Remove ‘using notify’ from nav (it’s a redirect now) | def features_nav():
return [
{
"name": "Features",
"link": "main.features",
"sub_navigation_items": [
{
"name": "Emails",
"link": "main.features_email",
},
{
"name"... | def features_nav():
return [
{
"name": "Features",
"link": "main.features",
"sub_navigation_items": [
{
"name": "Emails",
"link": "main.features_email",
},
{
"name"... |
Adjust starting frequency to be more fun. | /** Global variables for processing.js access **/
var waveSpeed = 3;
var timestep = 0.3
var w = 0.25;
var w2 = 0.45;
var playing = false;
/** Page setup **/
$(document).ready(function() {
$("#speed-slider").slider({min: -5, max: 5, step: 0.1, slide: setAnimSpeed,
value: timestep});
$... | /** Global variables for processing.js access **/
var waveSpeed = 3;
var timestep = 0.3
var w = 0.3;
var w2 = 0.45;
var playing = false;
/** Page setup **/
$(document).ready(function() {
$("#speed-slider").slider({min: -5, max: 5, step: 0.1, slide: setAnimSpeed,
value: timestep});
$(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.