text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix mari pointing to dead dir | /*
* itsjoke.js - It's Joke!.
*
* Contributed by Capuccino and Ovyerus.
*/
/* eslint-env node */
const fs = require('fs');
const files = fs.readdirSync(`${__baseDir}/assets/itsjoke`);
exports.commands = [
'mari'
];
exports.mari = {
desc: "It's joke!",
longDesc: "Send a random picture of the it's jo... | /*
* itsjoke.js - It's Joke!.
*
* Contributed by Capuccino and Ovyerus.
*/
/* eslint-env node */
const fs = require('fs');
const files = fs.readdirSync(`${__baseDir}/res/itsjoke`);
exports.commands = [
'mari'
];
exports.mari = {
desc: "It's joke!",
longDesc: "Send a random picture of the it's joke ... |
Fix filtering for deleted users | <?php
namespace ForkCMS\Modules\Backend\Backend\Actions;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use ForkCMS\Modules\Backend\Domain\Action\AbstractActionController;
use ForkCMS\Modules\Backend\Domain\UserGroup\UserGroup;
use Symfony\Component\HttpFoundation\Request;
/**
*Overview of the ava... | <?php
namespace ForkCMS\Modules\Backend\Backend\Actions;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use ForkCMS\Modules\Backend\Domain\Action\AbstractActionController;
use ForkCMS\Modules\Backend\Domain\UserGroup\UserGroup;
use Symfony\Component\HttpFoundation\Request;
/**
*Overview of the ava... |
Fix and ungodly number of linter errors | navigator.geolocation.getCurrentPosition(function (position) {
var mapToMake = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
makeMap(mapToMake);
}, function (err) {
console.error(err);
});
var map;
var marker;
var destinationMarker;
var makeMap = function (currentLatLngObj) {
map... | navigator.geolocation.getCurrentPosition(function(position) {
makeMap({lat: position.coords.latitude, lng: position.coords.longitude});
}, function(err) {
console.error(err);
});
var map;
var marker;
var destinationMarker;
var makeMap = function(currentLatLngObj) {
map = new google.maps.Map(document.getElementB... |
Include dotfiles when copying the site
Part one of fixing issue #141. | 'use strict';
const gulp = require('gulp');
const shell = require('shelljs');
const size = require('gulp-size');
const argv = require('yargs').argv;
// 'gulp jekyll:tmp' -- copies your Jekyll site to a temporary directory
// to be processed
gulp.task('site:tmp', () =>
gulp.src(['src/**/*', '!src/assets/**/*', '!src/... | 'use strict';
const gulp = require('gulp');
const shell = require('shelljs');
const size = require('gulp-size');
const argv = require('yargs').argv;
// 'gulp jekyll:tmp' -- copies your Jekyll site to a temporary directory
// to be processed
gulp.task('site:tmp', () =>
gulp.src(['src/**/*', '!src/assets/**/*', '!src/... |
Fix bug with messages not showing up for the user that sends the message | // require('./Pad.js')
function DrawingAppCtrl($scope, socket, drawingPad) {
console.log("starting");
$socket = socket;
$scope.message;
$scope.messages = [];
$scope.joined = false;
$scope.username;
drawingPad.initialize(socket);
$scope.sendMsg = function (message) {
$scope.messages.push({msg: me... | // require('./Pad.js')
function DrawingAppCtrl($scope, socket, drawingPad) {
console.log("starting");
$socket = socket;
$scope.message;
$scope.messages = [];
$scope.joined = false;
$scope.username;
drawingPad.initialize(socket);
$scope.sendMsg = function (message) {
$scope.messages.push(message)... |
Change Database with a more fitting name | //Dear source-code readers, pay no attention to these global variables
var APP_ID = 'YtKfTS2Zo8ELUk63LzB0';
var APP_CODE = 'SB1wcsUEGzLA3SRHJJ7CPw';
// Reference to the root of the Firebase database
var database = new Firebase("https://battleshiphere.firebaseio.com/");
$("#upload").click(function() {
var name = $("#... | //Dear source-code readers, pay no attention to these global variables
var APP_ID = 'YtKfTS2Zo8ELUk63LzB0';
var APP_CODE = 'SB1wcsUEGzLA3SRHJJ7CPw';
// Reference to the root of the Firebase database
var database = new Firebase("https://brilliant-torch-6592.firebaseio.com/");
$("#upload").click(function() {
var name ... |
Add flag option `start-hot` and apply env
* Add flag option `start-hot` to server.js
* Apply env to `start-hot` mode of server.js | /* eslint-disable no-console */
/**
* Setup and run the development server for Hot-Module-Replacement
* https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
* @flow
*/
import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import ... | /* eslint-disable no-console */
/**
* Setup and run the development server for Hot-Module-Replacement
* https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
* @flow
*/
import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import ... |
Make it parse (using PHP 5.5). | <?php
$path = $_SERVER['PATH_INFO'];
if ($path = '/address')
{
$controller = new \Controller();
$return = $controller->ex();
echo $return;
}
class Controller
{
private $addresses = [];
function ex()
{
$this->rcd();
$id = $_GET['id'];
$address = $this->addresses[$id];
return json_encode($... | <?php
$path = $_SERVER['PATH_INFO'];
if ($path = '/address')
{
$controller = new \Controller();
$return = $controller->ex();
echo $return;
}
class Controller
{
$addresses = [];
function ex()
{
$this->rcd();
$id = $_GET['id']
$address = $this->addresses[$id];
return json_encode($address);... |
BAP-4107: Change UX
- remove mock | <?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\ParameterBag;
class ProviderManager
{
protected $providers;
public function __construct()
{
$this->providers = new ArrayCollection();
}
/**
* @pa... | <?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\ParameterBag;
class ProviderManager
{
protected $providers;
public function __construct()
{
$this->providers = new ArrayCollection();
}
/**
* @pa... |
Make OidcTokenRequest a local struct | package api
import (
"errors"
"fmt"
)
var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience")
type OidcToken struct {
Token string `json:"token"`
}
func (c *Client) OidcToken(jobId string, audience ...string) (*OidcToken, *Response, error) {
type oidcTokenRequest struct ... | package api
import (
"errors"
"fmt"
)
var ErrAudienceTooLong = errors.New("the API only supports at most one element in the audience")
type OidcTokenRequest struct {
Audience string `json:"audience"`
}
type OidcToken struct {
Token string `json:"token"`
}
func (c *Client) OidcToken(jobId string, audience ...st... |
Insert new files, AngularJS para Zumbis, Aula 14 | angular.module('app').directive('ngCepValidator', function($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, $element, $attrs, ngModel) {
$scope.$watch($attrs.ngModel, function(value) {
if(value) {
if(value.match(/^[0-9]{5}-[0-9]{3}$/)) {
$http... | angular.module('app').directive('ngCepValidator', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, $element, $attrs, ngModel) {
$scope.$watch($attrs.ngModel, function(value) {
if(value) {
if(value.match(/^[0-9]{5}-[0-9]{3}$/)) {
ngModel.$s... |
Revert the mess WordPress makes | <?php
$m = new Mustache_Engine([
'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/build/govuk_template/views/layouts', [
'extension' => '.html',
]),
]);
$template = $m->loadTemplate('govuk_template');
echo $template->render([
'pageTitle' => html_entity_decode(\Missing\String::get_output(function ... | <?php
$m = new Mustache_Engine([
'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/build/govuk_template/views/layouts', [
'extension' => '.html',
]),
]);
$template = $m->loadTemplate('govuk_template');
echo $template->render([
'pageTitle' => \Missing\String::get_output(function () { wp_title('|', ... |
Handle label if plural or singular | import inflect from 'i';
import numeral from 'numeral';
import FormattedNumber from '../types/formatted_number';
import { GraphQLString } from 'graphql';
const { pluralize, singularize } = inflect();
export default fn => ({
type: FormattedNumber,
args: {
format: {
type: GraphQLString,
description:... | import inflect from 'i';
import numeral from 'numeral';
import FormattedNumber from '../types/formatted_number';
import { GraphQLString } from 'graphql';
const { pluralize } = inflect();
export default fn => ({
type: FormattedNumber,
args: {
format: {
type: GraphQLString,
description: 'Returns a `... |
Add a correct url to the qr-code to allow scanning with other apps | import View from './View'
export default class RoomView extends View {
constructor() {
super();
this.title = 'Room';
this.templateUrl = 'templates/room';
}
afterInit() {
const roomId = 'test';
const joinUrl = location.href.split('#')[0] + '#/join/';
[1, 2].forEach(playerId => {
const joi... | import View from './View'
export default class RoomView extends View {
constructor() {
super();
this.title = 'Room';
this.templateUrl = 'templates/room';
}
afterInit() {
const roomId = 'test';
[1, 2].forEach(playerId => {
const joinArea = this.find(`.join-area:nth-child(${playerId})`);
... |
Add copy image in gulp | var gulp = require('gulp'),
gulpCopy = require('gulp-file-copy');
gulp.task('copy', function() {
gulp.src('./bower_components/jquery/jquery.min.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./jquery-mobile/jquery.mobile-1.4.5.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./bower_components/mom... | var gulp = require('gulp'),
gulpCopy = require('gulp-file-copy');
gulp.task('copy', function() {
gulp.src('./bower_components/jquery/jquery.min.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./jquery-mobile/jquery.mobile-1.4.5.js')
.pipe(gulp.dest('./js/lib/'));
gulp.src('./bower_components/mom... |
Define Node properties and methods | <?php
namespace Gt\Dom;
use DOMNode;
/**
* Represents any web page loaded in the browser and serves as an entry point
* into the web page's content, the DOM tree (including elements such as
* <body> or <table>).
*
* @method Node importNode(DOMNode $importedNode, bool $deep = false)
*/
class Document extends \DOM... | <?php
namespace Gt\Dom;
/**
* Represents any web page loaded in the browser and serves as an entry point
* into the web page's content, the DOM tree (including elements such as
* <body> or <table>).
*/
class Document extends \DOMDocument {
use LiveProperty, ParentNode;
public function __construct($document = null... |
Move from python anywhere to webfaction | import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_c... | import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_c... |
Fix race in TestThrottle test.
Closes #355. | // Copyright (c) 2013-2014 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package legacyrpc
import (
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestThrottle(t *testing.T) {
const threshold = 1
busy := make(chan struct{})... | // Copyright (c) 2013-2014 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package legacyrpc
import (
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
)
func TestThrottle(t *testing.T) {
const threshold = 1
srv := httptest.Ne... |
Add importlib if not included | #!/usr/bin/env python
from setuptools import setup
from exoline import __version__ as version
with open('requirements.txt') as f:
required = f.read().splitlines()
try:
from collections import OrderedDict
except ImportError:
required.append('ordereddict>=1.1')
try:
import importlib
except ImportError... | #!/usr/bin/env python
from setuptools import setup
from exoline import __version__ as version
with open('requirements.txt') as f:
required = f.read().splitlines()
try:
from collections import OrderedDict
except ImportError:
required.append('ordereddict==1.1')
setup(
name='exoline',
version=versi... |
Make DQN backward compatible with pytorch 0.1.2. | from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Ta... | from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Ta... |
Add mode config based on MIN env variable | import path from 'path';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
const sourcePath = path.join(__dirname, './src');
const distPath = path.join(__dirname, './dist');
export default {
mode: (process.env.MIN === 'true') ? 'production' : 'none',
entry: {
js: [path.join(sourcePath, '/component.j... | import path from 'path';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
const sourcePath = path.join(__dirname, './src');
const distPath = path.join(__dirname, './dist');
export default {
mode: 'production',
entry: {
js: [path.join(sourcePath, '/component.js')],
},
output: {
path: distPat... |
Order tags: users first, guest after | <?php
class Denkmal_Paging_Tag_VenueUserLatest extends Denkmal_Paging_Tag_Abstract {
/**
* @param Denkmal_Model_Venue $venue
* @param DateTime|null $createdMin
*/
public function __construct(Denkmal_Model_Venue $venue, DateTime $createdMin = null) {
if ($createdMin == null) {
... | <?php
class Denkmal_Paging_Tag_VenueUserLatest extends Denkmal_Paging_Tag_Abstract {
/**
* @param Denkmal_Model_Venue $venue
* @param DateTime|null $createdMin
*/
public function __construct(Denkmal_Model_Venue $venue, DateTime $createdMin = null) {
if ($createdMin == null) {
... |
Add missing semicolons in Travis.Controllers.Builds.List | Travis.Controllers.Builds.List = SC.ArrayProxy.extend({
parent: null,
repositoryBinding: 'parent.repository',
contentBinding: 'parent.repository.builds',
init: function() {
SC.run.later(this.updateTimes.bind(this), Travis.UPDATE_TIMES_INTERVAL);
this.view = Travis.View.create({
builds: this,
... | Travis.Controllers.Builds.List = SC.ArrayProxy.extend({
parent: null,
repositoryBinding: 'parent.repository',
contentBinding: 'parent.repository.builds',
init: function() {
SC.run.later(this.updateTimes.bind(this), Travis.UPDATE_TIMES_INTERVAL);
this.view = Travis.View.create({
builds: this,
... |
Change ArcadeDrive to TankDrive for speed control | package edu.stuy.commands;
import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
* Rotates the Robot without PID values
*/
public class DrivetrainRotateNoPIDCommand extends Command {
private double degrees;
private double startAngle;
public DrivetrainRotateNoPIDCommand(double _degr... | package edu.stuy.commands;
import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
* Rotates the Robot without PID values
*/
public class DrivetrainRotateNoPIDCommand extends Command {
private double degrees;
private double startAngle;
public DrivetrainRotateNoPIDCommand(double _degr... |
Add test case for `count` method | var assert = require('assert')
var mongo = require('../')
var db = mongo('mongodb://read:read@ds031617.mongolab.com:31617/esdiscuss')
before(function (done) {
this.timeout(10000)
db._get(done)
})
describe('read only operation', function () {
it('db.getCollectionNames', function (done) {
db.getCollectionName... | var assert = require('assert')
var mongo = require('../')
var db = mongo('mongodb://read:read@ds031617.mongolab.com:31617/esdiscuss')
before(function (done) {
this.timeout(10000)
db._get(done)
})
describe('read only operation', function () {
it('db.getCollectionNames', function (done) {
db.getCollectionName... |
Remove unused import in TaskDefinitionViewer | // This file is part of BenchExec, a framework for reliable benchmarking:
// https://github.com/sosy-lab/benchexec
//
// SPDX-FileCopyrightText: 2019-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
import React from "react";
import TaskDefinitionViewer from "../components/TaskDefin... | // This file is part of BenchExec, a framework for reliable benchmarking:
// https://github.com/sosy-lab/benchexec
//
// SPDX-FileCopyrightText: 2019-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
import React from "react";
import TaskDefinitionViewer from "../components/TaskDefin... |
Change time frequency: one virtual day per second | import React, { PropTypes, Component } from 'react'
import moment from 'moment'
import eventActions from '../actions/eventActionCreators'
const TIME_INIT = moment('2190-07-02').utc()
const DELAY = 1000
class Time extends Component {
componentWillMount () {
this.setState({ time: TIME_INIT })
}
componentDid... | import React, { PropTypes, Component } from 'react'
import moment from 'moment'
import eventActions from '../actions/eventActionCreators'
const TIME_INIT = moment('2190-07-02').utc()
const DELAY = 250
class Time extends Component {
componentWillMount () {
this.setState({ time: TIME_INIT })
}
componentDidM... |
Fix the name of the COURSE_DISCOVERY_CFG variable to match what is configured in edx/configuration | from os import environ
import yaml
from edx_course_discovery.settings.base import *
from edx_course_discovery.settings.utils import get_env_setting
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['*']
LOGGING = environ.get('LOGGING', LOGGING)
CONFIG_FILE = get_env_setting('COURSE_DISCOVERY_CFG')
with open(C... | from os import environ
import yaml
from edx_course_discovery.settings.base import *
from edx_course_discovery.settings.utils import get_env_setting
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['*']
LOGGING = environ.get('LOGGING', LOGGING)
CONFIG_FILE = get_env_setting('EDX_COURSE_DISCOVERY_CFG')
with op... |
Add 'All' option to lists | from pymongo import MongoClient
def main():
client = MongoClient()
db = client.cityhotspots
db.drop_collection('dineroptions')
diners_collection = db.diners
doc = {}
diner_options_collection = db.dineroptions
doc['categories'] = diners_collection.distinct('category')
doc['categories']... | from pymongo import MongoClient
def main():
client = MongoClient()
db = client.cityhotspots
db.drop_collection('dineroptions')
diners_collection = db.diners
doc = {}
diner_options_collection = db.dineroptions
doc['categories'] = diners_collection.distinct('category')
doc['cuisines'] =... |
Replace @represent w/ @config throughout
New name, same functionality. | from tangled.web import Resource, config
from tangled.site.resources.entry import Entry
class Docs(Entry):
@config('text/html', template_name='tangled.website:templates/docs.mako')
def GET(self):
static_dirs = self.app.get_all('static_directory', as_dict=True)
links = []
for prefix, ... | from tangled.web import Resource, represent
from tangled.site.resources.entry import Entry
class Docs(Entry):
@represent('text/html', template_name='tangled.website:templates/docs.mako')
def GET(self):
static_dirs = self.app.get_all('static_directory', as_dict=True)
links = []
for pr... |
Set the module as auto_install
So it installs when both sale_payment_method and sale_automatic_workflow are installed.
This module acts as the glue between them | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... |
Allow NULL values in transformers. | <?php
namespace CatLab\Charon\Transformers;
use CatLab\Charon\Exceptions\InvalidPropertyException;
use CatLab\Charon\Interfaces\Context;
use CatLab\Charon\Interfaces\Transformer;
/**
* Class DateTransformer
* @package CatLab\Charon\Transformers
*/
class DateTransformer implements Transformer
{
protected $form... | <?php
namespace CatLab\Charon\Transformers;
use CatLab\Charon\Exceptions\InvalidPropertyException;
use CatLab\Charon\Interfaces\Context;
use CatLab\Charon\Interfaces\Transformer;
/**
* Class DateTransformer
* @package CatLab\Charon\Transformers
*/
class DateTransformer implements Transformer
{
protected $form... |
Fix Assigning Themes To Inputs
Fix the assigning the themes to inputs because Unbound Input is the only
input that uses Higher Order Components and is the only input that has
originialClass Props inside of them for the theme to attach to. | import Form from "./components/form.js"
import Input from "./components/input.js"
import UnboundInput from "./components/unbound_input.js"
import Submit from "./components/submit.js"
import FormErrorList from "./components/form_error_list.js"
import Fieldset from "./components/fieldset.js"
import FieldsetText from "./c... | import Form from "./components/form.js"
import Input from "./components/input.js"
import UnboundInput from "./components/unbound_input.js"
import Submit from "./components/submit.js"
import FormErrorList from "./components/form_error_list.js"
import Fieldset from "./components/fieldset.js"
import FieldsetText from "./c... |
Add parameter to UML constants | /**
* Created by Leandro Luque on 24/07/17.
*/
/* JSHint configurations */
/* jshint esversion: 6 */
/* jshint -W097 */
'use strict';
// A.
const ATTRIBUTE = "A1";
// C.
const CLASS = "C1";
// D.
const DEFAULT = "~";
// I.
const INITIAL_VALUE = "I1";
const INTERFACE = "I2";
const IS_ABSTRACT = "I3";
const... | /**
* Created by Leandro Luque on 24/07/17.
*/
/* JSHint configurations */
/* jshint esversion: 6 */
/* jshint -W097 */
'use strict';
// A.
const ATTRIBUTE = "A1";
// C.
const CLASS = "C1";
// D.
const DEFAULT = "~";
// I.
const INITIAL_VALUE = "I1";
const INTERFACE = "I2";
const IS_ABSTRACT = "I3";
const... |
Allow public download from S3 | 'use stirct'
var opbeat = require('opbeat').start()
var uuid = require('node-uuid')
var AWS = require('aws-sdk')
var Printer = require('ipp-printer')
var port = process.env.PORT || 3000
var s3 = new AWS.S3()
var printer = new Printer({ name: 'printbin', port: port, zeroconf: false })
printer.on('job', function (job... | 'use stirct'
var opbeat = require('opbeat').start()
var uuid = require('node-uuid')
var AWS = require('aws-sdk')
var Printer = require('ipp-printer')
var port = process.env.PORT || 3000
var s3 = new AWS.S3()
var printer = new Printer({ name: 'printbin', port: port, zeroconf: false })
printer.on('job', function (job... |
Add missing words to comment
+review REVIEW-6446 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... |
Add ability to add your own data in export (exporter.getJSON) | export default class Exporter {
constructor(editor) {
this.editor = editor;
}
getData() {
var tweenTime = this.editor.tweenTime;
var domain = this.editor.timeline.x.domain();
var domain_start = domain[0];
var domain_end = domain[1];
return {
settings: {
time: tweenTime.timer... | export default class Exporter {
constructor(editor) {
this.editor = editor;
}
getData() {
var tweenTime = this.editor.tweenTime;
var domain = this.editor.timeline.x.domain();
var domain_start = domain[0];
var domain_end = domain[1];
return {
settings: {
time: tweenTime.timer... |
Add status and exam in test Biopsy | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import models
from biopsy.models import Biopsy
class BiopsyTest(TestCase):
def biopy_test(self):
biopsy = Biopsy(
clinical_information= "clinica",
macroscopic= "macroscopia",
microscopic= "microscopia",
conclusion= "conclusao",
... | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import models
from biopsy.models import Biopsy
class BiopsyTest(TestCase):
def biopy_test(self):
biopsy = Biopsy(
clinical_information= "clinica",
macroscopic= "macroscopia",
microscopic= "microscopia",
conclusion= "conclusao",
... |
Fix extras_require for test deps | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from os import path
import sys
install_requires = [
'itsdangerous',
'msgpack-python',
'pysha3',
'six',
]
extras_require = {
'test': [
'coverage',
'nose',
],
}
if sys.version_info < (3, 4... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from os import path
import sys
install_requires = [
'itsdangerous',
'msgpack-python',
'pysha3',
'six',
]
extras_require = {
'test': [
'coverage',
'nose',
],
}
if sys.version_info < (3, 4... |
Add all of the states | /*global exports */
(function () {
"use strict";
var popularNamesPerState = function(req, res) {
var body = JSON.stringify([
{name: 'Smith', geo: {lat: -36.64, lon: 144.11}},
{name: 'Smith', geo: {lat: -31.0, lon: 146.4}},
{name: 'Smith', geo: {lat: -24.9, lon: 145.... | /*global exports */
(function () {
"use strict";
var popularNamesPerState = function(req, res) {
var body = JSON.stringify([
{name: 'Smith', geo: {lat: -37.716, lon: 144.891}},
{name: 'Jones', geo: {lat: -41.218, lon: 1446.188}},
{name: 'Nyuan', geo: {lat: -25.173, ... |
Simplify code loading MNIST dataset. | import os
import gzip
import pickle
import sys
# Python 2/3 compatibility.
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
'''Adapted from theano tutorial'''
def load_mnist(data_file = os.path.join(os.path.dirname(__file__), 'mnist.pkl.gz')):
if not os.pa... | import os
import gzip
import pickle
import sys
# Python 2/3 compatibility.
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
'''Adapted from theano tutorial'''
def load_mnist(data_file = os.path.join(os.path.dirname(__file__), 'mnist.pkl.gz')):
if not os.pa... |
Set audit job to Tuesday. | export default (app) => {
app.jobs.schedule('send audit email', '0 21 * * TUE', async () => {
app.info('CRON: sending audit email - starting')
const mailerConfig = app.get('mailer')
const recipients =
mailerConfig.auditRecipients && mailerConfig.auditRecipients.split(',')
app.info(`recipients:... | export default (app) => {
app.jobs.schedule('send audit email', '0 16 * * 5', async () => {
app.info('CRON: sending audit email - starting')
const mailerConfig = app.get('mailer')
const recipients =
mailerConfig.auditRecipients && mailerConfig.auditRecipients.split(',')
app.info(`recipients: $... |
Remove wpautop for full width template | <?php
/**
* Template Name: Full Width
*
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site may use a
* different template.
*
* @link https://codex.word... | <?php
/**
* Template Name: Full Width
*
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site may use a
* different template.
*
* @link https://codex.word... |
Fix building Mono 32-bit with Mac 10.7 SDK | class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10.6',
sources = [
'http://download.mono-project.com/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--wit... | class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10.6',
sources = [
'http://download.mono-project.com/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--wit... |
packer/rpc: Use the proper Server for tests | package rpc
import (
"cgl.tideland.biz/asserts"
"net/rpc"
"testing"
)
type testUi struct {
sayCalled bool
sayFormat string
sayVars []interface{}
}
func (u *testUi) Say(format string, a ...interface{}) {
u.sayCalled = true
u.sayFormat = format
u.sayVars = a
}
func TestUiRPC(t *testing.T) {
assert := assert... | package rpc
import (
"cgl.tideland.biz/asserts"
"net/rpc"
"testing"
)
type testUi struct {
sayCalled bool
sayFormat string
sayVars []interface{}
}
func (u *testUi) Say(format string, a ...interface{}) {
u.sayCalled = true
u.sayFormat = format
u.sayVars = a
}
func TestUiRPC(t *testing.T) {
assert := assert... |
Use _.uniqueId() instead of Math.random() for dummy badges | import _ from 'underscore';
import { PROJECT_BADGE } from '~/badges/constants';
import { DUMMY_IMAGE_URL, TEST_HOST } from 'spec/test_constants';
export const createDummyBadge = () => {
const id = _.uniqueId();
return {
id,
imageUrl: `${TEST_HOST}/badges/${id}/image/url`,
isDeleting: false,
linkUrl... | import { PROJECT_BADGE } from '~/badges/constants';
import { DUMMY_IMAGE_URL, TEST_HOST } from 'spec/test_constants';
export const createDummyBadge = () => {
const id = Math.floor(1000 * Math.random());
return {
id,
imageUrl: `${TEST_HOST}/badges/${id}/image/url`,
isDeleting: false,
linkUrl: `${TES... |
Change to more generic variable names in _fill_queue | from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
... | from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
... |
Append missing slash to fix expert request URL. | // @ngInject
export default function expertRequestsService(baseServiceClass, $q, $http, ENV) {
let ServiceClass = baseServiceClass.extend({
filterByCustomer: false,
init: function () {
this._super();
this.endpoint = '/expert-requests/';
},
create: function (expertRequest) {
return ... | // @ngInject
export default function expertRequestsService(baseServiceClass, $q, $http, ENV) {
let ServiceClass = baseServiceClass.extend({
filterByCustomer: false,
init: function () {
this._super();
this.endpoint = '/expert-requests/';
},
create: function (expertRequest) {
return ... |
Remove duplicate default progress condition. | package de.iani.cubequest.quests;
import de.iani.cubequest.Reward;
import de.iani.cubequest.conditions.ServerFlagCondition;
public abstract class EconomyInfluencingAmountQuest extends AmountQuest {
public static final String SURVIVAL_ECONOMY_TAG = "survival_economy";
public EconomyInfluen... | package de.iani.cubequest.quests;
import de.iani.cubequest.Reward;
import de.iani.cubequest.conditions.GameModeCondition;
import de.iani.cubequest.conditions.ServerFlagCondition;
import org.bukkit.GameMode;
public abstract class EconomyInfluencingAmountQuest extends AmountQuest {
public static fin... |
Fix and add tests for datastore.inmemory | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase,
MixInNestableTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixIn... | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
... |
Fix bug: replace static::class by get_class() | <?php namespace ThibaudDauce\MoloquentInheritance;
use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;
class MoloquentInheritanceScope implements ScopeInterface {
/**
* All of the extensions to be added to the builder.
*
* @var array
*/
protected $extensions = ['OnlyP... | <?php namespace ThibaudDauce\MoloquentInheritance;
use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;
class MoloquentInheritanceScope implements ScopeInterface {
/**
* All of the extensions to be added to the builder.
*
* @var array
*/
protected $extensions = ['OnlyP... |
Implement OPTIONS verb API handler | /*
* Copyright 2015 - 2016 Anton Tananaev (anton.tananaev@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless req... | /*
* Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required b... |
Copy and paste is the devil | package stream.flarebot.flarebot.mod.modlog;
public enum ModAction {
BAN(true, ModlogEvent.USER_BANNED),
FORCE_BAN(true, ModlogEvent.USER_BANNED),
TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED),
UNBAN(false, ModlogEvent.USER_UNBANNED),
KICK(true, ModlogEvent.USER_KICKED),
TEMP_MUTE(true, Modlo... | package stream.flarebot.flarebot.mod.modlog;
public enum ModAction {
BAN(true, ModlogEvent.USER_BANNED),
FORCE_BAN(true, ModlogEvent.USER_BANNED),
TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED),
UNBAN(false, ModlogEvent.USER_UNBANNED),
KICK(true, ModlogEvent.USER_KICKED),
TEMP_MUTE(true, Modlo... |
Add 'comment_id' parameter in 'delete_comment' url | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new... | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new... |
Enable '-h' help option from the pdtools root level. | """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
... | """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
... |
Use isinstance to check type
This should also allow to use subtypes like a SortedDict
to pass in headers. | from __future__ import absolute_import
from .base import BaseDataset
class SimpleDataset(BaseDataset):
def __init__(self, queryset, headers=None):
self.queryset = queryset
if headers is None:
fields = queryset.model._meta.fields
self.header_list = [field.name for field in f... | from __future__ import absolute_import
from .base import BaseDataset
class SimpleDataset(BaseDataset):
def __init__(self, queryset, headers=None):
self.queryset = queryset
if headers is None:
fields = queryset.model._meta.fields
self.header_list = [field.name for field in f... |
Fix Google Translator request & processing | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import requests
import json
def save_google_translation(queue, source_text, translate_from='et', translate_to='en'):
translation = ''
try:
begin = time.time()
translation = google_translation(source_text,
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import requests
def save_google_translation(queue, source_text, client_id, client_secret, translate_from='et', translate_to='en'):
translation = ''
try:
begin = time.time()
translation = google_translation(source_text,
... |
Prepare for adding to pypi | from setuptools import setup, find_packages
version = '0.2'
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
long_description = "Whitespace interpreter written in Python 3"
setup(
name='whitepy',
version=version,
author='Yasser Nabi',... | from setuptools import setup, find_packages
try:
import pypandoc
long_description=pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
long_description = "Whitespace interpreter written in Python 3"
setup(
name='whitepy',
version='0.0.1',
author='Yasser Nabi',
author_email='... |
Set default user name on persistent URLs | /*
* Copyright (C) 2015 SUSE Linux
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE.txt file for details.
*/
(function () {
'use strict';
angular.module('janusHangouts')
.service('StatesService', StatesService);
StatesService.$inject = ['$q', '$s... | /*
* Copyright (C) 2015 SUSE Linux
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE.txt file for details.
*/
(function () {
'use strict';
angular.module('janusHangouts')
.service('StatesService', StatesService);
StatesService.$inject = ['$q', '$s... |
Update version number to 0.1.2 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='llvmcpy',
version='... | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='llvmcpy',
version='... |
Modify export of FileIcons singleton | 'use babel';
import fs from 'fs-plus';
import path from 'path';
class FileIcons {
constructor() {
this.service = null;
}
setService(service) {
this.service = service;
}
resetService() {
this.service = null;
}
getIconClassForPath(filePath) {
return this.service
? this.service.ico... | 'use babel';
import fs from 'fs-plus';
import path from 'path';
class FileIcons {
constructor() {
this.service = null;
}
setService(service) {
this.service = service;
}
resetService() {
this.service = null;
}
getIconClassForPath(filePath) {
return this.service
? this.service.ico... |
Update javascript to use native API | function do_command(item, command, val) {
var data = {};
if (val != undefined) {
data["val"] = val;
}
$.get("/api/item/" + item + "/command/" + command, data);
}
function do_scene(scene, action) {
$.get("/api/scene/" + scene + "/command/" + (action?action:""));
}
$(function() {
$(".command")... | function do_command(item, command, val) {
var data = {};
data[item] = command;
if (val != undefined) {
data["value"] = val;
}
$.get("/CMD", data);
}
function do_scene(scene, action) {
$.get("/api/scene/" + scene + "/command/" + (action?action:""));
}
$(function() {
$(".command").each(fun... |
Rename url -> expected_url; Add URLsMixin | from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLsMixin(object):
"""A TestCase Mixin with a check_url helper method for testing urls"""
def check_url(self, view_class, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
... | from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLsTestCase(TestCase):
"""A TestCase with a check_url helper method for testing urls"""
def check_url(self, view_class, url, url_name, url_args=None, url_kwargs=None):
"""
Assert a view's url is corr... |
[REMOVE] Remove unused FormLogin in admin app | from django.contrib.auth.models import User
from django import forms
from apps.categories.models import *
from apps.books.models import *
class CategoryForm(forms.ModelForm):
"""docstring for CategoryForm"""
class Meta:
model = Category
fields = '__all__'
class BookForm(forms... | from django.contrib.auth.models import User
from django import forms
from apps.categories.models import *
from apps.books.models import *
class LoginForm(forms.ModelForm):
"""docstring for LoginForm"""
class Meta:
model = User
fields = ['username', 'password']
class CategoryForm(forms.ModelFo... |
Fix error with no space before tag | #! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#(... | #! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('\{#([a-z... |
Fix python object searilization problem in yaml | import io
import glob
import yaml
import logging
import os
from uuid import uuid4
from jinja2 import Template
logger = logging.getLogger(__name__)
def create_dir(dir_path):
logger.debug(u'Creating directory %s', dir_path)
if not os.path.isdir(dir_path):
os.makedirs(dir_path)
def yaml_load(file_pa... | import io
import glob
import yaml
import logging
import os
from uuid import uuid4
from jinja2 import Template
logger = logging.getLogger(__name__)
def create_dir(dir_path):
logger.debug(u'Creating directory %s', dir_path)
if not os.path.isdir(dir_path):
os.makedirs(dir_path)
def yaml_load(file_pa... |
Support for pushing to a queue via observer. | var Rx = require('rx'),
_ = require('lodash');
function receiveMessage(sqs, params, callback) {
sqs.receiveMessage(params, function (err, data) {
callback(err, data);
receiveMessage(sqs, params, callback);
});
}
exports.observerFromQueue = function (sqs, params) {
return Rx.Observer.cr... | var Rx = require('rx'),
_ = require('lodash');
function readMessage(sqs, params, callback) {
sqs.receiveMessage(params, function (err, data) {
callback(err, data);
readMessage(sqs, params, callback);
});
}
exports.observableFromQueue = function (sqs, params) {
return Rx.Observable.crea... |
Fix bug, use instance and not classes as storage | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache Licens... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache Licens... |
Telemetry: Add name attribute to each Page in ServiceWorkerPageSet
ServiceWorkerPerfTest loads the same page three times, but these should
have different characteristics because ServiceWorker works differently.
This patch gives each page load a name so we can track them separately.
BUG=
TEST=tools/perf/run_benchmark ... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page
from telemetry.page import page_set as page_set
archive_data_file_path = 'data/service_worker.json'
class Service... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page
from telemetry.page import page_set as page_set
archive_data_file_path = 'data/service_worker.json'
class Service... |
Load includes from within the api directory | <?php
/*
* Show debug code.
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
/*
* Load Composer requirements.
*/
require 'vendor/autoload.php';
/*
* Establish our routing table.
*/
$router = array();
$router['registrars'] = 'registrars';
$router['validator'] = 'validator';
$router['submit'] = 'submit';... | <?php
/*
* Show debug code.
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
/*
* Load Composer requirements.
*/
require 'vendor/autoload.php';
/*
* Establish our routing table.
*/
$router = array();
$router['registrars'] = 'registrars';
$router['validator'] = 'validator';
$router['submit'] = 'submit';... |
Replace markdown lib in test config | 'use strict';
module.exports = function(config) {
var files = [];
[
'jquery-1.8.2-min.js',
'angular.js',
'angular-resource.js',
'angular-mocks.js',
'angular-ui-states.js',
'lodash.js',
'markdown/marked.js'
].forEach(function(file) {
files.pu... | 'use strict';
module.exports = function(config) {
var files = [];
[
'jquery-1.8.2-min.js',
'angular.js',
'angular-resource.js',
'angular-mocks.js',
'angular-ui-states.js',
'lodash.js'
].forEach(function(file) {
files.push('app/vendor/' + file);
... |
Add a fix so users can touch the text in the boxes with out me getting
in the way. | // ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepun... | // ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepun... |
Allow for the failure of getServiceInfo(). Not sure why it's happening,
though. | from Zeroconf import *
import socket
class MyListener(object):
def __init__(self):
self.r = Zeroconf()
pass
def removeService(self, zeroconf, type, name):
print "Service", name, "removed"
def addService(self, zeroconf, type, name):
print "Service", name, "added"
print "Type is", type
inf... | from Zeroconf import *
import socket
class MyListener(object):
def __init__(self):
self.r = Zeroconf()
pass
def removeService(self, zeroconf, type, name):
print "Service", name, "removed"
def addService(self, zeroconf, type, name):
print "Service", name, "added"
print "Type is", type
inf... |
Fix node to set sentAuth whenever the object was generated | package network.thunder.core.communication;
import network.thunder.core.communication.objects.subobjects.AuthenticationObject;
public class Node {
private byte[] pubkey;
private boolean isAuth;
private boolean sentAuth;
private boolean authFinished;
private boolean isReady;
private boolean hasOpenChannel;
pub... | package network.thunder.core.communication;
import network.thunder.core.communication.objects.subobjects.AuthenticationObject;
public class Node {
private byte[] pubkey;
private boolean isAuth;
private boolean sentAuth;
private boolean authFinished;
private boolean isReady;
private boolean hasOpenChannel;
pub... |
Fix dispatcher stopping bug when using <Listener> component | const React = require("react")
const {merge} = require("./util")
export class Listener extends React.Component {
constructor(props) {
super(props)
const {dispatcher, initialState} = this.props
const ffux = dispatcher(initialState)
this.state = {
ffux,
model: {
state: ffux.getInit... | const React = require("react")
const {merge} = require("./util")
export class Listener extends React.Component {
constructor(props) {
super(props)
const {dispatcher, initialState} = this.props
const ffux = dispatcher(initialState)
this.state = {
ffux,
model: {
state: ffux.getInit... |
Make the item creation operation its own method. It was getting a bit convoluted as an inline callback | jsio('from common.javascript import Class')
jsio('import tasks.panels.Panel')
jsio('import ui.Button')
exports = Class(tasks.panels.Panel, function(supr) {
this._className += ' ListPanel'
this._width = 260
this._left = 150
this._createContent = function() {
supr(this, '_createContent')
var taskButton = ... | jsio('from common.javascript import Class')
jsio('import tasks.panels.Panel')
jsio('import ui.Button')
exports = Class(tasks.panels.Panel, function(supr) {
this._className += ' ListPanel'
this._width = 260
this._left = 150
this._createContent = function() {
supr(this, '_createContent')
var taskButton = ... |
Fix alembic revision after merge master | """text to JSON
Revision ID: 151b2f642877
Revises: ac115763654
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'ac115763654'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN in... | """text to JSON
Revision ID: 151b2f642877
Revises: aee7291c81
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'aee7291c81'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN info... |
Add a space between end of text output | <?php
namespace exussum12\CoverageChecker\Outputs;
use exussum12\CoverageChecker\Output;
class Text implements Output
{
public function output($coverage, $percent, $minimumPercent)
{
printf("%.2f%% Covered\n", $percent);
$output = '';
foreach ($coverage as $filename => $lines) {
... | <?php
namespace exussum12\CoverageChecker\Outputs;
use exussum12\CoverageChecker\Output;
class Text implements Output
{
public function output($coverage, $percent, $minimumPercent)
{
printf("%.2f%% Covered\n", $percent);
$output = '';
foreach ($coverage as $filename => $lines) {
... |
Use the environment secret key instead of default one | <?php
$config = array();
// Generals
$config['db_dsnw'] = 'sqlite:////data/roundcube.db';
$config['des_key'] = getenv('SECRET_KEY');
$config['identities_level'] = 3;
$config['reply_all_mode'] = 1;
// List of active plugins (in plugins/ directory)
$config['plugins'] = array(
'archive',
'zipdownload',
'mar... | <?php
$config = array();
// Generals
$config['db_dsnw'] = 'sqlite:////data/roundcube.db';
$config['des_key'] = 'rcmail-!24ByteDESkey*Str';
$config['identities_level'] = 3;
$config['reply_all_mode'] = 1;
// List of active plugins (in plugins/ directory)
$config['plugins'] = array(
'archive',
'zipdownload',
... |
Fix missing parameter to pass tests | const express = require('express')
const ERRORS = require('../../errors')
const User = require('../../models/User')
const utils = require('../../utils')
const router = express.Router()
router.post('/', register)
function register(req, res, next) {
const { body: { username, password } } = req
if (!username || !... | const express = require('express')
const ERRORS = require('../../errors')
const User = require('../../models/User')
const utils = require('../../utils')
const router = express.Router()
router.post('/', register)
function register(req, res, next) {
const { body: { username, password } } = req
if (!username || !... |
Update bower @ Uninstall angular-material-data-table | /**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
... | /**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
... |
Fix test on Django 1.9 | from django import template
from django.utils.safestring import mark_safe
from lazy_tags.decorators import lazy_tag
register = template.Library()
@register.simple_tag
def test():
return mark_safe('<p>hello world</p>')
@register.simple_tag
@lazy_tag
def test_decorator():
return 'Success!'
@register.simp... | from django import template
from lazy_tags.decorators import lazy_tag
register = template.Library()
@register.simple_tag
def test():
return '<p>hello world</p>'
@register.simple_tag
@lazy_tag
def test_decorator():
return 'Success!'
@register.simple_tag
@lazy_tag
def test_simple_dec_args(arg, kwarg=None... |
Change worker stats api url | import Promise from 'bluebird';
import request from 'superagent';
import camelcase from 'camelcase';
import snakecase from 'snake-case';
import _ from 'lodash';
Promise.promisifyAll(request);
export function transformForFrontend(payload) {
_.forOwn(payload, (value, key) => {
if (camelcase(key) !== key) {
... | import Promise from 'bluebird';
import request from 'superagent';
import camelcase from 'camelcase';
import snakecase from 'snake-case';
import _ from 'lodash';
Promise.promisifyAll(request);
export function transformForFrontend(payload) {
_.forOwn(payload, (value, key) => {
if (camelcase(key) !== key) {
... |
Enable disk and memory caching | package de.eightbitboy.hijacr;
import android.app.Application;
import com.crashlytics.android.Crashlytics;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.Di... | package de.eightbitboy.hijacr;
import android.app.Application;
import com.crashlytics.android.Crashlytics;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.Im... |
Allow for specifying a subclass of GeocodedLocation | /*
*
* * Licensed to the Apache Software Foundation (ASF) under one or more
* * contributor license agreements. See the NOTICE file distributed with
* * this work for additional information regarding copyright ownership.
* * The ASF licenses this file to You under the Apache License, Version 2.0
* * (the "L... | /*
*
* * Licensed to the Apache Software Foundation (ASF) under one or more
* * contributor license agreements. See the NOTICE file distributed with
* * this work for additional information regarding copyright ownership.
* * The ASF licenses this file to You under the Apache License, Version 2.0
* * (the "L... |
Add role property to mark item. | import Bounds from './Bounds';
import GroupItem from './GroupItem';
export default function Scenegraph() {
this.root = createMark({
marktype: 'group',
interactive: false
});
this.root.items = [new GroupItem(this.root)];
}
var prototype = Scenegraph.prototype;
prototype.select = function(path, markdef) ... | import Bounds from './Bounds';
import GroupItem from './GroupItem';
export default function Scenegraph() {
this.root = createMark({
marktype: 'group',
interactive: false
});
this.root.items = [new GroupItem(this.root)];
}
var prototype = Scenegraph.prototype;
prototype.select = function(path, markdef) ... |
Fix tests so they complete without auth info. | var vows = require('vows');
var assert = require('assert');
var winston = require('winston');
var helpers = require('winston/test/helpers');
var SQS = require('../lib/winston-sqs').SQS;
var transport = new (SQS)({
aws_queueurl: "queueurl",
aws_accesskeyid: "publickey",
aws_secretaccesskey: "secretkey"
});
... | var vows = require('vows');
var assert = require('assert');
var winston = require('winston');
var helpers = require('winston/test/helpers');
var SQS = require('../lib/winston-sqs').SQS;
var transport = new (SQS)({
aws_queueurl: "queueurl",
aws_accesskeyid: "publickey",
aws_secretaccesskey: "secretkey"
});
... |
:crescent_moon: Enable 'dark mode' by default | import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
const UiContext = createContext({
uiDarkMode: true,
uiIsLoading: false,
uiIsAnimating: false,
});
const UiProvider = ({ children }) => {
const [uiDarkMode, setUiDarkMode] = useState(true);
const [uiIsLoading, setUiIs... | import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
const UiContext = createContext({
uiDarkMode: false,
uiIsLoading: false,
uiIsAnimating: false,
});
const UiProvider = ({ children }) => {
const [uiDarkMode, setUiDarkMode] = useState(false);
const [uiIsLoading, setUi... |
Remove course from courses list when refunded | import { find } from 'lodash';
import moment from 'moment';
import {
BaseModel, identifiedBy, field, identifier, belongsTo, computed, observable,
} from '../base';
import Courses from '../courses-map';
import { TimeStore } from '../../flux/time';
@identifiedBy('purchase/product')
class Product extends BaseModel {
@... | import { find } from 'lodash';
import moment from 'moment';
import {
BaseModel, identifiedBy, field, identifier, belongsTo, computed, observable,
} from '../base';
import { TimeStore } from '../../flux/time';
@identifiedBy('purchase/product')
class Product extends BaseModel {
@identifier uuid;
@field name;
@fi... |
Add string representation for colors | class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __repr__(self):
return '%s,%s,%s' % (self.r, self.g, self.b)
__unicode__ = __repr__
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = na... | class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
... |
Add organization_set field in UserF | from datetime import timedelta
from django.utils import timezone
from locarise_drf_oauth2_support.users.models import User
try:
import factory
class UserF(factory.DjangoModelFactory):
first_name = factory.Sequence(lambda n: "first_name%s" % n)
last_name = factory.Sequence(lambda n: "last_name... | from datetime import timedelta
from django.utils import timezone
from locarise_drf_oauth2_support.users.models import User
try:
import factory
class UserF(factory.DjangoModelFactory):
first_name = factory.Sequence(lambda n: "first_name%s" % n)
last_name = factory.Sequence(lambda n: "last_name... |
Revert "[Core] Okay maybe this?"
This reverts commit 1fda217b32310c0db4e3a5e5b337071eeee376d1. |
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = ModuleAccessLevels.ANYONE
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
de... |
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = 1
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, me... |
Validate UK phone numbers correctly. | <?php namespace VotingApp\Providers;
use Illuminate\Support\ServiceProvider;
class ValidationServiceProvider extends ServiceProvider {
/**
* The validator instance
*
* @var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Bootstrap the application services.
*
* @retur... | <?php namespace VotingApp\Providers;
use Illuminate\Support\ServiceProvider;
class ValidationServiceProvider extends ServiceProvider {
/**
* The validator instance
*
* @var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Bootstrap the application services.
*
* @retur... |
Add "box.text" back to namespaced package | # coding: utf-8
from __future__ import unicode_literals
from setuptools import setup, find_packages
from os.path import dirname, join
def main():
base_dir = dirname(__file__)
setup(
name='genty',
version='0.0.1',
description='Allows you to run a test with multiple data sets',
... | # coding: utf-8
from __future__ import unicode_literals
from setuptools import setup, find_packages
from os.path import dirname, join
def main():
base_dir = dirname(__file__)
setup(
name='genty',
version='0.0.1',
description='Allows you to run a test with multiple data sets',
... |
Fix parsing irc messages with empty list of parameters | from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command... | from collections import namedtuple
IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix')
def parse(line):
""" Parses line and returns a named tuple IRCMsg
with fields (prefix, cmd, params, postfix).
- prefix is the first part starting with : (colon), without the :
- cmd is the command... |
Use bootstrap input styles to shrink quantity field width | # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args,... | # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args,... |
Tweak comment text for clarity | import urllib
import urlparse
def add_query_params(url, params):
"""
Inject additional query parameters into an existing URL. If
parameters already exist with the same name, they will be
overwritten. Return the modified URL as a string.
"""
# If any of the additional parameters have empty valu... | import urllib
import urlparse
def add_query_params(url, params):
"""
Inject additional query parameters into an existing URL. If
existing parameters already exist with the same name, they
will be overwritten.
Return the modified URL as a string.
"""
# If any of the additional parameters h... |
Fix teardown of resize handler in content management screen
refs #5659 ([comment](https://github.com/TryGhost/Ghost/issues/5659#issuecomment-137114898))
- cleans up resize handler on willDestroy hook of gh-content-view-container | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'section',
classNames: ['gh-view', 'content-view-container'],
previewIsHidden: false,
resizeService: Ember.inject.service(),
_resizeListener: null,
calculatePreviewIsHidden: function () {
if (this.$('.conten... | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'section',
classNames: ['gh-view', 'content-view-container'],
previewIsHidden: false,
resizeService: Ember.inject.service(),
calculatePreviewIsHidden: function () {
if (this.$('.content-preview').length) {
... |
Increase the timeout for Redis connections | package org.icij.extract.cli.factory;
import org.apache.commons.cli.CommandLine;
import org.redisson.Config;
/**
* Factory methods for creating Redis configuration.
*
* @author Matthew Caruana Galizia <mcaruana@icij.org>
* @since 1.0.0-beta
*/
public class RedisConfigFactory {
/**
* Create a new Redis confi... | package org.icij.extract.cli.factory;
import org.apache.commons.cli.CommandLine;
import org.redisson.Config;
/**
* Factory methods for creating Redis configuration.
*
* @author Matthew Caruana Galizia <mcaruana@icij.org>
* @since 1.0.0-beta
*/
public class RedisConfigFactory {
/**
* Create a new Redis confi... |
Remove the encode password. Cannot find a way to get this to work properly unfortunately. | <?php
/**
* This file is part of the LdapTools package.
*
* (c) Chad Sikorra <Chad.Sikorra@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace spec\LdapTools\AttributeConverter;
use PhpSpec\ObjectBehavior;
use Pr... | <?php
/**
* This file is part of the LdapTools package.
*
* (c) Chad Sikorra <Chad.Sikorra@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace spec\LdapTools\AttributeConverter;
use PhpSpec\ObjectBehavior;
use Pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.