text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Add text type as markdown. | """Set up script"""
from setuptools import setup
import os
def _create_long_desc():
"""Create long description and README formatted with rst."""
_long_desc = ''
if os.path.isfile('README.md'):
with open('README.md', 'r') as rf:
return rf.read()
if os.path.isfile('README.rst'):
... | """Set up script"""
from setuptools import setup
import os
def _create_long_desc():
"""Create long description and README formatted with rst."""
_long_desc = ''
if os.path.isfile('README.md'):
with open('README.md', 'r') as rf:
return rf.read()
if os.path.isfile('README.rst'):
... |
Store as a whole document instead of individual rows as it can get really expensive | var async = require('async');
var AWS = require('aws-sdk');
require('dotenv').config();
AWS.config.update({
region: process.env.AWS_REGION
});
var docClient = new AWS.DynamoDB.DocumentClient();
module.exports = {
// Log of taxis locations
// Trigger this every 30 seconds
logTaxis: function (event, context) {... | var async = require('async');
var AWS = require('aws-sdk');
require('dotenv').config();
AWS.config.update({
region: process.env.AWS_REGION
});
var docClient = new AWS.DynamoDB.DocumentClient();
module.exports = {
// Periodically recording of taxis locations
taxis: function (event, context) {
require('./tax... |
Exclude bower_components/ from watch task | module.exports = function(grunt) {
grunt.initConfig({
sass: {
dist: {
files: {
'sass/main.css': 'sass/main.scss'
},
options: {
style: 'compressed'
}
}
},
watch: {
sass: {
files: ['sass/*.scss'],
tasks: ['sass', 'autopr... | module.exports = function(grunt) {
grunt.initConfig({
sass: {
dist: {
files: {
'sass/main.css': 'sass/main.scss'
},
options: {
style: 'compressed'
}
}
},
watch: {
sass: {
files: ['sass/*.scss'],
tasks: ['sass', 'autopr... |
Add sleep during tests to prevent race | import sys
import unittest
import tempfile
import pathlib
import os
import os.path
import time
from unittest.mock import patch
import monitor
class TestMonitor(unittest.TestCase):
def test_MonitorConfigInterval(self):
with self.assertRaises(SystemExit):
testargs = ["monitor.py", "-f", "tests... | import sys
import unittest
import tempfile
import pathlib
import os
import os.path
from unittest.mock import patch
import monitor
class TestMonitor(unittest.TestCase):
def test_MonitorConfigInterval(self):
with self.assertRaises(SystemExit):
testargs = ["monitor.py", "-f", "tests/mocks/ini/m... |
Add bash script to add measures | from distutils.core import setup
setup(
name='boundary',
version='0.0.6',
url="https://github.com/boundary/boundary-api-cli",
author='David Gwartney',
author_email='davidg@boundary.com',
packages=['boundary',],
scripts=[
'bin/alarm-create',
'bin/alarm-list',
'bin/action-ins... | from distutils.core import setup
setup(
name='boundary',
version='0.0.6',
url="https://github.com/boundary/boundary-api-cli",
author='David Gwartney',
author_email='davidg@boundary.com',
packages=['boundary',],
scripts=[
'bin/alarm-create',
'bin/alarm-list',
'bin/action-ins... |
Remove notification type on log in | <?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "grade4_db";
$table_name = "students";
$name = $_POST['studname'];
$passphrase = $_POST['password'];
$url_success = 'pages/main_menu.php';
$url_fail = 'index.php';
try {
$conn = new PDO("mysql:host=$servername;dbname=$... | <?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "grade4_db";
$table_name = "students";
$name = $_POST['studname'];
$passphrase = $_POST['password'];
$url_success = 'pages/main_menu.php';
$url_fail = 'index.php';
try {
$conn = new PDO("mysql:host=$servername;dbname=$... |
Use tuple for version check | # -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp... | # -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp... |
Make simple option true by default as specified in README
Simple was undefined (falsy) unless specified explicitly | var Promise = require('bluebird'),
request = require('request');
function rp(options) {
var statusCodes = {
'GET' : [200],
'HEAD' : [200],
'PUT' : [200, 201],
'POST' : [200, 201],
'DELETE' : [200, 201]
}, c = {simple: true}, i;
if (typeof options === 'string'... | var Promise = require('bluebird'),
request = require('request');
function rp(options) {
var statusCodes = {
'GET' : [200],
'HEAD' : [200],
'PUT' : [200, 201],
'POST' : [200, 201],
'DELETE' : [200, 201]
}, c = {}, i;
if (typeof options === 'string') {
... |
Fix bug with ics url format with latest vobject version | import urllib
import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:V... | import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:... |
Remove the opposite event when image loading completes or fails . | define('summernote/core/async', function () {
/**
* Async functions which returns `Promise`
*/
var async = (function () {
/**
* read contents of file as representing URL
*
* @param {File} file
* @return {Promise} - then: sDataUrl
*/
var readFileAsDataURL = function (file) {
... | define('summernote/core/async', function () {
/**
* Async functions which returns `Promise`
*/
var async = (function () {
/**
* read contents of file as representing URL
*
* @param {File} file
* @return {Promise} - then: sDataUrl
*/
var readFileAsDataURL = function (file) {
... |
UPDATE autocomplete - set search string | var ResourceService = require("services/ResourceService");
var ItemListService = require("services/ItemListService");
Vue.component("item-search", {
template: "#vue-item-search",
data: function()
{
return {
searchString: "",
itemSearch: {}
};
},
ready: fun... | var ResourceService = require("services/ResourceService");
var ItemListService = require("services/ItemListService");
Vue.component("item-search", {
template: "#vue-item-search",
data: function()
{
return {
searchString: "",
itemSearch: {}
};
},
ready: fun... |
Remove uneccesary title for HTML in WebPack | const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: [
'./src/js/app.js',
'./src/sass/app.scss',
],
},
output: {
filename: 'assets/js/[name].js',
p... | const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: [
'./src/js/app.js',
'./src/sass/app.scss',
],
},
output: {
filename: 'assets/js/[name].js',
p... |
Modify test to test that bucketlist nolonger exists in system | import json
from api.test import BaseTestCase
from api.models import BucketList
class TestDeleteBucketList(BaseTestCase):
def test_delete_bucket_list(self):
bucket_list_one = {
"description": "Movies i have to watch by the end of the week",
"status": "Pending",
"title... | import json
from api.test import BaseTestCase
from api.models import BucketList
class TestDeleteBucketList(BaseTestCase):
def test_delete_bucket_list(self):
bucket_list_one = {
"description": "Movies i have to watch by the end of the week",
"status": "Pending",
"title... |
Fix button class on upload modal
no issue
- this makes sure that the cancel button on the upload modal gets the
correct class | import ModalDialog from 'ghost/components/gh-modal-dialog';
import upload from 'ghost/assets/lib/uploader';
var UploadModal = ModalDialog.extend({
layoutName: 'components/gh-modal-dialog',
didInsertElement: function () {
this._super();
upload.call(this.$('.js-drop-zone'), {fileStorage: this.ge... | import ModalDialog from 'ghost/components/gh-modal-dialog';
import upload from 'ghost/assets/lib/uploader';
var UploadModal = ModalDialog.extend({
layoutName: 'components/gh-modal-dialog',
didInsertElement: function () {
this._super();
upload.call(this.$('.js-drop-zone'), {fileStorage: this.ge... |
Update config tree builder constructor | <?php
namespace DataDog\AuditBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Configuration for DataDog/AuditBundle
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
... | <?php
namespace DataDog\AuditBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Configuration for DataDog/AuditBundle
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
... |
Check for state presence as well | import React, { Component } from 'react';
import Channel from 'jschannel';
const CHANNEL_NOT_READY = 'CHANNEL_NOT_READY';
class Seed extends Component {
componentWillUnmount() {
this.iframe.removeEventListener('load', this.iframeLoaded);
this.channel.destroy();
}
request = (requestOptions, callback) =... | import React, { Component } from 'react';
import Channel from 'jschannel';
const CHANNEL_NOT_READY = 'CHANNEL_NOT_READY';
class Seed extends Component {
componentWillUnmount() {
this.iframe.removeEventListener('load', this.iframeLoaded);
this.channel.destroy();
}
request = (requestOptions, callback) =... |
Add indented syntax for .sass files | let AutomaticComponent = require('./AutomaticComponent');
class Css extends AutomaticComponent {
/**
* webpack rules to be appended to the master config.
*/
webpackRules() {
return [
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
... | let AutomaticComponent = require('./AutomaticComponent');
class Css extends AutomaticComponent {
/**
* webpack rules to be appended to the master config.
*/
webpackRules() {
return [
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
... |
Change from constant public and secret key to retrieve it from database
Change the constant of public key and secret key that was fixed, to
retrieve it from database by using the class OmiseConfigProvider. | <?php
namespace Omise\Payment\Gateway\Http\Client;
use Magento\Payment\Gateway\Http\ClientInterface;
use Magento\Payment\Gateway\Http\TransferInterface;
use Omise\Payment\Model\Ui\OmiseConfigProvider;
abstract class AbstractOmiseClient implements ClientInterface
{
/**
* Client request status represented to ... | <?php
namespace Omise\Payment\Gateway\Http\Client;
use Magento\Payment\Gateway\Http\ClientInterface;
use Magento\Payment\Gateway\Http\TransferInterface;
define('OMISE_PUBLIC_KEY', 'pkey_test_51fl8dfabqmt3m27vl7');
define('OMISE_SECRET_KEY', 'skey_test_51fl8dfabe7sqnj8th2');
abstract class AbstractOmiseClient implem... |
Create folder if not exist | import os
from Measurement import Measurement
class Recorder(object):
def __init__(self, recorderType):
self.recorderType = recorderType
def record(self, measure: Measurement):
None
class PrintRecorder(Recorder):
def __init__(self, config):
Recorder.__init__(self, 'file')
... | from Measurement import Measurement
class Recorder(object):
def __init__(self, recorderType):
self.recorderType = recorderType
def record(self, measure: Measurement):
None
class PrintRecorder(Recorder):
def __init__(self, config):
Recorder.__init__(self, 'file')
self.form... |
Add missing line break on the first status line | <?php
require_once('class/3rdparty/OAuth.php');
require_once('class/3rdparty/twitter.class.php');
/**
* Generate tweet string
**/
class Tweet
{
/**
* Generate tweet from body
* Returns array of tweets
*
* @param $body
* @return array or false if no data
*/
public function gene... | <?php
require_once('class/3rdparty/OAuth.php');
require_once('class/3rdparty/twitter.class.php');
/**
* Generate tweet string
**/
class Tweet
{
/**
* Generate tweet from body
* Returns array of tweets
*
* @param $body
* @return array or false if no data
*/
public function gene... |
Remove all temporary files from disk | import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name... | import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name... |
Tweak media_type -> accepted_media_type. Need to document, but marginally less confusing | from django.core.handlers.wsgi import STATUS_CODE_TEXT
from django.template.response import SimpleTemplateResponse
class Response(SimpleTemplateResponse):
"""
An HttpResponse that allows it's data to be rendered into
arbitrary media types.
"""
def __init__(self, data=None, status=None, headers=No... | from django.core.handlers.wsgi import STATUS_CODE_TEXT
from django.template.response import SimpleTemplateResponse
class Response(SimpleTemplateResponse):
"""
An HttpResponse that allows it's data to be rendered into
arbitrary media types.
"""
def __init__(self, data=None, status=None, headers=No... |
Move fields for new output | #!/usr/bin/env python
import sys
import numpy as np
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-b",
"--bedpe_file",
dest="bedpe_file",
help="BEDPE file")
parser.add_option("-n",
"--name",
default="LUMPY BedGraph",
dest="name",
help="Name")
(options, ar... | #!/usr/bin/env python
import sys
import numpy as np
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-b",
"--bedpe_file",
dest="bedpe_file",
help="BEDPE file")
parser.add_option("-n",
"--name",
default="LUMPY BedGraph",
dest="name",
help="Name")
(options, ar... |
Validate that the function exists before execute. | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
v... | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
v... |
Remove unused var :police_car: :pencil: | "use strict";
var assert = require("assert"),
Processor = require("../src/processor");
describe("modular-css", function() {
describe("issue 56", function() {
it("shouldn't prune classes that have pseudo-classed variants", function(done) {
var processor = new Processor();
... | "use strict";
var assert = require("assert"),
Processor = require("../src/processor");
describe("modular-css", function() {
describe("issue 56", function() {
it("shouldn't prune classes that have pseudo-classed variants", function(done) {
var processor = new Processor();
... |
Refactor implement object entries locally | import invariant from "invariant";
const entries = (obj) => Object.keys(obj).map((key) => [key, obj[key]]);
const propValidates = ([name, propValidationFn]) => (props, componentName) => !(propValidationFn(props, name, componentName) instanceof Error);
export const satisfyOneOf = (propSet) => {
invariant(
... | import invariant from "invariant";
const propValidates = ([name, propValidationFn]) => (props, componentName) => !(propValidationFn(props, name, componentName) instanceof Error);
export const satisfyOneOf = (propSet) => {
invariant(
"object" === typeof propSet && null != propSet,
"Expected propSet... |
Switch to single-string commands and long ids | package forager.events;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import galileo.event.Event;
import galileo.net.NetworkDestination;
import galileo.serialization.SerializationInputStream;
import galileo.serialization.SerializationOutputStream;
public class TaskSpec implements Eve... | package forager.events;
import java.io.IOException;
import galileo.event.Event;
import galileo.serialization.SerializationInputStream;
import galileo.serialization.SerializationOutputStream;
public class TaskSpec implements Event {
public int taskId;
public String[] command;
public TaskSpec(int taskId,... |
Make data zoom match place zoom | import React, { PropTypes } from 'react'
import Map from '../home/map'
import LayerKey from './layer-key'
const PrimaryDataset = ({ dataset, lngLat }) => {
if (!dataset) return null
const { name, provider, description, url } = dataset
const selectedLayers = [dataset]
return (
<article className='cf'>
... | import React, { PropTypes } from 'react'
import Map from '../home/map'
import LayerKey from './layer-key'
const PrimaryDataset = ({ dataset, lngLat }) => {
if (!dataset) return null
const { name, provider, description, url } = dataset
const selectedLayers = [dataset]
return (
<article className='cf'>
... |
Use list instead of [:] to allow the pact argument to be an iterator | import itertools
from .base import PactBase
class PactGroup(PactBase):
def __init__(self, pacts=None, lazy=True):
if pacts is None:
pacts = []
self._pacts = list(pacts)
self._finished_pacts = []
self._is_lazy = lazy
super(PactGroup, self).__init__()
def _... | import itertools
from .base import PactBase
class PactGroup(PactBase):
def __init__(self, pacts=None, lazy=True):
if pacts is None:
pacts = []
self._pacts = pacts[:]
self._finished_pacts = []
self._is_lazy = lazy
super(PactGroup, self).__init__()
def __ia... |
Fix bug with space not working in input boxes | window.GLOBAL_ACTIONS = {
'play': function () {
wavesurfer.playPause();
},
'back': function () {
wavesurfer.skipBackward();
},
'forth': function () {
wavesurfer.skipForward();
},
'toggle-mute': function () {
wavesurfer.toggleMute();
}
};
// Bind actions to buttons and keypresses
doc... | window.GLOBAL_ACTIONS = {
'play': function () {
wavesurfer.playPause();
},
'back': function () {
wavesurfer.skipBackward();
},
'forth': function () {
wavesurfer.skipForward();
},
'toggle-mute': function () {
wavesurfer.toggleMute();
}
};
// Bind actions to buttons and keypresses
doc... |
Add some debug logging to books that fail to register | package amerifrance.guideapi.util;
import amerifrance.guideapi.api.GuideAPI;
import amerifrance.guideapi.api.GuideBook;
import amerifrance.guideapi.api.IGuideBook;
import amerifrance.guideapi.api.impl.Book;
import com.google.common.collect.Lists;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import org.... | package amerifrance.guideapi.util;
import amerifrance.guideapi.api.GuideAPI;
import amerifrance.guideapi.api.GuideBook;
import amerifrance.guideapi.api.IGuideBook;
import amerifrance.guideapi.api.impl.Book;
import com.google.common.collect.Lists;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import org.... |
Add extra constructor for backwards compatibility | package io.doist.recyclerviewext.click_listeners;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class ClickableViewHolder extends RecyclerView.ViewHolder {
public ClickableViewHolder(View itemView, OnItemClickListener onItemClickListener) {
this(itemView, onItemClickListe... | package io.doist.recyclerviewext.click_listeners;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class ClickableViewHolder extends RecyclerView.ViewHolder {
public ClickableViewHolder(View itemView, OnItemClickListener onItemClickListener,
OnItemLong... |
Fix issue with recursive arrays on exact matching domains, also added function to dump entire config | <?php
namespace ET;
class Config
{
private $config;
public function __construct($configFile, $visitDomain)
{
// Config not found at all
if (!file_exists($configFile)) {
throw new ConfigException('Configruation file not found: '.$configFile);
}
// Parse INI file... | <?php
namespace ET;
class Config
{
private $config;
public function __construct($configFile, $visitDomain)
{
// Config not found at all
if (!file_exists($configFile)) {
throw new ConfigException('Configruation file not found: '.$configFile);
}
// Parse INI fil... |
Use filter instead of for loop | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import omit from 'lodash.omit';
import theme from './theme.css';
class StatusLabel extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string,
mint: Pr... | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import omit from 'lodash.omit';
import theme from './theme.css';
class StatusLabel extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string,
mint: Pr... |
Fix line 40 to long issue. | const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
module.exports = function(options, fieldname, filename) {
const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/');
let hash = crypto.createHash('md5');
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
... | const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
module.exports = function(options, fieldname, filename) {
const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/');
let hash = crypto.createHash('md5');
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
... |
Add private constructor for factory. | package com.novoda.downloadmanager;
import com.novoda.notils.logger.simple.Log;
class WaitForLockRunnable {
interface Action {
void performAction();
}
private WaitForLockRunnable() {
// Uses static factory method.
}
static WaitForLockAndThenPerformActionRunnable waitFor(Object l... | package com.novoda.downloadmanager;
import com.novoda.notils.logger.simple.Log;
class WaitForLockRunnable {
interface Action {
void performAction();
}
static WaitForLockAndThenPerformActionRunnable waitFor(Object lock) {
return new WaitForLockAndThenPerformActionRunnable(lock);
}
... |
Change class to use new TaskDate | package seedu.doist.testutil;
import java.util.Date;
import seedu.doist.commons.exceptions.IllegalValueException;
import seedu.doist.model.tag.Tag;
import seedu.doist.model.tag.UniqueTagList;
import seedu.doist.model.task.Description;
import seedu.doist.model.task.Priority;
/**
*
*/
public class TaskBuilder {
... | package seedu.doist.testutil;
import java.util.Date;
import seedu.doist.commons.exceptions.IllegalValueException;
import seedu.doist.model.tag.Tag;
import seedu.doist.model.tag.UniqueTagList;
import seedu.doist.model.task.Description;
import seedu.doist.model.task.Priority;
/**
*
*/
public class TaskBuilder {
... |
Fix static path to match the /suppliers URL prefix | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/suppliers/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_clas... | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/supplier/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class... |
Fix form validation with editing form (values already here) | // Pay - /app/public/factories/formValidator.js
// Form Validator resource
'use strict';
pay.factory('FormValidator', [function () {
return function (form, imageSelector, imageValidator) {
// If we end directly the function, all errors may be not thrown
var formValid = true;
... | // Pay - /app/public/factories/formValidator.js
// Form Validator resource
'use strict';
pay.factory('FormValidator', [function () {
return function (form, imageSelector) {
// If we end directly the function, all errors may be not thrown
var formValid = true;
// Image validat... |
Make reporter succeed in talking to the graph server | #!/usr/bin/env python
# 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/.
import argparse
import glob
import os
import requests
import stoneridge
class StoneRidgeReporter... | #!/usr/bin/env python
# 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/.
import glob
import os
import requests
import stoneridge
class StoneRidgeReporter(object):
de... |
[ClientBundle] Fix for adding contact details | (function($) {
'use strict';
/**
* Form Collection
*/
$(document.body).on('click', '.contact_details_collection li', function(event) {
var $this = $(this),
value,
collectionHolder,
prototype,
regex,
form,
prototype_n... | (function($) {
'use strict';
/**
* Form Collection
*/
$(document.body).on('click', '.contact_details_collection li', function(event) {
var value,
collectionHolder,
prototype,
regex,
form,
prototype_name,
collectionCo... |
Make sequence marker types (:type) case insensitive | import bpy
def find_seqs(scene, select_marker):
sequences = {}
sequence_flags = {}
for marker in scene.timeline_markers:
if ":" not in marker.name or (select_marker and not marker.select):
continue
name, what = marker.name.rsplit(":", 1)
what = what.lower()
if... | import bpy
def find_seqs(scene, select_marker):
sequences = {}
sequence_flags = {}
for marker in scene.timeline_markers:
if ":" not in marker.name or (select_marker and not marker.select):
continue
name, what = marker.name.rsplit(":", 1)
if name not in sequences:
... |
Add tags to the component seeder | <?php
use CachetHQ\Cachet\Models\Component;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
class ComponentTableSeeder extends Seeder
{
/**
* Run the database seeding.
*
* @return void
*/
public function run()
{
Model::unguard();
$defaultCompone... | <?php
use CachetHQ\Cachet\Models\Component;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
class ComponentTableSeeder extends Seeder
{
/**
* Run the database seeding.
*
* @return void
*/
public function run()
{
Model::unguard();
$defaultCompone... |
Fix stupid deep equal check | import { assert } from 'chai';
import { expandNodesToLevel } from '../src';
const nestedTree = [{
value: '0',
label: 'Node 0',
children: [{
value: '0-0',
label: 'Node 0-0',
}, {
value: '0-1',
label: 'Node 0-1',
children: [{
value: '0-1-0',
... | import { assert } from 'chai';
import { expandNodesToLevel } from '../src';
const nestedTree = [{
value: '0',
label: 'Node 0',
children: [{
value: '0-0',
label: 'Node 0-0',
}, {
value: '0-1',
label: 'Node 0-1',
children: [{
value: '0-1-0',
... |
Use disable autorum api call | <?php
namespace NewRelic\Listener;
use Zend\EventManager\EventManagerInterface as Events;
use Zend\Mvc\MvcEvent;
class ResponseListener extends AbstractListener
{
/**
* @param Events $events
* @return void
*/
public function attach(Events $events)
{
$this->listeners[] = $events->at... | <?php
namespace NewRelic\Listener;
use Zend\EventManager\EventManagerInterface as Events;
use Zend\Mvc\MvcEvent;
class ResponseListener extends AbstractListener
{
/**
* @param Events $events
* @return void
*/
public function attach(Events $events)
{
$this->listeners[] = $events->at... |
Maintain alphabetical order in `install_requires`
PiperOrigin-RevId: 395092683
Change-Id: I87f23eafcb8a3cdafd36b8fd700f8a1f24f9fa6e
GitOrigin-RevId: a0819922a706dec7b8c2a17181c56a6900288e67 | # Copyright 2021 DeepMind Technologies Limited
#
# 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 agr... | # Copyright 2021 DeepMind Technologies Limited
#
# 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 agr... |
Add highlight to result in transformer | <?php
namespace makeandship\elasticsearch\transformer;
use makeandship\elasticsearch\Util;
class SearchTransformer
{
public function transform($response)
{
$val = array(
'total' => $response->getTotalHits(),
'facets' => array(),
'ids' => array(),
'resul... | <?php
namespace makeandship\elasticsearch\transformer;
use makeandship\elasticsearch\Util;
class SearchTransformer
{
public function transform($response)
{
$val = array(
'total' => $response->getTotalHits(),
'facets' => array(),
'ids' => array(),
'resul... |
Disable Flask 12h caching in debug mode
- prevented refreshing of Angular directive templates | #!/usr/bin/env python
"""Main module"""
from __future__ import print_function
from __future__ import absolute_import
import gevent
import gevent.monkey
gevent.monkey.patch_all()
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
import werkzeug.serving
# from werkzeug.debug impo... | #!/usr/bin/env python
"""Main module"""
from __future__ import print_function
from __future__ import absolute_import
import gevent
import gevent.monkey
gevent.monkey.patch_all()
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
import werkzeug.serving
# from werkzeug.debug impo... |
Add prop structure and performance models | " propeller model "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality
class Propeller(Model):
""" Propeller Model
Variables
---------
R 10 [m] prop radius
W 10 [lbf] prop weight
"""
def ... | " propeller model "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality
class Propeller(Model):
""" Propeller Model
Variables
---------
R 10 [m] prop radius
"""
def setup(self):
exec parse_variables(Propeller._... |
Include static subdirectories in package | """
Favien
======
Network canvas community.
"""
from setuptools import setup
setup(
name='Favien',
version='dev',
url='https://github.com/limeburst/favien',
author='Jihyeok Seo',
author_email='me@limeburst.net',
description='Network canvas community',
long_description=__doc__,
zip_sa... | """
Favien
======
Network canvas community.
"""
from setuptools import setup
setup(
name='Favien',
version='dev',
url='https://github.com/limeburst/favien',
author='Jihyeok Seo',
author_email='me@limeburst.net',
description='Network canvas community',
long_description=__doc__,
zip_sa... |
Remove comma for RT search | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self... | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self... |
Prepare for two-factor auth scenarios | export default function makeAuthActions (feathersClient) {
return {
authenticate (store, data) {
const { commit, state, dispatch } = store
commit('setAuthenticatePending')
if (state.errorOnAuthenticate) {
commit('clearAuthenticateError')
}
return feathersClient.authenticate(... | export default function makeAuthActions (feathersClient) {
return {
authenticate (store, data) {
const { commit, state, dispatch } = store
commit('setAuthenticatePending')
if (state.errorOnAuthenticate) {
commit('clearAuthenticateError')
}
return feathersClient.authenticate(... |
Add missing 'boltons' package & clean up | #!/usr/bin/env python
"""Setuptools setup."""
from setuptools import setup
readme = open('README.rst').read()
doclink = """
Documentation
-------------
The full documentation is at http://gryaml.rtfd.org."""
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='gryaml',
use_scm_ver... | #!/usr/bin/env python
import os
import sys
from setuptools import setup
readme = open('README.rst').read()
doclink = """
Documentation
-------------
The full documentation is at http://gryaml.rtfd.org."""
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='gryaml',
use_scm_versi... |
Allow augmented data passing to combineResources | var _ = require('underscore'),
lumbar = require('../lumbar');
function combineResources(context, outputData, callback) {
var resources = context.resources || [];
if (!resources.length) {
return callback();
}
context.outputFile(function(callback) {
lumbar.combine(
resources,
context.fil... | var lumbar = require('../lumbar');
function combineResources(context, callback) {
var resources = context.resources || [];
if (!resources.length) {
return callback();
}
context.outputFile(function(callback) {
lumbar.combine(
resources,
context.fileName,
context.options.minimize && co... |
Improve handling of profile defaults
If no profiles exist in the .novacfg, fall back to the default always. | var _ = require('underscore')
, fs = require('fs');
function loadConfiguration() {
var default_config = {
default: {
s3: {
region: null,
bucket: null,
keyPrefix: '',
},
},
profiles: {},
get: function(domain... | var _ = require('underscore')
, fs = require('fs');
function loadConfiguration() {
var default_config = {
default: {
s3: {
region: null,
bucket: null,
keyPrefix: '',
},
},
get: function(domain, profile) {
... |
BAP-11418: Implement Upload (Import) functionality
- remove not used import | <?php
namespace Oro\Bundle\TranslationBundle\ImportExport\Strategy;
use Oro\Bundle\TranslationBundle\Entity\Repository\TranslationRepository;
use Oro\Bundle\TranslationBundle\Entity\Translation;
class TranslationResetStrategy extends TranslationImportStrategy
{
/**
* @var array
*/
protected $proces... | <?php
namespace Oro\Bundle\TranslationBundle\ImportExport\Strategy;
use Oro\Bundle\ImportExportBundle\Strategy\Import\ConfigurableAddOrReplaceStrategy;
use Oro\Bundle\TranslationBundle\Entity\Repository\TranslationRepository;
use Oro\Bundle\TranslationBundle\Entity\Translation;
class TranslationResetStrategy extends... |
Update to return data in alphabetical order
Returns the countries and continents in alphabetical order, using the orderBy Method in Ascending order. | <?php
namespace Khsing\World;
use Khsing\World\Models\Continent;
use Khsing\World\Models\Country;
use Khsing\World\Models\Division;
/**
* World
*/
class World
{
public static function Continents()
{
return Continent::orderBy('name', 'asc')->get();
}
public static function Countries()
{... | <?php
namespace Khsing\World;
use Khsing\World\Models\Continent;
use Khsing\World\Models\Country;
use Khsing\World\Models\Division;
/**
* World
*/
class World
{
public static function Continents()
{
return Continent::get();
}
public static function Countries()
{
return Country:... |
Introduce integration tests using DropWizards ResourceTest. Include ability to return an Invalid Request message when the DLN or EnquiryId are missing. | package uk.gov.dvla.domain;
public class Message
{
private String key;
private String description;
private boolean error;
private int type;
public Message(){}
public Message(String key)
{
this.key = key;
}
public Message(String key, MessageType type)
... | package uk.gov.dvla.domain;
public class Message
{
private String key;
private String message;
private boolean error;
private int type;
public Message(){}
public Message(String key)
{
this.key = key;
}
public Message(String key, MessageType type)
{
... |
Fix missing text in services page | /* eslint-disable react/no-danger */
/* eslint-disable camelcase */
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import DOMPurify from 'dompurify';
const ServiceDetailStdout = ({ taskid }) => {
const [Taskresults, setTaskresults] = useState('');
const [Error, SetError] = ... | /* eslint-disable react/no-danger */
/* eslint-disable camelcase */
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import DOMPurify from 'dompurify';
const ServiceDetailStdout = ({ taskid }) => {
const [Taskresults, setTaskresults] = useState('');
const [Error, SetError] = ... |
Allow widget installation using the path. | <?php
namespace Yajra\CMS\Console;
use Illuminate\Console\Command;
use Yajra\CMS\Repositories\Extension\Repository;
class WidgetPublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'widget:install {name} {--path}';... | <?php
namespace Yajra\CMS\Console;
use Illuminate\Console\Command;
use Yajra\CMS\Repositories\Extension\Repository;
class WidgetPublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'widget:install {name}';
/**... |
Fix bad bound in Type 0x00 (Real) reading | <?php
/*
* Part of tivars_lib
* (C) 2015 Adrien 'Adriweb' Bertrand
* https://github.com/adriweb/tivars_lib
* License: MIT
*/
namespace tivars\TypeHandlers;
include_once "ITIVarTypeHandler.php";
// Type Handler for type 0x00: Real
class TH_0x00 implements ITIVarTypeHandler
{
public function makeDataFromStri... | <?php
/*
* Part of tivars_lib
* (C) 2015 Adrien 'Adriweb' Bertrand
* https://github.com/adriweb/tivars_lib
* License: MIT
*/
namespace tivars\TypeHandlers;
include_once "ITIVarTypeHandler.php";
// Type Handler for type 0x00: Real
class TH_0x00 implements ITIVarTypeHandler
{
public function makeDataFromStri... |
Install requirements now include SciPy.
Used in the operators subpackage, and will likely be used elsewhere due
to the sparse package being inside scipy. | from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs a... | from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs a... |
[BUGFIX] Make shuffle() a non-final operation
Change-Id: I675ee102d9f799c023c07f7abcbf839b48656429
Releases: master
Reviewed-on: https://review.typo3.org/27584
Reviewed-by: Karsten Dambekalns
Tested-by: Karsten Dambekalns
Reviewed-by: Christopher Hlubek
Original-Commit-Hash: cdc83573e41778089143dc5cdb2413b825e9c200 | <?php
namespace TYPO3\Eel\FlowQuery\Operations;
/* *
* This script belongs to the TYPO3 Flow package "TYPO3.Eel". *
* *
* It is free software; you can redistribut... | <?php
namespace TYPO3\Eel\FlowQuery\Operations;
/* *
* This script belongs to the TYPO3 Flow package "TYPO3.Eel". *
* *
* It is free software; you can redistribut... |
Change isinstance check to duck typing because this is Python lol | from discord.ext.commands import Bot, CommandInvokeError
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, ex... | from discord.ext.commands import Bot, CommandInvokeError
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
class BeattieBot(Bot):
async def reply(self, ctx, message):
return await ctx.send(f'{ctx.message.author.mention}\n{message}')
async def handle_error(self, ex... |
Use singular for project, visualization directories. | TileMill.controller.list = function() {
TileMill.backend.list('project', function(projects) {
TileMill.backend.list('visualization', function(visualizations) {
var page = $(TileMill.template('list', {
projects: TileMill.template('column', { 'name': 'Projects', 'type': 'project', 'data': projects }),... | TileMill.controller.list = function() {
TileMill.backend.list('projects', function(projects) {
TileMill.backend.list('visualizations', function(visualizations) {
var page = $(TileMill.template('list', {
projects: TileMill.template('column', { 'name': 'Projects', 'type': 'project', 'data': projects }... |
Add a secrets file in rnac notify
Nextflow doesn't propagate environment variables from the profile into
the event handler closures. This is the simplest workaround for that.
secrets.py should be on the cluster and symlinked into
rnacentral_pipeline | """
Send a notification to slack.
NB: The webhook should be configured in the nextflow profile
"""
import os
import requests
def send_notification(title, message, plain=False):
"""
Send a notification to the configured slack webhook.
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHO... | """
Send a notification to slack.
NB: The webhook should be configured in the nextflow profile
"""
import os
import requests
def send_notification(title, message, plain=False):
"""
Send a notification to the configured slack webhook.
"""
SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK')
if SLACK_WEBHO... |
Correct french translation module documents | /* eslint-disable no-undef */
import { Bert } from 'meteor/themeteorchef:bert';
import { upsertDocument } from '/imports/api/documents/methods';
import '/imports/lib/validation';
let component;
const handleUpsert = () => {
const { doc, history } = component.props;
const confirmation = doc && doc._id ? 'Document m... | /* eslint-disable no-undef */
import { Bert } from 'meteor/themeteorchef:bert';
import { upsertDocument } from '/imports/api/documents/methods';
import '/imports/lib/validation';
let component;
const handleUpsert = () => {
const { doc, history } = component.props;
const confirmation = doc && doc._id ? 'Document m... |
Update to Silverstripe 3.1.7
Included BootstrapLoadingFormAction for Submit Buttons | <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class BootstrapNavbarLanguageForm extends Form {
public function __construct($controller, $name, $fields = null, $actions = null) {
$Laguages = array();
foreach(LocaleGe... | <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class BootstrapNavbarLanguageForm extends Form {
public function __construct($controller, $name, $fields = null, $actions = null) {
$Laguages = array();
foreach(LocaleGe... |
Clean up main context class | <?php
use Behat\Behat\Context\Context;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
use Zeropingheroes\Lanager\Console\Kernel;
use Zeropingheroes\Lanager\User;
use Zeropingheroes\Lanager\UserOAuthAccount;
/**
* Defines application features from the specific context.
*/
class FeatureCont... | <?php
use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
use Zeropingheroes\Lanager\Console\Kernel;
use Zeropingheroes\Lanager\User;
use Zeropingheroes\Lanager\UserOAuthAccount;
/**
* Defines application features ... |
Remove 'field' and 'icon' from column list | from Products.CMFCore.utils import getToolByName
from Products.bika import logger
from Products.bika.browser.bika_folder_contents import BikaFolderContentsView
from plone.app.content.browser.interfaces import IFolderContentsView
from zope.interface import implements
class ClientFolderContentsView(BikaFolderContentsVie... | from Products.CMFCore.utils import getToolByName
from Products.bika import logger
from Products.bika.browser.bika_folder_contents import BikaFolderContentsView
from plone.app.content.browser.interfaces import IFolderContentsView
from zope.interface import implements
class ClientFolderContentsView(BikaFolderContentsVie... |
Convert atomno to int in case it is a different numpy dtype. | """
cclib (http://cclib.sf.net) is (c) 2006, the cclib development team
and licensed under the LGPL (http://www.gnu.org/copyleft/lgpl.html).
"""
__revision__ = "$Revision$"
import openbabel as ob
def makeopenbabel(atomcoords, atomnos, charge=0, mult=1):
"""Create an Open Babel molecule.
>>> import numpy, op... | """
cclib (http://cclib.sf.net) is (c) 2006, the cclib development team
and licensed under the LGPL (http://www.gnu.org/copyleft/lgpl.html).
"""
__revision__ = "$Revision$"
import openbabel as ob
def makeopenbabel(atomcoords, atomnos, charge=0, mult=1):
"""Create an Open Babel molecule.
>>> import numpy, op... |
Remove support for end-of-life Python 3.6 in next release
Checked again just now and we are still waiting on Python 3.10 stability | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]
setup(
author="Ryan Gibson",
author_email="ryanalexandergibson@gmail.com",
name... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]
setup(
author="Ryan Gibson",
author_email="ryanalexandergibson@gmail.com",
name... |
Introduce scope_types in migrate server
oslo.policy introduced the scope_type feature which can
control the access level at system-level and project-level.
- https://docs.openstack.org/oslo.policy/latest/user/usage.html#setting-scope
- http://specs.openstack.org/openstack/keystone-specs/specs/keystone/queens/system-... | # Copyright 2016 Cloudbase Solutions Srl
# 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 r... | # Copyright 2016 Cloudbase Solutions Srl
# 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 r... |
Use the mint database for capsule data | #
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_caps... | #
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_caps... |
Fix for IE + Edge | 'use strict';
(function (document) {
document.addEventListener('DOMContentLoaded', function () {
const details = document.getElementsByTagName('details');
if (details.length <= 0 || typeof details[0].open === 'boolean') {
return;
}
document.documentElement.setAttribute... | 'use strict';
(function (document) {
document.addEventListener('DOMContentLoaded', function () {
const details = document.getElementsByTagName('details');
if (details.length <= 0 || typeof details[0].open === 'boolean') {
return;
}
document.documentElement.setAttribute... |
Add credit where credit is due | <?php namespace Modules\Menu\Support;
use Illuminate\Database\Eloquent\Collection;
/**
* Class NestedCollection
* Credit: TypiCMS - https://github.com/sdebacker/TypiCMS/blob/master/app/TypiCMS/NestableCollection.php
*
* @package Modules\Menu\Support
*/
class NestedCollection extends Collection
{
private $tot... | <?php namespace Modules\Menu\Support;
use Illuminate\Database\Eloquent\Collection;
class NestedCollection extends Collection
{
private $total = 0;
public function __construct(array $items = array())
{
parent::__construct($items);
$this->total = count($items);
}
/**
* Nest it... |
Make sure to keep the property 'name' | 'use strict';
const _ = require('underscore');
function buildSlots(slots) {
const res = {};
_.each(slots, (value, key) => {
if ( _.isString(value)) {
res[key] = {
name: key,
value: value
};
} else {
res[key] = {
...value,
name: key
};
}
});
r... | 'use strict';
const _ = require('underscore');
function buildSlots(slots) {
const res = {};
_.each(slots, (value, key) => {
if ( _.isString(value)) {
res[key] = {
name: key,
value: value
};
} else {
res[key] = {
name: key,
...value
};
}
});
r... |
Make Room.getLOIs clone this.memory.sources instead of a directly using it | SetupPrototypes();
SetupRooms();
SpawnCreeps();
HandleCreeps();
EndTick();
function SetupPrototypes() {
Room.prototype.getLOIs = function() {
var lois = [];
this.memory.sources.forEach(function(sourceId) {
lois.push(sourceId);
});
if(this.controller) {
l... | SetupPrototypes();
SetupRooms();
SpawnCreeps();
HandleCreeps();
EndTick();
function SetupPrototypes() {
Room.prototype.getLOIs = function() {
var lois = this.memory.sources || []; // Need to clone that
if(this.controller) {
lois.push(this.controller.id);
}
return loi... |
Set default zIndex to 10000 | /**
* @name jquery-steamytext
* @version 1.1.0
* @description jQuery SteamyText animation plugin
* @author Maxim Zalysin <max@zalysin.ru>
*/
(function($){
$.fn.steamyText = function(data){
var defaults = {
text: '',
duration: 1500,
displace: 50,
tag: 'spa... | /**
* @name jquery-steamytext
* @version 1.0.0
* @description jQuery SteamyText animation plugin
* @author Maxim Zalysin <max@zalysin.ru>
*/
(function($){
$.fn.steamyText = function(data){
var defaults = {
text: ''
, duration: 1500
, displace: 50
, tag: '... |
Fix viewBox pre condition warning | const meetOrSliceTypes = {
meet: 0,
slice: 1,
none: 2,
};
const alignEnum = [
"xMinYMin",
"xMidYMin",
"xMaxYMin",
"xMinYMid",
"xMidYMid",
"xMaxYMid",
"xMinYMax",
"xMidYMax",
"xMaxYMax",
"none",
].reduce((prev, name) => {
prev[name] = name;
return prev;
}, {})... | const meetOrSliceTypes = {
meet: 0,
slice: 1,
none: 2,
};
const alignEnum = [
"xMinYMin",
"xMidYMin",
"xMaxYMin",
"xMinYMid",
"xMidYMid",
"xMaxYMid",
"xMinYMax",
"xMidYMax",
"xMaxYMax",
"none",
].reduce((prev, name) => {
prev[name] = name;
return prev;
}, {})... |
Fix script for release file already present case
This avoids a:
"AttributeError: 'HTTPError' object has no attribute 'message'"
Signed-off-by: Ulysses Souza <a0ff1337c6a0e43e9559f5f67fc3acb852912071@docker.com> | from __future__ import absolute_import
from __future__ import unicode_literals
from configparser import Error
from requests.exceptions import HTTPError
from twine.commands.upload import main as twine_upload
from twine.utils import get_config
from .utils import ScriptError
def pypi_upload(args):
print('Uploading... | from __future__ import absolute_import
from __future__ import unicode_literals
from configparser import Error
from requests.exceptions import HTTPError
from twine.commands.upload import main as twine_upload
from twine.utils import get_config
from .utils import ScriptError
def pypi_upload(args):
print('Uploading... |
Set a initial $scope.model.value for true/false | function booleanEditorController($scope, $rootScope, assetsService) {
function setupViewModel() {
$scope.renderModel = {
value: false
};
if ($scope.model.config && $scope.model.config.default && $scope.model.config.default.toString() === "1" && $scope.model && !$scope.mo... | function booleanEditorController($scope, $rootScope, assetsService) {
function setupViewModel() {
$scope.renderModel = {
value: false
};
if ($scope.model.config && $scope.model.config.default && $scope.model.config.default.toString() === "1" && $scope.model && !$scope.mo... |
Fix marked compatibility on API Doc | /**
* Display a SwaggerUI documentation
*/
import '../less/udata/swagger.less';
import $ from 'expose?$!expose?jQuery!jquery';
import commonmark from 'helpers/commonmark';
import hljs from 'highlight.js';
import log from 'logger';
// Required jQuery plugins
import 'jquery.browser';
import 'swaggerui/lib/jquery.slid... | /**
* Display a SwaggerUI documentation
*/
import '../less/udata/swagger.less';
import $ from 'expose?$!expose?jQuery!jquery';
import hljs from 'highlight.js';
import log from 'logger';
// Required jQuery plugins
import 'jquery.browser';
import 'swaggerui/lib/jquery.slideto.min';
import 'swaggerui/lib/jquery.wiggle... |
Rename to be consistent with backend name | """
Google App Engine support using User API
"""
from __future__ import absolute_import
from google.appengine.api import users
from social.backends.base import BaseAuth
from social.exceptions import AuthException
class GoogleAppEngineAuth(BaseAuth):
"""GoogleAppengine authentication backend"""
name = 'googl... | """
Google App Engine support using User API
"""
from __future__ import absolute_import
from google.appengine.api import users
from social.backends.base import BaseAuth
from social.exceptions import AuthException
class GoogleAppEngineAuth(BaseAuth):
"""GoogleAppengine authentication backend"""
name = 'googl... |
Fix Stream title alignment issue on Android | /* @flow */
import React, { PureComponent } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import type { Narrow, Stream } from '../types';
import StreamIcon from '../streams/StreamIcon';
import { isTopicNarrow } from '../utils/narrow';
const styles = StyleSheet.create({
wrapper: {
alignIte... | /* @flow */
import React, { PureComponent } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import type { Narrow, Stream } from '../types';
import StreamIcon from '../streams/StreamIcon';
import { isTopicNarrow } from '../utils/narrow';
const styles = StyleSheet.create({
wrapper: {
alignIte... |
Fix __repl__ implementation for TupleVal | from .environment import Environment
from viper.parser.ast.nodes import Expr
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def ... | from .environment import Environment
from viper.parser.ast.nodes import Expr
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(self.vals)})"
class NumVal(Value):
def __init__(s... |
Remove debug console.log - Rain IA
Remove debug console.log - Rain IA | (function(env) {
"use strict";
env.ddg_spice_rain = function(api_result) {
// Check for errors.
if(!api_result || api_result.error || !api_result.currently || !api_result.flags['ddg-location']) {
return Spice.failed('rain');
}
Spice.add({
id: 'rain',
... | (function(env) {
"use strict";
env.ddg_spice_rain = function(api_result) {
console.log(api_result);
// Check for errors.
if(!api_result || api_result.error || !api_result.currently || !api_result.flags['ddg-location']) {
return Spice.failed('rain');
}
Spice.... |
Add field 'creator' to table 'runs'
Example of values stored into *.tcx files:
runtastic - makes sports funtastic, http://www.runtastic.com | #!/usr/bin/python
# This script has to generate the sqlite database
#
# Requirements (import from):
# - sqlite3
#
# Syntax:
# ./generate_db.py
import sqlite3
DEFAULT_DB = "run-tracking.db"
def generate_tables(db=DEFAULT_DB):
conn = sqlite3.connect(db)
c = conn.cursor()
# Create tables
c.exe... | #!/usr/bin/python
# This script has to generate the sqlite database
#
# Requirements (import from):
# - sqlite3
#
# Syntax:
# ./generate_db.py
import sqlite3
DEFAULT_DB = "run-tracking.db"
def generate_tables(filename_db):
conn = sqlite3.connect(filename_db)
c = conn.cursor()
# Create tables
... |
Refactor key to access files from a folder's JSON | from .core import OSFCore
from .file import File
class Storage(OSFCore):
def _update_attributes(self, storage):
if not storage:
return
# XXX does this happen?
if 'data' in storage:
storage = storage['data']
self.id = self._get_attribute(storage, 'id')
... | from .core import OSFCore
from .file import File
class Storage(OSFCore):
def _update_attributes(self, storage):
if not storage:
return
# XXX does this happen?
if 'data' in storage:
storage = storage['data']
self.id = self._get_attribute(storage, 'id')
... |
Add ItemID response field to relist fixed price item command | package ebay
import "encoding/xml"
type RelistFixedPriceItem struct {
ItemID string
StartPrice string `xml:",omitempty"`
ConditionID uint `xml:",omitempty"`
Quantity uint `xml:",omitempty"`
Title ... | package ebay
import "encoding/xml"
type RelistFixedPriceItem struct {
ItemID string
StartPrice string `xml:",omitempty"`
ConditionID uint `xml:",omitempty"`
Quantity uint `xml:",omitempty"`
Title ... |
Fix a call to environment->debug | <?php
namespace Infinario;
class SynchronousTransport implements Transport
{
public function postAndForget(Environment $environment, $url, $payload)
{
$this->post($environment, $url, $payload);
}
public function post(Environment $environment, $url, $payload)
{
$ch = curl_init($url)... | <?php
namespace Infinario;
class SynchronousTransport implements Transport
{
public function postAndForget(Environment $environment, $url, $payload)
{
$this->post($environment, $url, $payload);
}
public function post(Environment $environment, $url, $payload)
{
$ch = curl_init($url)... |
MINOR: Print debug info to stderr | from __future__ import print_function
import sys
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep
def red(text):
RED = '\033[91m'
END = '\033[0m'
return RED + text + END
def log(*args):
print(*args, file=sys.stderr)
sys.stderr.flush()
cla... | #!/usr/bin/env python3
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep
def red(text):
RED = '\033[91m'
END = '\033[0m'
return RED + text + END
class HowLong(object):
def __init__(self):
parser = argparse.ArgumentParser(description='Ti... |
[utils] Add a function to clean dict keys
Remove None values. | from flask_restful import reqparse
from flask import request
class ArgsMixin(object):
"""
Helpers to retrieve parameters from GET or POST queries.
"""
def get_args(self, descriptors):
parser = reqparse.RequestParser()
for descriptor in descriptors:
action = None
... | from flask_restful import reqparse
from flask import request
class ArgsMixin(object):
"""
Helpers to retrieve parameters from GET or POST queries.
"""
def get_args(self, descriptors):
parser = reqparse.RequestParser()
for descriptor in descriptors:
action = None
... |
Fix resizer for election's embeds | colette.iframeResizer = (function() {
'use strict';
var pub = {},
cfg = {
selector: '#iframeContent',
el: null,
delay: 0,
resizeInternal: false,
iframeId: 'iframeId'
};
pub.init = function(args)
{
cfg.delay = args.dela... | colette.iframeResizer = (function() {
'use strict';
var pub = {},
cfg = {
selector: '#iframeContent',
el: null,
delay: 0,
resizeInternal: false
};
pub.init = function(args)
{
cfg.delay = args.delay || cfg.delay;
cfg.el = d... |
Allow editing of 'notes' field when creating new StockItem | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'par... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'par... |
Use FIREBASE_URL in waitList module. | (function() {
'use strict';
angular
.module('app.waitList')
.controller('WaitListController', WaitListController);
WaitListController.$inject = ['$firebaseArray', 'FIREBASE_URL'];
function WaitListController($firebaseArray, FIREBASE_URL) {
var vm = this;
var fireParties = new Firebase(FIREBA... | (function() {
'use strict';
angular
.module('app.waitList')
.controller('WaitListController', WaitListController);
WaitListController.$inject = ['$firebaseArray'];
function WaitListController($firebaseArray) {
var vm = this;
var fireParties = new Firebase('https://waitandeat-v2-demo.firebase... |
Fix compile error after rebase | package org.ovirt.mobile.movirt.ui.dashboard;
import android.os.Handler;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ProgressBar;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Vi... | package org.ovirt.mobile.movirt.ui.dashboard;
import android.os.Handler;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ProgressBar;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Vi... |
Allow user to type :) | import React, {PropTypes} from 'react'
const ENTER = 13
const ESCAPE = 27
const RawQueryEditor = React.createClass({
propTypes: {
query: PropTypes.shape({
rawText: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}).isRequired,
onUpdate: PropTypes.func.isRequired,
},
getInit... | import React, {PropTypes} from 'react'
const ENTER = 13
const ESCAPE = 27
const RawQueryEditor = React.createClass({
propTypes: {
query: PropTypes.shape({
rawText: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}).isRequired,
onUpdate: PropTypes.func.isRequired,
},
getInit... |
Read ApiKey from parent only if it is set | import invariant from 'invariant';
import PathStrategy from '../path';
import NativeStrategy from './nativeStrategy';
import FetchStrategy from './fetchStrategy';
const directionStrategy = ({ props, type: { defaultProps } }, parentProps) => {
const {
baseURL,
requestStrategy,
origin,
destination,
... | import invariant from 'invariant';
import PathStrategy from '../path';
import NativeStrategy from './nativeStrategy';
import FetchStrategy from './fetchStrategy';
const directionStrategy = ({ props, type: { defaultProps } }, parentProps) => {
const {
baseURL,
requestStrategy,
origin,
destination,
... |
Stop travis/phpunit complaining about defined constants
Local phpunit didn't throw this error | <?php
namespace Jadu\Pulsar\Twig\Extension;
class GetConstantExtensionTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->ext = new GetConstantExtension(array());
defined('STRING') or define('STRING', 'foo');
defined('BOOL') or define('BOOL', true);
defi... | <?php
namespace Jadu\Pulsar\Twig\Extension;
class GetConstantExtensionTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->ext = new GetConstantExtension(array());
define('STRING', 'foo');
define('BOOL', true);
define('INT', 42);
define('NULL', nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.