text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix pep8 to pass super checks | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software... |
Insert the current directory to the front of sys.path -- and remove it
at the end. This fixes a problem where
python Lib/test/test_import.py
failed while "make test" succeeded. | from test_support import TESTFN
import os
import random
import sys
sys.path.insert(0, os.curdir)
source = TESTFN + ".py"
pyc = TESTFN + ".pyc"
pyo = TESTFN + ".pyo"
f = open(source, "w")
print >> f, "# This will test Python's ability to import a .py file"
a = random.randrange(1000)
b = random.randrange(1000)
print ... | from test_support import TESTFN
import os
import random
source = TESTFN + ".py"
pyc = TESTFN + ".pyc"
pyo = TESTFN + ".pyo"
f = open(source, "w")
print >> f, "# This will test Python's ability to import a .py file"
a = random.randrange(1000)
b = random.randrange(1000)
print >> f, "a =", a
print >> f, "b =", b
f.clos... |
Convert Unix path to Windows path in jshint command (in node_modules)
Story #103 | 'use strict';
var exec = require('child_process').exec;
var path = require('path');
function fail() {
process.stdout.write(
'Style check failed (see the above output).\n' +
'If you still wish to commit your code, run git commit -n to skip this check.\n'
);
process.exit(1);
}
exec('git diff --staged --name-sta... | 'use strict';
var exec = require('child_process').exec;
function fail() {
process.stdout.write(
'Style check failed (see the above output).\n' +
'If you still wish to commit your code, run git commit -n to skip this check.\n'
);
process.exit(1);
}
exec('git diff --staged --name-status', function (error, stdou... |
Use get_or_create to avoid duplicate objects | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
import uuid
from cla_common.constants import RESEARCH_CONTACT_VIA
def create_default_contact_for_research_methods(apps, schema_editor):
ContactResearchMethods = apps.get_model("legalaid", "ContactResearchMethod")
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
import uuid
from cla_common.constants import RESEARCH_CONTACT_VIA
def create_default_contact_for_research_methods(apps, schema_editor):
ContactResearchMethods = apps.get_model("legalaid", "ContactResearchMethod")
... |
Fix for new version of slack
change span.message_content to div.messagee_content | $(function() {
// https://github.com/naugtur/insertionQuery
var anime_watch = function(selector, callback) {
var guid = selector.replace(/[^a-zA-Z0-9]+/g, "_") +"_"+ ((new Date()).getTime());
$("<style/>").html([
"@-webkit-keyframes {guid} { from { clip: rect(auto, auto, auto, auto); } to { clip: rect(auto, a... | $(function() {
// https://github.com/naugtur/insertionQuery
var anime_watch = function(selector, callback) {
var guid = selector.replace(/[^a-zA-Z0-9]+/g, "_") +"_"+ ((new Date()).getTime());
$("<style/>").html([
"@-webkit-keyframes {guid} { from { clip: rect(auto, auto, auto, auto); } to { clip: rect(auto, a... |
Add an example for a nonstrict named parameter method | /**
* Copyright 2010-2014 Ralph Schaer <ralphschaer@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 by... | /**
* Copyright 2010-2014 Ralph Schaer <ralphschaer@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 by... |
Fix _time_to_micros bug. It was calling time.time() when it should use its own argument. | """ Utility functions
"""
import random
import time
from . import constants
def _service_url_from_hostport(secure, host, port):
"""
Create an appropriate service URL given the parameters.
`secure` should be a bool.
"""
if secure:
protocol = 'https://'
else:
protocol = 'http://'... | """ Utility functions
"""
import random
import time
from . import constants
def _service_url_from_hostport(secure, host, port):
"""
Create an appropriate service URL given the parameters.
`secure` should be a bool.
"""
if secure:
protocol = 'https://'
else:
protocol = 'http://'... |
Make naming the destination file work | '''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.it... | '''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.it... |
Fix args to list. Args is a tuple, list takes a tuple | #!/usr/bin/env python
from genes.posix.traits import only_posix
from genes.process.commands import run
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def groupadd(*args):
run(['groupadd'] + list(args))
... | #!/usr/bin/env python
from genes.posix.traits import only_posix
from genes.process.commands import run
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def groupadd(*args):
run(['groupadd'] + list(*args))
... |
Add discord entry to config file | <?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, ... | <?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, ... |
Fix bug in football module caching | angular.module('notificationApp.footballController', []).
controller('footballController', function($scope, $interval, $timeout, footballFactory) {
$scope.currentTeam = footballFactory.getCurrentTeam();
$scope.rowClick = function(inputTeam) {
$scope.currentTeam = inputTeam;
footballFactory.set... | angular.module('notificationApp.footballController', []).
controller('footballController', function($scope, $interval, $timeout, footballFactory) {
$scope.currentTeam = footballFactory.getCurrentTeam();
$scope.rowClick = function(inputTeam) {
$scope.currentTeam = inputTeam;
footballFactory.set... |
Update Siddhi quick start guide link | /**
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.o... | /**
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.o... |
Decompress downloaded files from disk, not in memory | #!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing ... | #!/usr/bin/env python3
import ftplib
import gzip
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s... |
Improve internal flow of code / increase efficiency | var fs = require('fs');
var mime = require('mime');
module.exports = function(app, routes) {
// loop through routes
for (var index in routes) {
// closure: route is the HTTP request route, path is the file path
(function (route, path) {
app.get(route, function(req, res) {
// create a readable stream
v... | var fs = require('fs');
var mime = require('mime');
module.exports = function(app, routes) {
// loop through routes
for (var index in routes) {
// route: index, file location: routes[index]
(function (indexRoute) {
app.get(indexRoute, function(req, res) {
fs.readFile(routes[indexRoute], function(err, data... |
Fix syntax error in PHP 5 | <?php
namespace Bugsnag\BugsnagLaravel\Tests;
use Bugsnag\BugsnagLaravel\BugsnagServiceProvider;
use GrahamCampbell\TestBench\AbstractPackageTestCase;
abstract class AbstractTestCase extends AbstractPackageTestCase
{
/**
* Get the service provider class.
*
* @param \Illuminate\Contracts\Foundation... | <?php
namespace Bugsnag\BugsnagLaravel\Tests;
use Bugsnag\BugsnagLaravel\BugsnagServiceProvider;
use GrahamCampbell\TestBench\AbstractPackageTestCase;
abstract class AbstractTestCase extends AbstractPackageTestCase
{
/**
* Get the service provider class.
*
* @param \Illuminate\Contracts\Foundation... |
Add logging for SSH commands
Change-Id: I620bfe5b796e82ae408477752d1547bd8d39a644 | package com.cgi.eoss.ftep.clouds.service;
import lombok.extern.log4j.Log4j2;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import java.io.Closeable;
import java.io.IOException;
/**
*/
@Log4j2
public c... | package com.cgi.eoss.ftep.clouds.service;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import java.io.Closeable;
import java.io.IOException;
/**
*/
public class SSHSession implements Closeable {
... |
Change settings for normal light. | #!/usr/bin/env python
"""Test Raspberry Pi camera!"""
# http://picamera.readthedocs.org/en/release-1.10/index.html
import picamera
import sys
from fractions import Fraction
from time import sleep
filename = sys.argv[1]
camera = picamera.PiCamera()
camera.vflip = True
camera.hflip = True
## Low light
#camera.framer... | #!/usr/bin/env python
"""Test Raspberry Pi camera!"""
# http://picamera.readthedocs.org/en/release-1.10/index.html
import picamera
import sys
from fractions import Fraction
from time import sleep
filename = sys.argv[1]
camera = picamera.PiCamera()
camera.vflip = True
camera.hflip = True
camera.framerate = Fraction... |
Fix missing message in ValidationError | from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
username... | from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
username... |
Fix bug in building rendering | import colors from '../colors';
export const initialState = {
rendering: {
wall: {},
flatRoof: {},
brickRoof: {},
field: {}
}
}
const materialInstances = {};
for (let material of ["wall", "flatRoof", "brickRoof", "field"]) {
materialInstances[material] = new Float32Array([... | import colors from '../colors';
export const initialState = {
rendering: {
wall: {},
flatRoof: {},
brickRoof: {},
field: {}
}
}
const materialInstances = ["wall", "flatRoof", "brickRoof", "field"].map(material =>
new Float32Array([0.0, 0.0, 0.0, 1.0, 0.0, ...colors[material... |
Set defaultProp for Accordion's children | // @flow
import React, { Component, type Node } from 'react';
import { Provider } from 'mobx-react';
import { createAccordionStore } from '../accordionStore/accordionStore';
type AccordionProps = {
accordion: boolean,
children: Node,
// activeItems: Array<string | number>,
className: string,
onCha... | // @flow
import React, { Component, type Node } from 'react';
import { Provider } from 'mobx-react';
import { createAccordionStore } from '../accordionStore/accordionStore';
type AccordionProps = {
accordion: boolean,
children: Node,
// activeItems: Array<string | number>,
className: string,
onCha... |
Update speaker population command to set popit_url instead of popit_id | import logging
from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, ... | from django.core.management.base import NoArgsCommand
from django.conf import settings
from popit import PopIt
from speeches.models import Speaker
class Command(NoArgsCommand):
help = 'Populates the database with people from Popit'
def handle_noargs(self, **options):
api = PopIt(instance = settings.PO... |
Add template section for page menu. | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo (isset($page_title)) ? $page_title . ' - ' . lang('website_name') : lang('website_name'); ?></title>
<base href="<?php echo base_url(); ?>" />
<link rel="shortcut icon" href="<?php echo base_url('favicon.ico'); ?>" />
<?php echo $head... | <?php
$website_name = (isset($page_title)) ? $page_title . ' - ' . lang('website_name') : lang('website_name');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $website_name; ?></title>
<base href="<?php echo base_url(); ?>" />
<link rel="shortcut icon" href="<?php echo base_url(... |
Fix data races in internal.Timer tests | package internal_test
import (
"sync/atomic"
"testing"
"time"
"github.com/instana/go-sensor/autoprofile/internal"
"github.com/stretchr/testify/assert"
)
func TestTimer_Restart(t *testing.T) {
var fired int64
timer := internal.NewTimer(0, 20*time.Millisecond, func() {
atomic.AddInt64(&fired, 1)
})
time.Sl... | package internal_test
import (
"testing"
"time"
"github.com/instana/go-sensor/autoprofile/internal"
"github.com/stretchr/testify/assert"
)
func TestTimer_Restart(t *testing.T) {
var fired int
timer := internal.NewTimer(0, 20*time.Millisecond, func() {
fired++
})
time.Sleep(30 * time.Millisecond)
timer.St... |
Replace localhost with the host the page was requested through. | /**
* Created by Ryan Lamb on 9/16/16.
*/
define(function (require) {
var mapEngine = require('MapClient/MapEngine/mapengine');
var mapData = require('MapData/mapdata');
var engine = new mapEngine.MapEngine();
engine.start();
var version = undefined;
window.setInterval(function() {
... | /**
* Created by Ryan Lamb on 9/16/16.
*/
define(function (require) {
var mapEngine = require('MapClient/MapEngine/mapengine');
var mapData = require('MapData/mapdata');
var engine = new mapEngine.MapEngine();
engine.start();
var version = undefined;
window.setInterval(function() {
... |
Update workingOn initial state so it matches empty state
Former-commit-id: 299f828a4348abc930162dce36fae6bf46c50489
Former-commit-id: 040e5eded8b35b2792d28b398d085da28a18cd2c
Former-commit-id: 9fc80277314d8a553b8148703be9fcb62832c20b | export const initialState = {
user: {
isAuthenticated: false,
email: '',
userType: '',
isAdmin: false
},
global: {
workingOn: null
},
rootPath: "/florence",
teams: {
active: {},
all: [],
allIDsAndNames: [],
users: []
},
... | export const initialState = {
user: {
isAuthenticated: false,
email: '',
userType: '',
isAdmin: false
},
global: {
workingOn: {}
},
rootPath: "/florence",
teams: {
active: {},
all: [],
allIDsAndNames: [],
users: []
},
... |
Add toString() for invalid URL error | 'use strict';
var querystring = require('querystring');
var shortener = require('../shortener');
var urlValidator = require('../urlValidator');
module.exports = (req, res, done) => {
var shortUrlId, url;
req.on('data', function (data) {
let queryStr = data.toString();
url = querystring.par... | 'use strict';
var querystring = require('querystring');
var shortener = require('../shortener');
var urlValidator = require('../urlValidator');
module.exports = (req, res, done) => {
var shortUrlId, url;
req.on('data', function (data) {
let queryStr = data.toString();
url = querystring.par... |
Test if debugger work in safari | /* eslint-disable no-undef */
import { fork, call, select } from 'redux-saga/effects';
import { isIos } from 'worona-deps';
import * as deps from '../deps';
function* redirectHome() {
const contentType = yield select(deps.selectors.getContentType);
if (contentType === 'Home') {
const { type, category, page } =... | /* eslint-disable no-undef */
import { fork, call, select } from 'redux-saga/effects';
import { isIos } from 'worona-deps';
import * as deps from '../deps';
function* redirectHome() {
const contentType = yield select(deps.selectors.getContentType);
if (contentType === 'Home') {
const { type, category, page } =... |
Mark renderer test as flaky for mac tests | # coding: utf-8
'''
Integration tests for renderer functions
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.helpers import flaky
class TestJinjaRenderer(ModuleCase):
'''
... | # coding: utf-8
'''
Integration tests for renderer functions
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
# Import Salt Testing libs
from tests.support.case import ModuleCase
class TestJinjaRenderer(ModuleCase):
'''
Validate that ordering works correctly
... |
Update sort order in order to fix tie to be under jackets | module.exports = [
{
id: 'Hairstyles',
required: false,
sortOrder: 1
},
{
id: 'Beards',
required: false,
sortOrder: 5
},
{
id: 'Body',
required: true,
sortOrder: 0
},
{
id: 'Glasses',
required: false,
sortOrder: 2
},
{
id: 'Scarfes',
required: fa... | module.exports = [
{
id: 'Hairstyles',
required: false,
sortOrder: 1
},
{
id: 'Beards',
required: false,
sortOrder: 4
},
{
id: 'Body',
required: true,
sortOrder: 0
},
{
id: 'Glasses',
required: false,
sortOrder: 2
},
{
id: 'Scarfes',
required: fa... |
Correct sample with new qualified name of the class | #
# Menu: Examples > Views > Py > Google Web View
# Kudos: Paul Colton
# License: EPL 1.0
#
from org.eclipse.swt.browser import LocationListener
from org.eclipse.eclipsemonkey.ui.views import GenericScriptableView
from org.eclipse.ui import IWorkbenchPage
class MyLocationListener(LocationListener):
def changing(se... | #
# Menu: Examples > Views > Py > Google Web View
# Kudos: Paul Colton
# License: EPL 1.0
#
from org.eclipse.swt.browser import LocationListener
from org.eclipse.eclipsemonkey.ui.scriptableView import GenericScriptableView
from org.eclipse.ui import IWorkbenchPage
class MyLocationListener(LocationListener):
def ch... |
Update affected Puppet action constructor to take in "config" argument. | from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self, config):
super(PuppetBasePythonAction, self).__init__(config=config)
self.client = self._get_client()
def _get_client(self):
m... | from st2actions.runners.pythonrunner import Action
from lib.puppet_client import PuppetHTTPAPIClient
class PuppetBasePythonAction(Action):
def __init__(self):
super(PupperBasePythonAction, self).__init__()
self.client = self._get_client()
def _get_client(self):
master_config = self.c... |
Add new items when button is pressed | package net.emteeware.emteeseason;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import static net.emt... | package net.emteeware.emteeseason;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import static net.emteeware.emteeseason.R.id.Serie... |
Check msg in a way that passes for all GDAL versions | # Testing use of cpl_errs
import pytest
import rasterio
from rasterio.errors import RasterioIOError
def test_io_error(tmpdir):
"""RasterioIOError is raised when a disk file can't be opened.
Newlines are removed from GDAL error messages."""
with pytest.raises(RasterioIOError) as exc_info:
rasteri... | # Testing use of cpl_errs
import pytest
import rasterio
from rasterio.errors import RasterioIOError
def test_io_error(tmpdir):
with pytest.raises(RasterioIOError) as exc_info:
rasterio.open(str(tmpdir.join('foo.tif')))
msg, = exc_info.value.args
assert msg.startswith("'{0}'".format(tmpdir.join('... |
Support relative paths in bin/run_metric
As a result of this patch, it will be possible to run:
bin/run_metric MemoryMetric test_data/memory_dumps.json
^^^^^^^^^^^^^^^^^^^^^^^^^^^
instead of:
bin/run_metric MemoryMetric $PWD/test_data/memory_dumps.json
... | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from perf_insights import map_single_trace
from perf_insights import function_handle
from perf_insights.mre import file_handle
from perf_insights.m... | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from perf_insights import map_single_trace
from perf_insights import function_handle
from perf_insights.mre import file_handle
from perf_insights.m... |
Remove errant char and pass in encoding to make readFileSync read as text and not a buffer | var fs = require('fs');
var path = require('path');
var stripComments = require('strip-json-comments');
if (process.argv.length < 3) {
console.log("Usage: node charlie /path/to/object/schema");
console.log(" * Please see https://github.com/project-badass/charlie");
console.log(" * for information about the object... | var fs = require('fs');
var path = require('path');
var stripComments = require('strip-json-comments');
if (process.argv.length < 3) {
console.log("Usage: node charlie /path/to/object/schema");
console.log(" * Please see https://github.com/project-badass/charlie");
console.log(" * for information about the object... |
Add fix issue with linux time | import dotProp from 'dot-prop-immutable'
import * as types from './forecastDailyActionTypes'
const initialState = {
forecastDaily: {
data: [],
app: {
locationId: 5128581 // nyc usa
},
ui: {}
}
}
const updateAppIsFetching = (state, action, value) => {
return dotProp.set(state, 'forecastDail... | import dotProp from 'dot-prop-immutable'
import * as types from './forecastDailyActionTypes'
const initialState = {
forecastDaily: {
data: [],
app: {
locationId: 5128581 // nyc usa
},
ui: {}
}
}
const updateAppIsFetching = (state, action, value) => {
return dotProp.set(state, 'forecastDail... |
Add async attribute back to the install script | import React from "react";
const Template = ({ children }) => (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="Sylvain Bou... | import React from "react";
const Template = ({ children }) => (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="Sylvain Bou... |
Add page_size validator even if get.max_items is not set | <?php
$pagination_custom_page_size = $this->configuration->getValue('get.pagination_custom_page_size');
$max_items = $this->configuration->getValue('get.max_items');
?>
/**
* Returns the list of pagination validators
* @return array an array of validators
*/
protected function getPaginationValidators()
... | <?php
$pagination_custom_page_size = $this->configuration->getValue('get.pagination_custom_page_size');
$max_items = $this->configuration->getValue('get.max_items');
?>
/**
* Returns the list of pagination validators
* @return array an array of validators
*/
protected function getPaginationValidators()
... |
Put webhook custom data at root | "use strict";
var jade = require("jade");
var i18n = require("i18next");
var path = require("path");
var configuration = require("../server/utils/environment_configuration");
var mailgun = require("mailgun-js")({apiKey: configuration.emailApiKey, domain: configuration.emailApiUrl});
var templateWithModel = jade.compi... | "use strict";
var jade = require("jade");
var i18n = require("i18next");
var path = require("path");
var configuration = require("../server/utils/environment_configuration");
var mailgun = require("mailgun-js")({apiKey: configuration.emailApiKey, domain: configuration.emailApiUrl});
var templateWithModel = jade.compi... |
Remove redundant data (error time and events) |
ErrorModel = function (appId) {
var self = this;
this.appId = appId;
this.errors = {};
this.startTime = Date.now();
}
_.extend(ErrorModel.prototype, KadiraModel.prototype);
ErrorModel.prototype.buildPayload = function() {
var metrics = _.values(this.errors);
this.startTime = Date.now();
this.errors = {... |
ErrorModel = function (appId) {
var self = this;
this.appId = appId;
this.errors = {};
this.startTime = Date.now();
}
_.extend(ErrorModel.prototype, KadiraModel.prototype);
ErrorModel.prototype.buildPayload = function() {
var metrics = _.values(this.errors);
this.startTime = Date.now();
this.errors = {... |
Simplify and optimize the code
git-svn-id: 14496471c1e7f47aed4ccd4e743787d9efef7a8c@586 2772adf2-ac07-0410-9d30-e29d8120292e | <?php
require_once(dirname(__FILE__)."/../pfccommand.class.php");
class pfcCommand_connect extends pfcCommand
{
function run(&$xml_reponse, $clientid, $param, $sender, $recipient, $recipientid)
{
$c =& $this->c;
$u =& $this->u;
// disconnect last connected users from the server if necessary
$co... | <?php
require_once(dirname(__FILE__)."/../pfccommand.class.php");
class pfcCommand_connect extends pfcCommand
{
function run(&$xml_reponse, $clientid, $param, $sender, $recipient, $recipientid)
{
$c =& $this->c;
$u =& $this->u;
// disconnect last connected users from the server if necessary
$co... |
Change direction on game click | function Level(game, level) {
this.game = game;
this.remaining = level;
this.interval = undefined;
this.period = 4;
this.intervalTime = 10;
this.velocity = 2 * Math.PI / (1000 * this.period);
this.forward = true;
this.game.setRemaining(level);
var me = this;
this.game.board.on('click', function() {
if (me... | function Level(game, level) {
this.game = game;
this.level = level;
this.interval = undefined;
this.period = 4;
this.intervalTime = 10;
this.velocity = 2 * Math.PI / (1000 * this.period);
this.game.setRemaining(level);
var me = this;
this.game.board.on('click', function() {
if (me.interval) {
me.clicked... |
Use `ember-cli-babel` to resolve module paths | const Babel = require('broccoli-babel-transpiler');
const { resolveRelativeModulePath } = require('ember-cli-babel/lib/relative-module-paths');
const enifed = require('./transforms/transform-define');
const injectNodeGlobals = require('./transforms/inject-node-globals');
module.exports = function processModulesOnly(tr... | const Babel = require('broccoli-babel-transpiler');
const resolveModuleSource = require('amd-name-resolver').moduleResolve;
const enifed = require('./transforms/transform-define');
const injectNodeGlobals = require('./transforms/inject-node-globals');
module.exports = function processModulesOnly(tree, strict = false) ... |
Install latest oedialect version from GitHub instead from PyPi | #! /usr/bin/env python
# coding: utf-8
from setuptools import find_packages, setup
setup(name='egoio',
author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES',
author_email='ulf.p.mueller@hs-flensburg.de',
description='ego input/output repository',
version='0.4.5',
url='https://github.... | #! /usr/bin/env python
# coding: utf-8
from setuptools import find_packages, setup
setup(name='egoio',
author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES',
author_email='ulf.p.mueller@hs-flensburg.de',
description='ego input/output repository',
version='0.4.5',
url='https://github.... |
Add child_process.exec succeeds test case | /* global describe it */
'use strict'
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
require('sinon-as-promised')
chai.use(chaiAsPromised)
chai.use(sinonChai)
const ... | /* global describe it */
'use strict'
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
require('sinon-as-promised')
chai.use(chaiAsPromised)
chai.use(sinonChai)
const ... |
Fix pages containing multiple tab sets | jQuery(function($) {
$('.tabify .tabs a').bind('click', function() {
var href = $(this).attr('href'),
tabify = $(this).closest('.tabify'),
tabContent = tabify.find(href);
tabify.find('.tabs a').removeClass('active'); // clear the active tabs
tabify.find('.tabs a[href=' + href + ']').addCla... | jQuery(function($) {
$('.tabify .tabs a').bind('click', function() {
var href = $(this).attr('href');
var tabContent = $(href);
$('.tabify .tabs a').removeClass('active'); // clear the active tabs
$('.tabify .tabs a[href=' + href + ']').addClass('active'); // activate the clicked tab
$('.tabify .t... |
Add extra missing items to the entity | from mangopaysdk.entities.entitybase import EntityBase
class Card(EntityBase):
"""Card entity"""
def __init__(self, id = None):
self.UserId = None
# MMYY
self.ExpirationDate = None
# first 6 and last 4 are real card numbers for example: 497010XXXXXX4414
self.Alias... | from mangopaysdk.entities.entitybase import EntityBase
class Card(EntityBase):
"""Card entity"""
def __init__(self, id = None):
# MMYY
self.ExpirationDate = None
# first 6 and last 4 are real card numbers for example: 497010XXXXXX4414
self.Alias = None
# The card ... |
Remove errored state (lets rely on a single failure state) | from enum import Enum
class Status(Enum):
unknown = 0
queued = 1
in_progress = 2
finished = 3
collecting_results = 4
def __str__(self):
return STATUS_LABELS[self]
class Result(Enum):
unknown = 0
passed = 1
failed = 2
skipped = 3
aborted = 5
timedout = 6
... | from enum import Enum
class Status(Enum):
unknown = 0
queued = 1
in_progress = 2
finished = 3
collecting_results = 4
def __str__(self):
return STATUS_LABELS[self]
class Result(Enum):
unknown = 0
passed = 1
failed = 2
skipped = 3
errored = 4
aborted = 5
ti... |
Remove harmful disabling of scaling by user | <head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="apple-touch-icon-pre... | <head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes"... |
Support fatal errors in converter | <?php
/**
* Converts any PHP Error to ErrbitException
* Extracted from the Errbit Error Handler, in case you want to use your own errorhandler, and convert errors to Exceptions.
* @author deathowl <csergo.balint@ustream.tv>
*/
namespace Errbit\Utils;
use Errbit\Errors\Error;
use Errbit\Errors\Fatal;
use Errbit\Er... | <?php
/**
* Converts any PHP Error to ErrbitException
* Extracted from the Errbit Error Handler, in case you want to use your own errorhandler, and convert errors to Exceptions.
* @author deathowl <csergo.balint@ustream.tv>
*/
namespace Errbit\Utils;
use Errbit\Errors\Error;
use Errbit\Errors\Notice;
use Errbit\E... |
Use field.to_python to do django type conversions on the field before checking if dirty.
This solves issues where you might have a decimal field that you write a string to, eg:
>>> m = MyModel.objects.get(id=1)
>>> m.my_decimal_field
Decimal('1.00')
>>> m.my_decimal_field = u'1.00' # from a form or something
>>> m.is_... | # Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
post_save.connect(reset_state, sender=self.__cl... | # Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
post_save.connect(reset_state, sender=self.__cl... |
Remove menu links as triggers.
Issue created with the preventing default function where a menu link wouldn't redirect the page. | jQuery( document ).ready(function( $ ) {
// Variables
var open = false, // Set the state of the menu on load (false = closed)
body = $('body'),
siteContainer = $('.site-container'),
toggleButtons = $('.menu-btn, .close-btn, .site-overlay');
// Function to open the menu
function openMen... | jQuery( document ).ready(function( $ ) {
// Variables
var open = false, // Set the state of the menu on load (false = closed)
body = $('body'),
siteContainer = $('.site-container'),
toggleButtons = $('.menu-btn, .close-btn, .site-overlay, .nav-primary a'); // Also select menu links to cau... |
Fix regex on subdomain urls so empty string will match. | from django.conf.urls.defaults import url, patterns
from urls import urlpatterns as main_patterns
urlpatterns = patterns('',
url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$',
'core.views.subproject_serve_docs',
name='subproject_docs_detail... | from django.conf.urls.defaults import url, patterns
from urls import urlpatterns as main_patterns
urlpatterns = patterns('',
url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$',
'core.views.subproject_serve_docs',
name='subproject_docs_detail... |
Rename all containing 'Addressbook' to 'Tars' | package tars.testutil;
import tars.commons.exceptions.IllegalValueException;
import tars.model.Tars;
import tars.model.person.Person;
import tars.model.person.UniquePersonList;
import tars.model.tag.Tag;
/**
* A utility class to help with building Tars objects.
* Example usage: <br>
* {@code Tars ab = new Tars... | package tars.testutil;
import tars.commons.exceptions.IllegalValueException;
import tars.model.Tars;
import tars.model.person.Person;
import tars.model.person.UniquePersonList;
import tars.model.tag.Tag;
/**
* A utility class to help with building Addressbook objects.
* Example usage: <br>
* {@code Tars ab = n... |
Add pysqlite to the dependencies | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
# Copyright 2012 ShopWiki
#
# 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 requ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
# Copyright 2012 ShopWiki
#
# 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 requ... |
Update comment and add named routes | 'use strict';
import VueRouter from 'vue-router';
import TaskListView from '../views/TaskListView';
import IndexView from '../views/IndexView';
export default new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'Index',
component: IndexView
},
{
path: '/hello/:name... | 'use strict';
import VueRouter from 'vue-router';
import TaskListView from '../views/TaskListView';
import IndexView from '../views/IndexView';
export default new VueRouter({
mode: 'history',
routes: [
{
path: '/',
// name: 'Index',
component: IndexView
},
{
path: '/hello/:n... |
Make nested docs not modified by default | defaultConstructor = function(attrs) {
var doc = this;
var Class = doc.constructor;
attrs = attrs || {};
// Create "_values" property when legacy browsers support is turned on.
if (!Astro.config.supportLegacyBrowsers) {
doc._values = {};
}
// Set values of all fields.
Astro.utils.fields.setAllValu... | defaultConstructor = function(attrs) {
var doc = this;
var Class = doc.constructor;
attrs = attrs || {};
// Create "_values" property when legacy browsers support is turned on.
if (!Astro.config.supportLegacyBrowsers) {
doc._values = {};
}
// Set values of all fields.
Astro.utils.fields.setAllValu... |
Change package version to 0.5.0 | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.5.0',
description="Enables android adb in your python script",
long_description='This python package is... | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.4.0',
description="Enables android adb in your python script",
long_description='This python package is... |
Sort and indent the map lists.
PiperOrigin-RevId: 249276696 | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# 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 ... | #!/usr/bin/python
# Copyright 2019 Google Inc. All Rights Reserved.
#
# 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 ... |
Test for using local variables | // Copyright © 2013 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
package net.orfjackal.retrolambda.test;
import org.junit.Test;
import java.util.concurrent.Callable;
import static org.hamcrest.Matche... | // Copyright © 2013 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
package net.orfjackal.retrolambda.test;
import org.junit.Test;
import java.util.concurrent.Callable;
import static org.hamcrest.Matche... |
Use `PropTypes` instead of `React.PropTypes` | import PropTypes from 'prop-types';
import React from 'react';
import Relay from 'react-relay';
import QueryAggregator from './QueryAggregator';
const propTypes = {
location: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
};
const childContextTypes = {
queryAggregator: PropTypes.object.is... | import PropTypes from 'prop-types';
import React from 'react';
import Relay from 'react-relay';
import QueryAggregator from './QueryAggregator';
const propTypes = {
location: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
};
const childContextTypes = {
queryAggregator: React.PropTypes.obj... |
Add in a missing change from r67143 for print preview options.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/5334002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@67155 0039d316-1c4b-4281-b951-d872f2087c98 | // Copyright (c) 2010 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.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
$('cancel-button').addEventListener('c... | // Copyright (c) 2010 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.
var localStrings = new LocalStrings();
/**
* Window onload handler, sets up the page.
*/
function load() {
$('cancel-button').addEventListener('c... |
Allow widgets to use custom functions in templates | <?php
namespace ATPCore\View;
class Widget extends \Zend\View\Model\ViewModel
{
protected $_template = "";
public function __construct($params = null)
{
parent::__construct($params);
$this->setTemplate($this->_template);
$this->init();
$this->widget = $this;
}
protected fu... | <?php
namespace ATPCore\View;
class Widget extends \Zend\View\Model\ViewModel
{
protected $_template = "";
public function __construct($params = null)
{
parent::__construct($params);
$this->setTemplate($this->_template);
$this->init();
}
protected function init()
{
}
pub... |
Fix stop immediate propagation handling. | (function() {
const events = new Map();
const stopped = new WeakMap();
function before(subject, verb, fn) {
const source = subject[verb];
subject[verb] = function() {
fn.apply(subject, arguments);
return source.apply(subject, arguments);
};
return subject;
}
function dispatch(obs... | (function() {
const events = new Map();
const stopped = new WeakMap();
function before(subject, verb, fn) {
const source = subject[verb];
subject[verb] = function() {
fn.apply(subject, arguments);
return source.apply(event, arguments);
};
return subject;
}
function dispatch(obser... |
Replace log.Fatal usages with Println then return | package serve
import (
"log"
"net"
"net/http"
"os"
"os/signal"
)
func Serve(port, socket string, handler http.Handler) {
if socket == "" {
Port(port, handler)
} else {
Socket(socket, handler)
}
}
func Socket(socket string, handler http.Handler) {
l, err := net.Listen("unix", socket)
if err != nil {
l... | package serve
import (
"net"
"net/http"
"log"
"os"
"os/signal"
)
func Serve(port, socket string, handler http.Handler) {
if socket == "" {
Port(port, handler)
} else {
Socket(socket, handler)
}
}
func Socket(socket string, handler http.Handler) {
l, err := net.Listen("unix", socket)
if err != nil {
l... |
Fix double redirects pt 2 | <?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Teapot\StatusCode;
class AdminAuthenticate
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
... | <?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Teapot\StatusCode;
class AdminAuthenticate
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
... |
Change landing URLs to website | import sublime, sublime_plugin, webbrowser
QD_URL = "http://www.1self.co"
class GoTo1selfDashboardCommand(sublime_plugin.TextCommand):
def run(self,edit):
SETTINGS = {}
SETTINGS_FILE = "1self.sublime-settings"
SETTINGS = sublime.load_settings(SETTINGS_FILE)
stream_id = SETTINGS.get... | import sublime, sublime_plugin, webbrowser
QD_URL = "https://app.1self.co"
class GoTo1selfDashboardCommand(sublime_plugin.TextCommand):
def run(self,edit):
SETTINGS = {}
SETTINGS_FILE = "1self.sublime-settings"
SETTINGS = sublime.load_settings(SETTINGS_FILE)
stream_id = SETTINGS.ge... |
Fix bug in RegEx parser mixin | import re
from itertools import repeat
class RegexParserMixin(object):
quoted_re = r'''(?P<q>"|')(?P<x>.+)(?P=q)'''
version_re = r'''(?P<s>[<>=~]*)\s*(?P<n>.*)'''
def _get_value(self, lines, prefix, regex):
filtered = self._lines_startwith(lines, '{0} '.format(prefix))
return self._match(... | import re
from itertools import repeat
class RegexParserMixin(object):
quoted_re = r'''(?P<q>"|')(?P<x>.+)(?P=q)'''
version_re = r'''(?P<s>[<>=~]*)\s*(?P<n>.*)'''
def _get_value(self, lines, prefix, regex):
filtered = self._lines_startwith(lines, '{0} '.format(prefix))
return self._match(... |
Remove unused variable in $scope |
function AnalyzerCtrl($scope, $http, Analyzer, Data){
$scope.analyzer = Analyzer;
$scope.data = Data;
$scope.$watch('analyzer.query', function(value){
for (i in $scope.analyzer.analyzers){
$scope.analyze($scope.analyzer.analyzers[i]);
}
});
$scope.analyze = function(a... |
function AnalyzerCtrl($scope, $http, Analyzer, Data){
$scope.analyzer = Analyzer;
$scope.data = Data;
$scope.atext = {};
$scope.$watch('analyzer.query', function(value){
for (i in $scope.analyzer.analyzers){
$scope.analyze($scope.analyzer.analyzers[i]);
}
});
$sc... |
Fix some typos in concurrency test | import unittest
from requests import Request
from unittest.mock import patch, MagicMock
from concurrency.get_websites import load_url as load_url
class MockResponse():
def __init__(self):
self.text = "foo"
self.status_code = 200
class TestGetWebsites(unittest.TestCase):
@patch('concurrency.g... | import unittest
from requests import Request
from unittest.mock import patch, MagicMock
from concurrency.get_websites import load_url as load_url
class MockResponse():
def __init__(self):
self.text = "foo"
self.status_code = 200
class TestGetWebsites(unittest.TestCase):
@patch('concurrency.g... |
Configure app to include a components folder | const express = require('express')
const app = express()
const path = require('path')
const nunjucks = require('nunjucks')
module.exports = app
// Set up App
const appViews = [
path.join(__dirname, '/app/views/'),
path.join(__dirname, '/app/templates/'),
path.join(__dirname, '/app/components/')
]
nunjucks.conf... | const express = require('express')
const app = express()
const path = require('path')
const nunjucks = require('nunjucks')
module.exports = app
// Set up App
const appViews = [
path.join(__dirname, '/app/views/'),
path.join(__dirname, '/app/templates/')
]
nunjucks.configure(appViews, {
autoescape: true,
expr... |
Add support for item data | package info.tregmine.database.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import info.tregmine.database.IItemDAO;
import info.tregmine.database.DAOException;
public class DBItemDAO implements IItemDAO
{
private Connection conn;
... | package info.tregmine.database.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import info.tregmine.database.IItemDAO;
import info.tregmine.database.DAOException;
public class DBItemDAO implements IItemDAO
{
private Connection conn;
... |
Use an intejob delay of 0 for work queue | /**
*
* Delay jobs to make the page remain responsive during expensive jobs.
*
* Usage:
*
* require(["work_queue"], function(_work_queue) {
* _.each(ids, function(id) {
* _work_queue.add(function() {
* someExpensiveOperation(id);
* });
* }):
* });
*
* The queue run is started aft... | /**
*
* Delay jobs to make the page remain responsive during expensive jobs.
*
* Usage:
*
* require(["work_queue"], function(_work_queue) {
* _.each(ids, function(id) {
* _work_queue.add(function() {
* someExpensiveOperation(id);
* });
* }):
* });
*
* The queue run is started aft... |
Test work of API communication | (function () {
'use strict';
angular
.module('scrum_retroboard')
.controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]);
function UserController($scope, $http, sessionService, userService) {
var userVm = this;
//scope models
... | (function () {
'use strict';
angular
.module('scrum_retroboard')
.controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]);
function UserController($scope, $http, sessionService, userService) {
var userVm = this;
//scope models
... |
Improve the readaibility and hopefully make it easier to complete the kata and learn better. | // 9: object-literals - basics
// To do: make all tests pass, leave the assert lines unchanged!
describe('The object literal allows for new shorthands', () => {
const x = 1;
const y = 2;
describe('with variables', () => {
it('the short version for `{x: x}` is {x}', () => {
const short = {x};
as... | // 9: object-literals - basics
// To do: make all tests pass, leave the assert lines unchanged!
describe('new shorthands for objects', () => {
const x = 1;
const y = 2;
describe('with variables', () => {
it('use the variables name as key', () => {
const short = {x};
assert.deepEqual(short, {y: ... |
Check and fast return if object is already arrived | function isArrived(object, target) {
return object.x === target.x && object.y === target.y;
}
function getC(a, b) {
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
function getBeta(b, c) {
return Math.asin(b / c);
}
function getB(c, beta) {
return c * Math.sin(beta);
}
function getAlpha(a, c) {
retur... | function getC(a, b) {
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
function getBeta(b, c) {
return Math.asin(b / c);
}
function getB(c, beta) {
return c * Math.sin(beta);
}
function getAlpha(a, c) {
return Math.asin(a / c);
}
function getA(c, alpha) {
return c * Math.sin(alpha);
}
function round(... |
Update cfg.json in release package.
v5.1.5 壓縮包中的 cfg.json 有誤,重新更新一版到 v5.1.6,程式檔案不變,僅更新壓縮包中的 cfg.json。 | package g
import (
"time"
)
// changelog:
// 3.1.3: code refactor
// 3.1.4: bugfix ignore configuration
// 5.0.0: 支持通过配置控制是否开启/run接口;收集udp流量数据;du某个目录的大小
// 5.1.0: 同步插件的时候不再使用checksum机制
// 5.1.3: Fix config syntax error when deploying
// 5.1.4: Only trustable ip could access the webpage
// 5.1.5: New policy and plugi... | package g
import (
"time"
)
// changelog:
// 3.1.3: code refactor
// 3.1.4: bugfix ignore configuration
// 5.0.0: 支持通过配置控制是否开启/run接口;收集udp流量数据;du某个目录的大小
// 5.1.0: 同步插件的时候不再使用checksum机制
// 5.1.3: Fix config syntax error when deploying
// 5.1.4: Only trustable ip could access the webpage
// 5.1.5: New policy and plugi... |
Use utf8 to encode URLs.
PR: 8961
Submitted by: Matthew Faull
git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@323764 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: f20f9b66b4af229a29de308fe78c6306bbf79768 | package org.apache.jmeter.protocol.http.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.oro.util.Cache;
import org.apache.oro.util.CacheLRU;
/**
* @author Administrator
*
* To change this generated comment edit the template variable "typecomment":
* Window>Prefere... | package org.apache.jmeter.protocol.http.util;
import java.net.URLEncoder;
import org.apache.oro.util.Cache;
import org.apache.oro.util.CacheLRU;
/**
* @author Administrator
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
*/
public class Encoder... |
Allow data to be returned on the same request. | import json
from rest_framework import serializers
from django.core.urlresolvers import reverse
from landscapesim.models import Region
class ReportingUnitSerializer(serializers.Serializer):
type = serializers.SerializerMethodField()
properties = serializers.SerializerMethodField()
geometry = serializers... | import json
from rest_framework import serializers
from django.core.urlresolvers import reverse
from landscapesim.models import Region
class ReportingUnitSerializer(serializers.Serializer):
type = serializers.SerializerMethodField()
properties = serializers.SerializerMethodField()
geometry = serializers... |
Update docblock for Expired Request Exception | <?php
namespace SoapBox\SignedRequests\Exceptions;
use Exception;
use Throwable;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExpiredRequestException extends Exception implements HttpExceptionInterface
{
/**
* The default exception m... | <?php
namespace SoapBox\SignedRequests\Exceptions;
use Exception;
use Throwable;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExpiredRequestException extends Exception implements HttpExceptionInterface
{
/**
* The default exception m... |
Fix missing @Test annotations for JUnit tests.
Forgot to add the annotations when upgrading to JUnit 4. | package net.sf.commonclipse;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.util.regex.Pattern;
import org.junit.Test;
/**
* Tests for CCPluginPreferences.
* @author fgiust
* @version $Revision$ ($Author$)
*/
public... | package net.sf.commonclipse;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.util.regex.Pattern;
/**
* Tests for CCPluginPreferences.
* @author fgiust
* @version $Revision$ ($Author$)
*/
public class CCPluginPreferenc... |
Fix test of admin/custodian password change | var utils = require('./utils.js');
var temporary_password = "typ0drome@absurd.org";
describe('receiver first login', function() {
it('should redirect to /firstlogin upon successful authentication', function() {
utils.login_custodian('Custodian1', utils.vars['default_password'], '/#/custodian', true);
});
i... | var utils = require('./utils.js');
var temporary_password = "typ0drome@absurd.org";
describe('receiver first login', function() {
it('should redirect to /firstlogin upon successful authentication', function() {
utils.login_custodian('Custodian1', utils.vars['default_password'], '/#/custodian', true);
});
i... |
Correct the names of the default modules | <?php
namespace duncan3dc\MetaAudio;
use duncan3dc\MetaAudio\Modules\ModuleInterface;
/**
* Manage which modules are active and their priority sequence.
*/
trait ModuleManager
{
/**
* @var ModuleInterface[] $modules The modules used to read tags.
*/
protected $modules = [];
/**
* Add ... | <?php
namespace duncan3dc\MetaAudio;
use duncan3dc\MetaAudio\Modules\ModuleInterface;
/**
* Manage which modules are active and their priority sequence.
*/
trait ModuleManager
{
/**
* @var ModuleInterface[] $modules The modules used to read tags.
*/
protected $modules = [];
/**
* Add ... |
Put controller block in Meteor.startup() | var daysPerPage = 5;
var coreSubscriptions = new SubsManager({
// cache recent 50 subscriptions
cacheLimit: 50,
// expire any subscription after 30 minutes
expireIn: 30
});
// note: FastRender not defined here?
Meteor.startup(function () {
PostsDailyController = RouteController.extend({
template: get... | var daysPerPage = 5;
var coreSubscriptions = new SubsManager({
// cache recent 50 subscriptions
cacheLimit: 50,
// expire any subscription after 30 minutes
expireIn: 30
});
// note: FastRender not defined here?
PostsDailyController = RouteController.extend({
template: getTemplate('posts_daily'),
onBefore... |
Update header missed by the script
Really, who puts spaces in front of the comments of a file header?! | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundat... |
chore(generator): Fix false positives from ESLint in template files | 'use strict'
module.exports = {
parser: 'babel-eslint',
extends: [
'@strv/javascript/environments/nodejs/v8-3',
'@strv/javascript/environments/nodejs/optional',
'@strv/javascript/coding-styles/recommended',
],
rules: {
// If your editor cannot show these to you, occasionally turn this off and... | 'use strict'
module.exports = {
parser: 'babel-eslint',
extends: [
'@strv/javascript/environments/nodejs/v8-3',
'@strv/javascript/environments/nodejs/optional',
'@strv/javascript/coding-styles/recommended',
],
rules: {
// If your editor cannot show these to you, occasionally turn this off and... |
Remove all scores before populating the sorted set. | from django.core.management.base import BaseCommand
from django.conf import settings
from ...models import OverallDriverPrediction, OverallConstructorPrediction
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **kwargs):
conn = settings.REDIS_CONN
num_ranks = con... | from django.core.management.base import BaseCommand
from django.conf import settings
from ...models import OverallDriverPrediction, OverallConstructorPrediction
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **kwargs):
conn = settings.REDIS_CONN
num_ranks = con... |
Adjust log level in example 13 | package main
import (
"fmt"
sci "github.com/samuell/scipipe"
)
func main() {
sci.InitLogWarn()
fmt.Println("Starting program!")
ls := sci.Shell("ls -l / > {os:lsl}")
ls.OutPathFuncs["lsl"] = func(tsk *sci.ShellTask) string {
return "lsl.txt"
}
grp := sci.Shell("grep etc {i:in} > {o:grep}")
grp.OutPathFun... | package main
import (
"fmt"
sci "github.com/samuell/scipipe"
)
func main() {
sci.InitLogDebug()
fmt.Println("Starting program!")
ls := sci.Shell("ls -l / > {os:lsl}")
ls.OutPathFuncs["lsl"] = func(tsk *sci.ShellTask) string {
return "lsl.txt"
}
grp := sci.Shell("grep etc {i:in} > {o:grep}")
grp.OutPathFu... |
Fix Eclipse resolution of plugins; this may be different in other IDEs | package uk.co.uwcs.choob.modules;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
class ChoobURLStreamHandler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u... | package uk.co.uwcs.choob.modules;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
class ChoobURLStreamHandler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL u... |
Fix triangle wave for the modulo of a negative number issue | /**
* @depends TableLookupOscillator.js
*/
var Triangle = new Class({
Extends: TableLookupOscillator,
initialize: function(audiolet, frequency) {
TableLookupOscillator.prototype.initialize.apply(this, [audiolet,
Triangle.TABLE,
... | /**
* @depends TableLookupOscillator.js
*/
var Triangle = new Class({
Extends: TableLookupOscillator,
initialize: function(audiolet, frequency) {
TableLookupOscillator.prototype.initialize.apply(this, [audiolet,
Triangle.TABLE,
... |
Fix Typo bug. TRUST -> TRUSTEE | /*
* Copyright 2006-2014 innopost.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
... | /*
* Copyright 2006-2014 innopost.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
... |
Add support for tern complete_strings plugin | # -*- coding: utf-8 -*-
import json
import os.path
import re
from completor import Completor
from completor.compat import to_unicode
dirname = os.path.dirname(__file__)
class Tern(Completor):
filetype = 'javascript'
daemon = True
ident = re.compile(r"""(\w+)|(('|").+)""", re.U)
trigger = r"""\w+$|[... | # -*- coding: utf-8 -*-
import json
import os.path
from completor import Completor
from completor.compat import to_unicode
dirname = os.path.dirname(__file__)
class Tern(Completor):
filetype = 'javascript'
daemon = True
trigger = r'\w+$|[\w\)\]\}\'\"]+\.\w*$'
def format_cmd(self):
binary =... |
Fix reorder call in controller | <?php
namespace Code16\Sharp\Http\Api;
class EntityListController extends ApiController
{
/**
* @param string $entityKey
* @return \Illuminate\Http\JsonResponse
*/
public function show($entityKey)
{
sharp_check_ability("entity", $entityKey);
$list = $this->getListInstance(... | <?php
namespace Code16\Sharp\Http\Api;
class EntityListController extends ApiController
{
/**
* @param string $entityKey
* @return \Illuminate\Http\JsonResponse
*/
public function show($entityKey)
{
sharp_check_ability("entity", $entityKey);
$list = $this->getListInstance(... |
Allow having unique integer columns in the database | package sword.langbook3.android.sqlite;
import sword.database.DbColumn;
import sword.database.DbValue;
public final class SqliteUtils {
private SqliteUtils() {
}
public static String sqlType(DbColumn column) {
if (column.isPrimaryKey()) {
return "INTEGER PRIMARY KEY AUTOINCREMENT";
... | package sword.langbook3.android.sqlite;
import sword.database.DbColumn;
import sword.database.DbValue;
public final class SqliteUtils {
private SqliteUtils() {
}
public static String sqlType(DbColumn column) {
if (column.isPrimaryKey()) {
return "INTEGER PRIMARY KEY AUTOINCREMENT";
... |
Define scripts in a array instead of inline | angular
.module('ngSharepoint', [])
.run(function($sp, $spLoader) {
if ($sp.getAutoload()) {
if ($sp.getConnectionMode() === 'JSOM') {
var scripts = [
'//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js',
'SP.Runtime.js',
... | angular
.module('ngSharepoint', [])
.run(function($sp, $spLoader) {
if ($sp.getAutoload()) {
if ($sp.getConnectionMode() === 'JSOM') {
$spLoader.loadScripts('SP.Core', ['//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'SP.Runtime.js', 'SP.js']);
... |
Exit with code 1 if no connection to the DB | var orm = require('orm');
var connectionString;
if (process.env.SQLITE == 'true')
connectionString = 'sqlite://' + __dirname + '/db.sqlite';
else
connectionString = 'postgres://cote:ohgath2ig8eoP8@pg/cote';
var db = orm.connect(connectionString, function onConnect(err) {
if (err) {
console.log('E... | var orm = require('orm');
var connectionString;
if (process.env.SQLITE == 'true')
connectionString = 'sqlite://' + __dirname + '/db.sqlite';
else
connectionString = 'postgres://cote:ohgath2ig8eoP8@pg/cote';
var db = orm.connect(connectionString, function onConnect(err) {
if (err) {
console.log('E... |
Use t.Error if formatting is not needed | package crane
import "testing"
func TestDependencies(t *testing.T) {
container := &Container{Run: RunParameters{RawLink: []string{"a:b", "b:d"}}}
if deps := container.Dependencies(); deps[0] != "a" || deps[1] != "b" {
t.Error("Dependencies should have been a and b")
}
container = &Container{Run: RunParameters{R... | package crane
import "testing"
func TestDependencies(t *testing.T) {
container := &Container{Run: RunParameters{RawLink: []string{"a:b", "b:d"}}}
if deps := container.Dependencies(); deps[0] != "a" || deps[1] != "b" {
t.Errorf("Dependencies should have been a and b")
}
container = &Container{Run: RunParameters{... |
Add a little bit more documentation for round2submission script | #!/usr/bin/env python
import opensim as osim
from osim.redis.client import Client
from osim.env import *
import numpy as np
import argparse
import os
"""
NOTE: For testing your submission scripts, you first need to ensure that redis-server is running in the background
and you can locally run the grading service by r... | #!/usr/bin/env python
import opensim as osim
from osim.redis.client import Client
from osim.env import *
import numpy as np
import argparse
import os
"""
Please ensure that `visualize=False`, else there might be unexpected errors in your submission
"""
env = RunEnv(visualize=False)
client = Client()
# Create enviro... |
Add a zone port range. | # ##### BEGIN AGPL LICENSE BLOCK #####
# This file is part of SimpleMMO.
#
# Copyright (C) 2011, 2012 Charles Nelson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of... | # ##### BEGIN AGPL LICENSE BLOCK #####
# This file is part of SimpleMMO.
#
# Copyright (C) 2011, 2012 Charles Nelson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of... |
OLMIS-1128: Add redirecting when requisition id is not found | (function() {
'use strict';
angular.module('openlmis.requisitions').config(config);
config.$inject = ['$stateProvider'];
function config($stateProvider) {
$stateProvider.state('requisitions', {
abstract: true,
url: '/requisitions',
template: '<div ui-view></div>'
});
$stateProvider.state('requi... | (function() {
'use strict';
angular.module('openlmis.requisitions').config(config);
config.$inject = ['$stateProvider'];
function config($stateProvider) {
$stateProvider.state('requisitions', {
abstract: true,
url: '/requisitions',
template: '<div ui-view></div>'
});
$stateProvider.state('requi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.