text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Refactor run configuration into decorator | angular.module('resourceSolver', ['ui.router'])
.provider('resourceSolver', function ResourceSolver() {
var baseUrl = '';
this.setBaseUrl = function(url) {
baseUrl = url;
};
this.$get = function() {
return {
getBaseUrl: function() {
return baseUrl;
}
};
};
}).config(['$provi... | angular.module('resourceSolver', [])
.provider('resourceSolver', function ResourceSolver() {
var baseUrl = '';
this.setBaseUrl = function(url) {
baseUrl = url;
};
this.$get = function() {
return {
getBaseUrl: function() {
return baseUrl;
}
};
};
}).run(function($rootScope, $... |
Add a -clean flag to the cmd | package main
import (
// import plugins to ensure they're bound into the executable
_ "github.com/30x/apidApigeeSync"
//_ "github.com/30x/apidVerifyAPIKey"
_ "github.com/30x/apidGatewayDeploy"
// other imports
"github.com/30x/apid"
"github.com/30x/apid/factory"
"flag"
"os"
)
func main() {
configFlag := fla... | package main
import (
// import plugins to ensure they're bound into the executable
_ "github.com/30x/apidApigeeSync"
_ "github.com/30x/apidVerifyAPIKey"
_ "github.com/30x/apidGatewayDeploy"
// other imports
"github.com/30x/apid"
"github.com/30x/apid/factory"
"flag"
"os"
)
func main() {
configFlag := flag.... |
Fix some characters messing up the SECRET_KEY | from __future__ import unicode_literals
import os, re
import tenma
from django.conf import settings
from django.core import management
from django.utils.crypto import get_random_string
from shutil import copyfile, move
BASE_DIR = os.path.dirname(tenma.__file__)
class Command(management.BaseCommand):
help = 'Genera... | from __future__ import unicode_literals
import os, re
import tenma
from django.conf import settings
from django.core import management
from django.utils.crypto import get_random_string
from shutil import copyfile, move
BASE_DIR = os.path.dirname(tenma.__file__)
class Command(management.BaseCommand):
help = 'Genera... |
Add unit test for edge case that wasn't covered | package stats
import (
"testing"
)
func TestCorrelation(t *testing.T) {
s1 := []float64{1, 2, 3, 4, 5}
s2 := []float64{10, -51.2, 8}
s3 := []float64{1, 2, 3, 5, 6}
s4 := []float64{}
s5 := []float64{0, 0, 0}
a, err := Correlation(s5, s5)
if err != nil {
t.Errorf("Should not have returned an error")
}
if a... | package stats
import (
"testing"
)
func TestCorrelation(t *testing.T) {
s1 := []float64{1, 2, 3, 4, 5}
s2 := []float64{10, -51.2, 8}
s3 := []float64{1, 2, 3, 5, 6}
s4 := []float64{}
_, err := Correlation(s1, s2)
if err == nil {
t.Errorf("Mismatched slice lengths should have returned an error")
}
a, err :... |
BUG: Fix tests on old MPL
Old MPL do not have function-defined colormaps, so the corresponding
code path cannot be tested. | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Smoke testing the cm module
"""
from nose import SkipTest
try:
import matplotlib as mp
# Make really sure that we don't try to open an Xserver connection.
mp.use('svg', warn=False)
impo... | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Smoke testing the cm module
"""
from nose import SkipTest
try:
import matplotlib as mp
# Make really sure that we don't try to open an Xserver connection.
mp.use('svg', warn=False)
impo... |
Fix method call of sessionService.sessionExists | (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
... |
Put the `key` on the right element, to shut up React. | import React, { PropTypes } from 'react';
import slug from 'slug';
export default class MapPOILegend extends React.Component {
constructor (props) {
super(props);
}
render () {
let pois = [
{
icon: 'icon_bench',
iconSize: [30, 20],
label: 'benches'
},
{
icon: 'icon_picnic-table',
... | import React, { PropTypes } from 'react';
import slug from 'slug';
export default class MapPOILegend extends React.Component {
constructor (props) {
super(props);
}
render () {
let pois = [
{
icon: 'icon_bench',
iconSize: [30, 20],
label: 'benches'
},
{
icon: 'icon_picnic-table',
... |
Clean config and update it form twig call | <?php
namespace HeyDoc;
class Config
{
protected $config;
/**
*
*
* @param array $config The container
*/
public function __construct(array $config)
{
$this->config = new \ArrayObject(array_replace($this->getDefaults(), $config));
}
public function has($key)
... | <?php
namespace HeyDoc;
class Config
{
protected $config;
/**
*
*
* @param array $config The container
*/
public function __construct(array $config)
{
$this->config = new \ArrayObject(array_replace($this->getDefaults(), $config));
}
public function has($key)
... |
Fix bug in primitive name string put -> insert | package org.spoofax.interpreter.library.ssl;
import io.usethesource.capsule.BinaryRelation;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
public class SSL_im... | package org.spoofax.interpreter.library.ssl;
import io.usethesource.capsule.BinaryRelation;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
public class SSL_im... |
Change to didUpdateAttrs() from observers
Changed to use didUpdateAttrs instead of observers.
Not only is this the standard ember way now, this also prevent firing update() multiple times if multiple changes occur in a single render cycle.
Also added a animate property to allow the user to decide when to animte.
T... | /* global Chart */
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
didInsertElement() {
this._super(...arguments);
let context = this.get('element');
let data = this.get('data');
let type = this.get('type');
... | /* global Chart */
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
didInsertElement: function(){
var context = this.get('element');
var data = this.get('data');
var type = this.get('type');
var options = this.get... |
Embed required non python files in packaging : html and js files for report | #!/usr/bin/env python
"""Tuttle"""
import sys
from tuttle import __version__
try:
from setuptools import setup, find_packages
except ImportError:
print("Tuttle needs setuptools in order to build. Install it using"
" your package manager (usually python-setuptools) or via pip (pip"
" install... | #!/usr/bin/env python
"""Tuttle"""
import sys
from tuttle import __version__
try:
from setuptools import setup, find_packages
except ImportError:
print("Tuttle needs setuptools in order to build. Install it using"
" your package manager (usually python-setuptools) or via pip (pip"
" install... |
Change comment to indicate choice of alphanum order by uri | """A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
Ordinging is currently alphanumeric (using sorted(..)) on the
uri which is the key.
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and ResourceSync Desc... | """A set of Resource objects used for Capability List
Indexes and ResourceSync Description documents.
FIXME - what should the ordering be?
"""
class ResourceSet(dict):
"""Implementation of class to store resources in Capability List
Indexes and ResourceSync Description documents.
Key properties of this c... |
Fix println statement to write a string | package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/beard1ess/gauss/parsing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"io/ioutil"
"reflect"
"testing"
)
func TestDiff(t *testing.T) {
var expected, actual parsing.ConsumableDifference
assert := assert.New(t)
re... | package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/beard1ess/gauss/parsing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"io/ioutil"
"reflect"
"testing"
)
func TestDiff(t *testing.T) {
var expected, actual parsing.ConsumableDifference
assert := assert.New(t)
re... |
Add '--quiet' option for standalone usage
What
===
Add '--quiet' option for standalone usage. When provided the logger will
be turned off resulting in no information writing to stderr.
Why
===
When using standalone with IDEs like vim and plugins like vim-lsc the
stderr of the command will be outputted into the termin... | package org.javacs;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.javacs.lsp.*;
public class Main {
private static final Logger LOG = Logger.getLogger("main");
public static void setRootFormat() {
var root = Logger.getLogger("");
for (va... | package org.javacs;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.javacs.lsp.*;
public class Main {
private static final Logger LOG = Logger.getLogger("main");
public static void setRootFormat() {
var root = Logger.getLogger("");
for (var h : root.getHandlers())... |
Change error message of the weight validator. | # -*- coding: utf-8 -*-
from schematics.exceptions import ConversionError, ValidationError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=e.messages)
def weight_validator(val... | # -*- coding: utf-8 -*-
from schematics.exceptions import ConversionError, ValidationError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=e.messages)
def weight_validator(val... |
Add method to find first by parameter stable id | /*******************************************************************************
* Copyright © 2019 EMBL - European Bioinformatics Institute
* <p/>
* 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 Lic... | /*******************************************************************************
* Copyright © 2019 EMBL - European Bioinformatics Institute
* <p/>
* 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 Lic... |
Fix a problem that lister cannot get resource correctly | package io.kubernetes.client.informer.cache;
import com.google.common.base.Strings;
import java.util.List;
/** Lister interface is used to list cached items from a running informer. */
public class Lister<ApiType> {
private String namespace;
private String indexName;
private Indexer<ApiType> indexer;
publ... | package io.kubernetes.client.informer.cache;
import com.google.common.base.Strings;
import java.util.List;
/** Lister interface is used to list cached items from a running informer. */
public class Lister<ApiType> {
private String namespace;
private String indexName;
private Indexer<ApiType> indexer;
publ... |
Update function to get player stats using base_url | import json
import csv
import requests
from requests.auth import HTTPBasicAuth
import secret
base_url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/'
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
pl... | import json
import csv
import requests
import secret
base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings f... |
Use Opcodes.ASM7_EXPERIMENTAL if system property spotbugs.experimental=true | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2008 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, o... | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2008 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, o... |
Make create_tokenizer work with Japanese | # encoding: utf8
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language, BaseDefaults
from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..tokens import Doc
from .language_data import *
class JapaneseTokenizer(object):
def __init__(self, cls, nlp... | # encoding: utf8
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language
from ..attrs import LANG
from ..tokens import Doc
from .language_data import *
class Japanese(Language):
lang = 'ja'
def make_doc(self, text):
try:
from janome.t... |
Fix migration to run on mysql 5.6 version | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function ... | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function ... |
Add sleep in custom action | const Promise = require('bluebird');
const ld = require('lodash');
const moment = require('moment');
const setMetadata = require('../utils/updateMetadata.js');
/**
* Adds metadata from billing into usermix
* @param {String} username
* @return {Promise}
*/
module.exports = function mixPlan(username, audience) {
... | const ld = require('lodash');
const moment = require('moment');
const setMetadata = require('../utils/updateMetadata.js');
/**
* Adds metadata from billing into usermix
* @param {String} username
* @return {Promise}
*/
module.exports = function mixPlan(username, audience) {
const { amqp, config } = this;
cons... |
Use sha256 instead of sha1 to fix lint | package forgotpwdemail
import (
"crypto/sha256"
"fmt"
"io"
"time"
"github.com/skygeario/skygear-server/pkg/auth/dependency/userprofile"
"github.com/skygeario/skygear-server/pkg/core/auth/authinfo"
)
type CodeGenerator struct {
MasterKey string
}
func (c *CodeGenerator) Generate(
authInfo authinfo.AuthInfo,... | package forgotpwdemail
import (
"crypto/sha1"
"fmt"
"io"
"time"
"github.com/skygeario/skygear-server/pkg/auth/dependency/userprofile"
"github.com/skygeario/skygear-server/pkg/core/auth/authinfo"
)
type CodeGenerator struct {
MasterKey string
}
func (c *CodeGenerator) Generate(
authInfo authinfo.AuthInfo,
... |
Add backwards compatibility for Node.js 0.10 | var banner = require('./');
let chai = require('chai');
let expect = chai.expect;
describe('banner', () => {
let filepath = 'test-target.js';
context('without options (using defaults)', () => {
let expectation = `/*!
* add-banner <https://github.com/jonschlinkert/add-banner>
*
* Copyright (c) 2018 Jon Sch... | var banner = require('./');
let chai = require('chai');
let expect = chai.expect;
describe('banner', () => {
const FILEPATH = 'test-target.js';
context('without options (using defaults)', () => {
let expectation = `/*!
* add-banner <https://github.com/jonschlinkert/add-banner>
*
* Copyright (c) 2018 Jon S... |
Use constant resource to be replaced on reconnect
Network failures may leave the "ghost" bot in the MUC, and unless
it receives a MUC stanza while a replacement is offline, it may
hang in the room forever. Messages are sent to the new resource in
that case.
https://xmpp.org/extensions/xep-0045.html#impl-service-ghost... | #!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"... | #!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"... |
Fix bug with updated auth backend
Now it checks to see if an email is being submitted. | from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
class Emailbackend(ModelBackend):
def authenticate(self, email=None, password=None, *args, **kwargs):
if email is None:
if not 'username' in kwargs or kwargs['username'] is None:
... | from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
class Emailbackend(ModelBackend):
def authenticate(self, email=None, password=None, *args, **kwargs):
if email is None:
if not 'username' in kwargs or kwargs['username'] is None:
... |
FIX Values return type comment | <?php
/**
* Created by PhpStorm.
* User: ahmetturk
* Date: 19/03/2017
* Time: 09:04
*/
namespace Fabs\CouchDB2\Response;
use Fabs\Serialize\SerializableObject;
class ViewResponseElement extends SerializableObject
{
protected $id = null;
protected $key = null;
protected $value = null;
protected $... | <?php
/**
* Created by PhpStorm.
* User: ahmetturk
* Date: 19/03/2017
* Time: 09:04
*/
namespace Fabs\CouchDB2\Response;
use Fabs\Serialize\SerializableObject;
class ViewResponseElement extends SerializableObject
{
protected $id = null;
protected $key = null;
protected $value = null;
protected $... |
Add missing import for HttpResponse | from django.conf import settings
from django.conf.urls.defaults import patterns, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from events.api import EventResource
event_resource = EventResource()
#... | from django.conf import settings
from django.conf.urls.defaults import patterns, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from funfactory.monkeypatches import patch
patch()
from events.api import EventResource
event_resource = EventResource()
# Uncomment the next two lines to enab... |
Validate redirect for logout tests | package handlers
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestLogoutHandler(t *testing.T) {
setUp("/config/testing/handler_logout_url.yml")
handler := http.HandlerFunc(LogoutHandler)
tests := []struct {
name string
url string
wantcode int
}{
{"allowed", "http://myapp.example.c... | package handlers
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestLogoutHandler(t *testing.T) {
setUp("/config/testing/handler_logout_url.yml")
handler := http.HandlerFunc(LogoutHandler)
tests := []struct {
name string
url string
wantcode int
}{
{"allowed", "http://myapp.example.c... |
Fix agent class after merging | package com.kiselev.reflection.ui.bytecode.agent;
import java.lang.instrument.Instrumentation;
/**
* Created by Vadim Kiselev on 6/12/2017.
*/
public class Agent {
public static void agentmain(String args, Instrumentation instrumentation) {
try {
instrumentation.addTransformer(new Transform... | package com.kiselev.reflection.ui.bytecode.agent;
import com.kiselev.reflection.ui.bytecode.holder.ByteCodeHolder;
import java.lang.instrument.Instrumentation;
import java.util.List;
/**
* Created by Vadim Kiselev on 6/12/2017.
*/
public class Agent {
public static void agentmain(String args, Instrumentation ... |
Create the anonymous user server side instead | App.Router.map(function () {
this.resource('projects', {path: '/'}, function() {
this.resource('user-welcome');
this.resource('project', {path: '/:project_id'}, function() {
this.resource('investigation', {path: '/:investigation_id'}, function() {
this.resource('chart', {path: '/:chart_id'}, fun... | App.Router.map(function () {
this.resource('projects', {path: '/'}, function() {
this.resource('user-welcome');
this.resource('project', {path: '/:project_id'}, function() {
this.resource('investigation', {path: '/:investigation_id'}, function() {
this.resource('chart', {path: '/:chart_id'}, fun... |
Update click handler for setting current channel | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getChannels, setChannel } from '../../actions/items';
class ChannelDropdown extends Component {
componentWillMount() {
this.props.getChannels();
}
renderChannels(channelData)... | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getChannels } from '../../actions/items';
class ChannelDropdown extends Component {
componentWillMount() {
this.props.getChannels();
}
setChannel(channel) {
this.props.s... |
Add support for actions to remote dropdown | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'div',
classNames: ['ui', 'search', 'selection', 'dropdown', 'fluid'],
value: null,
text: null,
bindAttributes: ['value', 'text'],
setup: function () {
this.$().dropdown({
apiSettings: {
url: this.get('query-u... | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'div',
classNames: ['ui', 'search', 'selection', 'dropdown', 'fluid'],
value: null,
text: null,
bindAttributes: ['value', 'text'],
setup: function () {
this.$().dropdown({
apiSettings: {
url: this.get('query-u... |
pyecmd: Make fapi2 test conditional on fapi2 being built into ecmd | from pyecmd import *
extensions = {}
if hasattr(ecmd, "fapi2InitExtension"):
extensions["fapi2"] = "ver1"
with Ecmd(**extensions):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins... | from pyecmd import *
with Ecmd(fapi2="ver1"):
t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0]
data = t.getScom(0x1234)
t.putScom(0x1234, 0x10100000)
# These interfaces may not be defined for some plugins
# Pull them to prevent compile issues
#core_id, thread_id = t.targetToSequenceId... |
Clear output buffer only if it's not empty
Former-commit-id: 622fddc8c4d547ec1853d0b8cffe61d102215216 | <? defined('C5_EXECUTE') or die('Access Denied.');
class Concrete5_Helper_Ajax {
/** Sends a result to the client and ends the execution.
* @param mixed $result
*/
public function sendResult($result) {
if(@ob_get_length()) {
@ob_end_clean();
}
header('Content-Type: application/json; charset=' . APP_CHARS... | <? defined('C5_EXECUTE') or die('Access Denied.');
class Concrete5_Helper_Ajax {
/** Sends a result to the client and ends the execution.
* @param mixed $result
*/
public function sendResult($result) {
@ob_end_clean();
header('Content-Type: application/json; charset=' . APP_CHARSET, true);
echo Loader::hel... |
Fix changes in the registry of tile entity renderer in the latest forge updates (30.0.19) | package info.u_team.u_team_core.util.registry;
import java.util.function.Function;
import net.minecraft.client.renderer.tileentity.*;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.*;
import net.minecraft.tileentity.*;
import net.minecraftforge.api.distmarker.*;
import net.minec... | package info.u_team.u_team_core.util.registry;
import net.minecraft.client.renderer.tileentity.TileEntityRenderer;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.*;
import net.minecraft.tileentity.*;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.fml.client.r... |
Add "i have a problem" as new trigger | // Description
// Get an inspiring question form serenize.me
//
// Commands:
// hubot <serenize me> - <fetches a question>
// hubot <serenize.me> - <fetches a question>
// hubot <i have a problem> - <fetches a question>
//
// Author:
// Serenize
module.exports = function(robot) {
'use strict';
robot.res... | // Description
// Get an inspiring question form serenize.me
//
// Commands:
// hubot <serenize me> - <fetches a question>
// hubot <serenize.me> - <fetches a question>
//
// Author:
// Serenize
module.exports = function(robot) {
'use strict';
robot.respond(/serenize me/i, function(res) {
getQuestion(... |
Add construction counts to the qualities catalog. | @section('title')
Qualities - Cataclysm: Dark Days Ahead
@endsection
<h1>Qualities</h1>
<div class="row">
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked">
@foreach($qualities as $quality)
<li class="@if($quality->id==$id) active @endif"><a href="{{ route(Route::currentRouteName(), $quality->id) }}">{{{$... | @section('title')
Qualities - Cataclysm: Dark Days Ahead
@endsection
<h1>Qualities</h1>
<div class="row">
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked">
@foreach($qualities as $quality)
<li class="@if($quality->id==$id) active @endif"><a href="{{ route(Route::currentRouteName(), $quality->id) }}">{{{$... |
system: Fix style for controller class | <?php
/**
* This file contains the base abstract controller class.
*
* PHP Version 5.3
*
* @category Libraries
* @package Core
* @subpackage Libraries
* @author M2Mobi <info@m2mobi.com>
* @author Heinz Wiesinger <heinz@m2mobi.com>
*/
/**
* Base Controller class
*
* @category Libraries
* @... | <?php
/**
* This file contains the base abstract controller class.
*
* PHP Version 5.3
*
* @category Libraries
* @package Core
* @subpackage Libraries
* @author M2Mobi <info@m2mobi.com>
* @author Heinz Wiesinger <heinz@m2mobi.com>
*/
/**
* Base Controller class
*
* @category Libraries
* @... |
Add target to aui-button links | export default {
render(createComponent) {
const attrs = {
disabled: this.disabled,
href: this.href,
target: this.target
};
const elementType = this.href ? 'a' : 'button'
return createComponent(elementType, {
class: this.classObject,
attrs
}, this.$slots.default)
}... | export default {
render(createComponent) {
const attrs = {
disabled: this.disabled,
href: this.href
};
const elementType = this.href ? 'a' : 'button'
return createComponent(elementType, {
class: this.classObject,
attrs
}, this.$slots.default)
},
props: {
compact: ... |
Reduce the slugify rebounce to 250ms instead of 1000ms. | var seo = {
init: function() {
this.sluggable_input().on('keyup', $.debounce(250, this.keyup_listener));
},
data: function(key) {
return $('[data-seo]').data(key);
},
keyup_listener: function(e) {
if(seo.slug_input().attr('disabled')) return;
$.ajax({
url: seo.data('path'),
data... | var seo = {
init: function() {
this.sluggable_input().on('keyup', $.debounce(1000, this.keyup_listener));
},
data: function(key) {
return $('[data-seo]').data(key);
},
keyup_listener: function(e) {
if(seo.slug_input().attr('disabled')) return;
$.ajax({
url: seo.data('path'),
dat... |
Move status to database instead of status file (server side) | from __future__ import unicode_literals
import os
import logging
import sqlite3
from . import helper
def readStatus(config, student):
database = getStatusTable(config)
cursor = database.cursor()
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone... | from __future__ import unicode_literals
import os
import logging
from . import helper
def readStatus(config, student):
student = student.lower()
path = config("attachment_path")
if not os.path.exists(path):
return
path = os.path.join(path, student)
if not os.path.exists(path):
... |
Fix code as int test | package errors
import (
nativeErrors "errors"
"net/http"
"testing"
)
func TestHTTPStatusCode(t *testing.T) {
if HTTPStatusCode(nil) != http.StatusOK {
t.Error("Status code does not match")
}
if HTTPStatusCode(New(INTERNAL, "internal error")) != http.StatusInternalServerError {
t.Error("Status code does not... | package errors
import (
nativeErrors "errors"
"net/http"
"testing"
)
func TestHTTPStatusCode(t *testing.T) {
if HTTPStatusCode(nil) != http.StatusOK {
t.Error("Status code does not match")
}
if HTTPStatusCode(New(INTERNAL, "internal error")) != http.StatusInternalServerError {
t.Error("Status code does not... |
Make isAdmin method more readable. | <?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Phragile\PhabricatorAPI;
class User extends Eloquent implements UserInterface {
// This is used for password authentication, recovery etc which we don't need.
// Only using this because Auth::login won't work otherwise.
use UserTrait;
p... | <?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Phragile\PhabricatorAPI;
class User extends Eloquent implements UserInterface {
// This is used for password authentication, recovery etc which we don't need.
// Only using this because Auth::login won't work otherwise.
use UserTrait;
p... |
Swap the arguments being passed to trigger_error().
Fixes issue #247
http://symphony-cms.com/discuss/issues/view/247/ | <?php
Class DateTimeObj{
public static function setDefaultTimezone($timezone){
if(!@date_default_timezone_set($timezone)) trigger_error("Invalid timezone '{$timezone}'", E_USER_WARNING);
}
public static function getGMT($format, $timestamp=NULL){
return self::get($format, $timestamp, 'GMT');
}
p... | <?php
Class DateTimeObj{
public static function setDefaultTimezone($timezone){
if(!@date_default_timezone_set($timezone)) trigger_error(E_USER_WARNING, "Invalid timezone '{$timezone}'");
}
public static function getGMT($format, $timestamp=NULL){
return self::get($format, $timestamp, 'GMT');
}
p... |
Change the way golang packages are built | package buildcfg
import (
"net/url"
"strings"
)
func goImportPath(remote string) string {
if strings.Contains(remote, ":") && strings.Contains(remote, "@") {
rem := remote[strings.Index(remote, "@")+1:]
return strings.Replace(strings.Replace(rem, ".git", "", 1), ":", "/", 1)
}
u, err := url.Parse(remote)
if... | package buildcfg
import (
"net/url"
"strings"
)
func loadGoConfig(remote string, c *Config) {
u, _ := url.Parse(remote)
importPath := u.Hostname() + strings.Replace(u.Path, ".git", "", 1)
// Most part of this just moves everything from builddir to the correct go-import-path
setup := []string{
"export GOPATH=... |
Read current version from `package.json` | var VERSION = require('../package.json').version;
var _ = require('lodash');
var DEFAULT_API_URL = 'https://api.podio.com:443';
var utils = require('./utils');
var GeneralLib = require('./general');
var AuthLib = require('./auth');
var TransportLib = require('./transport');
var PodioJS = function(authOptions, optio... | var VERSION = '1.0.0';
var _ = require('lodash');
var DEFAULT_API_URL = 'https://api.podio.com:443';
var utils = require('./utils');
var GeneralLib = require('./general');
var AuthLib = require('./auth');
var TransportLib = require('./transport');
var PodioJS = function(authOptions, options) {
this.VERSION = VERS... |
Remove use of deprecated `scan_plugins` method
`scan_plugins` has been deprecated in favour of `scan_plugins_regex`. This
is causing warnings to be logged.
The new method takes a regular expression as its first argument, rather than a
simple prefix string. This commit adds a regular expression which does the s... | """
pyexcel.internal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pyexcel internals that subjected to change
:copyright: (c) 2015-2017 by Onni Software Ltd.
:license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER # noqa
from pyexcel.int... | """
pyexcel.internal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pyexcel internals that subjected to change
:copyright: (c) 2015-2017 by Onni Software Ltd.
:license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER # noqa
from pyexcel.int... |
Add default values to Build variables | package main
import (
"fmt"
"github.com/almighty/almighty-core/app"
"github.com/almighty/almighty-core/swagger"
"github.com/goadesign/goa"
"github.com/goadesign/goa/middleware"
)
var (
// Commit current build commit set by build script
Commit = "0"
// BuildTime set by build script
BuildTime = "0"
)
func ma... | package main
import (
"fmt"
"github.com/almighty/almighty-core/app"
"github.com/almighty/almighty-core/swagger"
"github.com/goadesign/goa"
"github.com/goadesign/goa/middleware"
)
var (
// Commit current build commit set by build script
Commit string
// BuildTime set by build script
BuildTime string
)
func ... |
Add version constraint for easy-meteor-settings | Package.describe({
name: 'hubaaa:endpoint-puller',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: 'Pulls API endpoints, checking for new data and passing it through json pipes.',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/hubaaa/... | Package.describe({
name: 'hubaaa:endpoint-puller',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: 'Pulls API endpoints, checking for new data and passing it through json pipes.',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/hubaaa/... |
[Feature] Create BucketList & BucketLists endpoints. | """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResour... | """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResour... |
Add generated code in exe_module. | // GENERATED BY grunt make_dir_module.
export var dir = {};
export default dir;
import m0 from "wash/exe/cat";
dir["cat"] = m0;
import m1 from "wash/exe/clear";
dir["clear"] = m1;
import m2 from "wash/exe/cp";
dir["cp"] = m2;
import m3 from "wash/exe/echo";
dir["echo"] = m3;
import m4 from "wash/exe/eval";
dir["eval"] ... | // GENERATED BY grunt make_dir_module.
export var dir = {};
export default dir;
import m0 from "wash/exe/cat";
dir["cat"] = m0;
import m1 from "wash/exe/clear";
dir["clear"] = m1;
import m2 from "wash/exe/cp";
dir["cp"] = m2;
import m3 from "wash/exe/echo";
dir["echo"] = m3;
import m4 from "wash/exe/import";
dir["impor... |
Support usage when size = 0
I got an error when encoding an empty message (`{}`).
When the message is empty, the size is 0 and `slab` is null, so`slice.call(slab, offset, offset += size);` gave me
```
Uncaught TypeError: Method get TypedArray.prototype.subarray called on incompatible receiver null
```
Adding thi... | "use strict";
module.exports = pool;
/**
* An allocator as used by {@link util.pool}.
* @typedef PoolAllocator
* @type {function}
* @param {number} size Buffer size
* @returns {Uint8Array} Buffer
*/
/**
* A slicer as used by {@link util.pool}.
* @typedef PoolSlicer
* @type {function}
* @param {number} start... | "use strict";
module.exports = pool;
/**
* An allocator as used by {@link util.pool}.
* @typedef PoolAllocator
* @type {function}
* @param {number} size Buffer size
* @returns {Uint8Array} Buffer
*/
/**
* A slicer as used by {@link util.pool}.
* @typedef PoolSlicer
* @type {function}
* @param {number} start... |
Update git url and bump version to 0.1.1 | Package.describe({
name: 'hubaaa:easy-meteor-settings',
version: '0.1.1',
// Brief, one-line summary of the package.
summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/hubaaa/meteor-easy-me... | Package.describe({
name: 'hubaaa:easy-meteor-settings',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default ... |
Add a default option to predicate mapper | /*
* Copyright 2009-2014 Marcelo Guimarães
*
* 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 applicab... | /*
* Copyright 2009-2014 Marcelo Guimarães
*
* 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 applicab... |
Create media file when it doesn't exist, use local copy when it does | package gitmediafilters
import (
".."
"../client"
"io"
"os"
)
func Smudge(writer io.Writer, sha string) error {
mediafile := gitmedia.LocalMediaPath(sha)
if stat, err := os.Stat(mediafile); err != nil || stat == nil {
reader, err := gitmediaclient.Get(mediafile)
if err != nil {
return &SmudgeError{sha, ... | package gitmediafilters
import (
".."
"../client"
"io"
"os"
)
func Smudge(writer io.Writer, sha string) error { // stdout, sha
mediafile := gitmedia.LocalMediaPath(sha)
reader, err := gitmediaclient.Get(mediafile)
if err != nil {
return &SmudgeError{sha, mediafile, err.Error()}
}
defer reader.Close()
me... |
Fix tiny typo in comment | <?php
namespace Nathiss\Bundle\QuoteGeneratorBundle\Repository;
/**
* QuoteRepository
*/
class QuoteRepository extends \Doctrine\ORM\EntityRepository
{
/**
* Selects Quote from DB randomly
*
* @return \Nathiss\Bundle\QuoteGenerateBundle\Entity\Quote
*/
public function findOneRandomly()
... | <?php
namespace Nathiss\Bundle\QuoteGeneratorBundle\Repository;
/**
* QuoteRepository
*/
class QuoteRepository extends \Doctrine\ORM\EntityRepository
{
/**
* Selects Query from DB randomly
*
* @return \Nathiss\Bundle\QuoteGenerateBundle\Entity\Quote
*/
public function findOneRandomly()
... |
Allow puphpet machine to see dev env | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This chec... | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This chec... |
Fix checksum failure when reexecuting changesets with
dropNotNullConstraint
The checksum validation failed when a changeset containing a
<dropNotNullConstraint> change was processed for the second time.
The reason is that the statement generation (which only occurs when the
change
is really executed, i.e. the first ti... | package liquibase.change.ext;
import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.core.DropNotNullConstraintChange;
import liquibase.database.Database;
import liquibase.database.ext.HanaDBDatabase;
import liquibase.statement.SqlStatement;
import liquibase.statement.c... | package liquibase.change.ext;
import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.core.DropNotNullConstraintChange;
import liquibase.database.Database;
import liquibase.database.ext.HanaDBDatabase;
import liquibase.statement.SqlStatement;
import liquibase.statement.c... |
Add default type to declarations | import {
CREATE_DECLARATION, REMOVE_DECLARATION, EDIT_DECLARATION
} from '../actions/declaration'
import {
LOAD_QUESTIONNAIRE_SUCCESS
} from '../actions/questionnaire'
import { DECLARATION_TYPE } from '../constants/pogues-constants'
const { INSTRUCTION } = DECLARATION_TYPE
const emptyDeclaration = {
type: INSTR... | import {
CREATE_DECLARATION, REMOVE_DECLARATION, EDIT_DECLARATION
} from '../actions/declaration'
import {
LOAD_QUESTIONNAIRE_SUCCESS
} from '../actions/questionnaire'
const emptyDeclaration = {
type: '',
disjoignable: true,
text: ''
}
export default function (state={}, action) {
const { type, payload } ... |
Make a copy of dicts before deleting things from them when printing. | import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o.copy()
else:... | import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o
else:
... |
Add missing extension in import | import Map from '../../../src/ol/Map.js';
import View from '../../../src/ol/View.js';
import {Group as LayerGroup, Tile as TileLayer} from '../../../src/ol/layer.js';
import XYZ from '../../../src/ol/source/XYZ.js';
new Map({
target: 'map',
view: new View({
center: [0, 0],
zoom: 3
}),
layers: new Layer... | import Map from '../../../src/ol/Map.js';
import View from '../../../src/ol/View.js';
import {Group as LayerGroup, Tile as TileLayer} from '../../../src/ol/layer.js';
import XYZ from '../../../src/ol/source/XYZ';
new Map({
target: 'map',
view: new View({
center: [0, 0],
zoom: 3
}),
layers: new LayerGro... |
Add support for flash messages | <?php
namespace Framework;
class Controller {
private $app;
private $api;
function __construct($app){
$this->app = $app;
}
protected function setHeader($header, $value)
{
$this->app->response->headers->set($header, $value);
}
protected function setLayout($layout) {
$this->app->view->setLayout($layou... | <?php
namespace Framework;
class Controller {
private $app;
private $api;
function __construct($app){
$this->app = $app;
}
protected function setHeader($header, $value)
{
$this->app->response->headers->set($header, $value);
}
protected function setLayout($layout) {
$this->app->view->setLayout($layou... |
chore: Correct typo in pg_table_def create view query | package jp.ne.opt.redshiftfake.views;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by frankfarrell on 14/06/2018.
*
* Some system tables that exist in redshift do not necessarily exist in postgres
*
* This creates pg_tableef as a view on each connection if it... | package jp.ne.opt.redshiftfake.views;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by ffarrell on 14/06/2018.
*
* Some system tables that exist in redshift do not necessarily exist in postgres
*
* This creates pg_tableef as a view on each connection if it doe... |
Support user-defined convenience package names | package gogist
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
const t = `
<html>
<head>
<meta name="go-import" content="%s git https://gist.github.com/%s.git" />
<script>window.location='https://github.com/ImJasonH/go-gist/';</script>
</head>
</html>
`
func init() {
r := mux.NewRouter()
h := ... | package gogist
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
const t = `
<html>
<head>
<meta name="go-import" content="%s git https://gist.github.com/%s.git" />
<script>window.location='https://github.com/ImJasonH/go-gist/';</script>
</head>
</html>
`
func init() {
r := mux.NewRouter()
h := ... |
Use if-elif instead of multiple if statements to check types
Use if-elif instead of multiple if statements to check types when converting from MongoDB BaseDict and BaseList to python dict and list types. Once the value is converted, use another if-elif block to recursively evaluate and convert the values of dict and l... | # Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
Use alt thumb for front page tysky block
if set | <?php
$meta = get_post_meta($post->ID);
?>
<a href="<?php the_permalink() ?>">
<article <?php post_class('margin-bottom-small'); ?> id="post-<?php the_ID(); ?>">
<?php
if (!empty($meta['_cmb_alt_thumb_id'])) {
echo wp_get_attachment_image($meta['_cmb_alt_thumb_id'][0], 'col6-16to9', false, array(... | <?php
$meta = get_post_meta($post->ID);
?>
<a href="<?php the_permalink() ?>">
<article <?php post_class('margin-bottom-small'); ?> id="post-<?php the_ID(); ?>">
<?php the_post_thumbnail('col6-16to9', array('class' => 'margin-bottom-micro only-desktop')); ?>
<?php the_post_thumbnail('mobile-16to9', array('... |
Fix xml declaration not parsed | <?php
if(!function_exists('wp_bootstrap_the_content')) {
function wp_bootstrap_the_content($content) {
$html = new DOMDocument();
@$html->loadHTML('<?xml encoding="utf-8" ?>' . $content );
$image_nodes = $html->getElementsByTagName( 'img' );
foreach ($image_nodes as $image_node) {
$cl... | <?php
if(!function_exists('wp_bootstrap_the_content')) {
function wp_bootstrap_the_content($content) {
$html = new DOMDocument();
@$html->loadHTML('<?xml encoding="utf-8" ?>' . $content );
$image_nodes = $html->getElementsByTagName( 'img' );
foreach ($image_nodes as $image_node) {
$cl... |
Use table instead of separate lines | import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some ba... | import string
import textwrap
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some basic info about the string such as:
- Len... |
Allow indexing blank country field | from haystack.indexes import SearchIndex, CharField, MultiValueField, BooleanField
from haystack import site
from .models import MuseumObject
class MuseumObjectIndex(SearchIndex):
text = CharField(document=True, use_template=True)
categories = MultiValueField(faceted=True)
item_name = CharField(model_attr... | from haystack.indexes import SearchIndex, CharField, MultiValueField, BooleanField
from haystack import site
from .models import MuseumObject
class MuseumObjectIndex(SearchIndex):
text = CharField(document=True, use_template=True)
categories = MultiValueField(faceted=True)
item_name = CharField(model_attr... |
Disable icon temporarily and adjust the debug print statements | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Local Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.registe... | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.register()
... |
Unify variable names in components(junit5-spring) | /*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
*
* 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 require... | /*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
*
* 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 require... |
Disable all timing output in production for now | // These are the primary log levels.
// Your logger object has a method for each of these.
var LOG_LEVELS = {
emergency : 7,
alert : 6,
critical : 5,
error : 4,
warning : 3,
notice : 2,
info : 1,
debug : 0,
}
// Need these to be shared across triton and corvair (can actually be modified
... | // These are the primary log levels.
// Your logger object has a method for each of these.
var LOG_LEVELS = {
emergency : 7,
alert : 6,
critical : 5,
error : 4,
warning : 3,
notice : 2,
info : 1,
debug : 0,
}
// Need these to be shared across triton and corvair (can actually be modified
... |
Fix ajax request in Stimulus maps controller | import {Controller} from "stimulus"
export default class extends Controller {
static targets = ["mapInfo"]
connect() {
const courseId = this.mapInfoTarget.dataset.courseId;
const splitId = this.mapInfoTarget.dataset.splitId;
Rails.ajax({
url: "/api/v1/courses/" + courseId... | import {Controller} from "stimulus"
export default class extends Controller {
static targets = ["mapInfo"]
connect() {
const courseId = this.mapInfoTarget.dataset.courseId;
const splitId = this.mapInfoTarget.dataset.splitId;
Rails.ajax({
url: "/courses/" + courseId + '.js... |
Allow config access to app object | #! /usr/bin/env python3
from functools import partial
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
app = Flask("odie", template_folder='admin/templates', static_folder='admin/static')
import config # pylint: disable=unused-import
app.config.from_objec... | #! /usr/bin/env python3
import config # pylint: disable=unused-import
from functools import partial
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
app = Flask("odie", template_folder='admin/templates', static_folder='admin/static')
app.config.from_obje... |
Change MIME-type for JSON-LD graph query responses
- Addresses EBISPOT/lodestar#25 upstream and HHS/meshrdf#91 downstream | package uk.ac.ebi.fgpt.lode.utils;
/**
* @author Simon Jupp
* @date 21/02/2013
* Functional Genomics Group EMBL-EBI
*/
public enum GraphQueryFormats {
RDFXML ("RDF/XML", "application/rdf+xml"),
N3 ("N3", "application/rdf+n3"),
JSON ("JSON-LD", "application/ld+json"),
TURTLE ("TURTLE", "text/turtle... | package uk.ac.ebi.fgpt.lode.utils;
/**
* @author Simon Jupp
* @date 21/02/2013
* Functional Genomics Group EMBL-EBI
*/
public enum GraphQueryFormats {
RDFXML ("RDF/XML", "application/rdf+xml"),
N3 ("N3", "application/rdf+n3"),
JSON ("JSON-LD", "application/rdf+json"),
TURTLE ("TURTLE", "text/turtl... |
Make JS observation on 'change notice period' form live.
Now our JavaScript can still catch events even when the form
elements are added to the DOM after page load. | // Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(document).ready(function () {
$(document).on('change', '#change_meeting_notice_period_resolution_meeting_notice_period', function() {
var currentMeetingNoticePeriod ... | // Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(document).ready(function () {
var currentMeetingNoticePeriod = parseInt($('span.meeting_notice_period').first().text());
$('#change_meeting_notice_period_resolution_me... |
cmd/table: Change interface to search nodes by role. | // Chef client command-line tool.
package main
import (
"flag"
"fmt"
"os"
"github.com/marpaia/chef-golang"
"github.com/shurcooL/go-goon"
)
var _ = goon.Dump
func chefConnect() *chef.Chef {
c, err := chef.Connect()
if err != nil {
panic(err)
}
c.SSLNoVerify = true
return c
}
func main() {
flag.Parse()
... | // Chef client command-line tool.
package main
import (
"flag"
"fmt"
"os"
"github.com/marpaia/chef-golang"
"github.com/shurcooL/go-goon"
)
var _ = goon.Dump
func chefConnect() *chef.Chef {
c, err := chef.Connect()
if err != nil {
panic(err)
}
c.SSLNoVerify = true
return c
}
func main() {
flag.Parse()
... |
Change to promise for Wit runactions | 'use strict';
const config = require('../../config');
const Facebook = require('../../app/services/facebook');
const sessions = require('../../app/services/sessions');
module.exports = {
get: (req, reply) => {
if (req.query['hub.verify_token'] === config.Facebook.verifyToken) {
return reply(req.query['hub... | 'use strict';
const config = require('../../config');
const Facebook = require('../../app/services/facebook');
const sessions = require('../../app/services/sessions');
module.exports = {
get: (req, reply) => {
if (req.query['hub.verify_token'] === config.Facebook.verifyToken) {
return reply(req.query['hub... |
Increase version 3.1.6 -> 3.1.7 | #!/usr/bin/env python
from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code
version = '3.1.7'
author = 'Yannick Dieter, David-Leon Pohl, Jens Janssen'
author_email = 'dieter@physik.uni-bonn.de, pohl@physik.uni-bonn.de, janssen@physik.uni-bo... | #!/usr/bin/env python
from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code
version = '3.1.6.dev0'
author = 'David-Leon Pohl, Jens Janssen'
author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de'
# requirements for core functi... |
Add comments to HTTPError interface
This can be very confusing potentially | package errors
import "fmt"
type HttpError interface {
error
StatusCode() int // actual HTTP status code
ErrorCode() string // error code returned in response body from CC or UAA
Headers() string // see: known_error_codes.go
Body() string
}
type httpError struct {
statusCode int
headers string
body ... | package errors
import "fmt"
type HttpError interface {
Error
StatusCode() int
Headers() string
Body() string
}
type httpError struct {
statusCode int
headers string
body string
code string
description string
}
type HttpNotFoundError struct {
*httpError
}
func NewHttpError(statusCode in... |
Fix bug when saving users in mailing list | <?php
// fetch email addresses and remove duplicates
$emails = Lista::remove_duplicates_from($_POST['email_addresses']);
/* Saves users in the list.
* @param $list_id the ID of the mailing list you want to save the users to.
* @param $emails an array of unique emails.
*/
foreach ($emails as $email) {
$_... | <?php
// fetch email addresses and remove duplicates
$emails = Lista::remove_duplicates_from($_POST['email_addresses']);
/* Saves users in the list.
* @param $list_id the ID of the mailing list you want to save the users to.
* @param $emails an array of unique emails.
*
*/
foreach ($emails as $email) {
i... |
Add date in log format | """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
LOGGING_FORMAT = "%(asctime)-15s:%(levelname)s:%(name)s:%(message)s"
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer... | """Provide all package executables
"""
import logging
from docopt import docopt
from hpcbench import __version__
from hpcbench.toolbox.loader import load_components
def setup_logger(verbose):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = loggin... |
Use DIRECTORY_SEPARATOR instead of hard-coded '/'
We never know where this thing is going to be run on. | <?php
namespace UView;
class View {
protected $storage = [];
protected $path;
public function __construct( $path ) {
$this->path = $path;
}
public function set( $var, $value ) {
$this->storage[ $var ] = $value;
}
public function __toString() {
ob_start();
// "Trigger" a "-" error, so that we can ch... | <?php
namespace UView;
class View {
protected $storage = [];
protected $path;
public function __construct( $path ) {
$this->path = $path;
}
public function set( $var, $value ) {
$this->storage[ $var ] = $value;
}
public function __toString() {
ob_start();
// "Trigger" a "-" error, so that we can ch... |
Remove print-link JS. There aren't any print links in the template | $(document).ready(function() {
// fix for printing bug in Windows Safari
var windowsSafari = (window.navigator.userAgent.match(/(\(Windows[\s\w\.]+\))[\/\(\s\w\.\,\)]+(Version\/[\d\.]+)\s(Safari\/[\d\.]+)/) !== null),
style;
if (windowsSafari) {
// set the New Transport font to Arial for printing
s... | $(document).ready(function() {
$('.print-link a').attr('target', '_blank');
// fix for printing bug in Windows Safari
var windowsSafari = (window.navigator.userAgent.match(/(\(Windows[\s\w\.]+\))[\/\(\s\w\.\,\)]+(Version\/[\d\.]+)\s(Safari\/[\d\.]+)/) !== null),
style;
if (windowsSafari) {
// set th... |
[SMALLFIX] Replace lambda with method reference
replace lambda with method reference in
/alluxio/core/server/master/src/main/java/alluxio/master/file/BlockDeletionContext.java#registerBlocksForDeletion
Change
blockIds.forEach(id -> registerBlockForDeletion(id));
to
blockIds.forEach(this::registerBlockForDeletion);
p... | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI... | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI... |
Fix typo at calendar transaction
Summary:
* Fixed conveted => converted
Ref T11576
Test Plan: * Looked at a page, where somebody converted an AllDay Event to a normal one
Reviewers: #blessed_reviewers, epriestley
Reviewed By: #blessed_reviewers, epriestley
Subscribers: epriestley
Tags: #calendar
Maniphest Tasks:... | <?php
final class PhabricatorCalendarEventAllDayTransaction
extends PhabricatorCalendarEventTransactionType {
const TRANSACTIONTYPE = 'calendar.allday';
public function generateOldValue($object) {
return (int)$object->getIsAllDay();
}
public function generateNewValue($object, $value) {
return (int... | <?php
final class PhabricatorCalendarEventAllDayTransaction
extends PhabricatorCalendarEventTransactionType {
const TRANSACTIONTYPE = 'calendar.allday';
public function generateOldValue($object) {
return (int)$object->getIsAllDay();
}
public function generateNewValue($object, $value) {
return (int... |
Fix for requiring autoloader in bin script. | #!/usr/bin/env php
<?php
/*
* This file is part of StaticReview
*
* Copyright (c) 2014 Samuel Parkinson <@samparkinson_>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @see http://github.com/sjparkinson/static-review/blob/master... | #!/usr/bin/env php
<?php
/*
* This file is part of StaticReview
*
* Copyright (c) 2014 Samuel Parkinson <@samparkinson_>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @see http://github.com/sjparkinson/static-review/blob/master... |
Add comment about allowed accesses. | class ArrayAccessExpressionTest {
public static void main(String[] args) {
int i;
int[] ia;
long l;
long[] la;
boolean b;
A cA;
B cB;
//i = ia[i];// OK!
i = ia[ia]; // INVALID_INDEX_TYPE
i = ia[l]; // INVALID_INDEX_TYPE
i = ia... | class ArrayAccessExpressionTest {
public static void main(String[] args) {
int i;
int[] ia;
long l;
long[] la;
boolean b;
A cA;
B cB;
i = ia[ia]; // INVALID_INDEX_TYPE
i = ia[l]; // INVALID_INDEX_TYPE
i = ia[la]; // INVALID_INDEX_TYPE... |
Use async await on test | import createCredentialsAuthenticator from '../../src/authenticators/credentials'
beforeEach(() => {
fetch.resetMocks()
})
it('fetches from given endpoint using default config', () => {
fetch.mockResponse(JSON.stringify({ ok: true }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenti... | import createCredentialsAuthenticator from '../../src/authenticators/credentials'
beforeEach(() => {
fetch.resetMocks()
})
it('fetches from given endpoint using default config', () => {
fetch.mockResponse(JSON.stringify({ ok: true }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenti... |
Add better python path description | var path = require('path');
var fs = require('fs');
module.exports = function() {
verifyNode();
verifyPython27();
};
function verifyNode() {
var nodeVersion = process.versions.node.split('.');
var nodeMajorVersion = +nodeVersion[0];
var nodeMinorVersion = +nodeVersion[1];
if (nodeMajorVersion === 0 && nod... | var path = require('path');
var fs = require('fs');
module.exports = function() {
verifyNode();
verifyPython27();
};
function verifyNode() {
var nodeVersion = process.versions.node.split('.');
var nodeMajorVersion = +nodeVersion[0];
var nodeMinorVersion = +nodeVersion[1];
if (nodeMajorVersion === 0 && nod... |
Fix double quotes to single quotes | from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
class Config:
schema_extra = {
'examples': [
{
'name': 'John Doe',
'age': 25,
}
]
}
print(Person.schema())
# {'title... | from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
class Config:
schema_extra = {
"examples": [
{
"name": "John Doe",
"age": 25,
}
]
}
print(Person.schema())
# {'title... |
Test that there are errors instead of exact number | import React from 'react';
import { mount, shallow } from 'enzyme';
import App from './App';
import TimeTable from 'timetablescreen';
describe('App', () => {
beforeEach( () => {
Object.defineProperty(window.location, 'href', {
writable: true,
value: 'localhost:3000/kara'
});
});
it('renders without crash... | import React from 'react';
import { mount, shallow } from 'enzyme';
import App from './App';
import TimeTable from 'timetablescreen';
describe('App', () => {
beforeEach( () => {
Object.defineProperty(window.location, 'href', {
writable: true,
value: 'localhost:3000/kara'
});
});
it('renders without crash... |
Apply ember codemods on tests | import { module, test, todo } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | bs datetimepicker', function(hooks) {
setupRenderingTest(hooks);
todo('it renders iconClasses ... | import { moduleForComponent, test, todo } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('bs-datetimepicker', 'Integration | Component | bs datetimepicker', {
integration: true
});
todo('it renders iconClasses and iconText', function(assert) {
assert.expect(2);
this.render... |
Drop meteor-base version to 1.5 for tests to pass | Package.describe({
name: 'meteor-base',
version: '1.5.0-beta230.2',
// Brief, one-line summary of the package.
summary: 'Packages that every Meteor app needs',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentati... | Package.describe({
name: 'meteor-base',
version: '2.0.0-beta230.2',
// Brief, one-line summary of the package.
summary: 'Packages that every Meteor app needs',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentati... |
Use requests 0.14.1 from now on. | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
from setuptools import find_packages
classifiers = [
"Intended Audience :: Developers",
"Programming Language :: Python",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries",
"Environment :: Web Envir... | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
from setuptools import find_packages
classifiers = [
"Intended Audience :: Developers",
"Programming Language :: Python",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries",
"Environment :: Web Envir... |
Use sphinx-apidoc to generate API docs from docstrings. | from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
run("rm -rf docs/binaryornot.rst")
run("rm -rf docs/modules.rst")
@task('clean_docs')
def docs():
run("sphinx-apidoc -o docs/ binaryornot/")
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@... | from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
@task('clean_docs')
def docs():
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -... |
Add Adress to lat, lng converter | define(["backbone", "underscore", "jquery"], function(Backbone, _, $) {
var UserProfile = Backbone.Model.extend({
//data attributes
defaults: {
age: null,
gender: null,
address: null,
pricePerSMeter: null,
color: null,
extras: null,
},
convertAddress... | define(["backbone", "underscore" ], function(Backbone, _) {
var UserProfile = Backbone.Model.extend({
//data attributes
defaults: {
age: null,
gender: null,
address: null,
pricePerSMeter: null,
color: null,
extras: null,
},
//converters
getMinMax... |
Add correct props to mapStateToProps | import { connect } from 'react-redux';
import {
fetchNavigation,
setNavigationVisibility,
fetchTOS,
setPhaseVisibility,
setPhasesVisibility,
setDocumentState,
fetchRecordTypes,
fetchAttributeTypes,
addAction,
addRecord,
addPhase,
changeOrder,
importItems,
closeMessage
} from '../modules/home... | import { connect } from 'react-redux';
import {
fetchNavigation,
setNavigationVisibility,
fetchTOS,
setPhaseVisibility,
setPhasesVisibility,
setDocumentState,
fetchRecordTypes,
fetchAttributeTypes,
addAction,
addRecord,
addPhase,
changeOrder,
importItems,
closeMessage
} from '../modules/home... |
Make sure to always restore "debug" state in page-example test | <?php
class CM_Page_ExampleTest extends CMTest_TestCase {
/** @var bool */
private $_debugBackup;
protected function setUp() {
$this->_debugBackup = CM_Bootloader::getInstance()->isDebug();
}
protected function tearDown() {
CM_Bootloader::getInstance()->setDebug($this->_debugBack... | <?php
class CM_Page_ExampleTest extends CMTest_TestCase {
public function testAccessible() {
$debugBackup = CM_Bootloader::getInstance()->isDebug();
$page = new CM_Page_Example();
CM_Bootloader::getInstance()->setDebug(true);
$this->_renderPage($page);
CM_Bootloader::getI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.