text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
[BUGFIX] Check for existance of $releasesList[0] before using
<?php namespace Deployer; task('buffer:stop', function () { $releasesList = get('releases_list'); // Remove lock files also from previous release because it can be still read by apache/nginx after switching. // get('releases_list') is cached by deployer on first call in other task so it does not have the ...
<?php namespace Deployer; task('buffer:stop', function () { $releasesList = get('releases_list'); // Remove lock files also from previous release because it can be still read by apache/nginx after switching. // get('releases_list') is cached by deployer on first call in other task so it does not have the ...
Fix broken pagination with Elasticsearch and Undertow Thanks @ashakhov for the solution Fix #4158
(function(){ 'use strict'; angular .module('<%=angularAppName%>') .factory('ParseLinks', ParseLinks); function ParseLinks () { var service = { parse : parse }; return service; function parse(header) { if (header.length === 0) { ...
(function(){ 'use strict'; angular .module('<%=angularAppName%>') .factory('ParseLinks', ParseLinks); function ParseLinks () { var service = { parse : parse }; return service; function parse(header) { if (header.length === 0) { ...
Put in a raise for status for now
from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from social.app.models.author import Author class FriendRequestsListView(generic.ListView): context_object_name = "all_friend_requests" template_name = "app/friend_requests_list.html" def get_qu...
from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from social.app.models.author import Author class FriendRequestsListView(generic.ListView): context_object_name = "all_friend_requests" template_name = "app/friend_requests_list.html" def get_qu...
Reduce complexity and try/catch block in Logger
# -*- coding: utf-8 -*- import os import logging import threading class Logger(object): def configure_logging(self): log_level = getattr(logging, os.environ.get('LOGLEVEL', 'INFO').upper()) logging.getLogger().setLevel(log_level) def __call__(self, function): self.configure_logging() ...
# -*- coding: utf-8 -*- import os import logging import threading class Logger(object): def configure_logging(self): log_level = getattr(logging, os.environ.get('LOGLEVEL', 'INFO').upper()) logging.getLogger().setLevel(log_level) def __call__(self, function): self.configure_logging()...
Document the type of NamedEnumField properly
from django.utils import six from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class EnumField(serializers.ChoiceField): default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')} def __init__(self, enum, **kwargs): self.enum = enum...
from django.utils import six from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class EnumField(serializers.ChoiceField): default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')} def __init__(self, enum, **kwargs): self.enum = enum...
Make rememberable cache flushes trigger on deletes too
<?php namespace Amelia\Rememberable; use Amelia\Rememberable\Query\Builder as QueryBuilder; use Amelia\Rememberable\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Model; trait Rememberable { protected static function bootRememberable() { if (static::rememberable()) { ...
<?php namespace Amelia\Rememberable; use Amelia\Rememberable\Query\Builder as QueryBuilder; use Amelia\Rememberable\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Model; trait Rememberable { protected static function bootRememberable() { if (static::rememberable()) { ...
Increase the buffer to satisfy appmanifest
var phantom = require("phantomjs") , execFile = require("child_process").execFile , jn = require("path").join , u = require("url") , querystring = require("querystring") , r2hPath = jn(__dirname, "../node_modules/respec/tools/respec2html.js") ; exports.generate = function (url, params, cb) { url = u.par...
var phantom = require("phantomjs") , execFile = require("child_process").execFile , jn = require("path").join , u = require("url") , querystring = require("querystring") , r2hPath = jn(__dirname, "../node_modules/respec/tools/respec2html.js") ; exports.generate = function (url, params, cb) { url = u.par...
Use Properties interface to get Manager properties. Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
""" Manager interface. """ from ._properties import Properties class Manager(object): """ Manager interface. """ _INTERFACE_NAME = 'org.storage.stratis1.Manager' def __init__(self, dbus_object): """ Initializer. :param dbus_object: the dbus object """ se...
""" Manager interface. """ class Manager(object): """ Manager interface. """ _INTERFACE_NAME = 'org.storage.stratis1.Manager' def __init__(self, dbus_object): """ Initializer. :param dbus_object: the dbus object """ self._dbus_object = dbus_object def...
Resolve styles from the scss directory
var path = require('path') module.exports = { entry: { app: './src/main.js', vendors: [ 'vue', 'vue-resource', 'vue-router', ], }, output: { path: path.resolve(__dirname, '../dist'), publicPath: '/themes/{{ name }}/dist/', ...
var path = require('path') module.exports = { entry: { app: './src/main.js', vendors: [ 'vue', 'vue-resource', 'vue-router', ], }, output: { path: path.resolve(__dirname, '../dist'), publicPath: '/themes/{{ name }}/dist/', ...
Edit logic for creating mesage success action
import { group, member, message } from '../actions/actionTypes'; const groupReducer = (state = {}, action = {}) => { switch (action.type) { case group.CREATE_SUCCESS: return { ...state, [action.group.id]: { members: [], messages: [] } }; case member.ADD...
import { group, member, message } from '../actions/actionTypes'; const groupReducer = (state = {}, action = {}) => { switch (action.type) { case group.CREATE_SUCCESS: return { ...state, [action.group.id]: { members: [], messages: [] } }; case member.ADD...
[Form] Allow setting different options to repeating fields
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\...
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\...
Fix _ function call from schedule window
Ext.define('Clonos.window.Schedule', { extend: 'Ext.window.Window', alias: 'widget.scheduleWindow', title: 'Schedule refresh', modal: true, draggable: false, shadow: false, items: [{ xtype: 'form', frame: true, width: 320, bodyPadding: 10, reference: ...
Ext.define('Clonos.window.Schedule', { extend: 'Ext.window.Window', alias: 'widget.scheduleWindow', title: _('Schedule refresh'), modal: true, draggable: false, shadow: false, items: [{ xtype: 'form', frame: true, width: 320, bodyPadding: 10, referenc...
Remove unnessesairy check in if statement
<?php /** * Particle. * * @link http://github.com/particle-php for the canonical source repository * @copyright Copyright (c) 2005-2015 Particle (http://particle-php.com) * @license https://github.com/particle-php/Filter/blob/master/LICENSE New BSD License */ namespace Particle\Filter; /** * Class Chain ...
<?php /** * Particle. * * @link http://github.com/particle-php for the canonical source repository * @copyright Copyright (c) 2005-2015 Particle (http://particle-php.com) * @license https://github.com/particle-php/Filter/blob/master/LICENSE New BSD License */ namespace Particle\Filter; /** * Class Chain ...
Add post fetching on props update
import React, { Component } from 'react' import PostItemContainer from '../../containers/PostItemContainer' import debounce from '../../util/debounce' class PostList extends Component { constructor (props) { super(props) this.onScroll = debounce(this.onScroll, 350).bind(this) } componentDidMount () { ...
import React, { Component } from 'react' import PostItemContainer from '../../containers/PostItemContainer' import debounce from '../../util/debounce' class PostList extends Component { constructor (props) { super(props) this.onScroll = debounce(this.onScroll, 350).bind(this) } componentDidMount () { ...
Add banner to Grunt banner
module.exports = function(grunt) { require('google-closure-compiler').grunt(grunt); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { banner: '// Simple2D.js — v<%= pkg.version %>, built <%= grunt.template.today("mm-dd-yyyy") %>\n\n', separator: '\...
module.exports = function(grunt) { require('google-closure-compiler').grunt(grunt); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: '\n\n' }, dist: { src: [ 'src/start.js', 'src/simple2d.js', '...
Handle navigation on keydown instead of keypress to work around automatic input focus acquisition.
window.addEventListener("keydown", function handleNavigation (event) { if (window.document.activeElement !== window.document.body) { return; } const keyCode = event.code; if (keyCode.indexOf("Digit") !== 0) { return; } const digit = Number(keyCode[5]); if (digit < 0 || digi...
window.addEventListener("keypress", function (event) { if (window.document.activeElement !== window.document.body) { return; } const keyCode = event.code; if (keyCode.indexOf("Digit") !== 0) { return; } const digit = Number(keyCode[5]); if (digit < 0 || digit > 9) { ...
Fix another regression in the architect test dummy
/** * Bogus plugin. Circularity ftw. */ define(function(require, exports, module) { "use strict"; main.consumes = [ "Plugin", "ui", "myplugin" ]; main.provides = ["myplugin"]; return main; function main(options, imports, register) { var Plugin = imports.Plugin; var ui ...
"use blacklist"; /** * Bogus plugin. Circularity ftw. */ define(function(require, exports, module) { "use strict"; main.consumes = [ "Plugin", "ui", "myplugin" ]; main.provides = ["myplugin"]; return main; function main(options, imports, register) { var Plugin = imports.Plugi...
Handle filenames with path prefixes in git commit logs
import redis import json from django.conf import settings import iconclass import requests import time import os def handle_githubpushes(): redis_c = redis.StrictRedis() while True: data = redis_c.lpop(settings.REDIS_PREFIX + '_gitpushes') if not data: break data = json.loads(data) ...
import redis import json from django.conf import settings import iconclass import requests import time def handle_githubpushes(): redis_c = redis.StrictRedis() while True: data = redis_c.lpop(settings.REDIS_PREFIX + '_gitpushes') if not data: break data = json.loads(data) ...
Make ribbon-webapp's context path configurable.
package org.wildfly.swarm.ribbon.webapp.runtime; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset; import org.wildfly.swarm.container.runtime.AbstractServerConfiguration; import org.wildfly.swarm.netflix.ribbon.RibbonArchive; im...
package org.wildfly.swarm.ribbon.webapp.runtime; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset; import org.wildfly.swarm.container.runtime.AbstractServerConfiguration; import org.wildfly.swarm.netflix.ribbon.RibbonArchive; im...
Add some debug for debian box
import subprocess import string from pprint import pprint class Command(object): def execute(self, command: str): cliArgs = self.parseCliArgs(command) pprint(cliArgs) process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = process.c...
import subprocess import string class Command(object): def execute(self, command: str): cliArgs = self.parseCliArgs(command) process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = process.communicate() if process.returncode != 0: ...
Set the title of the default page
<?php /** * @author Manuel Thalmann <m@nuth.ch> * @license Apache-2.0 */ namespace ManuTh\TemPHPlate\Pages; use System\Web; use System\Web\Forms\Rendering\PaintEventArgs; use System\Web\Forms\MenuItem; use ManuTh\TemPHPlate\Templates\BootstrapTemplate; { /** *...
<?php /** * @author Manuel Thalmann <m@nuth.ch> * @license Apache-2.0 */ namespace ManuTh\TemPHPlate\Pages; use System\Web; use System\Web\Forms\Rendering\PaintEventArgs; use System\Web\Forms\MenuItem; use ManuTh\TemPHPlate\Templates\BootstrapTemplate; { /** *...
Add new getExtendedTypes method in form extension for Symfony 4.2 When bumping the requirement to PHP 7.1 the iterable return type should be added
<?php namespace Payum\Bundle\PayumBundle\Form\Extension; use Payum\Core\Bridge\Symfony\Form\Type\GatewayFactoriesChoiceType; use Payum\Core\Registry\GatewayFactoryRegistryInterface; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Exception; use Symfony\Component\OptionsResolver\OptionsReso...
<?php namespace Payum\Bundle\PayumBundle\Form\Extension; use Payum\Core\Bridge\Symfony\Form\Type\GatewayFactoriesChoiceType; use Payum\Core\Registry\GatewayFactoryRegistryInterface; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Exception; use Symfony\Component\OptionsResolver\OptionsReso...
Add php to extras task
'use strict'; var url = 'http://www.samplesite.com'; var src = './src/'; var build = "./build/"; var dist = "./dist/"; module.exports = { site: { url: url, host: 'hosting.com', user: 'username', password: 'password', uploadPath: '/public_html' }, paths: { src: src, build: build, ...
'use strict'; var url = 'http://www.samplesite.com'; var src = './src/'; var build = "./build/"; var dist = "./dist/"; module.exports = { site: { url: url, host: 'hosting.com', user: 'username', password: 'password', uploadPath: '/public_html' }, paths: { src: src, build: build, ...
Fix invalid error code format for Axes Signed-off-by: Aleksi Häkli <44cb6a94c0d20644d531e2be44779b52833cdcd2@iki.fi>
from django.core.checks import Error, Tags, register from axes.conf import settings class Messages: CACHE_INVALID = 'invalid cache configuration for settings.AXES_CACHE' class Hints: CACHE_INVALID = ( 'django-axes does not work properly with LocMemCache as the cache backend' ' please add e....
from django.core.checks import Error, Tags, register from axes.conf import settings class Messages: CACHE_INVALID = 'invalid cache configuration for settings.AXES_CACHE' class Hints: CACHE_INVALID = ( 'django-axes does not work properly with LocMemCache as the cache backend' ' please add e....
[REF] openacademy: Modify copy method into inherit
from openerp import api,fields, models ''' ...
from openerp import fields, models ''' ...
Allow for 404 not found
'use strict'; var fluxApp = require('fluxapp'); var router = fluxApp.getRouter(); function isEnabled() { return !! (typeof window !== 'undefined' && window.history); } module.exports = { router: { init: function init(url, meta) { var request = router.build(url, meta, false); if (! request) { ...
'use strict'; var fluxApp = require('fluxapp'); var router = fluxApp.getRouter(); function isEnabled() { return !! (typeof window !== 'undefined' && window.history); } module.exports = { router: { init: function init(url, meta) { var request = router.build(url, meta); if (! request) { th...
Add Execption for invalid Integer Exception class created for invalid integer and raise it if a bad integer is found
from .lexerconstants import * from .ws_token import Tokeniser class IntError(ValueError): '''Exception when invalid integer is found''' class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() ...
from .lexerconstants import * from .ws_token import Tokeniser class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.sca...
Make sponsored event redirect permanent (HTTP 301)
from django.http import Http404 from django.views.generic import DetailView, ListView, RedirectView from proposals.models import TalkProposal from .models import SponsoredEvent class AcceptedTalkMixin: queryset = ( TalkProposal.objects .filter(accepted=True) .select_related('submitter') ...
from django.http import Http404 from django.views.generic import DetailView, ListView, RedirectView from proposals.models import TalkProposal from .models import SponsoredEvent class AcceptedTalkMixin: queryset = ( TalkProposal.objects .filter(accepted=True) .select_related('submitter') ...
REMOVE DEBUG CODE FROM PRODUCTION *whistles innocently*
<?php namespace Korobi\WebBundle\Extension; class ExtensionTwigFunctions extends \Twig_Extension { public function getName() { return 'korobi_extension_twig_functions'; } public function getFunctions() { return [ new \Twig_SimpleFunction('cahFullCard', [$this, 'cahFullCard'])...
<?php namespace Korobi\WebBundle\Extension; class ExtensionTwigFunctions extends \Twig_Extension { public function getName() { return 'korobi_extension_twig_functions'; } public function getFunctions() { return [ new \Twig_SimpleFunction('cahFullCard', [$this, 'cahFullCard'])...
Fix wrong merge parameters with same hash
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\Doctrine\QueryBuilder\Filter\ORM; class Between extends AbstractFilter { public function filter($queryBuilder, $metadata, $option) ...
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\Doctrine\QueryBuilder\Filter\ORM; class Between extends AbstractFilter { public function filter($queryBuilder, $metadata, $option) ...
Remove confirm_phone_number method from model
#from flask.ext.login import UserMixin from account_verification_flask import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String, nullable = False) email = db.Column(db.String, nullable = False) password = db.Column(d...
#from flask.ext.login import UserMixin from account_verification_flask import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String, nullable = False) email = db.Column(db.String, nullable = False) password = db.Column(d...
Fix race condition in test Registering an event with the shorthand syntax behaves like `.on` and not like `.once` so in this case, if more than one request *will be sent* by the "New Tab" of Chrome then the Mocha's `done()` function gets called twice causing an error. This has been hidden until 85409d3a4633ddb928c64f...
var Chrome = require('../'); var assert = require('assert'); describe('registering event', function () { describe('"event"', function () { it('should give the raw message', function (done) { Chrome(function (chrome) { chrome.once('event', function (message) { ...
var Chrome = require('../'); var assert = require('assert'); describe('registering event', function () { describe('"event"', function () { it('should give the raw message', function (done) { Chrome(function (chrome) { chrome.once('event', function (message) { ...
Check if text content has been changed
function removeWhitespace(string) { return string.replace(/\s+/g, ''); } describe('scrambler tests', function(){ beforeEach(function() { fixture.setBase('fixtures') }); beforeEach(function(){ this.sample = fixture.load('sample.html'); runSpy = spyOn(scrambler._scrambler, "run"...
describe('scrambler tests', function(){ beforeEach(function() { fixture.setBase('fixtures') }); beforeEach(function(){ this.sample = fixture.load('sample.html'); runSpy = spyOn(scrambler._scrambler, "run").and.callThrough(); jasmine.clock().install(); }); afterEach...
Revert "Reduce anonymous function creation during iteration for edge cases" This reverts commit 38006447b94b9113998954f15b6b869313e09d9e.
'use strict' var values = require('../sources/values') var once = require('../sources/once') //convert a stream of arrays or streams into just a stream. module.exports = function flatten () { return function (read) { var _read return function (abort, cb) { if (abort) { //abort the current stream, and ...
'use strict' var values = require('../sources/values') var once = require('../sources/once') function getAbortCb(read, abort, cb) { return function(err) { read(err || abort, cb) } } function getChunkErrorCb(err, cb) { return function() { cb(err) } } //convert a stream of arrays or streams into just a...
Add origin function to vendor
(function() { tinymce.PluginManager.requireLangPack('uploadimage'); var currentOrigin = function(url){ var parts = url.split(/\/\/?/); parts[1] = location.origin; return parts.slice(1).join("/"); } tinymce.create('tinymce.plugins.UploadImagePlugin', { init: function(ed, url) { ed.addComman...
(function() { tinymce.PluginManager.requireLangPack('uploadimage'); tinymce.create('tinymce.plugins.UploadImagePlugin', { init: function(ed, url) { ed.addCommand('mceUploadImage', function() { return ed.windowManager.open({ file: url + '/dialog.html', width: 350 + parseInt(ed.g...
Use the user's getters to check if we need to set the plainpassword
<?php namespace SumoCoders\FrameworkMultiUserBundle\DataTransferObject; use SumoCoders\FrameworkMultiUserBundle\User\User; use SumoCoders\FrameworkMultiUserBundle\User\UserWithPassword; class UserWithPasswordDataTransferObject implements UserDataTransferObject { /** * @var int */ public $id; /...
<?php namespace SumoCoders\FrameworkMultiUserBundle\DataTransferObject; use SumoCoders\FrameworkMultiUserBundle\User\User; use SumoCoders\FrameworkMultiUserBundle\User\UserWithPassword; class UserWithPasswordDataTransferObject implements UserDataTransferObject { /** * @var int */ public $id; /...
Decrease the threshold for lines in unit tests coverage by 1%
const TEST_TYPE = ((argv) => { let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/); return match && match[1] || ''; })(process.argv); function configOverrides (testType) { switch (testType) { case 'cli': return { statements: 80, bra...
const TEST_TYPE = ((argv) => { let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/); return match && match[1] || ''; })(process.argv); function configOverrides (testType) { switch (testType) { case 'cli': return { statements: 80, bra...
Fix pagination of locations filter
from django.http.response import JsonResponse from django.utils.decorators import method_decorator from django.views.generic.base import View from corehq.apps.domain.decorators import login_and_domain_required from corehq.apps.locations.permissions import location_safe from corehq.apps.userreports.reports.filters.choi...
from django.http.response import JsonResponse from django.utils.decorators import method_decorator from django.views.generic.base import View from corehq.apps.domain.decorators import login_and_domain_required from corehq.apps.locations.permissions import location_safe from corehq.apps.userreports.reports.filters.choi...
Mark feedback comments starting with a html tag as spammy
from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_protect from models import Feedback from forms import FeedbackForm import re @csrf_protect def add(request): """Gather feedback for a page, and if it is ok show a thanks messa...
from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_protect from models import Feedback from forms import FeedbackForm @csrf_protect def add(request): """Gather feedback for a page, and if it is ok show a thanks message and link ...
Format translation of "Delete Attribute" for javascript
<?php defined('C5_EXECUTE') or die("Access Denied."); ?> <div style="display: none"> <div id="ccm-dialog-delete-attribute" class="ccm-ui"> <form method="post" action="<?= $deleteAction ?>"> <?=Core::make("token")->output('delete_attribute')?> <input type="hidden" name="id" value="<?=$key->getAttrib...
<?php defined('C5_EXECUTE') or die("Access Denied."); ?> <div style="display: none"> <div id="ccm-dialog-delete-attribute" class="ccm-ui"> <form method="post" action="<?= $deleteAction ?>"> <?=Core::make("token")->output('delete_attribute')?> <input type="hidden" name="id" value="<?=$key->getAttrib...
Make \G or \g to end a query.
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CLIBuffer(Buffer): def __init__(self, always_multiline, *args, **kwargs): self.always_multiline = always_multiline @Condition def is_multiline(): doc = self.document return s...
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CLIBuffer(Buffer): def __init__(self, always_multiline, *args, **kwargs): self.always_multiline = always_multiline @Condition def is_multiline(): doc = self.document return s...
Fix error with TV screen
var TvApi = require('node-lgtv-api'); var imageName = 'screen.jpg'; module.exports = { handle: function (ctx, message, sendMessage) { var lgTV = ctx.config.network.lgTV; var tvApi = new TvApi(lgTV.host, lgTV.port, lgTV.pairingKey); tvApi.authenticate(function (err, sessionKey) { ...
var TvApi = require('node-lgtv-api'); var imageName = 'screen.jpg'; module.exports = { handle: function (ctx, message, sendMessage) { var lgTV = ctx.network.lgTV; var tvApi = new TvApi(lgTV.host, lgTV.port, lgTV.pairingKey); tvApi.authenticate(function (err, sessionKey) { if...
Add default template for testimonial block
<?php namespace Concrete\Package\Worldskills\Theme\Worldskills; use Concrete\Core\Page\Theme\Theme; class PageTheme extends Theme { public function registerAssets() { $this->requireAsset('javascript', 'jquery'); $this->providesAsset('css', 'bootstrap/*'); $this->providesAsset('css', ...
<?php namespace Concrete\Package\Worldskills\Theme\Worldskills; use Concrete\Core\Page\Theme\Theme; class PageTheme extends Theme { public function registerAssets() { $this->requireAsset('javascript', 'jquery'); $this->providesAsset('css', 'bootstrap/*'); $this->providesAsset('css', ...
Use numbers instead of percent in chart
$(document).ready(function () { google.charts.load('current', { packages: ['corechart', 'bar'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var elem = $('#pie_chart').get(0); var headerParts = elem.dataset.header.split(','); var data = [[headerParts[0], he...
$(document).ready(function () { google.charts.load('current', { packages: ['corechart', 'bar'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var elem = $('#pie_chart').get(0); var headerParts = elem.dataset.header.split(','); var data = [[headerParts[0], he...
Fix PicleCache error on Python3
from __future__ import with_statement import os import pickle from contextlib import closing try: from redis import Redis except ImportError: Redis = None class Cache(object): def __init__(self): self._cache = {} def get(self, k): return self._cache.get(k) def set(self, k, v): ...
from __future__ import with_statement import os import pickle from contextlib import closing try: from redis import Redis except ImportError: Redis = None class Cache(object): def __init__(self): self._cache = {} def get(self, k): return self._cache.get(k) def set(self, k, v): ...
Add catch for Travis CI testing.
__all__ = [ 'test', ] def test(close=False): """ @desc: This is a convienance method to run all of the tests in `PVGeo`. @notes: This can be executed from either the command line of within a standard Python environment: ```bash $ python -m PVGeo test ``` ```py >>> import PVGe...
__all__ = [ 'test', ] def test(): """ @desc: This is a convienance method to run all of the tests in `PVGeo`. @notes: This can be executed from either the command line of within a standard Python environment: ```bash $ python -m PVGeo test ``` ```py >>> import PVGeo >>> P...
Add basic e2e for search field.
describe('idai field app', function() { function createObject() { return clickCreateObject() .then(selectTypeObject) .then(typeInIdentifier) .then(saveObject); } function clickCreateObject() { return element(by.id('object-overview-button-cr...
describe('idai field app', function() { function createObject() { return clickCreateObject() .then(selectTypeObject) .then(typeInIdentifier) .then(saveObject); } function clickCreateObject() { return element(by.id('object-overview-button-cr...
Handle an authentication edge case
from django.http import Http404 from django.utils import timezone from clubadm.models import Member, Season class SeasonMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if "year" in view_kwargs: year = int(view_kwargs["year"]) try: ...
from django.http import Http404 from django.utils import timezone from clubadm.models import Member, Season class SeasonMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if "year" in view_kwargs: year = int(view_kwargs["year"]) try: ...
Add note about how to generate trajectories
"""Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename # command for generating reference data: # gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend # # Do that three times. def write_run_c...
"""Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename def write_run_clone(proj, run, clone, gens=None): if gens is None: gens = [0, 1] rc = "data/PROJ{proj}/RUN{run}/CLONE{cl...
Allow webpack errors to be displayed (suppress browserSyncInstance.reload)
let argv = require('yargs').argv; let command = require('node-cmd'); let jigsaw = require('./tasks/bin'); let mix = require('laravel-mix'); let AfterBuild = require('on-build-webpack'); let BrowserSync = require('browser-sync'); let BrowserSyncPlugin = require('browser-sync-webpack-plugin'); let Watch = require('webpa...
let argv = require('yargs').argv; let command = require('node-cmd'); let jigsaw = require('./tasks/bin'); let mix = require('laravel-mix'); let AfterBuild = require('on-build-webpack'); let BrowserSync = require('browser-sync'); let BrowserSyncPlugin = require('browser-sync-webpack-plugin'); let Watch = require('webpa...
Use LocalFileAdapter when no scheme is given >>> t1 = Transporter('/file/path') >>> t2 = Transporter('file:/file/path') >>> type(t1.adapter) == type(t2.adapter) True >>> t1.pwd() == t2.pwd() True
from urlparse import urlparse import os import adapters try: import paramiko except ImportError: pass """The following protocals are supported ftp, ftps, http and https. sftp and ssh require paramiko to be installed """ class Transporter(object): availible_adapters = { "ftp": adapters.FtpAdapte...
from urlparse import urlparse import os import adapters try: import paramiko except ImportError: pass """The following protocals are supported ftp, ftps, http and https. sftp and ssh require paramiko to be installed """ class Transporter(object): availible_adapters = { "ftp": adapters.FtpAdapte...
Remove beta. from email domain
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart DOMAIN = 'donut.caltech.edu' def send_email(to, text, subject, use_prefix=True, group=None, poster='', richtext=''): """ ...
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart DOMAIN = "beta.donut.caltech.edu" def send_email(to, text, subject, use_prefix=True, group=None, poster='', richtext=''): ""...
Hide starting dots when n/a
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Dots from './Dots'; import StartingDots from './StartingDots'; import dotSelector from '../utils/dotSelector'; import { capitalizeFirstLetter } from '../utils/stringUtils'; class Trait extends Component { static propTypes = { na...
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Dots from './Dots'; import StartingDots from './StartingDots'; import dotSelector from '../utils/dotSelector'; import { capitalizeFirstLetter } from '../utils/stringUtils'; class Trait extends Component { static propTypes = { na...
Fix password field name on administration page.
<?php /** @var array $roles */ return [ 'elements' => [ 'name' => [ 'text', [ 'label' => __('Display Name'), 'class' => 'half-width', 'label_class' => 'mb-2', ], ], 'email' => [ 'email', ...
<?php /** @var array $roles */ return [ 'elements' => [ 'name' => [ 'text', [ 'label' => __('Display Name'), 'class' => 'half-width', 'label_class' => 'mb-2', ] ], 'email' => [ 'email', ...
BB-2188: Add posibility to use parameters in data providers - fixed old-style data-providers after master backmerge
<?php namespace Oro\Component\Layout\Extension\Theme\DataProvider; use Oro\Component\Layout\Extension\Theme\Model\Theme; use Oro\Component\Layout\Extension\Theme\Model\ThemeManager; class ThemeProvider { /** @var ThemeManager */ protected $themeManager; /** @var Theme[] */ protected $themes = []; ...
<?php namespace Oro\Component\Layout\Extension\Theme\DataProvider; use Oro\Component\Layout\Extension\Theme\Model\Theme; use Oro\Component\Layout\Extension\Theme\Model\ThemeManager; class ThemeProvider { /** @var ThemeManager */ protected $themeManager; /** @var Theme[] */ protected $themes = []; ...
Use previous commit as reference point for updates
import binascii import git import sys import os import logging logger = logging.getLogger('root') __match__ = r"!update|!reload" def on_message(bot, channel, user, message): requires_reload = message == '!reload' if message == '!update': local = git.Repo(os.getcwd()) origin = git.remote.Remo...
import binascii import git import sys import os import logging logger = logging.getLogger('root') __match__ = r"!update|!reload" def on_message(bot, channel, user, message): requires_reload = message == '!reload' if message == '!update': local = git.Repo(os.getcwd()) origin = git.remote.Remo...
Update the driving time periodically
(function(N) { N.Map = function(opts) { self = this; self.directionsService = new google.maps.DirectionsService(); self.directionsDisplay = new google.maps.DirectionsRenderer(); var mapOptions = { center: new google.maps.LatLng(39.875, -75.238), zoom: 13, ...
(function(N) { N.Map = function(opts) { self = this; self.directionsService = new google.maps.DirectionsService(); self.directionsDisplay = new google.maps.DirectionsRenderer(); var mapOptions = { center: new google.maps.LatLng(39.875, -75.238), zoom: 13, ...
Verify that recent list is cleared when language is changed
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import nose.tools as nose import yv_suggest.set_pref as yvs import context_managers as ctx def test_set_language(): """should set preferred language""" with ctx.preserve_prefs() as prefs: with ctx.preserve_recent_re...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import nose.tools as nose import yv_suggest.set_pref as yvs import context_managers as ctx def test_set_language(): """should set preferred language""" with ctx.preserve_prefs() as prefs: with ctx.preserve_recent_re...
Use initialState in Modal reducer spec
import reducer from './'; describe('Modal reducer', () => { let initialState; let state; let actionType; let payload; const callReducer = () => reducer(state, { type: actionType, payload }); beforeEach(() => { initialState = { isOpen: false, modalName: '', modalOptions: {} }; ...
import reducer from './'; describe('Modal reducer', () => { let initialState; let state; let actionType; let payload; const callReducer = () => reducer(state, { type: actionType, payload }); beforeEach(() => { initialState = { isOpen: false, modalName: '', modalOptions: {} }; ...
Change from `preLoaders` to `postLoaders`
var _ = require('lodash'), path = require('path'), webpackConfig = require('./webpack.config.js'); _.merge(webpackConfig, { devtool: 'inline-source-map', module: { postLoaders: [ { test: /\.(js|jsx)?$/, include: path.resolve('src/'), loader: 'babel-istanbul-i...
var _ = require('lodash'), path = require('path'), webpackConfig = require('./webpack.config.js'); _.merge(webpackConfig, { devtool: 'inline-source-map', module: { preLoaders: [ { test: /\.(js|jsx)?$/, include: path.resolve('src/'), loader: 'babel-istanbul-in...
Swap order of clean calls
from django import forms from django.forms.fields import IntegerField, CharField import evelink.account class AddAPIForm(forms.Form): key_id = IntegerField() v_code = CharField(max_length=64, min_length=1) def clean(self): super(AddAPIForm, self).clean() self._clean() return self...
from django import forms from django.forms.fields import IntegerField, CharField import evelink.account class AddAPIForm(forms.Form): key_id = IntegerField() v_code = CharField(max_length=64, min_length=1) def clean(self): self._clean() return super(AddAPIForm, self).clean() def _cl...
Use input param key instead of using HEADER field
from app.dataformats import mzidtsv as psmtsvdata def add_peptide(allpeps, psm, key, scorecol=False, fncol=None, new=False, track_psms=True): peptide = {'score': psm[scorecol], 'line': psm, 'psms': [] } if track_psms: if not new: ...
from app.dataformats import peptable as peptabledata from app.dataformats import mzidtsv as psmtsvdata def add_peptide(allpeps, psm, scorecol=False, fncol=None, new=False, track_psms=True): peptide = {'score': psm[scorecol], 'line': psm, 'psms': [] } ...
Enable .map extension in CompressionPlugin to ship compressed source maps as well
const TerserPlugin = require('terser-webpack-plugin') const CompressionPlugin = require('compression-webpack-plugin') const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin') const safePostCssParser = require('postcss-safe-parser') const Base = require('./base') module.exports = class extends Base...
const TerserPlugin = require('terser-webpack-plugin') const CompressionPlugin = require('compression-webpack-plugin') const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin') const safePostCssParser = require('postcss-safe-parser') const Base = require('./base') module.exports = class extends Base...
Make use of jquery no conflict for stripe JS
Stripe.setPublishableKey('$PublishKey'); jQuery.noConflict(); var payment_form_id = '#$FormName'; (function($) { var payment_form = $(payment_form_id); payment_form.bind( "submit", function(event) { // Disable the submit button to prevent repeated clicks: payment_form ...
Stripe.setPublishableKey('$PublishKey'); var payment_form_id = '#$FormName'; $(function() { var payment_form = $(payment_form_id); payment_form.bind( "submit", function(event) { // Disable the submit button to prevent repeated clicks: payment_form .find(...
Clean up implementation of TimeModifierTemplatePlugin No need to use the DateUtil here. `getDateTimeByTimestamp()` is trivial, localization already happens via `IntlDateFormatter` and the `c` format is meant for technical consumption, thus no need to run this via `DateUtil`’s localization and TZ logic.
<?php namespace wcf\system\template\plugin; use wcf\system\template\TemplateEngine; use wcf\system\WCF; /** * Template modifier plugin which formats a unix timestamp. * Default date format contains year, month, day, hour and minute. * * Usage: * {$timestamp|time} * {"132845333"|time} * * @author Alexander ...
<?php namespace wcf\system\template\plugin; use wcf\system\template\TemplateEngine; use wcf\system\WCF; use wcf\util\DateUtil; /** * Template modifier plugin which formats a unix timestamp. * Default date format contains year, month, day, hour and minute. * * Usage: * {$timestamp|time} * {"132845333"|time} ...
Clear warnings and errors when type checking passes
from app.questionnaire_state.item import Item class Answer(Item): def __init__(self, id): super().__init__(id=id) # typed value self.value = None # actual user input self.input = None def update_state(self, user_input, schema_item): if self.id in user_input.key...
from app.questionnaire_state.item import Item class Answer(Item): def __init__(self, id): super().__init__(id=id) # typed value self.value = None # actual user input self.input = None def update_state(self, user_input, schema_item): if self.id in user_input.key...
Update comments in message repo remote
'use strict'; var request = require('superagent'); var glimpse = require('glimpse'); module.exports = { triggerGetLastestSummaries: function() { // TODO: need to pull this out different source (i.e. Metadata) var uri = '/Glimpse/MessageHistory'; request .get(uri) ...
'use strict'; var request = require('superagent'); var glimpse = require('glimpse'); module.exports = { triggerGetLastestSummaries: function() { // TODO: need to pull this out different source var uri = '/Glimpse/MessageHistory'; request //TODO: this will probably chan...
Use any_endpoint on invalid id test
""" Tests for passing invalid endpoints which require a target ID to be given. """ import pytest import requests from requests import codes from mock_vws._constants import ResultCodes from tests.mock_vws.utils import ( TargetAPIEndpoint, VuforiaDatabaseKeys, assert_vws_failure, delete_target, ) @pyt...
""" Tests for passing invalid endpoints which require a target ID to be given. """ import pytest import requests from requests import codes from mock_vws._constants import ResultCodes from tests.mock_vws.utils import ( TargetAPIEndpoint, VuforiaDatabaseKeys, assert_vws_failure, delete_target, ) @pyt...
Update vigenereDicitonaryHacker: fixed PEP8 spacing
# Vigenère Cipher Dictionary Hacker # https://www.nostarch.com/crackingcodes/ (BSD Licensed) import detectEnglish, vigenereCipher, pyperclip def main(): ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz.""" hackedMessage = hackVigenereDictionary(ciphertext) if hackedMessage != None: print...
# Vigenère Cipher Dictionary Hacker # https://www.nostarch.com/crackingcodes/ (BSD Licensed) import detectEnglish, vigenereCipher, pyperclip def main(): ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz.""" hackedMessage = hackVigenereDictionary(ciphertext) if hackedMessage != None: print(...
Add print statement to send invite command
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def ha...
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def ha...
Update sidebar logic and UI
import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Drawer from 'material-ui/Drawer'; import AppBar from 'material-ui/AppBar'; import MenuItem from 'material-ui/MenuItem'; import { isSidebarOpen } from...
import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Drawer from 'material-ui/Drawer'; import AppBar from 'material-ui/AppBar'; import MenuItem from 'material-ui/MenuItem'; import { isSidebarOpen } from...
Change method name for archive and add unarchive method
<?php namespace Belvedere\Basecamp\Sections; use Belvedere\Basecamp\Models\Recording; class Recordings extends AbstractSection { /** * Index all recordings. * * @param string $type * @param array $parameters * @param int $page * @return \Illuminate\Support\Collection ...
<?php namespace Belvedere\Basecamp\Sections; use Belvedere\Basecamp\Models\Recording; class Recordings extends AbstractSection { /** * Index all recordings. * * @param string $type * @param array $parameters * @param int $page * @return \Illuminate\Support\Collection ...
Add Framework::Pytest to list of classifiers
import re from setuptools import setup with open('pytest_mock.py') as f: m = re.search("version = '(.*)'", f.read()) assert m is not None version = m.group(1) setup( name='pytest-mock', version=version, entry_points={ 'pytest11': ['pytest_mock = pytest_mock'], }, py_modules=['...
import re from setuptools import setup with open('pytest_mock.py') as f: m = re.search("version = '(.*)'", f.read()) assert m is not None version = m.group(1) setup( name='pytest-mock', version=version, entry_points={ 'pytest11': ['pytest_mock = pytest_mock'], }, py_modules=['...
Fix deployer not finding resources
'use strict'; const _ = require('lodash'); const Promise = require('bluebird'); const assert = require('hoek').assert; class Deployer { constructor(namespace, kubectl) { this.namespace = namespace; this.kubectl = kubectl; } deployResource(path, options) { let requirements = Promise.resolve(); c...
'use strict'; const _ = require('lodash'); const Promise = require('bluebird'); const assert = require('hoek').assert; class Deployer { constructor(namespace, kubectl) { this.namespace = namespace; this.kubectl = kubectl; } deployResource(path, options) { let requirements = Promise.resolve(); c...
Use `npm test' to run test in grunt
'use strict'; module.exports = function(grunt) { var path = require('path'); var shell = require('shelljs'); var bin = ['node_modules', '.bin'].join(path.sep); var lsc = [bin, 'lsc'].join(path.sep); var npm = 'npm'; grunt.registerTask('livescript_src', 'update LiveScript source', function ()...
'use strict'; module.exports = function(grunt) { var path = require('path'); var shell = require('shelljs'); var bin = ['node_modules', '.bin'].join(path.sep); var lsc = [bin, 'lsc'].join(path.sep); var mocha = [bin, 'mocha'].join(path.sep); var npm = 'npm'; grunt.registerTask('livescrip...
Change to map rather use `FlatList` to avoid press event handling issues
import React, { Component } from 'react'; import { StyleSheet, View } from 'react-native'; import Prediction from './Prediction'; class Predictions extends Component { static defaultProps = { predictions: [] } constructor(props) { super(props); } render() { return ...
import React, { Component } from 'react'; import { StyleSheet, FlatList, View } from 'react-native'; import Prediction from './Prediction'; class Predictions extends Component { constructor(props) { super(props); } render() { return ( <View style={style.container}> ...
Split item search into its own function
<?php namespace Scat; class SearchService { public function __construct() { } public function search($q) { return [ 'items' => $this->searchItems($q), 'products' => $this->searchProducts($q) ]; } public function searchItems($q) { $scanner= new \OE\Lukas\Parser\QueryScanner(); $p...
<?php namespace Scat; use OE\Lukas\Parser\QueryParser; use OE\Lukas\Visitor\QueryItemPrinter; class SearchService { public function __construct() { } public function search($q) { $scanner= new \OE\Lukas\Parser\QueryScanner(); $parser= new \OE\Lukas\Parser\QueryParser($scanner); $parser->readString(...
Fix bug with appending new attributes
<?php namespace MageTest\Manager\Attributes\Provider; /** * Trait OverrideAttributes * * @package spec\MageTest\Manager\Attributes\Provider */ trait OverrideAttributes { /** * Overrides previously defined attributes, and optionally adds new * * @param array $attributes * @param bool $ap...
<?php namespace MageTest\Manager\Attributes\Provider; /** * Trait OverrideAttributes * * @package spec\MageTest\Manager\Attributes\Provider */ trait OverrideAttributes { /** * Overrides previously defined attributes, and optionally adds new * * @param array $attributes * @param bool $ap...
Sort guests in ad form
<?php namespace DinnerBundle\Form; use DinnerBundle\Entity\Guest; use Doctrine\ORM\EntityRepository; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Componen...
<?php namespace DinnerBundle\Form; use DinnerBundle\Entity\Guest; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; ...
Fix fatal error in data processing. The wrong identifier was being used as the key to tell whether a propagandist had been seen before in the dataset, leading to a completely, and incorrectly disconnected graph.
import bson.json_util from bson.objectid import ObjectId import json import sys def main(): node_table = {} while True: line = sys.stdin.readline() if not line: break record = json.loads(line) ident = str(record["twitter_id"]) aoid = node_table.get(ident)...
import bson.json_util from bson.objectid import ObjectId import json import sys def main(): node_table = {} while True: line = sys.stdin.readline() if not line: break record = json.loads(line) ident = str(record["twitter_id"]) aoid = node_table.get(ident)...
Allow Pro users to specify multiple domains to serve their blog. Specifically for www/non-www setups.
from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from annoying.functions import get_object_or_None class BlogMiddleware: def process_request(self, request): request.blog_user = None host = request.META.get('HTTP_HOST', '') host_s = host.replace('...
from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from annoying.functions import get_object_or_None class BlogMiddleware: def process_request(self, request): request.blog_user = None host = request.META.get('HTTP_HOST', '') host_s = host.replace('...
Change author and email to the same as atomic-reactor has
#!/usr/bin/python """ Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ import re from setuptools import setup, find_packages data_files = { "share/osbs": [ "inputs/prod.json", ...
#!/usr/bin/python """ Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ import re from setuptools import setup, find_packages data_files = { "share/osbs": [ "inputs/prod.json", ...
Fix a bug in file_open (os.open does not take keyword argument).
# -*- encoding: utf-8 -*- import os import errno def ensure_intermediate_dir(path): """ Basiclly equivalent to command `mkdir -p` """ try: os.makedirs(os.path.dirname(path)) except OSError, e: if e.errno != errno.EEXIST: raise e def open_file(filename, flag, mo...
# -*- encoding: utf-8 -*- import os import errno def ensure_intermediate_dir(path): """ Basiclly equivalent to command `mkdir -p` """ try: os.makedirs(os.path.dirname(path)) except OSError, e: if e.errno != errno.EEXIST: raise e def open_file(filename, flag, mo...
Return object, not string from Cordova plugin calls
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var ReactNative = require('react-native'); function CordovaPluginAdapter() { this.nativeInterface = ReactNative.NativeModules.CordovaPluginAdapter; this._callbackCount = Math.random(); this._callbacks = {}; this.initCallbackChannel(); }; C...
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var ReactNative = require('react-native'); function CordovaPluginAdapter() { this.nativeInterface = ReactNative.NativeModules.CordovaPluginAdapter; this._callbackCount = Math.random(); this._callbacks = {}; this.initCallbackChannel(); }; C...
Make mutation trigger guarantee a probability
package com.agricraft.agricore.templates; import com.agricraft.agricore.core.AgriCore; import com.google.gson.JsonObject; public class AgriMutationTrigger { private final String id; private final boolean required; private final double guaranteedChance; private final JsonObject parameters; public ...
package com.agricraft.agricore.templates; import com.agricraft.agricore.core.AgriCore; import com.google.gson.JsonObject; public class AgriMutationTrigger { private final String id; private final boolean required; private final boolean guaranteed; private final JsonObject parameters; public AgriM...
Fix JSON test data parsing
package org.ethereum.jsontestsuite.builder; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import org.ethereum.jsontestsuite.Utils; import org.ethereum.jsontestsuite.model.BlockHeaderTck; import java.math.BigInteger; import static org.ethereum.jsontestsuite.Utils.parseData; import static org.e...
package org.ethereum.jsontestsuite.builder; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import org.ethereum.jsontestsuite.Utils; import org.ethereum.jsontestsuite.model.BlockHeaderTck; import java.math.BigInteger; import static org.ethereum.jsontestsuite.Utils.parseData; import static org.e...
Fix variable already defined JSHint error
exports.fixed = function(x, y, r) { var orient = r.split('!')[1]; var ratio = r.split('!')[0].split(':').sort(); var vertical = y > x; var rotate = y > x && orient === 'h' || x > y && orient === 'v'; if ((vertical || rotate) && !(vertical && rotate)) { x = x + y; y = x - y; x = x - y; } va...
exports.fixed = function(x, y, ratio) { var orient = ratio.split('!')[1]; var ratio = ratio.split('!')[0].split(':').sort(); var vertical = y > x; var rotate = y > x && orient === 'h' || x > y && orient === 'v'; if ((vertical || rotate) && !(vertical && rotate)) { x = x + y; y = x - y; x = x - ...
Fix fatal error on pages with nested nodes in header
import React, {PureComponent, PropTypes, createElement} from 'react' import {Link} from 'react-scroll' import {Link as LinkIcon} from '../icons' import {scrollDuration} from '../../constants/animations' const createId = data => { if (Array.isArray(data)) { data = data.map(value => { if (typeof value === '...
import React, {PureComponent, PropTypes, createElement} from 'react' import {Link} from 'react-scroll' import {Link as LinkIcon} from '../icons' import {scrollDuration} from '../../constants/animations' const createId = str => str.toLowerCase().replace(/\s/g, '-').replace(/[^-\w]/g, '') /** * Renders `h*` tags and ...
Return full path if it exists for OSF
from waterbutler.core import metadata class BaseOsfStorageMetadata: @property def provider(self): return 'osfstorage' class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata): @property def name(self): return self.raw['name'] @property def path(self): ...
from waterbutler.core import metadata class BaseOsfStorageMetadata: @property def provider(self): return 'osfstorage' class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata): @property def name(self): return self.raw['name'] @property def path(self): ...
Add optional dependencies for the docs
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='dltk', version='0.1', description='Deep Learning Toolkit for Medical Image Analysis', author='DLTK Contributors', url='https://dltk.github.io', packages=find_packages(exclude=['_docs', 'contrib', 'data', 'examp...
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='dltk', version='0.1', description='Deep Learning Toolkit for Medical Image Analysis', author='DLTK Contributors', url='https://dltk.github.io', packages=find_packages(exclude=['_docs', 'contrib', 'data', 'examp...
Clone context to prevent pass-by-reference issues
'use strict'; const _ = require('lodash'); const utils = require('../utils'); const Log = require('../log'); const mix = require('../mixins/mix'); const Heritable = require('../mixins/heritable'); const EntityMixin = require('../mixins/entity'); module.exports = class Entity extends mix(Heritable, EntityMixin) { ...
'use strict'; const _ = require('lodash'); const utils = require('../utils'); const Log = require('../log'); const mix = require('../mixins/mix'); const Heritable = require('../mixins/heritable'); const EntityMixin = require('../mixins/entity'); module.exports = class Entity extends mix(Heritable, EntityMixin) { ...
BAP-2667: Modify CLI installer to allow run common commands from Package Manager[
<?php namespace Oro\Bundle\InstallerBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Oro\Bundle\InstallerBundle\CommandExecutor; class PlatformUpdateCommand extends Containe...
<?php namespace Oro\Bundle\InstallerBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Oro\Bundle\InstallerBundle\CommandExecutor; class PlatformUpdateCommand extends Containe...
Add more libraries that are used at runtime
from distutils.core import setup setup(name="stellar-magnate", version="0.1", description="A space-themed commodity trading game", long_description=""" Stellar Magnate is a space-themed trading game in the spirit of Planetary Travel by Brian Winn. """, author="Toshio Kuratomi", ...
from distutils.core import setup setup(name="stellar-magnate", version="0.1", description="A space-themed commodity trading game", long_description=""" Stellar Magnate is a space-themed trading game in the spirit of Planetary Travel by Brian Winn. """, author="Toshio Kuratomi", ...
Rename master to main request
<?php declare(strict_types=1); namespace App\EventSubscriber; use App\Service\Config; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; class Redir...
<?php declare(strict_types=1); namespace App\EventSubscriber; use App\Service\Config; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; class Redir...
Replace jQuery .unbind with .off The .unbind method is deprecated in jQuery 3.
import $ from 'jquery'; import _ from 'underscore'; import AlertDialogTemplate from './alertDialog.pug'; /** * Miscellaneous utility functions. */ /** * Show an alert dialog with a single button. * @param [text] The text to display. * @param [buttonText] The text for the button. * @param [buttonClass] Class st...
import $ from 'jquery'; import _ from 'underscore'; import AlertDialogTemplate from './alertDialog.pug'; /** * Miscellaneous utility functions. */ /** * Show an alert dialog with a single button. * @param [text] The text to display. * @param [buttonText] The text for the button. * @param [buttonClass] Class st...
Disable SSL test on python 2.5
#!/usr/bin/env python from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase from tornado.web import Application, RequestHandler import os import pycurl import re import unittest import urllib try: import ssl except ImportError: ssl = None class HelloWorldRequestHandler(RequestHandler): def get(s...
#!/usr/bin/env python from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase from tornado.web import Application, RequestHandler import os import pycurl import re import unittest import urllib class HelloWorldRequestHandler(RequestHandler): def get(self): self.finish("Hello world") class SSLTest(...
Allow passing of template folder path as a string argument
/* * grunt-nunjucks-2-html * https://github.com/vitkarpov/grunt-nunjucks-2-html * * Copyright (c) 2014 Vit Karpov * Licensed under the MIT license. */ 'use strict'; var nunjucks = require('nunjucks'); var path = require('path'); module.exports = function(grunt) { grunt.registerMultiTask('nunjucks', 'Render...
/* * grunt-nunjucks-2-html * https://github.com/vitkarpov/grunt-nunjucks-2-html * * Copyright (c) 2014 Vit Karpov * Licensed under the MIT license. */ 'use strict'; var nunjucks = require('nunjucks'); var path = require('path'); module.exports = function(grunt) { grunt.registerMultiTask('nunjucks', 'Render...
Refactor duplication out of tests.
/* global describe, it */ import assert from 'assert'; import GroupedKata from '../src/grouped-kata.js'; function remoteFileLoaderWhichReturnsGivenData(data) { return (url, onLoaded) => { onLoaded(null, data); }; } function remoteFileLoaderWhichReturnsError(error) { return (url, onLoaded) => { onLoaded(...
/* global describe, it */ import assert from 'assert'; import {KATAS_URL, URL_PREFIX} from '../src/config.js'; import GroupedKata from '../src/grouped-kata.js'; describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { const loadRemoteFileStub = (url, onLoaded) => { l...
Update triangle validate check at main script
$(window).ready(function(){ $('#triangle-calculator').submit(function(e){ e.preventDefault(); // // Code start here // var triangleType = 'Not a triangle'; var a = parseInt( $('#a_number').val() ); var b = parseInt( $('#b_number').val() ); var c = par...
$(window).ready(function(){ $('#triangle-calculator').submit(function(e){ e.preventDefault(); // // Code start here // var triangleType = 'Not a triangle'; var a = parseInt( $('#a_number').val() ); var b = parseInt( $('#b_number').val() ); var c = par...
Add dynamic 'column' key for foreign constraints
<?php namespace Illuminate\Database\Schema; use Illuminate\Support\Str; class ForeignIdColumnDefinition extends ColumnDefinition { /** * The schema builder blueprint instance. * * @var \Illuminate\Database\Schema\Blueprint */ protected $blueprint; /** * Create a new foreign ID c...
<?php namespace Illuminate\Database\Schema; use Illuminate\Support\Str; class ForeignIdColumnDefinition extends ColumnDefinition { /** * The schema builder blueprint instance. * * @var \Illuminate\Database\Schema\Blueprint */ protected $blueprint; /** * Create a new foreign ID c...