text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use data attribute instead of val() | var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).dat... | var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).val... |
Fix JS test causing navigation away from tests | module("Double click protection", {
setup: function(){
this.$form = $('<form action="/go" method="POST"><input type="submit" name="input_name" value="Save" /></form>');
$('#qunit-fixture').append(this.$form);
}
});
test('clicking submit input disables the button', function() {
GOVUK.doubleClickProtectio... | module("Double click protection", {
setup: function(){
this.$form = $('<form action="/go" method="POST"><input type="submit" name="input_name" value="Save" /></form>');
$('#qunit-fixture').append(this.$form);
}
});
test('clicking submit input disables the button', function() {
GOVUK.doubleClickProtectio... |
Fix eslint config for v8 | const path = require('path')
module.exports = {
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
],
overrides: [
{
files: ['*.js'],
rules: {
'@typescript-eslint/no-var-requires': 'off',
},
},
],
parser: '@typescript-esli... | const path = require('path')
module.exports = {
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
overrides: [
{
files: ['*.js'],
rules: {
'@typescript-eslint/no-var-requires': 'off',
},
... |
Truncate filename if it exceeds 50 characters | package com.thinksincode.tailstreamer.controller;
import com.thinksincode.tailstreamer.FileTailService;
import com.thinksincode.tailstreamer.TailStreamer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.spr... | package com.thinksincode.tailstreamer.controller;
import com.thinksincode.tailstreamer.FileTailService;
import com.thinksincode.tailstreamer.TailStreamer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.spr... |
Add url to check for incoming sms's. | # BULKSMS Configuration.
# BULKSMS base url.
BULKSMS_BASE_API_URL = 'https://bulksms.2way.co.za'
# Credentials required to use bulksms.com API.
BULKSMS_AUTH_USERNAME = ''
BULKSMS_AUTH_PASSWORD = ''
# URL for sending single and batch sms.
BULKSMS_API_URL = {
'batch': '/{}eapi/submission/send_batch/1/1.0'.format(B... | # BULKSMS Configuration.
# BULKSMS base url.
BULKSMS_BASE_API_URL = 'https://bulksms.2way.co.za'
# Credentials required to use bulksms.com API.
BULKSMS_AUTH_USERNAME = ''
BULKSMS_AUTH_PASSWORD = ''
# URL for sending single and batch sms.
BULKSMS_API_URL = {
'batch': '/{}eapi/submission/send_batch/1/1.0'.format(B... |
Use a separate lock per ivorn database | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from threading import Lock
from collections import defaultdict
class IVORN_DB(object):
def __init__(self, root):
self.root = root
self.locks = defaultdict(Lo... | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from contextlib import closing
from threading import Lock
class IVORN_DB(object):
# Using one big lock for all the databases is a little clunky.
def __init__(self, root)... |
Add support for beforeEach / afterEach to ember-dev assertions. | /* globals QUnit */
export default function setupQUnit(assertion, _qunitGlobal) {
var qunitGlobal = QUnit;
if (_qunitGlobal) {
qunitGlobal = _qunitGlobal;
}
var originalModule = qunitGlobal.module;
qunitGlobal.module = function(name, _options) {
var options = _options || {};
var originalSetup ... | /* globals QUnit */
export default function setupQUnit(assertion, _qunitGlobal) {
var qunitGlobal = QUnit;
if (_qunitGlobal) {
qunitGlobal = _qunitGlobal;
}
var originalModule = qunitGlobal.module;
qunitGlobal.module = function(name, _options) {
var options = _options || {};
var originalSetup ... |
Check if the x-frame-options header is already set | <?php
namespace Concrete\Core\Http;
use Cookie;
use Config;
use Core;
class Response extends \Symfony\Component\HttpFoundation\Response {
public function send() {
$cleared = Cookie::getClearedCookies();
foreach($cleared as $cookie) {
$this->headers->clearCookie($cookie);
}
$coo... | <?php
namespace Concrete\Core\Http;
use Cookie;
use Config;
use Core;
class Response extends \Symfony\Component\HttpFoundation\Response {
public function send() {
$cleared = Cookie::getClearedCookies();
foreach($cleared as $cookie) {
$this->headers->clearCookie($cookie);
}
$coo... |
Update failure key in test
Signed-off-by: Zane Burstein <0b53c6e52ca2d19caefaa4da7d81393843bcf79a@anchore.com> | class TestOversizedImageReturns400:
# Expectation for this test is that the image with tag is greater than the value defined in config
def test_oversized_image_post(self, make_image_analysis_request):
resp = make_image_analysis_request("anchore/test_images:oversized_image")
details = resp.body[... | class TestOversizedImageReturns400:
# Expectation for this test is that the image with tag is greater than the value defined in config
def test_oversized_image_post(self, make_image_analysis_request):
resp = make_image_analysis_request("anchore/test_images:oversized_image")
details = resp.body[... |
Update EEA Form Build Info Comments/Source | 'use strict';
app.component("eeaFormBuild", {
template: '<div style="line-height: 10px;color: #f0f0f0;">Build date: {{$ctrl.date}}<br>{{$ctrl.diff}} ago<br>by {{$ctrl.user}}</div>',
bindings: {
date: '@',
user: '@'
},
controller: function() {
this.$onInit = function() {
// https://stackoverflow.com/quest... | 'use strict';
app.component("eeaFormBuild", {
template: '<div style="line-height: 10px;color: #f0f0f0;">Build date: {{$ctrl.date}}<br>{{$ctrl.diff}} ago<br>by {{$ctrl.user}}</div>',
bindings: {
date: '@',
user: '@'
},
controller: function() {
this.$onInit = function() {
var delta = Math.abs(new Date().ge... |
Make video card a link | import * as _ from 'lodash'
import React from 'react'
import {connect} from 'react-redux'
import {Link} from 'react-router-dom'
import {compose} from 'recompose'
import {refreshVideo} from '../../actions/videos'
import {withDatabaseSubscribe} from '../hocs'
const mapStateToProps = ({videos}) => ({
videos
})
const... | import * as _ from 'lodash'
import React from 'react'
import {connect} from 'react-redux'
import {compose} from 'recompose'
import {withDatabaseSubscribe} from '../hocs'
import {refreshVideo} from '../../actions/videos'
const mapStateToProps = ({videos}) => ({
videos
})
const enhance = compose(
connect(mapState... |
Update to not include test packages. | from setuptools import setup
import os
def read(fn):
"""
Read the contents of the provided filename.
Args:
fn: The filename to read in.
Returns:
The contents of the file.
"""
abs_fn = os.path.join(os.path.dirname(__file__), fn)
f = open(abs_fn)
contents = f.read()
f.close(... | from setuptools import setup, find_packages
import os
def read(fn):
"""
Read the contents of the provided filename.
Args:
fn: The filename to read in.
Returns:
The contents of the file.
"""
abs_fn = os.path.join(os.path.dirname(__file__), fn)
f = open(abs_fn)
contents = f.read... |
Switch to current year's database URL | package be.digitalia.fosdem.api;
import java.util.Locale;
/**
* This class contains all FOSDEM Urls
*
* @author Christophe Beyls
*
*/
public class FosdemUrls {
private static final String SCHEDULE_URL = "https://fosdem.org/schedule/xml";
private static final String EVENT_URL_FORMAT = "https://fosdem.org/%1$... | package be.digitalia.fosdem.api;
import java.util.Locale;
/**
* This class contains all FOSDEM Urls
*
* @author Christophe Beyls
*
*/
public class FosdemUrls {
// private static final String SCHEDULE_URL = "https://fosdem.org/schedule/xml";
private static final String SCHEDULE_URL = "https://archive.fosdem.... |
Remove unused name in Statistics constructor. | 'use strict';
const Stats = require('fast-stats').Stats;
function percentileName(percentile) {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else if (percentile === 50) {
return 'median';
}
return `p${String(percentile).replace('.', '_')}`;
}
class Stati... | 'use strict';
const Stats = require('fast-stats').Stats;
function percentileName(percentile) {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else if (percentile === 50) {
return 'median';
}
return `p${String(percentile).replace('.', '_')}`;
}
class Stati... |
Update dependency to Markdown 2.6+ & bleach 2.0.0+ | import os.path as path
from setuptools import setup
def get_readme(filename):
if not path.exists(filename):
return ""
with open(path.join(path.dirname(__file__), filename)) as readme:
content = readme.read()
return content
setup(name="mdx_linkify",
version="0.6",
author="Rait... | import os.path as path
from setuptools import setup
def get_readme(filename):
if not path.exists(filename):
return ""
with open(path.join(path.dirname(__file__), filename)) as readme:
content = readme.read()
return content
setup(name="mdx_linkify",
version="0.6",
author="Rait... |
[TASK] Add TYPO3 CMS 8 as compatible version | <?php
/************************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
************************************************************************/
$EM_CONF[$_EXTKEY] = array(
'title' => 'Bootstrap Package',
'description' => 'Boots... | <?php
/************************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
************************************************************************/
$EM_CONF[$_EXTKEY] = array(
'title' => 'Bootstrap Package',
'description' => 'Boots... |
Revert "Req-52 Alignment of file names in traceability matrix is "right-aligned""
This reverts commit 9bada791cfc5b699feaf0132ea1f302a9e006314. | package de.fau.osr.gui;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.table.JTableHeader;
class RowHeaderRenderer extends JLabel implements ListCellRenderer {
RowHead... | package de.fau.osr.gui;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.table.JTableHeader;
class RowHeaderRenderer extends JLabel implements ListCellRenderer {
RowHead... |
Use config to build paths | /**
* Copyright (c) 2013-2015 Memba Sarl. All rights reserved.
* Sources at https://github.com/Memba
*/
/* jshint node: true, expr: true */
/* globals describe: false, before: false, it: false */
'use strict';
var request = require('supertest'),
//We cannot define app like this because the server is already ... | /**
* Copyright (c) 2013-2015 Memba Sarl. All rights reserved.
* Sources at https://github.com/Memba
*/
/* jshint node: true, expr: true */
/* globals describe: false, before: false, it: false */
'use strict';
var request = require('supertest'),
//We cannot define app like this because the server is already ... |
Fix build with new sass-loader | const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
test: /\.s?css$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 2,
},
},
{
loader: 'postcss-loader',
options: {... | const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
test: /\.s?css$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 2,
},
},
{
loader: 'postcss-loader',
options: {... |
Rename variable name from "val" to "node". | # coding: utf-8
"""
Exposes a class that represents a parsed (or compiled) template.
"""
class ParsedTemplate(object):
"""
Represents a parsed or compiled template.
An instance wraps a list of unicode strings and node objects. A node
object must have a `render(engine, stack)` method that accepts ... | # coding: utf-8
"""
Exposes a class that represents a parsed (or compiled) template.
"""
class ParsedTemplate(object):
"""
Represents a parsed or compiled template.
An instance wraps a list of unicode strings and node objects. A node
object must have a `render(engine, stack)` method that accepts ... |
Use version of slots admin already in production
While building the schedule for the conference, the admin view for
`schedule.models.Slot` was changed in production* to figure out what
implementation made the most sense. This formalizes it as the preferred
version.
Closes #111
*Don't do this at home. | """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = ... | """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = ... |
Fix cache tests to account for callback style.
Were built with a return value in mind | var Memory = require('../lib/cache').Memory
, assert = require('assert')
;
describe('cache', function(){
var cache = new Memory();
before(function(){
})
describe('#get/#set', function(){
it('should set a value', function(){
cache.set('foo', 'bar', function(){
cache.get('foo', function(err, value ){
... | var Memory = require('../lib/cache').Memory
, assert = require('assert')
;
describe('cache', function(){
var cache = new Memory();
before(function(){
})
describe('#get/#set', function(){
it('should set a value', function(){
cache.set('foo', 'bar' );
assert.equal( cache.get('foo'), 'bar')
})
it('... |
Check if function exists before adding | package main
import (
"archive/zip"
"bytes"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/lambda"
)
var runtimeFunction = `
exports.handler = function(event, context) {
eval(event.source);
};
`
func install(role string, region string) {
svc := lambda.New(&aws.Config{Region: region})
if ... | package main
import (
"archive/zip"
"bytes"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/lambda"
)
var runtimeFunction = `
exports.handler = function(event, context) {
eval(event.source);
};
`
func install(role string, region string) {
svc := lambda.New(&aws.Config{Region: region})
par... |
Add subprocess32 as package dependency | from setuptools import setup, find_packages
setup(
name='pycalico',
# Don't need a version until we publish to PIP or other forum.
# version='0.0.0',
description='A Python API to Calico',
# The project's main homepage.
url='https://github.com/projectcalico/libcalico/',
# Author details
... | from setuptools import setup, find_packages
setup(
name='pycalico',
# Don't need a version until we publish to PIP or other forum.
# version='0.0.0',
description='A Python API to Calico',
# The project's main homepage.
url='https://github.com/projectcalico/libcalico/',
# Author details
... |
Fix null error when there's no data | <?php
namespace App\Http\Controllers;
use App\Services\Ranking;
use App\Services\Slack;
use App\SlackProp;
use App\SlackUser;
class DashboardController extends Controller
{
public function index()
{
$ranking = Ranking::getRanking();
$props = SlackProp::query()->orderBy('created_at', 'DESC')->... | <?php
namespace App\Http\Controllers;
use App\Services\Ranking;
use App\Services\Slack;
use App\SlackProp;
use App\SlackUser;
class DashboardController extends Controller
{
public function index()
{
$ranking = Ranking::getRanking();
$props = SlackProp::query()->orderBy('created_at', 'DESC')->... |
Use root element instead of global in CSS | // ==UserScript==
// @name Firefox GTK+ dark themes fix
// @version 0.4
// @description Resets colors in all pages to match those of a bright theme and, hopefully, fix annoying inconsistencies caused by using darker GTK+ themes with Firefox.
// @namespace https://github.com/darkalemanbr/userscripts
// @include *
// @do... | // ==UserScript==
// @name Firefox GTK+ dark themes fix
// @version 0.3
// @description Resets colors in all pages to match those of a bright theme and, hopefully, fix annoying inconsistencies caused by using darker GTK+ themes with Firefox.
// @namespace https://github.com/darkalemanbr/userscripts
// @include *
// @do... |
Add fix for embroider tests | /* eslint-disable prettier/prettier */
'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
let app = new EmberAddon(defaults, {
minifyCSS: {
enabled: false
},
'ember-prism': {
'components': ['bash', 'javascript', 'handlebars'... | /* eslint-disable prettier/prettier */
'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
let app = new EmberAddon(defaults, {
minifyCSS: {
enabled: false
},
'ember-prism': {
'components': ['bash', 'javascript', 'handlebars'... |
Enable minification for esbuild in production. | const watch = process.argv.includes("--watch") && {
/**
* Log when a build is finished or failed.
*
* @param {Error|null} error The possible error.
* @returns {void}
*/
onRebuild(error) {
if (error) {
// eslint-disable-next-line no-console
console.error("[watch] build failed", error)... | const watch = process.argv.includes("--watch") && {
/**
* Log when a build is finished or failed.
*
* @param {Error|null} error The possible error.
* @returns {void}
*/
onRebuild(error) {
if (error) {
// eslint-disable-next-line no-console
console.error("[watch] build failed", error)... |
Add python package install dependency
Add babel as python package install dependency. Babel is used in
phonenumber_field.widget. | from setuptools import setup, find_packages
from phonenumber_field import __version__
setup(
name="django-phonenumber-field",
version=__version__,
url='http://github.com/stefanfoulis/django-phonenumber-field',
license='BSD',
platforms=['OS Independent'],
description="An international phone num... | from setuptools import setup, find_packages
from phonenumber_field import __version__
setup(
name="django-phonenumber-field",
version=__version__,
url='http://github.com/stefanfoulis/django-phonenumber-field',
license='BSD',
platforms=['OS Independent'],
description="An international phone num... |
Add comment about more efficient than bubble sort | def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
Selection sort is more efficient than bubble sort
since the former does not s... | def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
... |
Delete Report models before reloading them | # -*- encoding: UTF-8 -*-
#
# Copyright 2015
#
# STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
# This file is part of CVN.
#
# CVN is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by
# the ... | # -*- encoding: UTF-8 -*-
#
# Copyright 2015
#
# STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
# This file is part of CVN.
#
# CVN is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by
# the ... |
Remove forgotten bits of buildbot 0.7.12 compatibility code.
A second take of https://chromiumcodereview.appspot.com/13560017 but should work now.
R=iannucci@chromium.org
BUG=
Review URL: https://chromiumcodereview.appspot.com/20481003
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@217592 0039d316-1c4b-4281-b... | # Copyright (c) 2012 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.
"""Script to setup the environment to run unit tests.
Modifies PYTHONPATH to automatically include parent, common and pylibs
directories.
"""
import os... | # Copyright (c) 2012 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.
"""Script to setup the environment to run unit tests.
Modifies PYTHONPATH to automatically include parent, common and pylibs
directories.
"""
import os... |
fix: Use README as the long description on PyPI | #!/usr/bin/env python
import sys
from setuptools import setup
from shortuuid import __version__
assert sys.version >= "3.5", "Requires Python v3.5 or above."
classifiers = [
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 3.5",
"Programm... | #!/usr/bin/env python
import sys
from setuptools import setup
from shortuuid import __version__
assert sys.version >= "3.5", "Requires Python v3.5 or above."
classifiers = [
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 3.5",
"Programm... |
Destroy stream early on error | let Stream = require('stream');
const {SaxesParser, EVENTS} = require('saxes');
// Backwards compatibility for earlier node versions and browsers
if (!Stream.Readable || typeof Symbol === 'undefined' || !Stream.Readable.prototype[Symbol.asyncIterator]) {
Stream = require('readable-stream');
}
module.exports = class... | let Stream = require('stream');
const {SaxesParser, EVENTS} = require('saxes');
// Backwards compatibility for earlier node versions and browsers
if (!Stream.Readable || typeof Symbol === 'undefined' || !Stream.Readable.prototype[Symbol.asyncIterator]) {
Stream = require('readable-stream');
}
module.exports = class... |
Add return type to `conduit.query`
Summary: Fixes T6950. Adds the return type of Conduit API methods to the `conduit.query` call.
Test Plan: Called `echo '{}' | arc call-conduit conduit.query` and verified that the return types were present in the response.
Reviewers: epriestley, #blessed_reviewers
Reviewed By: epr... | <?php
final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod {
public function getAPIMethodName() {
return 'conduit.query';
}
public function getMethodDescription() {
return 'Returns the parameters of the Conduit methods.';
}
public function defineParamTypes() {
return array();
}
... | <?php
final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod {
public function getAPIMethodName() {
return 'conduit.query';
}
public function getMethodDescription() {
return 'Returns the parameters of the Conduit methods.';
}
public function defineParamTypes() {
return array();
}
... |
Make sure handle all the exceptions | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import requests
def check(url):
try:
response = requests.get(
"https://isitup.org/{0}.json".format(url),
headers={'User-Agent': 'https://github.com/lord63/isitup'})
except r... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import requests
def check(url):
try:
response = requests.get(
"https://isitup.org/{0}.json".format(url),
headers={'User-Agent': 'https://github.com/lord63/isitup'})
except r... |
Fix a bug that failed to show Rekit Studio. | const setItem = type => (key, item) => {
const obj = window[`${type}Storage`];
return obj.setItem(key, JSON.stringify(item));
};
const getItem = type => (key, defaultValue, saveIfNotExist) => {
const obj = window[`${type}Storage`];
const savedItem = obj.getItem(key);
if (!savedItem && saveIfNotExist) {
se... | const setItem = type => (key, item) => {
const obj = window[`${type}Storage`];
return obj.setItem(key, JSON.stringify(item));
};
const getItem = type => (key, defaultValue, saveIfNotExist) => {
const obj = window[`${type}Storage`];
const savedItem = obj.getItem(key);
if (!savedItem && saveIfNotExist) {
se... |
Add in election title to content pane | <?php
require_once('config.php');
global $config;
require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');
$stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?");
$stmt->bindParam(1, $row["election"]);
$stmt->execute();
$election_name = $stmt->fetch(PDO::... | <?php
require_once('config.php');
global $config;
require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Edit Election
<small>Optional description</small>
</h... |
Add @glimmer/env to vendor.js in local builds. | "use strict";
const build = require('@glimmer/build');
const packageDist = require('@glimmer/build/lib/package-dist');
const buildVendorPackage = require('@glimmer/build/lib/build-vendor-package');
const funnel = require('broccoli-funnel');
const path = require('path');
module.exports = function() {
let vendorTrees... | "use strict";
const build = require('@glimmer/build');
const packageDist = require('@glimmer/build/lib/package-dist');
const buildVendorPackage = require('@glimmer/build/lib/build-vendor-package');
const funnel = require('broccoli-funnel');
const path = require('path');
module.exports = function() {
let vendorTrees... |
Return 404 instead of 400 if the translation is not found. | /*
* Copyright (c) 2014 ZionSoft. All rights reserved.
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file.
*/
package translation
import (
"net/http"
"net/url"
"appengine"
"appengine/blobstore"
"src/core"
)
func DownloadTranslationHandler(w ... | /*
* Copyright (c) 2014 ZionSoft. All rights reserved.
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file.
*/
package translation
import (
"net/http"
"net/url"
"appengine"
"appengine/blobstore"
"src/core"
)
func DownloadTranslationHandler(w ... |
Add HTML IDs to CloseDialogConfirmation | import React from 'react'
import PropTypes from 'prop-types'
import { Modal, Button } from 'react-bootstrap'
import style from './style.css'
const CloseDialogConfirmation = ({ onYes, onNo }) => {
const idPrefix = 'closedialogconfim'
return (
<Modal show dialogClassName={style['cust-modal-content']}>
<M... | import React from 'react'
import PropTypes from 'prop-types'
import { Modal, Button } from 'react-bootstrap'
import style from './style.css'
const CloseDialogConfirmation = ({ onYes, onNo }) => {
return (
<Modal show dialogClassName={style['cust-modal-content']}>
<Modal.Header bsClass={`modal-header ${st... |
Remove setting user id and access token from response method in auth response handler | package com.simperium.client;
import com.simperium.util.AuthUtil;
import org.json.JSONObject;
public class AuthResponseHandler {
private AuthResponseListener mListener;
private User mUser;
public AuthResponseHandler(User user, AuthResponseListener listener) {
mUser = user;
mListener = li... | package com.simperium.client;
import com.simperium.util.AuthUtil;
import org.json.JSONException;
import org.json.JSONObject;
public class AuthResponseHandler {
private AuthResponseListener mListener;
private User mUser;
public AuthResponseHandler(User user, AuthResponseListener listener){
mUser... |
Add some missing disabled features for Cassandra | import mysql from './mysql';
import postgresql from './postgresql';
import sqlserver from './sqlserver';
import cassandra from './cassandra';
/**
* List of supported database clients
*/
export const CLIENTS = [
{
key: 'mysql',
name: 'MySQL',
defaultPort: 3306,
},
{
key: 'postgresql',
name:... | import mysql from './mysql';
import postgresql from './postgresql';
import sqlserver from './sqlserver';
import cassandra from './cassandra';
/**
* List of supported database clients
*/
export const CLIENTS = [
{
key: 'mysql',
name: 'MySQL',
defaultPort: 3306,
},
{
key: 'postgresql',
name:... |
Introduce global template function `url_for_snippet`
Use it to ease the transition to a multisite-capable snippet URL rule system. | """
byceps.blueprints.snippet.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import abort, g, url_for
from ...services.snippet import mountpoint_service
from ...util.framework.blueprint import create_blueprint
from .te... | """
byceps.blueprints.snippet.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import abort, g
from ...services.snippet import mountpoint_service
from ...util.framework.blueprint import create_blueprint
from .templating ... |
ETM: Add doc note that stages shouldn't change column headers
The reason for the stage system is because of ERED. I'm planning on two
stages. The first allows the user to input event results. In preparing
for the second stage, the application generates sweepstakes points using
the event's specification. Then, in the s... | /**
*
*/
package mathsquared.resultswizard2;
import javax.swing.table.TableModel;
/**
* Represents data that can be edited in one or more stages and then transformed into another object.
*
* <p>Note that these stages should not change the column headers or layout in this table. They should only change which co... | /**
*
*/
package mathsquared.resultswizard2;
import javax.swing.table.TableModel;
/**
* Represents data that can be edited in one or more stages and then transformed into another object.
*
* @author MathSquared
* @param <T> the type of data that can be obtained from this model using {@link #getResult()}
*
*... |
Fix bad indexing in array | if (!localStorage['saved']){
localStorage['letA'] = '#800000'; //maroon
localStorage['letE'] = '#008000'; //green
localStorage['letI'] = '#0000ff'; //blue
localStorage['letO'] = '#008080'; //teal
localStorage['letU'] = '#800080'; //purple
localStorage['saved'] = 'Y';
}
// Converts an integer (unicode ... | if (!localStorage['saved']){
localStorage['letA'] = '#800000'; //maroon
localStorage['letE'] = '#008000'; //green
localStorage['letI'] = '#0000ff'; //blue
localStorage['letO'] = '#008080'; //teal
localStorage['letU'] = '#800080'; //purple
localStorage['saved'] = 'Y';
}
// Converts an integer (unicode ... |
Add one more line of comment in printList function. | """
This file includes several data structures used in LeetCode question.
"""
# Definition for a list node.
class ListNode(object):
def __init__(self, n):
self.val = n
self.next = None
def createLinkedList(nodelist):
#type nodelist: list[int/float]
#rtype: head of linked list
linkedList = ListNode(0)
head = ... | """
This file includes several data structures used in LeetCode question.
"""
# Definition for a list node.
class ListNode(object):
def __init__(self, n):
self.val = n
self.next = None
def createLinkedList(nodelist):
#type nodelist: list[int/float]
#rtype: head of linked list
linkedList = ListNode(0)
head = ... |
Add a method to print a message on the sense hat | class HatManager(object):
def __init__(self, sense):
self.sense = sense
self._pressure = self.sense.get_pressure()
self._temperature = self.sense.get_temperature()
self._humidity = self.sense.get_humidity()
def refresh_state(self):
self._pressure = self.sense.get_press... | class HatManager(object):
def __init__(self, sense):
self.sense = sense
self._pressure = self.sense.get_pressure()
self._temperature = self.sense.get_temperature()
self._humidity = self.sense.get_humidity()
def refresh_state(self):
self._pressure = self.sense.get_press... |
Save value in storage on init | (function (angular) {
'use strict';
var StoredItem = function (storage, itemName, defaultValueFactory, log) {
var value = defaultValueFactory();
this.get = function () {
return value;
};
this.save = function (newValue) {
value = newValue;
storage.setItem(itemName, angular.toJso... | (function (angular) {
'use strict';
var StoredItem = function (storage, itemName, defaultValueFactory, log) {
var value = defaultValueFactory();
var storedValue = storage.getItem(itemName);
if (_.isString(storedValue)) {
try {
_.merge(value, angular.fromJson(storedValue));
} catch... |
Fix error in History table if stack does not exist
Change-Id: Ic47761ddff23207a30eae0b7b523a996c545b3ba | # -*- coding: utf8 -*-
#
# 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... | # -*- coding: utf8 -*-
#
# 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 a shebang for a python interpreter. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_deb... | # -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_debugger = True,
use_... |
Remove tree layout, use default layout instead. | package nl.tudelft.dnainator.ui;
import nl.tudelft.dnainator.graph.DNAGraph;
import org.graphstream.graph.Graph;
import org.graphstream.ui.view.Viewer;
/**
* The viewer is responsible for managing the interactable views of the the strain graph.
* Use the addDefaultView() method to obtain a view.
*/
public class D... | package nl.tudelft.dnainator.ui;
import nl.tudelft.dnainator.graph.DNAGraph;
import nl.tudelft.dnainator.graph.DNALayout;
import org.graphstream.graph.Graph;
import org.graphstream.ui.layout.Layout;
import org.graphstream.ui.view.Viewer;
/**
* The viewer is responsible for managing the interactable views of the the... |
Fix comma and newline text.Word matching | package text
import (
"unicode"
)
type Query interface {
Match(string) int
}
// Word matches complete words only.
// The "complete words" of a string s is defined as the result of
// splitting the string on every single Unicode whitespace character.
type Word struct {
W string
}
func (q Word) Match(s string) int... | package text
import "unicode"
type Query interface {
Match(string) int
}
// Word matches complete words only.
// The "complete words" of a string s is defined as the result of
// splitting the string on every single Unicode whitespace character.
type Word struct {
W string
}
func (q Word) Match(s string) int {
i... |
Add X- headers for security
X-XSS, X-Content-Type-Options, X-Download-Options have sane defaults,
but X-Frame-Options would break existing functionality of including
concourse on iframes if we added this header by default.
Instead, we expose what to put in this header in the ATC flags,
defaulting it to no header.
[#... | package web
import (
"html/template"
"net/http"
"code.cloudfoundry.org/lager"
)
type templateData struct{}
type handler struct {
logger lager.Logger
template *template.Template
}
func NewHandler(logger lager.Logger) (http.Handler, error) {
tfuncs := &templateFuncs{
assetIDs: map[string]string{},
}
fun... | package web
import (
"html/template"
"net/http"
"code.cloudfoundry.org/lager"
)
type templateData struct{}
type handler struct {
logger lager.Logger
template *template.Template
}
func NewHandler(logger lager.Logger) (http.Handler, error) {
tfuncs := &templateFuncs{
assetIDs: map[string]string{},
}
fun... |
Update to display notes count bubble only when new notes are available | from django.template import Library, Node, TemplateSyntaxError
from django.utils.html import escape
from django.utils.http import urlquote
from django.utils.safestring import mark_safe
from notes.models import Note
from castle.models import Profile
register = Library()
#-----------------------------------------------... | from django.template import Library, Node, TemplateSyntaxError
from django.utils.html import escape
from django.utils.http import urlquote
from django.utils.safestring import mark_safe
from notes.models import Note
from castle.models import Profile
register = Library()
#-----------------------------------------------... |
Change thumbnail to display self | import React from 'react'
import styled from 'styled-components'
const isActualThumbnail = thumbnail => thumbnail.startsWith('http')
const getPlaceholder = str => {
if (['nsfw'].includes(str)) {
return str
} else {
return 'self'
}
}
const BaseThumbnail = styled.div`
width: 70px;
height: 70px;
bord... | import React from 'react'
import styled from 'styled-components'
const isActualThumbnail = thumbnail => thumbnail.startsWith('http')
const getPlaceholder = str => {
if (['nsfw'].includes(str)) {
return str
} else {
return 's'
}
}
const BaseThumbnail = styled.div`
width: 70px;
height: 70px;
border-... |
Fix test for python 2 | from __future__ import print_function, division, absolute_import
import numpy as np
from .common import *
from train.utils import preprocessImage, loadNetwork, predict
from constants import *
test_image = 234 * np.ones((MAX_WIDTH, MAX_HEIGHT, 3), dtype=np.uint8)
def testPreprocessing():
image = preprocessImage(... | from __future__ import print_function, division, absolute_import
import numpy as np
from .common import *
from train.utils import preprocessImage, loadNetwork, predict
from constants import *
test_image = 234 * np.ones((*CAMERA_RESOLUTION, 3), dtype=np.uint8)
def testPreprocessing():
image = preprocessImage(tes... |
Load asset at the footer.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Diskus;
use \Asset,
\Event,
Orchestra\Acl,
Orchestra\Core as O;
class Core {
/**
* Start your engine
*
* @static
* @access public
* @return void
*/
public static function start()
{
Acl::make('diskus')->attach(O::memory());
// Append all Diskus required assets for Orchestra Adm... | <?php namespace Diskus;
use \Asset,
\Event,
Orchestra\Acl,
Orchestra\Core as O;
class Core {
/**
* Start your engine
*
* @static
* @access public
* @return void
*/
public static function start()
{
Acl::make('diskus')->attach(O::memory());
// Append all Diskus required assets for Orchestra Adm... |
Move stuff so it looks prettier.. | <?php
// Imports
use Slim\Slim;
use Slim\Views\Twig;
use ProjectRena\Lib\SessionHandler;
use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware;
// Error display
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Load the autoloader
if(file_exists(__DIR__."/vendor/autoload.php"))
require_once(__DIR... | <?php
// Imports
use ProjectRena\Lib\SessionHandler;
use Slim\Slim;
use Slim\Views\Twig;
use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware;
// Error display
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Load the autoloader
if(file_exists(__DIR__."/vendor/autoload.php"))
require_once(__DIR... |
Update the service provider to publish the migrations | <?php
namespace Michaeljennings\Feed;
use Illuminate\Support\ServiceProvider;
class FeedServiceProvider extends ServiceProvider
{
/**
* @inheritdoc
*/
public function boot()
{
$this->publishes([
__DIR__.'/../migrations/' => database_path('migrations')
], 'migrations'... | <?php
namespace Michaeljennings\Feed;
use Illuminate\Support\ServiceProvider;
class FeedServiceProvider extends ServiceProvider
{
/**
* @inheritdoc
*/
public function register()
{
$this->app->bind('michaeljennings.feed.repository', 'Michaeljennings\Feed\Notifications\Repository');
... |
Change message that detects instance type | #!/usr/bin/env python
import sys
import click
from aws_util import Ec2Util
@click.command()
@click.option('-p', '--profile', default='default', help='Profile name to use.')
@click.argument('id_or_tag', required=True)
@click.argument('new_instance_type', required=True)
def cli(profile, id_or_tag, new_instance_type):
... | #!/usr/bin/env python
import sys
import click
from aws_util import Ec2Util
@click.command()
@click.option('-p', '--profile', default='default', help='Profile name to use.')
@click.argument('id_or_tag', required=True)
@click.argument('new_instance_type', required=True)
def cli(profile, id_or_tag, new_instance_type):
... |
Add userid to geotagging callback | 'use strict';
var request = require('request');
var Q = require('q');
var config = require('../config');
const plugins = require('../../plugins');
const geoTagController = plugins.getFirst('geo-tag-controller');
if(!geoTagController) {
throw new Error('Missing a geo-tag-controller plugin!');
}
function deg(w) {
... | 'use strict';
var request = require('request');
var Q = require('q');
var config = require('../config');
const plugins = require('../../plugins');
const geoTagController = plugins.getFirst('geo-tag-controller');
if(!geoTagController) {
throw new Error('Missing a geo-tag-controller plugin!');
}
function deg(w) {
... |
Set meta descripting for the main page.
closes #77 | import Vue from 'vue'
import Router from 'vue-router'
import index from '@/components/index'
import four from '@/components/four'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'github',
component: index,
meta: {
title: 'Linux Kernel C... | import Vue from 'vue'
import Router from 'vue-router'
import index from '@/components/index'
import four from '@/components/four'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'github',
component: index
},
{
path: '/streams/:stream_id... |
Add command line arguments for program | import argparse
import logging
import Portal
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog="Dynatrace Synthetic Automation")
parser.add_argument(
"-t", "--type", help="The account type: [gpn|dynatrace]", ... | import argparse
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog="BTScreenshotAutomation")
parser.add_argument(
"-a", "--account", help="The name of the account", type=str, required=True)
p... |
Add unique constraint to user email | module.exports = {
up: function (migration, DataTypes) {
return migration.createTable('Users', {
id: {
primaryKey: true,
allowNull: false,
type: DataTypes.UUID
},
name: {
allowNull: false,
type: DataTypes.STRING
},
email: {
unique: true... | module.exports = {
up: function (migration, DataTypes) {
return migration.createTable('Users', {
id: {
primaryKey: true,
allowNull: false,
type: DataTypes.UUID
},
name: {
allowNull: false,
type: DataTypes.STRING
},
email: {
allowNull: f... |
Print selection in selectionChanged handler. | from PySide import QtGui, QtCore
class Tree(QtGui.QTreeView):
def __init__(self, parent=None):
super(Tree, self).__init__(parent)
def load_from_path(self, path):
""" Load directory containing file into the tree. """
# Link the tree to a model
model = QtGui.QFileSystemModel()
model.setRootPath(path)
... | from PySide import QtGui, QtCore
class Tree(QtGui.QTreeView):
def __init__(self, parent=None):
super(Tree, self).__init__(parent)
def load_from_path(self, path):
""" Load directory containing file into the tree. """
# Link the tree to a model
model = QtGui.QFileSystemModel()
model.setRootPath(path)
... |
Remove duplicate test, fix duplicate test | import transformCss from '../..'
it('textShadow with all values', () => {
expect(transformCss([['text-shadow', '10px 20px 30px red']])).toEqual({
textShadowOffset: { width: 10, height: 20 },
textShadowRadius: 30,
textShadowColor: 'red',
})
})
it('textShadow omitting blur', () => {
expect(transformCs... | import transformCss from '../..'
it('textShadow with all values', () => {
expect(transformCss([['text-shadow', '10px 20px 30px red']])).toEqual({
textShadowOffset: { width: 10, height: 20 },
textShadowRadius: 30,
textShadowColor: 'red',
})
})
it('textShadow omitting blur', () => {
expect(transformCs... |
Clean local db and webapp references | package org.openmrs.reference.page;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class TestProperties {
private Properties properties;
public TestProperties() {
properties = new Properties();
try {
In... | package org.openmrs.reference.page;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class TestProperties {
private Properties properties;
public TestProperties() {
properties = new Properties();
try {
In... |
Update the active class for the current step | var GtfsEditor = GtfsEditor || {};
(function(G, $, ich) {
G.Router = Backbone.Router.extend({
routes: {
'': 'showStep',
':step': 'showStep'
},
initialize: function () {
var router = this;
$('#route-nav').on('click', 'a', function (evt) {
evt.preventDefault();
rout... | var GtfsEditor = GtfsEditor || {};
(function(G, $, ich) {
G.Router = Backbone.Router.extend({
routes: {
'': 'showStep',
':step': 'showStep'
},
initialize: function () {
var router = this;
$('#route-nav').on('click', 'a', function (evt) {
evt.preventDefault();
rout... |
Fix outdated command line help | import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import DataUse, def_def_train_input_fn, def_def_eval_input_fn
def def_def_experiment_fn():
adder = FlagAdder()
for use in DataUse:
use = use.value
adder.add_flag("{}_steps".format(use... | import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import def_def_train_input_fn
from .inputs import def_def_eval_input_fn
def def_def_experiment_fn():
adder = FlagAdder()
works_with = lambda name: "Works only with {}".format(name)
train_help = w... |
Add string as a possible prop type | import React, { Fragment, PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';
class Link extends PureComponent {
render() {
const { children, className, icon, iconPlacement, element, inherit, ...others } = this.props;
const classNam... | import React, { Fragment, PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';
class Link extends PureComponent {
render() {
const { children, className, icon, iconPlacement, element, inherit, ...others } = this.props;
const classNam... |
Order filter for report page | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from wye.organisations.models import Organisation
from wye.workshops.models import Workshop
from wye.profiles.models import Profile
import datetime
from wye.base.constants import WorkshopStatus
@login_required
def index(requ... | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from wye.organisations.models import Organisation
from wye.workshops.models import Workshop
from wye.profiles.models import Profile
import datetime
from wye.base.constants import WorkshopStatus
@login_required
def index(requ... |
Add missing dependency for tastypie | from setuptools import setup, find_packages
from gcm import VERSION
setup(
name='django-gcm',
version=VERSION,
description='Google Cloud Messaging Server',
author='Adam Bogdal',
author_email='adam@bogdal.pl',
url='https://github.com/bogdal/django-gcm',
download_url='https://github.com/bogda... | from setuptools import setup, find_packages
from gcm import VERSION
setup(
name='django-gcm',
version=VERSION,
description='Google Cloud Messaging Server',
author='Adam Bogdal',
author_email='adam@bogdal.pl',
url='https://github.com/bogdal/django-gcm',
download_url='https://github.com/bogda... |
Remove stupid South thing that is messing up Heroku
remove, I say!! | #!/usr/bin/env python
# This manage.py exists for the purpose of creating migrations
import sys
import django
from django.conf import settings
settings.configure(
ROOT_URLCONF='',
DATABASES={'default':
{'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
... | #!/usr/bin/env python
# This manage.py exists for the purpose of creating migrations
import sys
import django
from django.conf import settings
settings.configure(
ROOT_URLCONF='',
DATABASES={'default':
{'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
... |
Change the default logging level to error | import logging
import click
from detectem.response import get_har
from detectem.plugin import load_plugins
from detectem.core import Detector
# Set up logging
logger = logging.getLogger('detectem')
ch = logging.StreamHandler()
logger.setLevel(logging.ERROR)
logger.addHandler(ch)
@click.command()
@click.option(
... | import logging
import click
from detectem.response import get_har
from detectem.plugin import load_plugins
from detectem.core import Detector
# Set up logging
logger = logging.getLogger('detectem')
ch = logging.StreamHandler()
logger.setLevel(logging.DEBUG)
logger.addHandler(ch)
@click.command()
@click.option(
... |
Store new user instead of just id | <?php
namespace BasicUser\Model\Form;
use Solleer\User\{User, SigninStatus};
class Signup implements \MVC\Model\Form {
private $model;
private $status;
public $successful = false;
public $submitted = false;
public $newUser;
public function __construct(User $model, SigninStatus $status) {
... | <?php
namespace BasicUser\Model\Form;
use Solleer\User\{User, SigninStatus};
class Signup implements \MVC\Model\Form {
private $model;
private $status;
public $successful = false;
public $submitted = false;
public $newId;
public function __construct(User $model, SigninStatus $status) {
... |
Fix instagram script on feed | (function () {
'use strict';
window.scrollTo(0, document.body.scrollHeight);
var likeElements = document.querySelectorAll(".coreSpriteLikeHeartOpen");
var likeCount = 0;
var nextTime = 1000;
function doLike(photo) {
photo.click();
}
likeElements.forEach(photo => {
nextT... | (function () {
'use strict';
window.scrollTo(0, document.body.scrollHeight);
var likeElements = document.querySelectorAll(".coreSpriteHeartOpen");
var likeCount = 0;
var nextTime = 1000;
function doLike(i) {
likeElements[i].click();
}
for (var i = 0; i < likeElements.length; i+... |
Fix distinct asset in the basket. | "use strict";
(function () {
angular
.module("conpa")
.factory("basketService", basketService);
function basketService() {
var assets = [],
service = {
getAssets: getAssets,
addAsset: addAsset
};
return serv... | "use strict";
(function () {
angular
.module("conpa")
.factory("basketService", basketService);
function basketService() {
var assets = [],
service = {
getAssets: getAssets,
addAsset: addAsset
};
return serv... |
Change server port to 4000 | 'use strict';
module.exports = {
'serverport': 4000,
'styles': {
'src' : 'app/styles/**/*.scss',
'dest': 'build/css'
},
'scripts': {
'src' : 'app/js/**/*.js',
'dest': 'build/js'
},
'images': {
'src' : 'app/images/**/*',
'dest': 'build/images'
},
'views': {
'watch': [
... | 'use strict';
module.exports = {
'serverport': 3000,
'styles': {
'src' : 'app/styles/**/*.scss',
'dest': 'build/css'
},
'scripts': {
'src' : 'app/js/**/*.js',
'dest': 'build/js'
},
'images': {
'src' : 'app/images/**/*',
'dest': 'build/images'
},
'views': {
'watch': [
... |
Check AuthToken header if empty before query database | package middlewares
import (
"net/http"
"time"
"github.com/freeusd/solebtc/Godeps/_workspace/src/github.com/gin-gonic/gin"
"github.com/freeusd/solebtc/errors"
"github.com/freeusd/solebtc/models"
)
type authRequiredDependencyGetAuthToken func(authTokenString string) (models.AuthToken, *errors.Error)
// AuthRequ... | package middlewares
import (
"net/http"
"time"
"github.com/freeusd/solebtc/Godeps/_workspace/src/github.com/gin-gonic/gin"
"github.com/freeusd/solebtc/errors"
"github.com/freeusd/solebtc/models"
)
type authRequiredDependencyGetAuthToken func(authTokenString string) (models.AuthToken, *errors.Error)
// AuthRequ... |
Fix new form confirm code
@atfornes please note that this code is common for the + buttons
of project and community
Fixes #249 | 'use strict';
angular.module('Teem')
.factory('NewForm', [
'$location', '$window', '$rootScope',
function($location, $window, $rootScope) {
var scope,
objectName,
scopeFn = {
isNew () {
return $location.search().form === 'new';
},
cancelNew () {
... | 'use strict';
angular.module('Teem')
.factory('NewForm', [
'$location', '$window', '$rootScope',
function($location, $window, $rootScope) {
var scope,
objectName,
scopeFn = {
isNew () {
return $location.search().form === 'new';
},
cancelNew () {
... |
Add some prints to improve verbosity | """
Main script to execute the gesture recognition software.
"""
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe())... | """
Main script to execute the gesture recognition software.
"""
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe())... |
Update upstream version of vo | from distutils.core import Extension
from os.path import join
from astropy import setup_helpers
def get_extensions(build_type='release'):
VO_DIR = 'astropy/io/vo/src'
return [Extension(
"astropy.io.vo.tablewriter",
[join(VO_DIR, "tablewriter.c")],
include_dirs=[VO_DIR])]
def get_pa... | from distutils.core import Extension
from os.path import join
from astropy import setup_helpers
def get_extensions(build_type='release'):
VO_DIR = 'astropy/io/vo/src'
return [Extension(
"astropy.io.vo.tablewriter",
[join(VO_DIR, "tablewriter.c")],
include_dirs=[VO_DIR])]
def get_pa... |
New: Return child from execute method | const spawn = require('child_process').spawn;
const reorder = require('./lib/reorder');
exports.needed = function needed (flags, argv) {
var shouldRespawn = false;
if (!argv) {
argv = process.argv;
}
return (JSON.stringify(argv) !== JSON.stringify(reorder(flags, argv)));
};
exports.execute = function exec... | const spawn = require('child_process').spawn;
const reorder = require('./lib/reorder');
exports.needed = function needed (flags, argv) {
var shouldRespawn = false;
if (!argv) {
argv = process.argv;
}
return (JSON.stringify(argv) !== JSON.stringify(reorder(flags, argv)));
};
exports.execute = function exec... |
Add a broader set of events for inline event handler rewrite function |
opera.isReady(function() {
// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
document.addEventListener('DOMContentLoaded', function(e) {
var selectors = ['load', 'beforeunload', 'unload', 'click', 'dblclick', 'mouseover', 'mousemove',
... |
// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
document.addEventListener('DOMContentLoaded', function(e) {
var selectors = ['load', 'click', 'mouseover', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
for(var i = 0, l = selectors.length; i... |
Configure anti-spam form type constraints. | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Form\Type;
... | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Form\Type;
... |
Move structure to a separate directory | import countershape
from countershape import Page, Directory, PythonModule
import countershape.grok
this.layout = countershape.Layout("_layout.html")
this.markdown = "rst"
ns.docTitle = "Countershape Manual"
ns.docMaintainer = "Aldo Cortesi"
ns.docMaintainerEmail = "dev@nullcube.com"
ns.copyright = "Copyright Nullcub... | import countershape
from countershape import Page, Directory, PythonModule
import countershape.grok
this.layout = countershape.Layout("_layout.html")
this.markdown = "rst"
ns.docTitle = "Countershape Manual"
ns.docMaintainer = "Aldo Cortesi"
ns.docMaintainerEmail = "dev@nullcube.com"
ns.copyright = "Copyright Nullcub... |
Update @ Sat Mar 11 2017 17:01:59 GMT+0800 (CST) | const { exec } = require('child_process')
const ora = require('ora')
const config = require('../config')
const spinner = ora('Deploy to gh-pages...')
spinner.start()
function execute (cmd) {
return new Promise((resolve, reject) => {
exec(cmd, (err, stdout, stderr) => {
if (err) return reject(err)
if... | const { exec } = require('child_process')
const ora = require('ora')
const config = require('../config')
const spinner = ora('Deploy to gh-pages...')
spinner.start()
function execute (cmd) {
return new Promise((resolve, reject) => {
exec(cmd, (err, stdout, stderr) => {
if (err) return reject(err)
if... |
Replace duplicate test with valid address kwarg | import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, ... | import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, ... |
Fix style of unoriginal names plugin | <?php
$query = Query("SELECT name FROM {$dbpref}users");
$names = array();
while ($name = FetchRow($query))
{
$name = strtolower(preg_replace('/[^a-zA-Z]/', '', $name[0]));
// Name might not use any letters. Skip those.
if ($name)
$names[] = $name;
}
?>
<script>
$(function () {
var names = <?php echo json_encode(... | <?php
$query = Query("SELECT name FROM {$dbpref}users");
$names = array();
while ($name = FetchRow($query))
{
$name = strtolower(preg_replace('/[^a-zA-Z]/', '', $name[0]));
// Name might not use any letters. Skip those.
if ($name) {
$names[] = $name;
}
}
?>
<script>
$(function () {
var names = <?php echo json_en... |
Use medium text to store posts summary. | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table)
{
$... | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table)
{
$... |
Add new calculations; still needs work | public class ArrayAnalyzerLarge {
public static void main(String[] args) {
ArrayUtil au = new ArrayUtil();
//StopWatch sw = new StopWatch();
int size = 10000000;
int valueSize = 250000001;
for (int i=0; i<11; i++) {
int[] array = au.randomIntArray(size, valueSize);
size += 10... | public class ArrayAnalyzerLarge {
public static void main(String[] args) {
ArrayUtil au = new ArrayUtil();
StopWatch sw = new StopWatch();
int min = 999999999;
int max = 0;
int average = 0;
int[] mainArray = createArray(10, 10000000);
au.print(mainArray);
sw.reset()... |
Add tests for setting prefix | import { expect } from 'chai';
import { Tags, addOrRemoveTag, pre, mac } from '../extra-keys';
// see: https://github.com/mochajs/mocha/issues/1847
const { describe, it } = global;
describe('Markdown/extra-keys', () => {
it('should add tags to a selection', () => {
const result = addOrRemoveTag(Tags.STRONG, '... | import { expect } from 'chai';
import { Tags, addOrRemoveTag } from '../extra-keys';
// see: https://github.com/mochajs/mocha/issues/1847
const { describe, it } = global;
describe('Markdown/extra-keys', () => {
it('should add tags to a selection', () => {
const result = addOrRemoveTag(Tags.STRONG, 'foo');
... |
Make file uploading return more descriptive error messages. | <?php
/**
* @author marcus@silverstripe.com.au
* @license BSD License http://silverstripe.org/bsd-license/
*/
class FileUploadTask extends ScavengerTask {
public function updateTaskFields(FieldList $fields) {
$fields->push(new FileField('File', 'Upload file'));
}
public function processSubmission($data) {... | <?php
/**
* @author marcus@silverstripe.com.au
* @license BSD License http://silverstripe.org/bsd-license/
*/
class FileUploadTask extends ScavengerTask {
public function updateTaskFields(FieldList $fields) {
$fields->push(new FileField('File', 'Upload file'));
}
public function processSubmission($data) {... |
Install console script only in Py2.x. | from distutils.util import convert_path
import re
from setuptools import setup
import sys
def get_version():
with open(convert_path('cinspect/__init__.py')) as f:
metadata = dict(re.findall("__([a-z]+)__\s*=\s*'([^']+)'", f.read()))
return metadata.get('version', '0.1')
def get_long_description(... | from distutils.util import convert_path
import re
from setuptools import setup
import sys
def get_version():
with open(convert_path('cinspect/__init__.py')) as f:
metadata = dict(re.findall("__([a-z]+)__\s*=\s*'([^']+)'", f.read()))
return metadata.get('version', '0.1')
def get_long_description(... |
Fix revision numbers in migration 0177 | """
Revision ID: 0177_add_virus_scan_statuses
Revises: 0176_alter_billing_columns
Create Date: 2018-02-21 14:05:04.448977
"""
from alembic import op
revision = '0177_add_virus_scan_statuses'
down_revision = '0176_alter_billing_columns'
def upgrade():
op.execute("INSERT INTO notification_status_types (name) VA... | """
Revision ID: 0177_add_virus_scan_statuses
Revises: 0176_alter_billing_columns
Create Date: 2018-02-21 14:05:04.448977
"""
from alembic import op
revision = '0176_alter_billing_columns'
down_revision = '0175_drop_job_statistics_table'
def upgrade():
op.execute("INSERT INTO notification_status_types (name) ... |
Fix path for test logs | <?php
namespace ApiTest;
use Zend\Json\Json;
class JsonFileIterator extends \GlobIterator
{
/**
* Override parent to force pattern for JSON file
* @param string $path
*/
public function __construct($path)
{
$path = $path . '/*.json';
parent::__construct($path, \FilesystemI... | <?php
namespace ApiTest;
use Zend\Json\Json;
class JsonFileIterator extends \GlobIterator
{
/**
* Override parent to force pattern for JSON file
* @param string $path
*/
public function __construct($path)
{
$path = $path . '/*.json';
parent::__construct($path, \FilesystemI... |
:muscle: Structure of data generator iimproved
Structure of dataset generator improved | import numpy as np
import os
import sys
import time
from unrealcv import client
class Dataset(object):
def __init__(self,folder,nberOfImages):
self.folder=folder
self.nberOfImages=nberOfImages
self.client.connect()
def scan():
try:
p=self.client.request('vget /c... | import numpy as np
import os
import sys
import time
from unrealcv import client
class Dataset(object):
def __init__(self,folder,nberOfImages):
self.folder=folder
self.nberOfImages=nberOfImages
self.client.connect()
def scan():
try:
p=self.client.request('vget /c... |
Send original Stream in Sync with GetStream | package cdp
import (
"fmt"
"github.com/mafredri/cdp/rpcc"
)
type eventClient interface {
rpcc.Stream
}
type getStreamer interface {
GetStream() rpcc.Stream
}
// Sync takes two or more event clients and sets them into synchronous operation,
// relative to each other. This operation cannot be undone. If an error... | package cdp
import (
"github.com/mafredri/cdp/rpcc"
)
type eventClient interface {
rpcc.Stream
}
// Sync takes two or more event clients and sets them into synchronous operation,
// relative to each other. This operation cannot be undone. If an error is
// returned this function is no-op and the event clients will... |
Remove a Rails accent of use subject in favor of Zen of Python: explicit is better than implicit and readbility counts | from unittest import TestCase
import numpy as np
import pandas as pd
from rosie.chamber_of_deputies.classifiers import ElectionExpensesClassifier
class TestElectionExpensesClassifier(TestCase):
def setUp(self):
self.dataset = pd.read_csv('rosie/chamber_of_deputies/tests/fixtures/election_expenses_class... | from unittest import TestCase
import numpy as np
import pandas as pd
from rosie.chamber_of_deputies.classifiers import ElectionExpensesClassifier
class TestElectionExpensesClassifier(TestCase):
def setUp(self):
self.dataset = pd.read_csv('rosie/chamber_of_deputies/tests/fixtures/election_expenses_class... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.