text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use absolute usage file path | #!/usr/bin/env node
require('exit-code');
var fs = require('fs');
var path = require('path');
var minimist = require('minimist');
var argv = minimist(process.argv.slice(2), {
alias: {
n: 'node',
b: 'browser',
r: 'report',
h: 'help',
v: 'version'
}
});
if (argv.help) {
logHelp();
} else if ... | #!/usr/bin/env node
require('exit-code');
var fs = require('fs');
var minimist = require('minimist');
var argv = minimist(process.argv.slice(2), {
alias: {
n: 'node',
b: 'browser',
r: 'report',
h: 'help',
v: 'version'
}
});
if (argv.help) {
logHelp();
} else if (argv.version) {
logVersio... |
Monitor temperature script as used for heating measurement | import time
import serial
import matplotlib.pyplot as plt
import csv
import os
import brewkettle
reload(brewkettle)
filename = time.strftime("%Y-%m-%d %H:%M") + ".csv"
path = os.path.join("data", filename)
f = open(path, "w")
csv_writer = csv.writer(f)
csv_writer.writerow(["Time [s]", "Temperature [C]"])
kettle = bre... | import time
import serial
import matplotlib.pyplot as plt
import csv
import os
import brewkettle
reload(brewkettle)
filename = time.strftime("%Y-%m-%d %H:%M") + ".csv"
path = os.path.join("data", filename)
f = open(path, "w")
csv_writer = csv.writer(f)
kettle = brewkettle.BrewKettle()
kettle.turn_pump_on()
start = t... |
Remove QUnit UI's checkboxes from the DOM during tests to prevent false positives
Refs #373 | /* global QUnit, expect, bootlint */
/* jshint browser: true */
/*eslint-env browser */
(function () {
'use strict';
function lintCurrentDoc() {
var lints = [];
var reporter = function (lint) {
lints.push(lint.message);
};
bootlint.lintCurrentDocument(reporter, []);... | /* global QUnit, expect, bootlint */
/* jshint browser: true */
/*eslint-env browser */
(function () {
'use strict';
function lintCurrentDoc() {
var lints = [];
var reporter = function (lint) {
lints.push(lint.message);
};
bootlint.lintCurrentDocument(reporter, []);... |
Handle expired session and ajax call | <?php
/**
* Set the site to invite only mode, valid login credentials required
*
* @package Anqh
* @author Antti Qvickström
* @copyright (c) 2009 Antti Qvickström
* @license http://www.opensource.org/licenses/mit-license.php MIT license
*/
class invite_hook {
/**
* Adds invite only check to the ro... | <?php
/**
* Set the site to invite only mode, valid login credentials required
*
* @package Anqh
* @author Antti Qvickström
* @copyright (c) 2009 Antti Qvickström
* @license http://www.opensource.org/licenses/mit-license.php MIT license
*/
class invite_hook {
/**
* Adds invite only check to the ro... |
Define generic MsgPackReceiver and re-define Receiver as a sub class of MsgPackReceiver | var net = require('net');
var EventEmitter = require('events').EventEmitter;
var msgpack = require('msgpack');
function MsgPackReceiver(port) {
this.port = port || undefined;
this._init();
}
MsgPackReceiver.prototype = new EventEmitter();
MsgPackReceiver.prototype._init = function() {
this._server = net.create... | var net = require('net');
var EventEmitter = require('events').EventEmitter;
var msgpack = require('msgpack');
function Receiver(port) {
this.port = port || undefined;
this._init();
}
Receiver.prototype = new EventEmitter();
Receiver.prototype._init = function() {
this._server = net.createServer(this._onConnec... |
Allow overrides to be blank | from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3'... | from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3'... |
Modify the perfect simulator to calculate dedup percentages based on file sizes (1 - data_in / data_total) | #!/usr/bin/env python3
import timer
import sys
import utils
def simulate():
# A set of files already in the storage
seen = set()
# The size of the all uploads combined (deduplicated or not)
total_in = 0
# The size of the data sent to the service
data_in = 0
tmr = timer.Timer()
for (... | #!/usr/bin/env python3
import timer
import sys
import utils
# A set of files already in the storage
seen = set()
# The total number of uploads
total_uploads = 0
# The number of files in the storage
files_in = 0
tmr = timer.Timer()
for (hsh, _) in utils.read_upload_stream():
if hsh not in seen:
files_in ... |
Fix plug-in ID to match bundle's symbolic name. | package org.cohorte.studio.eclipse.ui.node;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.cohorte.... | package org.cohorte.studio.eclipse.ui.node;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.cohorte.... |
Prepare 0.17.0 Vegas for BlackHat Arsenal | # -*- coding: utf-8 -*-
#
##################################################################################
#
# Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# OSRFramework is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gener... | # -*- coding: utf-8 -*-
#
##################################################################################
#
# Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# OSRFramework is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gener... |
Make Search Controller request all facets be shown | <?php
class SearchController extends BaseController {
protected $layout = 'layouts.master';
public function showSearchForm()
{
$this->layout->content = View::make('search');
}
public function showResults()
{
$query = Input::get('q');
$facets = array('about' => 10, 'author' => 10, 'datePubl... | <?php
class SearchController extends BaseController {
protected $layout = 'layouts.master';
public function showSearchForm()
{
$this->layout->content = View::make('search');
}
public function showResults()
{
$query = Input::get('q');
$facets = array('author' => 10, 'inLanguage' => 10);
... |
Use local port for now. | package ca.islandora.sync.routes;
import org.apache.camel.builder.RouteBuilder;
import org.fcrepo.camel.JmsHeaders;
import org.fcrepo.camel.RdfNamespaces;
import ca.islandora.sync.processors.DrupalNodeCreateJsonTransform;
public class DrupalNodeCreate extends RouteBuilder {
public void configure() throws Exceptio... | package ca.islandora.sync.routes;
import org.apache.camel.builder.RouteBuilder;
import org.fcrepo.camel.JmsHeaders;
import org.fcrepo.camel.RdfNamespaces;
import ca.islandora.sync.processors.DrupalNodeCreateJsonTransform;
public class DrupalNodeCreate extends RouteBuilder {
public void configure() throws Exceptio... |
BAP-3701: Package Manager Exception during installing or updating | <?php
namespace Oro\Bundle\SecurityBundle\Cache;
class OroDataCacheManager
{
/**
* @var array
*/
protected $cacheProviders = [];
/**
* Registers a cache provider in this manager
*
* @param object $cacheProvider
*/
public function registerCacheProvider($cacheProvider)
... | <?php
namespace Oro\Bundle\SecurityBundle\Cache;
class OroDataCacheManager
{
/**
* @var array
*/
protected $cacheProviders = [];
/**
* Registers a cache provider in this manager
*
* @param object $cacheProvider
*/
public function registerCacheProvider($cacheProvider)
... |
Add Octocat icon to Header | //@flow
import React from "react";
import { Ul, Li, Nav } from "./styled-components";
import { LinkedInIcon } from "../../../../elements/linkedin-icon";
import { OctocatIcon } from "../../../../elements/octocat-icon";
import { Highlight } from "../../../../elements/highlight";
import { Chevron } from "../../../../elem... | //@flow
import React from "react";
import { Ul, Li, Nav } from "./styled-components";
import { LinkedInIcon } from "../../../../elements/linkedin-icon";
import { Highlight } from "../../../../elements/highlight";
import { Chevron } from "../../../../elements/chevron";
import theme from "../../../../global/style/mainTh... |
Change to code style that reflects rest of project |
module.exports = function(grunt) {
return grunt.registerMultiTask('mkdir', 'Make directories.', function() {
var options;
options = this.options({
mode: null,
create: []
});
grunt.verbose.writeflags(options, 'Options');
return options.create.forEach(function(filepath) {
grunt.lo... |
module.exports = function(grunt) {
return grunt.registerMultiTask('mkdir', 'Make directories.', function() {
var options;
options = this.options({
mode: null,
create: []
});
grunt.verbose.writeflags(options, 'Options');
return options.create.forEach(function(filepath) {
grunt.lo... |
Fix ruler menu for breakpoints
Review URL: http://codereview.chromium.org/99357 | // Copyright (c) 2009 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.
package org.chromium.debug.ui.editors;
import org.eclipse.ui.editors.text.TextEditor;
/**
* A simplistic Javascript editor which supports its own k... | // Copyright (c) 2009 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.
package org.chromium.debug.ui.editors;
import org.eclipse.ui.editors.text.TextEditor;
/**
* A simplistic Javascript editor which supports its own k... |
Fix Rotues by RESTify Rules | exports.default = {
routes: function (api) {
return {
get: [
/* URIs */
{
path: '/:apiVersion/account/:accountHashID/monitor',
action: 'monitorList'
},
{
path: '/:apiVersion/account/:accountHashID/monitor/:monitorHashID',
action: 'monitorModel'
},
/* STATUS */
{
... | exports.default = {
routes: function (api) {
return {
get: [
/* URIs */
{
path: '/:apiVersion/account/:accountHashId/monitor',
action: 'monitorList'
},
{
path: '/:apiVersion/account/:accountHashId/monitor/:monitorHashID',
action: 'monitorModel'
},
/* STATUS */
{
... |
Reformat source code according to Vaadin conventions | package org.vaadin.mcont.demo;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("demo")
@Title("MCont Add-on Demo")
@SuppressWarnings("serial")
public class... | package org.vaadin.mcont.demo;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("demo")
@Title("MCont Add-on Demo")
@SuppressWarnings("serial")
public clas... |
Change PyPI development status from pre-alpha to beta. | #!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cr... | #!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cr... |
Convert data to a string then apply the regex | 'use strict';
/* global require */
/* global process */
var fs = require ('fs');
var path = require ('path');
var mkdirSync = function (path) {
try {
fs.mkdirSync (path);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
};
var cwd = process.cwd ().replace (/\\/g, '/');
var suffix = '/nod... | 'use strict';
/* global require */
/* global process */
var fs = require ('fs');
var path = require ('path');
var mkdirSync = function (path) {
try {
fs.mkdirSync (path);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
};
var cwd = process.cwd ().replace (/\\/g, '/');
var suffix = '/nod... |
Add correct namespace to webservice and add project id to querydata | <?php
namespace fennecweb\ajax\details;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'detailsProjectsTestUser';
const USERID = 'detailsProjectsTestUser';
const PROVIDER = 'detailsProjectsTestUser';
public function testExecute()
{
//Test if the selected project... | <?php
namespace fennecweb\ajax\details;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'detailsProjectsTestUser';
const USERID = 'detailsProjectsTestUser';
const PROVIDER = 'detailsProjectsTestUser';
public function testExecute()
{
//Test if the selected project... |
Remove specific versions of dependencies | import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='wagtail-tinify',
ve... | import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='wagtail-tinify',
ve... |
Put 'abstract' keyword before visibility to follow psr-2 standard | <?php
namespace App\Middleware;
use Interop\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Cartalyst\Sentinel\Sentinel;
use Slim\Flash\Messages;
use Slim\Router;
use Slim\Views\Twig;
/**
* @property Twig view
* @propert... | <?php
namespace App\Middleware;
use Interop\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Cartalyst\Sentinel\Sentinel;
use Slim\Flash\Messages;
use Slim\Router;
use Slim\Views\Twig;
/**
* @property Twig view
* @propert... |
Add view function for councili arhive | # -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
from protocols.models import Protocol
def homepage(request):
return render(request, "index.html", {})
@json_vi... | # -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
memb... |
Return activity objects to template | Template.latestActivitiesByType.created = function () {
// Create 'instance' variable for use througout template logic
var instance = this;
// Create variable to hold activity type selection
instance.activityTypeSelection = new ReactiveVar();
// Create a reactive var to hold data containing latest activitie... | Template.latestActivitiesByType.created = function () {
// Create 'instance' variable for use througout template logic
var instance = this;
// Create variable to hold activity type selection
instance.activityTypeSelection = new ReactiveVar();
// Create a reactive var to hold data containing latest activitie... |
Add another missing import and only handle specific exceptions | from django.views import View
from django import http
from uxhelpers.utils import json_response
import json
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def pos... | from django.views import View
from django import http
from uxhelpers.utils import json_response
import logging
logger = logging.getLogger(__name__)
LEVELS = {
'CRITICAL': 50,
'ERROR': 40,
'WARNING': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0
}
class LogPostView(View):
def post(self, requ... |
Add a space to let it shine. | <?php
/**
* _s Theme Customizer
*
* @package _s
* @since _s 1.2
*/
/**
* Add postMessage support for site title and description for the Theme Customizer.
*
* @param WP_Customize_Manager $wp_customize Theme Customizer object.
*
* @since _s 1.2
*/
function _s_customize_register( $wp_customize ) {
$wp_customi... | <?php
/**
* _s Theme Customizer
*
* @package _s
* @since _s 1.2
*/
/**
* Add postMessage support for site title and description for the Theme Customizer.
*
* @param WP_Customize_Manager $wp_customize Theme Customizer object.
*
* @since _s 1.2
*/
function _s_customize_register( $wp_customize ) {
$wp_customi... |
Set up defaults so it doesn't crash in tests | package weavedns
import (
"io"
"io/ioutil"
"log"
"os"
)
const (
standard_log_flags = log.Ldate | log.Ltime | log.Lshortfile
)
// Inspired by http://www.goinggo.net/2013/11/using-log-package-in-go.html
var (
Debug *log.Logger = log.New(ioutil.Discard, "DEBUG: ", standard_log_flags)
Info *log.Logger = log... | package weavedns
import (
"io"
"log"
)
// Inspired by http://www.goinggo.net/2013/11/using-log-package-in-go.html
var (
Debug *log.Logger
Info *log.Logger
Warning *log.Logger
Error *log.Logger
)
func InitLogging(debugHandle io.Writer,
infoHandle io.Writer,
warningHandle io.Writer,
errorHandle io.Wri... |
Create 2.3 release with recent PR merges | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='widget-party',
version='2.3',
... | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='widget-party',
vers... |
Revert 11533 now that TestKey is checked in.
git-svn-id: 6bd94cac40bd5c1df74b384d972046d926de6ffa@11535 a8845c50-7012-0410-95d3-8e1449b9b1e4 | package org.mifos.framework.components.configuration;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.mifos.application.master.business.TestMifosCurrency;
import org.mifos.framework.components.configuration.business.TestConfiguration;
import org.mifos.framework.components.configuration.cache... | package org.mifos.framework.components.configuration;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.mifos.application.master.business.TestMifosCurrency;
import org.mifos.framework.components.configuration.business.TestConfiguration;
import org.mifos.framework.components.configuration.persi... |
Fix mocha tests to handle Features | const jsdom = require('jsdom');
global.document = jsdom.jsdom('<!doctype html><html><body><div></div></body></html>', {
url: 'http://localhost',
skipWindowCheck: true
});
global.window = document.defaultView;
global.navigator = global.window.navigator;
const sinon = require('sinon');
const React = require('react'... | const jsdom = require('jsdom');
global.document = jsdom.jsdom('<!doctype html><html><body><div></div></body></html>', {
url: 'http://localhost',
skipWindowCheck: true
});
global.window = document.defaultView;
global.navigator = global.window.navigator;
const sinon = require('sinon');
const React = require('react'... |
Create new ViewHolder for Crime | package com.bignerdranch.android.criminalintent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Vi... | package com.bignerdranch.android.criminalintent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Vi... |
Remove test cruft that is causing failures. | import { test , moduleForComponent } from 'appkit/tests/helpers/module-for';
import BayeuxStub from 'appkit/tests/helpers/bayeux-stub';
import PipedriveDealsComponent from 'appkit/components/pipedrive-deals';
moduleForComponent('dashboard-widget', 'Unit - Pipedrive Deals component', {
subject: function() {
var o... | import { test , moduleForComponent } from 'appkit/tests/helpers/module-for';
import BayeuxStub from 'appkit/tests/helpers/bayeux-stub';
import PipedriveDealsComponent from 'appkit/components/pipedrive-deals';
moduleForComponent('dashboard-widget', 'Unit - Pipedrive Deals component', {
subject: function() {
var o... |
Use $directive prefix for directive traces | var utils = require('../utils')
module.exports = function ($provide) {
var instrumentDirective = function (name) {
var directiveName = name + 'Directive'
$provide.decorator(directiveName, ['$delegate', '$injector', function ($delegate, $injector) {
utils.instrumentObject($delegate[0], $injector, {
... | var utils = require('../utils')
module.exports = function ($provide) {
var instrumentDirective = function (name) {
var directiveName = name + 'Directive'
$provide.decorator(directiveName, ['$delegate', '$injector', function ($delegate, $injector) {
utils.instrumentObject($delegate[0], $injector, {
... |
Reduce starting upgrader quantity to 3 at practical room level 6
Because of the size of the upgraders the storage is drained
considerably while they work. This means the system is basically doing
a big burst of upgrading, stopping to rebuild the energy buffer, and
then upgrading again.
Reducing to three upgraders wil... |
// Each key corresponds to the current practical room level and contains a separate objects containing settings enabled
// at that level. Each higher level inherits the settings from the level below it.
let roomLevelOptions = {
1: {
'UPGRADERS_QUANTITY': 5
},
2: {},
3: {},
4: {
'DEDICATED_MINERS': tr... |
// Each key corresponds to the current practical room level and contains a separate objects containing settings enabled
// at that level. Each higher level inherits the settings from the level below it.
let roomLevelOptions = {
1: {
'UPGRADERS_QUANTITY': 5
},
2: {},
3: {},
4: {
'DEDICATED_MINERS': tr... |
Fix ordering for test executions | <?php namespace Nestor\Repositories;
use Nestor\Model\Execution;
class DbExecutionRepository extends DbBaseRepository implements ExecutionRepository {
public function __construct(Execution $model)
{
parent::__construct($model);
}
public function findByTestRunId($test_run_id)
{
return $this->model->where('t... | <?php namespace Nestor\Repositories;
use Nestor\Model\Execution;
class DbExecutionRepository extends DbBaseRepository implements ExecutionRepository {
public function __construct(Execution $model)
{
parent::__construct($model);
}
public function findByTestRunId($test_run_id)
{
return $this->model->where('t... |
Set unichr = chr for Python 3. | """
Internal utility functions.
`htmlentitydecode` came from here:
http://wiki.python.org/moin/EscapingHtml
"""
import re
import sys
try:
from html.entities import name2codepoint
unichr = chr
except ImportError:
from htmlentitydefs import name2codepoint
def htmlentitydecode(s):
return re.sub(
... | """
Internal utility functions.
`htmlentitydecode` came from here:
http://wiki.python.org/moin/EscapingHtml
"""
import re
import sys
try:
from html.entities import name2codepoint
except ImportError:
from htmlentitydefs import name2codepoint
def htmlentitydecode(s):
return re.sub(
'&(%s);' % ... |
Increase timeout on RC sensor readings | #!/usr/bin/env python
import pexpect
import os
import re
path = os.path.dirname(__file__)
class RcSensor(object):
def __init__(self, gpio, cycles=200, discharge_delay=10):
if gpio is None:
raise ValueError("Must supply gpio value")
self.gpio = gpio
self.cycles = cycles
... | #!/usr/bin/env python
import pexpect
import os
import re
path = os.path.dirname(__file__)
class RcSensor(object):
def __init__(self, gpio, cycles=200, discharge_delay=10):
if gpio is None:
raise ValueError("Must supply gpio value")
self.gpio = gpio
self.cycles = cycles
... |
Fix svg rich backend to correctly show multiple figures. | """Produce SVG versions of active plots for display by the rich Qt frontend.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
from cStringIO import StringIO
# System li... | # Standard library imports
from cStringIO import StringIO
# System library imports.
from matplotlib.backends.backend_svg import new_figure_manager
from matplotlib._pylab_helpers import Gcf
# Local imports.
from backend_payload import add_plot_payload
def show():
""" Deliver a SVG payload.
"""
figure_man... |
Clarify message for unexpected errors
When reading a lot, the phrasing "Expected error" at the start makes me think it
*is* expected...then we say "not to have occurred" which is awkward.
Let's avoid the double negative. | package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
type HaveOccurredMatcher struct {
}
func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) {
// is purely nil?
if actual == nil {
return false, nil
}
// must be an 'error' type
if !isError(actual) {
return... | package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
)
type HaveOccurredMatcher struct {
}
func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) {
// is purely nil?
if actual == nil {
return false, nil
}
// must be an 'error' type
if !isError(actual) {
return... |
Add label in error message | import pprint
import sublime
import json
from .util import Util
# for debug
pp = pprint.PrettyPrinter(indent=4)
class Base(object):
def settings(self, attr):
settings = json.loads(sublime.load_resource('Packages/MarkdownTOC/MarkdownTOC.sublime-settings'))
user_settings = json.loads(su... | import pprint
import sublime
import json
from .util import Util
# for debug
pp = pprint.PrettyPrinter(indent=4)
class Base(object):
def settings(self, attr):
settings = json.loads(sublime.load_resource('Packages/MarkdownTOC/MarkdownTOC.sublime-settings'))
user_settings = json.loads(su... |
Replace with trivial lambda default fixed after 2cfd1ece23 | // "Fix all 'Constant conditions & exceptions' problems in file" "true"
import org.jetbrains.annotations.*;
import java.util.*;
import java.util.stream.Stream;
public class MethodReferenceConstantValue {
@Contract(value = "!null -> false", pure = true)
public boolean strangeMethod(String s) {
return s == null... | // "Fix all 'Constant conditions & exceptions' problems in file" "true"
import org.jetbrains.annotations.*;
import java.util.*;
import java.util.stream.Stream;
public class MethodReferenceConstantValue {
@Contract(value = "!null -> false", pure = true)
public boolean strangeMethod(String s) {
return s == null... |
Fix arguments to pass done through correctly. | var request = require('request');
var xml2js = require('xml2js');
function init() {
var module = {};
function latestRelease(project, majorVersion, done, cb) {
var releaseUri = 'https://updates.drupal.org/release-history/';
request(releaseUri + project + '/' + majorVersion, function (error, response, body)... | var request = require('request');
var xml2js = require('xml2js');
function init() {
var module = {};
function latestRelease(project, majorVersion, done, cb) {
var releaseUri = 'https://updates.drupal.org/release-history/';
request(releaseUri + project + '/' + majorVersion, function (error, response, body)... |
Resolve urls embedded in stylus sheets | var _ = require('lodash'),
StylusIncludesPlugin = require('./plugins/stylus-includes');
module.exports.config = function(additions) {
var options = additions.stylus || {},
defines = options.defines || {};
return _.defaults({
module: _.defaults({
loaders: loaders(defines, additions.module && ad... | var _ = require('lodash'),
StylusIncludesPlugin = require('./plugins/stylus-includes');
module.exports.config = function(additions) {
var options = additions.stylus || {},
defines = options.defines || {};
return _.defaults({
module: _.defaults({
loaders: loaders(defines, additions.module && ad... |
Update api test util to create files to use target name instead | from blinker import ANY
from urlparse import urlparse
from contextlib import contextmanager
from addons.osfstorage import settings as osfstorage_settings
def create_test_file(target, user, filename='test_file', create_guid=True):
osfstorage = target.get_addon('osfstorage')
root_node = osfstorage.get_root()
... | from blinker import ANY
from urlparse import urlparse
from contextlib import contextmanager
from addons.osfstorage import settings as osfstorage_settings
def create_test_file(node, user, filename='test_file', create_guid=True):
osfstorage = node.get_addon('osfstorage')
root_node = osfstorage.get_root()
te... |
Hide scrollbar when scroll reaches the bottom of the page | var globalOffset = require("global-offset");
module.exports = function(element) {
var offset = globalOffset(element),
scrollbar = document.createElement("div"),
inner = document.createElement("div");
element.style.overflowX = "scroll";
element.parentNode.insertBefore(scrollbar, element);
scrollbar.s... | var globalOffset = require("global-offset");
module.exports = function(element) {
var offset = globalOffset(element),
scrollbar = document.createElement("div"),
inner = document.createElement("div");
element.style.overflowX = "scroll";
element.parentNode.insertBefore(scrollbar, element);
scrollbar.s... |
Fix missing json encoding for support of large text chunks | <?php header('Content-Type: application/ld+json'); ?>
<?php header('Access-Control-Allow-Origin: *'); ?>
{
"@context": "<?php echo get_option('ldp_context', 'http://owl.openinitiative.com/oicontext.jsonld'); ?>",
"@graph": [
<?php while (have_posts()) : the_post(); ?>
{
<?php
$valu... | <?php header('Content-Type: application/ld+json'); ?>
<?php header('Access-Control-Allow-Origin: *'); ?>
{
"@context": "<?php echo get_option('ldp_context', 'http://owl.openinitiative.com/oicontext.jsonld'); ?>",
"@graph": [
<?php while (have_posts()) : the_post(); ?>
{
<?php
$valu... |
Use revert() instead of throw | // Using web3 for its sha function...
var Web3 = require("web3");
var Deployed = {
makeSolidityDeployedAddressesLibrary: function(mapping) {
var self = this;
var source = "";
source += "pragma solidity ^0.4.6; \n\n library DeployedAddresses {" + "\n";
Object.keys(mapping).forEach(function(name) {
... | // Using web3 for its sha function...
var Web3 = require("web3");
var Deployed = {
makeSolidityDeployedAddressesLibrary: function(mapping) {
var self = this;
var source = "";
source += "pragma solidity ^0.4.6; \n\n library DeployedAddresses {" + "\n";
Object.keys(mapping).forEach(function(name) {
... |
Make sure region name is uppercase. | import pyrax
from st2actions.runners.pythonrunner import Action
__all__ = [
'PyraxBaseAction'
]
class PyraxBaseAction(Action):
def __init__(self, config):
super(PyraxBaseAction, self).__init__(config)
self.pyrax = self._get_client()
def _get_client(self):
username = self.config[... | from st2actions.runners.pythonrunner import Action
import pyrax
__all__ = [
'PyraxBaseAction'
]
class PyraxBaseAction(Action):
def __init__(self, config):
super(PyraxBaseAction, self).__init__(config)
self.pyrax = self._get_client()
def _get_client(self):
username = self.config['u... |
Move user input prompt (and input manip) inside activate() | var openBlockList = function (blog) {
$('document').ready( function () {
$("#blocked_blogs > .accordion_trigger_wrapper > .accordion_trigger").click();
block(blog);
});
}
var block = function (blog) {
$("#blocked_blogs > .accordion_content > .block-input > .text > #block").v... | var openBlockList = function (blog) {
$('document').ready( function () {
$("#blocked_blogs > .accordion_trigger_wrapper > .accordion_trigger").click();
block(blog);
});
}
var block = function (blog) {
$("#blocked_blogs > .accordion_content > .block-input > .text > #block").v... |
Update task creds as well | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
module.exports = function (grunt) {
'use strict';
grunt.config('intern', {
node: {
options: {
... | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
module.exports = function (grunt) {
'use strict';
grunt.config('intern', {
node: {
options: {
... |
Switch to using Eimann's mirror to resolve jamendo track ids, due to jamendo downtime. | <?php
function resolve_external_url($url) {
if (substr($url, 0, 10) == 'jamendo://') {
return process_jamendo_url($url);
}
return $url;
}
function process_jamendo_url($url) {
if (substr($url, 10, 13) == 'track/stream/') {
$id = substr($url, 23);
return 'http://gigue.rrbone.net/' . $id . '.ogg2';
}
if (su... | <?php
function resolve_external_url($url) {
if (substr($url, 0, 10) == 'jamendo://') {
return process_jamendo_url($url);
}
return $url;
}
function process_jamendo_url($url) {
if (substr($url, 10, 13) == 'track/stream/') {
$id = substr($url, 23);
return 'http://api.jamendo.com/get2/stream/track/redirect/?id=... |
Use tabs in new completions file snippet
Respects the user's indentation configuration. | import sublime_plugin
from sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = "Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage" % PLUGIN_NAME
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger"... | import sublime_plugin
from sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = "Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage" % PLUGIN_NAME
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger"... |
Update dsub version to 0.2.3.
PiperOrigin-RevId: 222307052 | # Copyright 2017 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 applicable law or a... | # Copyright 2017 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 applicable law or a... |
Add ability to change the response status code on ErrorsException | <?php
/**
* Created by PhpStorm.
* User: Alex
* Date: 14/04/2019
* Time: 12:48
*/
namespace vr\api\components;
use Error;
use Exception;
use vr\core\ErrorsException;
use Yii;
/**
* Class ErrorHandler
* @package vr\api\components
*/
class ErrorHandler extends \yii\web\ErrorHandler
{
/**
* @var int
... | <?php
/**
* Created by PhpStorm.
* User: Alex
* Date: 14/04/2019
* Time: 12:48
*/
namespace vr\api\components;
use Error;
use Exception;
use vr\core\ErrorsException;
/**
* Class ErrorHandler
* @package vr\api\components
*/
class ErrorHandler extends \yii\web\ErrorHandler
{
/**
* @param Error|Excepti... |
Use the correct type for Metrics in the Config struct | // Package config allows for reading configuration from a JSON file
package config
import (
"encoding/json"
"io/ioutil"
)
var conf *Config
type (
// Config struct holds data from a JSON config file
Config struct {
DB DB `json:"db"`
Metrics Metrics `json:"me... | // Package config allows for reading configuration from a JSON file
package config
import (
"encoding/json"
"io/ioutil"
)
var conf *Config
type (
// Config struct holds data from a JSON config file
Config struct {
DB DB `json:"db"`
Metrics map[string]string `json:"me... |
Correct an AttributeError and a potential IndexErr | # -*- coding: utf-8 -*-
"""
utils.py
~~~~~~~~
Defines utility functions used by UPnPy.
"""
def camelcase_to_underscore(text):
"""
Convert a camelCasedString to one separated_by_underscores. Treats
neighbouring capitals as acronyms and doesn't separated them, e.g. URL does
not become u_r_l. That would... | # -*- coding: utf-8 -*-
"""
utils.py
~~~~~~~~
Defines utility functions used by UPnPy.
"""
def camelcase_to_underscore(text):
"""
Convert a camelCasedString to one separated_by_underscores. Treats
neighbouring capitals as acronyms and doesn't separated them, e.g. URL does
not become u_r_l. That would... |
Change case of Django to django else pypi lookup fails | from setuptools import setup, find_packages
setup(
name='django-dfp',
version='0.3.2',
description='DFP implementation for Django',
long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(),
author='Praekelt Foundation',
author_email... | from setuptools import setup, find_packages
setup(
name='django-dfp',
version='0.3.2',
description='DFP implementation for Django',
long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(),
author='Praekelt Foundation',
author_email... |
Fix user not defined error for not logged in users | from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators imp... | from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
class ManagersChoiceField (forms.field... |
Increase the timeout to an absurd value | # Load in core dependencies
import code
import os
import sublime
# Set up constants
__dir__ = os.path.dirname(os.path.abspath(__file__))
def run():
# On every run, re-import the test class
# TODO: Determine if this is necessary
filepath = __dir__ + '/plugin_runner.py'
plugin_dict = {
'__dir__... | # Load in core dependencies
import code
import os
import sublime
# Set up constants
__dir__ = os.path.dirname(os.path.abspath(__file__))
def run():
# On every run, re-import the test class
# TODO: Determine if this is necessary
filepath = __dir__ + '/plugin_runner.py'
plugin_dict = {
'__dir__... |
Add specific test scenario for pre-2.0 | module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'pre-2',
dependencies: {
'ember': '1.13.9'
}
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
... | module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {... |
Increase default search count to 12
Based off designer feedback
Change-Id: Icbccadb089a2ce650fdcfe4f0560aa5ef0087441 | package org.wikipedia.search;
import org.json.JSONArray;
import org.mediawiki.api.json.Api;
import org.mediawiki.api.json.ApiResult;
import org.mediawiki.api.json.RequestBuilder;
import org.wikipedia.ApiTask;
import org.wikipedia.PageTitle;
import org.wikipedia.Site;
import org.wikipedia.concurrency.ExecutorService;
... | package org.wikipedia.search;
import org.json.JSONArray;
import org.mediawiki.api.json.Api;
import org.mediawiki.api.json.ApiResult;
import org.mediawiki.api.json.RequestBuilder;
import org.wikipedia.ApiTask;
import org.wikipedia.PageTitle;
import org.wikipedia.Site;
import org.wikipedia.concurrency.ExecutorService;
... |
Make sure that organization new button goes to organization page | import React, {Component} from 'react'
import {connect} from 'react-redux'
import {httpRequestSelector} from 'gComponents/organizations/show/httpRequestSelector'
import {organizationMemberSelector} from 'gComponents/organizations/show/organizationMemberSelector'
import Card, {CardListElement} from 'gComponents/utilit... | import React, {Component} from 'react'
import {connect} from 'react-redux'
import {httpRequestSelector} from 'gComponents/organizations/show/httpRequestSelector'
import {organizationMemberSelector} from 'gComponents/organizations/show/organizationMemberSelector'
import Card, {CardListElement} from 'gComponents/utilit... |
Fix broken test (new "countries" added to data) | <?php
class KeyValueTest extends \PHPUnit_Framework_TestCase
{
protected $maker;
public function setUp()
{
$this->maker = new PeterColes\Countries\Maker;
}
public function testDefaultSettings()
{
$keyValue = $this->maker->keyValue();
$this->assertEquals(255, $... | <?php
class KeyValueTest extends \PHPUnit_Framework_TestCase
{
protected $maker;
public function setUp()
{
$this->maker = new PeterColes\Countries\Maker;
}
public function testDefaultSettings()
{
$keyValue = $this->maker->keyValue();
$this->assertEquals(253, $... |
CRM-1480: Create jobs to load files to database | <?php
namespace Oro\Bundle\TrackingBundle\Tests\Unit\DependencyInjection;
use Oro\Bundle\TrackingBundle\DependencyInjection\OroTrackingExtension;
class OroBundleTrackingExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var OroTrackingExtension
*/
protected $extension;
/**
* @var ... | <?php
namespace Oro\Bundle\TrackingBundle\Tests\Unit\DependencyInjection;
use Oro\Bundle\TrackingBundle\DependencyInjection\OroTrackingExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class OroBundleTrackingExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var OroTrackingExten... |
typing: Use `getUsersById` for fast user search.
part of #3339. | /* @flow strict-local */
import { createSelector } from 'reselect';
import type { Narrow, Selector, User } from '../types';
import { getTyping } from '../directSelectors';
import { getOwnEmail } from '../account/accountsSelectors';
import { isPrivateOrGroupNarrow } from '../utils/narrow';
import { normalizeRecipients ... | /* @flow strict-local */
import { createSelector } from 'reselect';
import type { Narrow, Selector, User } from '../types';
import { getTyping, getUsers } from '../directSelectors';
import { getOwnEmail } from '../account/accountsSelectors';
import { getUserById } from '../users/userHelpers';
import { isPrivateOrGroup... |
Remove undefined import in coach plugin. | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from kolibri.core.auth.constants.user_kinds import COACH
from kolibri.core.hooks import NavigationHook
from kolibri.core.hooks import RoleBasedRedirectHook
from kolibri.core.webpack import hooks as webp... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from . import hooks
from kolibri.core.auth.constants.user_kinds import COACH
from kolibri.core.hooks import NavigationHook
from kolibri.core.hooks import RoleBasedRedirectHook
from kolibri.core.webpack ... |
ui: Check the return value of ReleaseDC() | // Copyright 2016 Hajime Hoshi
//
// 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 in... | // Copyright 2016 Hajime Hoshi
//
// 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 in... |
Add hashCode method to starter solution | class Rational {
Rational(int numerator, int denominator) {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}
int getNumerator() {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}... | class Rational {
Rational(int numerator, int denominator) {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}
int getNumerator() {
throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
}... |
Remove warning for existing output directory.
In our configuration puppet will manage the output directory, so it
is expected behavior for it to exist, removing warning. Also
switching to distutils.dir_util copy_tree since that allows for
copying of required supporting files into an existing output
directory.
Change-... | import os
import html_helper
from Cheetah.Template import Template
from distutils.dir_util import copy_tree
def prep_out_dir(out_dir='out_report'):
src_dir = os.path.dirname(__file__)
report_files_dir = os.path.join(src_dir, 'report_files')
copy_tree(report_files_dir, out_dir)
def create_report(name_spa... | import os
import shutil
import html_helper
from Cheetah.Template import Template
def prep_out_dir(out_dir='out_report'):
src_dir = os.path.dirname(__file__)
report_files_dir = os.path.join(src_dir, 'report_files')
if os.path.exists(out_dir):
print 'WARNING: output directory "%s" already exists' % ... |
Fix variable store breaking crash | package org.cyclops.integrateddynamics.network;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.network.IPartNetwork;
import org.cyclops.integrateddynamics.core.network.TileNetworkElement;
import org.cyclops.integrateddynamics.tileentity.TileVariablestore;
/**
* Network... | package org.cyclops.integrateddynamics.network;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.network.IPartNetwork;
import org.cyclops.integrateddynamics.core.network.TileNetworkElement;
import org.cyclops.integrateddynamics.tileentity.TileVariablestore;
/**
* Network... |
Use just the default exports | import color from "./src/color";
import rgb from "./src/rgb";
import hsl from "./src/hsl";
import lab from "./src/lab";
import hcl from "./src/hcl";
import cubehelix from "./src/cubehelix";
import interpolateRgb from "./src/interpolateRgb";
import interpolateHsl from "./src/interpolateHsl";
import interpolateHslLong fr... | import {default as color, Color} from "./src/color";
import {default as rgb, Rgb} from "./src/rgb";
import {default as hsl, Hsl} from "./src/hsl";
import {default as lab, Lab} from "./src/lab";
import {default as hcl, Hcl} from "./src/hcl";
import {default as cubehelix, Cubehelix} from "./src/cubehelix";
import interpo... |
Add margin between open job posting rows. | import { Component, PropTypes } from 'react'
import {Link} from 'react-router'
class JobListing extends Component {
static propTypes: {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
}
constructor(props) {
super(props)
}
... | import { Component, PropTypes } from 'react'
import {Link} from 'react-router'
class JobListing extends Component {
static propTypes: {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
url: PropTypes.string.isRequired
}
constructor(props) {
super(props)
}
... |
Change to exists instead of catching DoesNotExist exception. | # -*- coding: utf8 -*-
from django.conf import settings
from holonet.mappings.helpers import clean_address, split_address
from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist
def is_blacklisted(sender):
sender = clean_address(sender)
prefix, domain = split_address(sender)
... | # -*- coding: utf8 -*-
from django.conf import settings
from holonet.mappings.helpers import clean_address, split_address
from .models import DomainBlacklist, DomainWhitelist, SenderBlacklist, SenderWhitelist
def is_blacklisted(sender):
sender = clean_address(sender)
prefix, domain = split_address(sender)
... |
Load Vue globals before app | import Vue from 'vue'
import VueFire from 'vuefire'
import App from './App'
import 'jquery-ui/jquery-ui.min.js'
// import imagesLoaded from 'imagesloaded'
// imagesLoaded.makeJQueryPlugin($)
import 'semantic-ui-css/semantic.js'
import 'semantic-ui-css/semantic.css'
// import marked from 'marked'
Vue.... | import Vue from 'vue'
import VueFire from 'vuefire'
import App from './App'
import 'jquery-ui/jquery-ui.min.js'
import imagesLoaded from 'imagesloaded'
imagesLoaded.makeJQueryPlugin($)
import 'semantic-ui-css/semantic.js'
import 'semantic-ui-css/semantic.css'
// import marked from 'marked'
Vue.use(Vu... |
Apply jscs to server code
Atom's jscs-fixer automatically fixed some problems: now all lines have a tab
indentation and statements are well spaced. Google's preset also converts all
double quotes into single quotes unless it's pure JSON. | Jobs = new Mongo.Collection('jobs'); //both on client and server
Applications = new Mongo.Collection('applications');
// added repoz channel
Meteor.startup(function() {
// console.log('Jobs.remove({})');
// Jobs.remove({});
if (Jobs.find({}).count() == 0) {
console.log('job count == ', Jobs.find({}).count()... | Jobs = new Mongo.Collection('jobs'); //both on client and server
Applications = new Mongo.Collection('applications');
// added repoz channel
Meteor.startup(function() {
// console.log('Jobs.remove({})');
// Jobs.remove({});
if(Jobs.find({}).count()==0) {
console.log("job count == ", Jobs.find({}).... |
Add correct dependencies to gulp tasks | var gulp = require('gulp');
var less = require('gulp-less');
var exec = require('child_process').exec;
var sourcemaps = require('gulp-sourcemaps');
var csso = require('gulp-csso');
var rename = require('gulp-rename');
function run(command) {
var child = exec(command);
child.stdout.pipe(process.stdout);
child.std... | var gulp = require('gulp');
var less = require('gulp-less');
var exec = require('child_process').exec;
var sourcemaps = require('gulp-sourcemaps');
var csso = require('gulp-csso');
var rename = require('gulp-rename');
function run(command) {
var child = exec(command);
child.stdout.pipe(process.stdout);
child.std... |
Add refines to getClassDeps and prepend any deps with no package with 'foam.core.' | foam.CLASS({
package: 'foam.apploader',
name: 'ModelRefines',
refines: 'foam.core.Model',
methods: [
{
name: 'getClassDeps',
code: function() {
var deps = this.requires ?
this.requires.map(function(r) { return r.path }) :
[];
deps = deps.concat(this.imple... | foam.CLASS({
package: 'foam.apploader',
name: 'ModelRefines',
refines: 'foam.core.Model',
methods: [
{
name: 'getClassDeps',
code: function() {
var deps = this.requires ?
this.requires.map(function(r) { return r.path }) :
[];
deps = deps.concat(this.imple... |
Add ability to disable frame evaluation
(cherry picked from commit 6cd89d0) | import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
use_frame_eval = os.environ.get('PYDEVD_USE_FRAME_EVAL', None)
if use_frame_eval == 'NO':
frame_eval_func,... | import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, s... |
Support python 2 with io.open | import io
import os.path
import yaml
from sphinx.util.osutil import ensuredir
def create_directory(app):
''' Creates the yaml directory if necessary '''
app.env.yaml_dir = os.path.join(app.builder.confdir, '_build', 'yaml')
ensuredir(app.env.yaml_dir)
def file_path(env, name):
''' Creates complete y... | import os.path
import yaml
from sphinx.util.osutil import ensuredir
def create_directory(app):
''' Creates the yaml directory if necessary '''
app.env.yaml_dir = os.path.join(app.builder.confdir, '_build', 'yaml')
ensuredir(app.env.yaml_dir)
def file_path(env, name):
''' Creates complete yaml file p... |
Use fully qualified class name instead of string | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
... | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Jenssegers\Rollbar\RollbarServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
... |
Change the order of the subcommands. | from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands.sdk import build, create
from .commands import install, logs, screenshot, timeline, account, repl
from .commands.sdk import convert, emu... | from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands import repl, install, screenshot, logs, account, timeline
from .commands.sdk import build, emulator, create, convert
from .exceptions im... |
eslint: Allow dangling commas and warn about console statements | module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'standard',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'svelte3',
],
overrides: [
{
files: ['**/*.svelte'],
... | module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'standard',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'svelte3',
],
overrides: [
{
files: ['**/*.svelte'],
... |
[Enhancement] Add the interface name for comodity | package toscalib
type Playbook struct {
AdjacencyMatrix Matrix
Index map[int]Play
Inputs map[string]PropertyDefinition
Outputs map[string]Output
}
type Play struct {
NodeTemplate NodeTemplate
InterfaceName string
OperationName string
}
func GeneratePlaybook(s ServiceTemplateDefinit... | package toscalib
type Playbook struct {
AdjacencyMatrix Matrix
Index map[int]Play
Inputs map[string]PropertyDefinition
Outputs map[string]Output
}
type Play struct {
NodeTemplate NodeTemplate
OperationName string
}
func GeneratePlaybook(s ServiceTemplateDefinition) Playbook {
var e... |
Handle other links in content view to browser | package com.erakk.lnreader.helper;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.erakk.lnreader.Constants;
import com.erakk.lnreader.DisplayImageActivity;
public class Baka... | package com.erakk.lnreader.helper;
import com.erakk.lnreader.Constants;
import com.erakk.lnreader.DisplayImageActivity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class... |
Fix spelling in help text | #!/usr/bin/env node
"use strict";
var backup = require("../lib/backup");
var ArgumentParser = require('argparse').ArgumentParser;
var pkg = require('../package.json');
function main(argv) {
var parser = new ArgumentParser({
version: pkg.version,
addHelp: true,
description: pkg.description
});
parser.addArg... | #!/usr/bin/env node
"use strict";
var backup = require("../lib/backup");
var ArgumentParser = require('argparse').ArgumentParser;
var pkg = require('../package.json');
function main(argv) {
var parser = new ArgumentParser({
version: pkg.version,
addHelp: true,
description: pkg.description
});
parser.addArg... |
Fix last printer not showing when there was odd number of printers | import React, { PropTypes } from 'react';
import style from './style.css';
import Printer from '../printer';
class PrinterListComponent extends React.Component {
getPrinterComponent(key) {
return (<Printer
{...this.props.printers[key]} key={key}
toggleSelected={() => { this.props.toggleSelected(key... | import React, { PropTypes } from 'react';
import style from './style.css';
import Printer from '../printer';
class PrinterListComponent extends React.Component {
getPrinterComponent(key) {
return (<Printer
{...this.props.printers[key]} key={key}
toggleSelected={() => { this.props.toggleSelected(key... |
test: Add some failing tests to fix... | /*global describe, it, before, beforeEach */
/*jshint -W030 */
'use strict';
var join = require('path').join
, fs = require('fs')
, expect = require('chai').expect
, cheerio = require('cheerio')
, bd = require('../lib/bedecked');
// Fixtures dir
var fxd = join(__dirname, 'fixtures');
describe(... | /*global describe, it, before, beforeEach */
/*jshint -W030 */
'use strict';
var join = require('path').join
, fs = require('fs')
, expect = require('chai').expect
, cheerio = require('cheerio')
, bd = require('../lib/bedecked');
// Fixtures dir
var fxd = join(__dirname, 'fixtures');
describe(... |
Allow null values to be provided for source. | <?php
namespace Rogue\Http\Requests;
class SignupRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
... | <?php
namespace Rogue\Http\Requests;
class SignupRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
... |
Update the PyPI version to 7.0.16. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.16',
packages=['todoist', 'todoist.managers'],
author='Doist Team... | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.15',
packages=['todoist', 'todoist.managers'],
author='Doist Team... |
Add service functions to get transactions by time | from datetime import datetime
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
first_day_of_a_month = datetime(today.year, today.month, 1,
tzinfo=today.tzinfo)
q... | from datetime import date
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
first_day_of_a_month = date(today.year, today.month, 1)
qs = Transaction.objects.filter(created__gte=first_day_of_a_month)... |
BAP-9558: Create new type Origin oauthOrigin | <?php
namespace Oro\Bundle\ImapBundle\Migrations\Schema\v1_4;
use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class OroImapBundle implements Migration
{
/**
* {@inheritdoc}
... | <?php
namespace Oro\Bundle\ImapBundle\Migrations\Schema\v1_4;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class OroImapBundle implements Migration
{
/**
* {@inheritdoc}
*/
public function up(Schema $schema,... |
Change exec time to response time |
/**
* default options
*/
const defaultOptions = {
requestTimeout: 10 * 1000, //request timeout, default is 10s
requestTimeoutCallback: () => {}, //request timeout callback
sendPowerBy: true, //send power by
sendResponseTime: true //send response time
}
/**
* send meta middleware
*/
module.exports = (opti... |
/**
* default options
*/
const defaultOptions = {
requestTimeout: 10 * 1000, //request timeout, default is 10s
requestTimeoutCallback: () => {}, //request timeout callback
sendPowerBy: true,
sendExecTime: true
}
/**
* send meta middleware
*/
module.exports = (options, app) => {
options = Object.assign(... |
:bug: Fix bug breaking webpages with yt embeds | // listen for new tabs
chrome.tabs.onCreated.addListener(function (tabId , info) {
if(isYouTubeUrl(info.url) && doesUrlNotContainField(info.url)){
revertYT(tabId);
}
});
// listen for updated tabs
chrome.tabs.onUpdated.addListener(function (tabId , info) {
// check
if(isYouTubeUrl(info.url) && doesUrlNotCo... | // listen for page navigations, detect if they're YT & include our disable
chrome.webNavigation.onBeforeNavigate.addListener((details) => {
if(detectYTURL(details.url) && details.url.indexOf("disable_polymer=true") === -1){
// append the disabling field
if(details.url.indexOf("?") !== -1){
chrome.tabs.u... |
Make importing secrets explicitly relative | # -*- coding: utf-8 -*-
import pytest
from epo_ops.middlewares import Dogpile, Throttler
from epo_ops.middlewares.throttle.storages import sqlite
from inet.sources.ops import OpsClient
from .secrets import OPS_KEY, OPS_SECRET
def test_ops_client_instantiated():
"""Test our subclass od epo_ops.RegisteredClient
... | # -*- coding: utf-8 -*-
import pytest
from epo_ops.middlewares import Dogpile, Throttler
from epo_ops.middlewares.throttle.storages import sqlite
from inet.sources.ops import OpsClient
from secrets import OPS_KEY, OPS_SECRET
def test_ops_client_instantiated():
"""Test our subclass od epo_ops.RegisteredClient
... |
Use is_null to check if a state isn't available. | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Categories
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
defined('KOOWA') ... | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Categories
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
defined('KOOWA') ... |
Add with_statement import for python2.5.
See http://www.python.org/dev/peps/pep-0343/ which describes
the with statement.
Review URL: http://codereview.chromium.org/5690003
git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@863 78cadc50-ecff-11dd-a971-7dbc132099af | #!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .so files that are order only dependencies are specified by
their install location rather than by their alias.
"""
# Pyth... | #!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .so files that are order only dependencies are specified by
their install location rather than by their alias.
"""
import... |
Add the NewSpec testing helper. | // Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package cmd
import (
"strings"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"gopkg.in/juju/charm.v6-unstable"
"github.com/juju/juju/resource"
)
func NewSpec(c *gc.C, name, suffix, comment string) resou... | // Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package status
import (
"fmt"
"strings"
gc "gopkg.in/check.v1"
"gopkg.in/juju/charm.v6-unstable"
"github.com/juju/juju/resource"
)
func NewSpecs(c *gc.C, names ...string) []resource.Spec {
var specs []resource.Spec
... |
Refactor default value for BankAccountType as refactored on enum | package me.pagarme.factory;
import me.pagar.BankAccountType;
import me.pagar.model.BankAccount;
public class BankAccountFactory {
public static String DEFAULT_AGENCIA = "0192";
public static String DEFAULT_AGENCIA_DV = "0";
public static String DEFAULT_CONTA = "03245";
public static String DEFAULT_CO... | package me.pagarme.factory;
import me.pagar.BankAccountType;
import me.pagar.model.BankAccount;
public class BankAccountFactory {
public static String DEFAULT_AGENCIA = "0192";
public static String DEFAULT_AGENCIA_DV = "0";
public static String DEFAULT_CONTA = "03245";
public static String DEFAULT_CO... |
Fix unicode encoding of Slack message posts | #! /usr/bin/env python2.7
import requests
class Slackbot(object):
def __init__(self, slack_name, token):
self.slack_name = slack_name
self.token = token
assert self.token, "Token should not be blank"
self.url = self.sb_url()
def sb_url(self):
url = "https://{}.slack.... | #! /usr/bin/env python2.7
import requests
class Slackbot(object):
def __init__(self, slack_name, token):
self.slack_name = slack_name
self.token = token
assert self.token, "Token should not be blank"
self.url = self.sb_url()
def sb_url(self):
url = "https://{}.slack.... |
Check an authentication in the group router | import {check_authentication, validate_request} from '../utils/errors'
import express from 'express'
function validate_request_body(request, response, next_handler) {
request.checkBody({
'screen_name': {
notEmpty: {
errorMessage: 'parameter is required',
},
},
})
validate_request(req... | import {validate_request} from '../utils/errors'
import express from 'express'
function validate_request_body(request, response, next_handler) {
request.checkBody({
'screen_name': {
notEmpty: {
errorMessage: 'parameter is required',
},
},
})
validate_request(request, next_handler)
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.