text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Create a statsd_client anyway, even if there is no STATSD_URL env variable set | import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.StatsClient(host=ip, port=int(port),
prefix=os.environ.get('STATSD_PREFIX',
... | import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.StatsClient(host=ip, port=int(port),
prefix=os.environ.get('STATSD_PREFIX',
... |
Return boolean instead of if statement. | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
... | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
... |
Throw a more user-friendly exception when the SearchBehavior is not attached
Rather than throw the following error/exception:
```
Unknown method "filterParams"
```
We throw a RuntimeException that informs the developer that they have misconfigured their application, allowing them to more quickly debug the issu... | <?php
namespace Crud\Listener;
use Cake\Core\Plugin;
use Cake\Event\Event;
use RuntimeException;
class SearchListener extends BaseListener
{
/**
* Settings
*
* @var array
*/
protected $_defaultConfig = [
'enabled' => [
'Crud.beforeLookup',
'Crud.beforePagin... | <?php
namespace Crud\Listener;
use Cake\Core\Plugin;
use Cake\Event\Event;
use RuntimeException;
class SearchListener extends BaseListener
{
/**
* Settings
*
* @var array
*/
protected $_defaultConfig = [
'enabled' => [
'Crud.beforeLookup',
'Crud.beforePagin... |
Add support for `CheckoutSession` on `Discount` | package stripe
import "encoding/json"
// DiscountParams is the set of parameters that can be used when deleting a discount.
type DiscountParams struct {
Params `form:"*"`
}
// Discount is the resource representing a Stripe discount.
// For more details see https://stripe.com/docs/api#discounts.
type Discount struct... | package stripe
import "encoding/json"
// DiscountParams is the set of parameters that can be used when deleting a discount.
type DiscountParams struct {
Params `form:"*"`
}
// Discount is the resource representing a Stripe discount.
// For more details see https://stripe.com/docs/api#discounts.
type Discount struct... |
Update gearman client call due to changes | <?php
namespace Soil\QueueHttpEndpointBundle\Controller;
use Soilby\EventComponent\Service\GearmanClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Created by PhpStorm.
* User: fliak
* Date: 5.2.15
* Time: 15.14
*/
class EndpointController {
/**... | <?php
namespace Soil\QueueHttpEndpointBundle\Controller;
use Soilby\EventComponent\Service\GearmanClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Created by PhpStorm.
* User: fliak
* Date: 5.2.15
* Time: 15.14
*/
class EndpointController {
/**... |
Use runUnsafeAction in lazy binding implementation | package org.reactfx;
import java.util.function.Consumer;
/**
* Event stream that has one or more sources (most commonly event streams,
* but not necessarily) to which it is subscribed only when it itself has
* at least one subscriber.
*
* @param <T> type of events emitted by this event stream.
*/
public abstrac... | package org.reactfx;
import java.util.function.Consumer;
/**
* Event stream that has one or more sources (most commonly event streams,
* but not necessarily) to which it is subscribed only when it itself has
* at least one subscriber.
*
* @param <T> type of events emitted by this event stream.
*/
public abstrac... |
Stop changing moment locale twice | import { stringify } from 'querystring'
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'next/router'
import { translate } from 'react-i18next'
import Dropdown from '../../dropdown'
export class LanguageSelection extends React.PureComponent {
static propTypes = {
i18n: Pr... | import { stringify } from 'querystring'
import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { withRouter } from 'next/router'
import { translate } from 'react-i18next'
import Dropdown from '../../dropdown'
export class LanguageSelection extends React.PureComponent {
stati... |
Return res in inherit (even if res is empty in this case) | # -*- encoding: utf-8 -*-
##############################################################################
#
# Account Payment Partner module for OpenERP
# Copyright (C) 2014 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <alexis.delattre@akretion.com>
#
# This program is free software: you can... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Account Payment Partner module for OpenERP
# Copyright (C) 2014 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <alexis.delattre@akretion.com>
#
# This program is free software: you can... |
Detach debugger from process after each test. | """Tests for scripts/print_view_controller_hierarchy.py."""
import re
import unittest
from test_utils import import_utils
import_utils.prepare_lldb_import_or_exit()
import lldb
import_utils.prepare_for_scripts_imports()
from scripts import print_view_controller_hierarchy
class PrintViewControllerHierarchyTest(unit... | """Tests for scripts/print_view_controller_hierarchy.py."""
import re
import unittest
from test_utils import import_utils
import_utils.prepare_lldb_import_or_exit()
import lldb
import_utils.prepare_for_scripts_imports()
from scripts import print_view_controller_hierarchy
class PrintViewControllerHierarchyTest(unit... |
Add node env to script
- helps with optimising production code like react | import gulp from 'gulp';
import gulpif from 'gulp-if';
import named from 'vinyl-named';
import webpack from 'webpack';
import gulpWebpack from 'webpack-stream';
import plumber from 'gulp-plumber';
import livereload from 'gulp-livereload';
import args from './lib/args';
const ENV = args.production ? 'production' : 'dev... | import gulp from 'gulp';
import gulpif from 'gulp-if';
import named from 'vinyl-named';
import webpack from 'webpack';
import gulpWebpack from 'webpack-stream';
import plumber from 'gulp-plumber';
import livereload from 'gulp-livereload';
import args from './lib/args';
gulp.task('scripts', (cb) => {
return gulp.src(... |
Set default value for json.dumps
Use default value when type cannot be serialized. | import json
import logging
import platform
from django.core.serializers.json import DjangoJSONEncoder
from django.http import UnreadablePostError
def skip_unreadable_post(record):
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
if isinstance(exc_value, UnreadablePostError):
... | import json
import logging
import platform
from django.core.serializers.json import DjangoJSONEncoder
from django.http import UnreadablePostError
def skip_unreadable_post(record):
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
if isinstance(exc_value, UnreadablePostError):
... |
Fix 500 error on Category show page. | <?php namespace VotingApp\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
class Winner extends Model
{
/**
* The attributes which may be mass-assigned.
*
* @var array
*/
protected $fillable = [
'candidate_id', 'rank', 'description'
];
// No timestamps on the winne... | <?php namespace VotingApp\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
class Winner extends Model
{
/**
* The attributes which may be mass-assigned.
*
* @var array
*/
protected $fillable = [
'candidate_id', 'rank', 'description'
];
// No timestamps on the winne... |
Change designer index page title. | @extends('layout.app', [
'title' => 'Design Stories',
'body_id' => 'designer-index-page',
'body_class' => 'designer-index index',
])
@section('main')
<div class="container">
<div class="row">
@foreach ($designers as $designer)
<article id="story-{{ $designer->id }}" class="story gri... | @extends('layout.app', [
'title' => 'Designers',
'body_id' => 'designer-index-page',
'body_class' => 'designer-index index',
])
@section('main')
<div class="container">
<div class="row">
@foreach ($designers as $designer)
<article id="story-{{ $designer->id }}" class="story grid-ite... |
Increase machine model field size from 20 chars to 50 chars | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachinesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machines', function (Blueprint $table) {
... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachinesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machines', function (Blueprint $table) {
... |
Adjust message code in exception | package de.innoaccel.wamp.server.converter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import de.innoaccel.wamp.server.Websocket;
import de.innoaccel.wamp.server.message.Message;
import de.innoaccel.wamp.server.message.PrefixMessage;
public class PrefixM... | package de.innoaccel.wamp.server.converter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import de.innoaccel.wamp.server.Websocket;
import de.innoaccel.wamp.server.message.Message;
import de.innoaccel.wamp.server.message.PrefixMessage;
public class PrefixM... |
Add auth models and validators to initial db migration. | # -*- coding: utf-8 -*-
""" Initial migration file for creating Note model """
from __future__ import unicode_literals
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
""" Initial migration file for creating No... | # -*- coding: utf-8 -*-
""" Initial migration file for creating Note model """
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
""" Initial migration file for creating Note model """
dependencies = [
]
operations = [
mig... |
Remove a useless method declaration. | <?php
namespace Predis\Commands;
class InfoV24x extends Info {
public function canBeHashed() { return false; }
public function parseResponse($data) {
$info = array();
$current = null;
$infoLines = explode("\r\n", $data, -1);
foreach ($infoLines as $row) {
if... | <?php
namespace Predis\Commands;
class InfoV24x extends Info {
public function canBeHashed() { return false; }
public function getId() { return 'INFO'; }
public function parseResponse($data) {
$info = array();
$current = null;
$infoLines = explode("\r\n", $data, -1);
... |
Add event trigger when legend changes. | var OpenLayersPlusLegend = function(opts) {
if (opts == null) {
return;
}
var self = this;
this.map = $(opts).data('map');
this.setLegend = function(layer) {
// The layer param may vary based on the context from which we are called.
layer = layer.object ? layer.object : laye... | var OpenLayersPlusLegend = function(opts) {
if (opts == null) {
return;
}
var self = this;
this.map = $(opts).data('map');
this.setLegend = function(layer) {
// The layer param may vary based on the context from which we are called.
layer = layer.object ? layer.object : laye... |
Set type to javascript to force JS compilation | 'use strict';
const compiler = require('vueify').compiler;
const fs = require('fs');
class VueBrunch {
constructor(config) {
this.config = config && config.plugins && config.plugins.vue || {};
this.styles = {};
}
compile(file) {
if (this.config) {
compiler.applyConfig(this.config);
}
... | 'use strict';
const compiler = require('vueify').compiler;
const fs = require('fs');
class VueBrunch {
constructor(config) {
this.config = config && config.plugins && config.plugins.vue || {};
this.styles = {};
}
compile(file) {
if (this.config) {
compiler.applyConfig(this.config);
}
... |
Fix issue with old wagtail core paths | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'consol... | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'consol... |
Fix issue with "titles" in SectionContainer.filter() | from plex.core.helpers import to_iterable
from plex.objects.container import Container
from plex.objects.core.base import Property
from plex.objects.directory import Directory
class Section(Directory):
uuid = Property
filters = Property(type=bool)
refreshing = Property(type=bool)
agent = Property
... | from plex.core.helpers import to_iterable
from plex.objects.container import Container
from plex.objects.core.base import Property
from plex.objects.directory import Directory
class Section(Directory):
uuid = Property
filters = Property(type=bool)
refreshing = Property(type=bool)
agent = Property
... |
Fix bug in Pipeline call where we run the whole Pipeline on list input | class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
... | class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
... |
:white_check_mark: Update completion tests, checking for printed message | import os
import subprocess
import sys
from pathlib import Path
import typer
from typer.testing import CliRunner
from first_steps import tutorial001 as mod
runner = CliRunner()
app = typer.Typer()
app.command()(mod.main)
def test_show_completion():
result = subprocess.run(
[
"bash",
... | import os
import subprocess
import sys
from pathlib import Path
import typer
from typer.testing import CliRunner
from first_steps import tutorial001 as mod
runner = CliRunner()
app = typer.Typer()
app.command()(mod.main)
def test_show_completion():
result = subprocess.run(
[
"bash",
... |
Allow the "crash early" behavior of snippets to be configured
This way it can be turned off in testing environment, making testing
setup simpler. | <?php
/**
* Garp_Model_Db_Snippet
* Snippet model. Snippets are small dynamic chunks of content.
*
* @package Garp_Model_Db
* @author Harmen Janssen <harmen@grrr.nl>
*/
class Garp_Model_Db_Snippet extends Model_Base_Snippet {
/**
* Fetch a snippet by its identifier
*
* @param string $identifie... | <?php
/**
* Garp_Model_Db_Snippet
* Snippet model. Snippets are small dynamic chunks of content.
*
* @package Garp_Model_Db
* @author Harmen Janssen <harmen@grrr.nl>
*/
class Garp_Model_Db_Snippet extends Model_Base_Snippet {
/**
* Fetch a snippet by its identifier
*
* @param string $identifie... |
Revert "[ncl] fix Font examples"
This reverts commit 7af688afaac71c74de68b5ab42aed38f0196fd0d.
fbshipit-source-id: b91e873 | import React from 'react';
import { Platform, ScrollView, Text, View } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
export default class FontScreen extends React.Component {
static navigationOptions = {
title: 'Font',
};
render() {
return (
<ScrollView style={{ flex: 1 ... | import React from 'react';
import { Platform, ScrollView, Text, View } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
export default class FontScreen extends React.Component {
static navigationOptions = {
title: 'Font',
};
render() {
const fontFamily = Platform.OS === 'ios' ? '... |
Add some logging to the EVE API task | import logging
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
l = logging.getLogger('import_apikey')
l.info("Im... | from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
acc = import_eve_account(api_key, api_userid, force_cache=force_cach... |
Refactor: Move some construction to __init__. | #!/usr/bin/python
import urlparse
import curie
import link
class Document(object):
def __init__(self, o, relative_to_url, parent_curie=None):
self.attrs = o
self.__dict__.update(o)
self.links = {}
for key, value in o.get("_links", {}).iteritems():
self.links[key] = link... | #!/usr/bin/python
import urlparse
import curie
import link
class Document(object):
def expand_curie(self, link):
return self.curie.expand(link)
@classmethod
def from_object(cls, o, relative_to_url=None, parent_curie=None):
if isinstance(o, list):
return map(lambda x: cls.from_... |
Make sure a project is set for the project-specific validator | from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer... | from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer... |
Use class for logout instead of href, to please IE8 | from djangosanetesting import SeleniumTestCase
class NewmanTestCase(SeleniumTestCase):
fixtures = ['newman_admin_user']
SUPERUSER_USERNAME = u"superman"
SUPERUSER_PASSWORD = u"xxx"
NEWMAN_URI = "/newman/"
def __init__(self):
super(NewmanTestCase, self).__init__()
self.elements = ... | from djangosanetesting import SeleniumTestCase
class NewmanTestCase(SeleniumTestCase):
fixtures = ['newman_admin_user']
SUPERUSER_USERNAME = u"superman"
SUPERUSER_PASSWORD = u"xxx"
NEWMAN_URI = "/newman/"
def __init__(self):
super(NewmanTestCase, self).__init__()
self.elements = ... |
Change classname in auth adapter listener | <?php
namespace EdpGithub;
use Zend\Module\Manager,
Zend\Module\Consumer\AutoloaderProvider,
Zend\EventManager\StaticEventManager;
class Module implements AutoloaderProvider
{
protected static $options;
public function init(Manager $moduleManager)
{
$moduleManager->events()->attach('load... | <?php
namespace EdpGithub;
use Zend\Module\Manager,
Zend\Module\Consumer\AutoloaderProvider,
Zend\EventManager\StaticEventManager;
class Module implements AutoloaderProvider
{
protected static $options;
public function init(Manager $moduleManager)
{
$moduleManager->events()->attach('load... |
Fix missed plugin code update.
This `Meta` business is from an earlier draft. | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Stat... | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
class Meta:
description = 'F... |
Revert "Revert "Do not cache discovery""
This reverts commit e8aca80abcf8c309c13360c386b9505a595e1998. | # -*- coding: utf-8 -*-
import logging
import httplib2
import json
import time
import random
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
class OAuth():
__services = dict()
@staticmethod
def getCredentials(email, scopes, ... | # -*- coding: utf-8 -*-
import logging
import httplib2
import json
import time
import random
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
class OAuth():
__services = dict()
@staticmethod
def getCredentials(email, scopes, ... |
Allow fallback translation for page path | <?php namespace Anomaly\PagesModule\Page\Command;
use Anomaly\PagesModule\Page\Contract\PageInterface;
use Anomaly\PagesModule\Page\PageTranslationsModel;
/**
* Class SetPath
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <support@pyrocms.com>
* @author Ryan Thompson <ryan@pyrocms.com>
*/
class SetPath... | <?php namespace Anomaly\PagesModule\Page\Command;
use Anomaly\PagesModule\Page\Contract\PageInterface;
use Anomaly\PagesModule\Page\PageTranslationsModel;
/**
* Class SetPath
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <support@pyrocms.com>
* @author Ryan Thompson <ryan@pyrocms.com>
*/
class SetPath... |
Fix middleware: an undefined value was being assigned in the Socket constructor | 'use strict';
const validate = require('./validate'),
_ = require('lodash'),
assert = require('assert'),
schema = {
properties: {
event: {
type: 'string',
required: true,
allowEmpty: false
},
onEvent: {
... | 'use strict';
const validate = require('./validate'),
_ = require('lodash'),
assert = require('assert'),
schema = {
properties: {
event: {
type: 'string',
required: true,
allowEmpty: false
},
onEvent: {
... |
Use __builtins__ directly instead of import __builtin__. | from disco import util
from discodb import DiscoDB, Q
def open(url, task=None):
if task:
disco_data = task.disco_data
ddfs_data = task.ddfs_data
else:
from disco.settings import DiscoSettings
settings = DiscoSettings()
disco_data = settings['DISCO_DATA']
ddfs_dat... | import __builtin__
from disco import util
from discodb import DiscoDB, Q
def open(url, task=None):
if task:
disco_data = task.disco_data
ddfs_data = task.ddfs_data
else:
from disco.settings import DiscoSettings
settings = DiscoSettings()
disco_data = settings['DISCO_DAT... |
Add proper logging to tests when in verbose mode | #######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
######################################################... | #######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
######################################################... |
Add tests for the Field class. | # -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import (
ValidationError, Field, FieldDescriptor, Integer, Unicode, ForeignKey,
ForeignKeyDescriptor)
class TestBaseField(TestCase):
def test_validate(self):
f = Fie... | # -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import Field, ValidationError, Integer, Unicode
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
sel... |
Send emails to biosamples-dev@ebi.ac.uk until we find what is wrong in sending to tech | package uk.ac.ebi.biosamples.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
public class MailSender {
private static final String BODY_PART_FAIL = " failed execution on ";
private static final String MAILX ... | package uk.ac.ebi.biosamples.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
public class MailSender {
private static final String BODY_PART_FAIL = " failed execution on ";
private static final String MAILX ... |
Support for value coming in as a string (eg. from URLs). | import Webiny from 'Webiny';
import styles from './styles.css';
class Switch extends Webiny.Ui.FormComponent {
constructor(props) {
super(props);
this.bindMethods('switch');
}
componentWillMount() {
super.componentWillMount();
this.id = _.uniqueId('switch-');
}
sw... | import Webiny from 'Webiny';
import styles from './styles.css';
class Switch extends Webiny.Ui.FormComponent {
constructor(props) {
super(props);
this.bindMethods('switch');
}
componentWillMount() {
super.componentWillMount();
this.id = _.uniqueId('switch-');
}
sw... |
Use the filetime of the actual file instead of that of the parameters.yml file for caching assets | <?php
namespace Common\Core\Header;
use DateTimeImmutable;
final class Asset
{
/** @var string */
private $file;
/** @var Priority */
private $priority;
/** @var bool */
private $addTimestamp;
/** @var DateTimeImmutable */
private $createdOn;
public function __construct(string... | <?php
namespace Common\Core\Header;
use DateTimeImmutable;
final class Asset
{
/** @var string */
private $file;
/** @var Priority */
private $priority;
/** @var bool */
private $addTimestamp;
/** @var DateTimeImmutable */
private $createdOn;
public function __construct(string... |
Handle no results from category page | from bs4 import BeautifulSoup
import logging
from jetcomcrawl import browser
import jetcomcrawl.libs.queue
class Worker(object):
def __init__(self):
self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories')
self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items')
def wor... | from bs4 import BeautifulSoup
import logging
from jetcomcrawl import browser
import jetcomcrawl.libs.queue
class Worker(object):
def __init__(self):
self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories')
self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items')
def wor... |
[TIMOB-19435] Allow for setting of the Title | package ti.modules.titanium.ui.android;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.util.TiRHelper;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class TiPreferencesFragment extends PreferenceFragment {
... | package ti.modules.titanium.ui.android;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.util.TiRHelper;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class TiPreferencesFragment extends PreferenceFragment {
... |
Correct the name of the test class
Was different from the filename | <?php
use Lfj\ZfRenderer\Service\Renderer;
use Zend\View\Resolver;
class RendererTest extends PHPUnit_Framework_TestCase
{
public function testRenderSimpleView()
{
$template = realpath('view/template-simple.phtml');
$expectedContent = file_get_contents($template);
$renderer = new Rend... | <?php
use Lfj\ZfRenderer\Service\Renderer;
use Zend\View\Resolver;
class StackTest extends PHPUnit_Framework_TestCase
{
public function testRenderSimpleView()
{
$template = realpath('view/template-simple.phtml');
$expectedContent = file_get_contents($template);
$renderer = new Rendere... |
Raise modern browser support bar | // External
const mem = require('mem');
// Ours
const { merge } = require('../utils/structures');
const { getProjectConfig } = require('./project');
const PROJECT_TYPES_CONFIG = {
preact: {
plugins: [
[
require.resolve('@babel/plugin-transform-react-jsx'),
{
pragma: 'h'
}... | // External
const mem = require('mem');
// Ours
const { merge } = require('../utils/structures');
const { getProjectConfig } = require('./project');
const PROJECT_TYPES_CONFIG = {
preact: {
plugins: [
[
require.resolve('@babel/plugin-transform-react-jsx'),
{
pragma: 'h'
}... |
Fix up for Django 1.9 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedConte... | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedConte... |
Add documentation to the method. | <?php
namespace ValueObjects\Base;
use ValueObjects\ValueObject;
/**
* Class Strings
* ValueObject that represents a String with lots of useful methods.
* It is called string since string is a reserved word in Php 7.
* @package ValueObjects\Base
*/
class Strings extends ValueObject
{
public function __const... | <?php
namespace ValueObjects\Base;
use ValueObjects\ValueObject;
/**
* Class Strings
* ValueObject that represents a String with lots of useful methods.
* It is called string since string is a reserved word in Php 7.
* @package ValueObjects\Base
*/
class Strings extends ValueObject
{
public function __const... |
Make tick thicker to facilitate hovering
cc: da39a3ee5e6b4b0d3255bfef95601890afd80709@zeningqu | 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config... | 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config... |
Fix inverted longitude and latitude when saving the coordinates to the DB | <?php
namespace geotime\helpers;
use geotime\models\CalibrationPoint;
use geotime\models\CoordinateLatLng;
use geotime\models\CoordinateXY;
use Logger;
Logger::configure("lib/geotime/logger.xml");
class CalibrationPointHelper
{
/** @var \Logger */
static $log;
/**
* @param $calibrationPoint \stdClas... | <?php
namespace geotime\helpers;
use geotime\models\CalibrationPoint;
use geotime\models\CoordinateLatLng;
use geotime\models\CoordinateXY;
use Logger;
Logger::configure("lib/geotime/logger.xml");
class CalibrationPointHelper
{
/** @var \Logger */
static $log;
/**
* @param $calibrationPoint \stdClas... |
Add "гугли" google search query | <?php
namespace App\Middlewares;
use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;
/**
* Class GoogleSearchMiddleware
* @package App\Gitter\Middleware
*/
class GoogleSearchMiddleware implements MiddlewareInterface
{
/**
* @param Message $message
* @return mixed
*/
public functi... | <?php
namespace App\Middlewares;
use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;
/**
* Class GoogleSearchMiddleware
* @package App\Gitter\Middleware
*/
class GoogleSearchMiddleware implements MiddlewareInterface
{
/**
* @param Message $message
* @return mixed
*/
public functi... |
Fix incorrect option causing crash on logout | import chalk from 'chalk'
import getUserConfig from '../../util/getUserConfig'
export default {
name: 'logout',
signature: 'logout',
description: 'Logs out of the Sanity.io session',
async action(args, {output, prompt, apiClient}) {
const cfg = getUserConfig()
const token = cfg.get('authToken')
co... | import chalk from 'chalk'
import getUserConfig from '../../util/getUserConfig'
export default {
name: 'logout',
signature: 'logout',
description: 'Logs out of the Sanity.io session',
async action(args, {output, prompt, apiClient}) {
const cfg = getUserConfig()
const token = cfg.get('authToken')
co... |
Use config schema singleton instance if none was provided | <?php
class HTMLPurifier_HTML5Config
{
/**
* @param string|array|HTMLPurifier_Config $config
* @param HTMLPurifier_ConfigSchema $schema
* @return HTMLPurifier_Config
*/
public static function create($config = null, HTMLPurifier_ConfigSchema $schema = null)
{
if (!$schema insta... | <?php
class HTMLPurifier_HTML5Config
{
/**
* @param string|array|HTMLPurifier_Config $config
* @param HTMLPurifier_ConfigSchema $schema
* @return HTMLPurifier_Config
*/
public static function create($config = null, HTMLPurifier_ConfigSchema $schema = null)
{
if (!$schema insta... |
Update double-width emoji list to improve "sbase print FILE" | from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
... | from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
... |
Replace big alerts with inline alerts for register view | @extends('layout')
@section('body')
<div class="row">
<div class="column size-560 align-center">
<h1 class="spacing-bottom-large">Register</h1>
<div class="box spacing-small">
<form method="POST">
{{ csrf_field() }}
<label>Name... | @extends('layout')
@section('body')
<div class="row">
<div class="column size-560 align-center">
@if ($errors->any())
@foreach ($errors->all() as $error)
<div class="alert spacing-bottom-large">{{ $error }}</div>
@endforeach
@endif... |
Fix name of an attribute and PEP8-ify | #! /usr/bin/env python3
""" A Word class
Originally obtained from the 'pharm' repository, but modified.
"""
class Word(object):
doc_id = None
sent_id = None
in_sent_idx = None
word = None
pos = None
ner = None
lemma = None
dep_path = None
dep_parent = None
sent_id = None
... | #! /usr/bin/env python3
""" A Word class
Originally obtained from the 'pharm' repository, but modified.
"""
class Word(object):
doc_id = None
sent_id = None
insent_idx = None
word = None
pos = None
ner = None
lemma = None
dep_path = None
dep_parent = None
sent_id = None
... |
Allow notifications to be send async | <?php declare(strict_types = 1);
namespace Cmnty\Push;
use Cmnty\Push\Crypto\Cryptograph;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;
class Client implements PushClient
{
/**
* @var PushService
*/
private $pushService;
/... | <?php declare(strict_types = 1);
namespace Cmnty\Push;
use Cmnty\Push\Crypto\Cryptograph;
use GuzzleHttp\Client as HttpClient;
use Psr\Http\Message\ResponseInterface;
class Client implements PushClient
{
/**
* @var PushService
*/
private $pushService;
/**
* @var Client
*/
private... |
Add parameters for dealing with SNAP output to Pathoscope sam module | from virtool.pathoscope import sam
def run(isolate_sam, host_sam, snap=False):
# Get a mapping score for every read mapped to the host genome
host_scores = sam.all_scores(host_sam, snap=snap)
# This list will contain the read_ids for all reads that had better mapping qualities against the host
# geno... | from virtool.pathoscope import sam
def run(isolate_sam, host_sam):
# Get a mapping score for every read mapped to the host genome
host_scores = sam.all_scores(host_sam)
# This list will contain the read_ids for all reads that had better mapping qualities against the host
# genome
skipped = list()... |
Fix errors reported by php-cs-fixer | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ... | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ... |
Fix mono-extensions checkout for PR branches ('origin/pull/N/merge') | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
... | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
... |
Remove me from song title report send | # Django
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from openpyxl import Workbook
# First-Party
from api.models import Chart
class Command(BaseCommand):
help = "Command to sync database with BHS ."
def handle(self, *args, **options):
self.stdout.wri... | # Django
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from openpyxl import Workbook
# First-Party
from api.models import Chart
class Command(BaseCommand):
help = "Command to sync database with BHS ."
def handle(self, *args, **options):
self.stdout.wri... |
Correct typo of 'injector' method name as 'inject'. | 'use strict';
var contextify = require('contextify');
var fs = require('fs');
var Context = function () {
var rawContext = contextify();
rawContext.globals = rawContext.getGlobal();
return {
run: function (source, filename) {
rawContext.run(source, filename);
},
runF... | 'use strict';
var contextify = require('contextify');
var fs = require('fs');
var Context = function () {
var rawContext = contextify();
rawContext.globals = rawContext.getGlobal();
return {
run: function (source, filename) {
rawContext.run(source, filename);
},
runF... |
Make the UI use the native look and feel of the system itself.. Don't hardcode it! | import guiLayer.startUpFrame;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.SQLException;
public class startUI extends Thread {
private static JPanel startupFrame;
public void run() {
try {
startUI();
} catch (ClassNotFoundException... | import guiLayer.startUpFrame;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.SQLException;
public class startUI extends Thread {
private static JPanel startupFrame;
public void run() {
try {
startUI();
} catch (ClassNotFoundException... |
Stop the loader in the finally to make sure it allways stops | 'use strict';
angular.module('app.controllers')
.controller('HomeController', ['$scope', '$state', 'fileModel', 'imageModel', function HomeController($scope, $state, fileModel, imageModel) {
// private
var _this = {
onCreate: function() {
if(imageModel.getImages().l... | 'use strict';
angular.module('app.controllers')
.controller('HomeController', ['$scope', '$state', 'fileModel', 'imageModel', function HomeController($scope, $state, fileModel, imageModel) {
// private
var _this = {
onCreate: function() {
if(imageModel.getImages().l... |
[FrameworkBundle] Fix BrowserKit assertions to make them compatible with Panther | <?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\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Con... | <?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\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Con... |
Put workspaces in a top-level Firebase key | import values from 'lodash/values';
import {Promise} from 'es6-promise';
import appFirebase from '../services/appFirebase';
class FirebasePersistor {
constructor(user) {
this.user = user;
this.firebase = appFirebase.child(`workspaces/${user.id}`);
}
getCurrentProjectKey() {
return new Promise((resol... | import values from 'lodash/values';
import {Promise} from 'es6-promise';
import appFirebase from '../services/appFirebase';
class FirebasePersistor {
constructor(user) {
this.user = user;
this.firebase = appFirebase.child(user.id);
}
getCurrentProjectKey() {
return new Promise((resolve) => {
t... |
Add country code to country table. | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCountryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('country', function (Blueprint $table) {
$t... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCountryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('country', function (Blueprint $table) {
$t... |
Revert "avoid unnecesary call to onLoad"
This reverts commit 5a81300cb8a99c7428d9aeea26276d4415efcf64. | 'use strict';
/**
* @ngdoc function
* @name Pear2Pear.controller:NavbarTopCtrl
* @description
* # NavbarTop Ctrl
*/
angular.module('Pear2Pear')
.controller(
'NavbarTopCtrl', [
'SwellRTSession', '$scope',
function(SwellRTSession, $scope){
var getSharedMode = function(){
if ($s... | 'use strict';
/**
* @ngdoc function
* @name Pear2Pear.controller:NavbarTopCtrl
* @description
* # NavbarTop Ctrl
*/
angular.module('Pear2Pear')
.controller(
'NavbarTopCtrl', [
'SwellRTSession', '$scope',
function(SwellRTSession, $scope){
var getSharedMode = function(){
if ($s... |
Remove unnecessary import of logging | from rdflib import Graph
class BenchableGraph(object):
"""
Provides a convenient way to use a graph for benchmarks.
"""
def __init__(self, store, graph_id, store_config, graph_create=False):
"""
:param str store: Type of store to use.
:param str graph_id: The graph identifier.... | import logging
from rdflib import Graph
class BenchableGraph(object):
"""
Provides a convenient way to use a graph for benchmarks.
"""
def __init__(self, store, graph_id, store_config, graph_create=False):
"""
:param str store: Type of store to use.
:param str graph_id: The g... |
Bump version: 1.0.0 -> 1.1.0 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
try:
from setuptools import setup, find_packages, Command
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages, Command
description = 'Generate version strings based on semantic versioning ru... | # -*- coding: utf-8 -*-
#!/usr/bin/env python
try:
from setuptools import setup, find_packages, Command
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages, Command
description = 'Generate version strings based on semantic versioning ru... |
Undo functionality. In case you typed the wrong number... | import React from 'react';
import styles from "../css/App.css";
export class PlayerScoreComponent extends React.Component {
/**
* Constructor
* @param props
*/
constructor(props) {
super(props);
this.state = {
score: 0,
history: []
}
}
up... | import React from 'react';
import styles from "../css/App.css";
export class PlayerScoreComponent extends React.Component {
/**
* Constructor
* @param props
*/
constructor(props) {
super(props);
this.state = {
score: 0
}
}
updateScore = () => {
... |
Fix SimpleXMLElement::asXML() can also be of type false | <?php
namespace CfdiUtils\Nodes;
use DOMDocument;
use DOMElement;
use SimpleXMLElement;
class XmlNodeUtils
{
public static function nodeToXmlElement(NodeInterface $node, DOMDocument $document = null): DOMElement
{
return (new XmlNodeExporter($document))->export($node);
}
public static functio... | <?php
namespace CfdiUtils\Nodes;
use DOMDocument;
use DOMElement;
use SimpleXMLElement;
class XmlNodeUtils
{
public static function nodeToXmlElement(NodeInterface $node, DOMDocument $document = null): DOMElement
{
return (new XmlNodeExporter($document))->export($node);
}
public static functio... |
Allow overridable message formatting in the RSS bot. |
try:
from feedparser import parse
except ImportError:
parse = None
from gnotty.bots import events
class RSSMixin(object):
"""
Mixin for bots that consume RSS feeds and post them to the
channel. Feeds are defined by the ``feeds`` keyword arg to
``__init__``, and should contain a sequence of R... |
try:
from feedparser import parse
except ImportError:
parse = None
from gnotty.bots import events
class RSSMixin(object):
"""
Mixin for bots that consume RSS feeds and post them to the
channel. Feeds are defined by the ``feeds`` keyword arg to
``__init__``, and should contain a sequence of R... |
Rename const to be more obvious | import glob from 'glob';
import path from 'path';
import immutable from 'immutable';
import merger from './merger';
function loadLanguages() {
const files = glob
.sync('src/client/*/i18n/*.js')
.map(file => {
const translations = require(path.join(__dirname, '../../../', file));
const tokens = fi... | import glob from 'glob';
import path from 'path';
import immutable from 'immutable';
import merger from './merger';
function loadLanguages() {
const files = glob
.sync('src/client/*/i18n/*.js')
.map(file => {
const translations = require(path.join(__dirname, '../../../', file));
const tokens = fi... |
Fix var. In strict mode | /*global define */
define(['jquery'], function($) {
'use strict';
// Loads the specified JSON config file and returns a promise
// to tell you when it's done.
return function(url) {
var loaded = $.Deferred();
// Uses a HEAD request to figure out if
// the file exists so it doesn'... | /*global define */
define(['jquery'], function($) {
'use strict';
// Loads the specified JSON config file and returns a promise
// to tell you when it's done.
return function(url) {
var loaded = $.Deferred();
// Uses a HEAD request to figure out if
// the file exists so it doesn'... |
Add error return strings to the NHS number validator | package uk.ac.ox.ndm.grails.utils.validator;
import com.google.common.base.Strings;
/**
* @since 14/08/2015
*/
public class NhsNumberValidator implements Validator<String> {
public Object isValid(String nhsNumberStr) {
if (!Strings.isNullOrEmpty(nhsNumberStr)) {
nhsNumberStr = nhsNumberStr... | package uk.ac.ox.ndm.grails.utils.validator;
import com.google.common.base.Strings;
/**
* @since 14/08/2015
*/
public class NhsNumberValidator implements Validator<String> {
public Object isValid(String nhsNumberStr) {
if (!Strings.isNullOrEmpty(nhsNumberStr)) {
nhsNumberStr = nhsNumberStr... |
Fix issue where server error thrown if user does not have aecData | AECData = new Mongo.Collection('aecData');
Meteor.methods({
profileInsert: function (profileData) {
check(Meteor.userId(), String);
//check(Meteor.user().profile.aecData, undefined);
check(profileData, {
givenName: String,
familyName: String,
federalDivi... | AECData = new Mongo.Collection('aecData');
Meteor.methods({
profileInsert: function (profileData) {
check(Meteor.userId(), String);
check(Meteor.user().profile.aecData, undefined);
check(profileData, {
givenName: String,
familyName: String,
federalDivisio... |
Fix a bug with incorrect param | @extends('layouts._one_column')
@section('content')
<section class="auth">
<h1>We're going to create an account with this information.</h1>
<div class="user">
{{ ReCaptcha::getScript() }}
{{ Form::open() }}
<div class="bio">
<p><img src=... | @extends('layouts._one_column')
@section('content')
<section class="auth">
<h1>We're going to create an account with this information.</h1>
<div class="user">
{{ ReCaptcha::getScript() }}
{{ Form::open() }}
<div class="bio">
<p><img src=... |
Replace inline array copy with Arrays.clone | package org.bouncycastle.bcpg;
import java.io.IOException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
/**
* Generic literal data packet.
*/
public class LiteralDataPacket
extends InputStreamPacket
{
int format;
byte[] fileName;
long modDate;
LiteralDataP... | package org.bouncycastle.bcpg;
import java.io.IOException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
/**
* Generic literal data packet.
*/
public class LiteralDataPacket
extends InputStreamPacket
{
int format;
byte[] fileName;
long modDate;
LiteralDataP... |
Clean up some PEP8 stuff | from __future__ import absolute_import
# Import python libs
from StringIO import StringIO
# Import salt libs
from salt.exceptions import SaltRenderError
import salt.utils.templates
def render(template_file, env='', sls='', argline='',
context=None, tmplpath=None, **kws):
'''
Render... | from __future__ import absolute_import
# Import python libs
from StringIO import StringIO
# Import salt libs
from salt.exceptions import SaltRenderError
import salt.utils.templates
def render(template_file, env='', sls='', argline='',
context=None, tmplpath=None, **kws):
'''
Render... |
Set main method to also run gui for testing. |
import ClassLibrary.CmdRepl;
import GUI.ConcordanatorWindow;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Concordanator{
public static void main(String[] args) {
ConcordanatorWindow window = new ConcordanatorWindow();
... |
import ClassLibrary.CmdRepl;
import GUI.ConcordanatorWindow;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Concordanator{
public static void main(String[] args) {
//ConcordanatorWindow window = new ConcordanatorWindow();
... |
Fix bugs from thrown exceptions
In the drag and drop functions, variables are checked if null before being worked on. This stops exceptions from being thrown and further bugs from happening. | /* Source file for graphical functionality for Gear Bag project */
function dragging() {
$$('.device_block').addEvent('mousedown', function(event) {
event.stop();
console.log("boom");
// This refers to element with 'device_block' class
var device = this;
var clone = device.cl... | /* Source file for graphical functionality for Gear Bag project */
function dragging() {
$$('.device_block').addEvent('mousedown', function(event) {
event.stop();
console.log("boom");
// This refers to element with 'device_block' class
var device = this;
var clone = device.cl... |
Handle missing route definition with meaningful error message | !function() {
'use strict';
angular.module('crumble', ['ngRoute'])
.factory('crumble', function ($location, $route, $interpolate) {
var crumble = {
trail: [],
context: {},
};
crumble.update = function (context) {
crumble.context = context || crumble.context;
c... | !function() {
'use strict';
angular.module('crumble', ['ngRoute'])
.factory('crumble', function ($location, $route, $interpolate) {
var crumble = {
trail: [],
context: {},
};
crumble.update = function (context) {
crumble.context = context || crumble.context;
c... |
Allow overriding database name with DBNAME environment variable | from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI')... | from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
from os import environ
import urlparse
# configure the logging
logging.basicConfig(level='DEBUG',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app = Flask(__name__)
if environ.get('MONGOLAB_URI')... |
Fix minor issue in REST controller | <?php
namespace CuteControllers\Base;
class Rest extends Controller
{
public function route()
{
$method = strtolower($this->request->method) . '_';
if ($this->request->file_name === '') {
$method .= 'index';
} else {
$method .= $this->request->file_name;
... | <?php
namespace CuteControllers\Base;
class Rest extends Controller
{
public function route()
{
$method = strtolower($this->request->method) . '_';
if ($this->request->file_name === '') {
$method .= 'index';
} else {
$method .= $this->request->file_name;
... |
Resolve symlinks when detecting YUNO_HOME. | #!/usr/bin/env python3
import os
import re
import sys
from yuno.core import cli, config
from yuno.core.util import working_dir
def main(argv=None):
# Figure out where Yuno lives so plugins can cd correctly if they need to.
yuno_home = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
config.u... | #!/usr/bin/env python3
import os
import re
import sys
from yuno.core import cli, config
from yuno.core.util import working_dir
def main(argv=None):
# Figure out where Yuno lives so plugins can cd correctly if they need to.
yuno_home = os.path.abspath(os.path.dirname(__file__))
config.update('YUNO_HOME',... |
Revert "Construct proper URL for org projects"
This reverts commit 8748f46ce1e1f93de5c343e3f2d2bcaf3844b4e9. | import React from 'react'
import { NavLink } from 'react-router-dom'
import EditTools from './EditTools'
import PreviewTools from './PreviewTools'
import styles from './Toolbar.styl'
export default ({ params, project, layout, theme, onLayoutChanged, onThemeChanged }) => {
const { username, owner, project: projectNa... | import React from 'react'
import { NavLink } from 'react-router-dom'
import EditTools from './EditTools'
import PreviewTools from './PreviewTools'
import styles from './Toolbar.styl'
export default ({ params, project, layout, theme, onLayoutChanged, onThemeChanged }) => {
const { username, owner, project: projectNa... |
Revert "check multiple acheteurs popup formulaire validation parcellaire"
This reverts commit 8c66cde56f88d699a468d6515a1d8c8e9e1df8b2. | <?php
class ParcellaireValidationForm extends acCouchdbObjectForm {
public function configure() {
if(!$this->getObject()->isPapier()) {
$this->setWidget('autorisation_acheteur', new sfWidgetFormInputCheckbox());
$this->setValidator('autorisation_acheteur', new sfValidatorBoolean())... | <?php
class ParcellaireValidationForm extends acCouchdbObjectForm {
public function configure() {
if(!$this->getObject()->isPapier() && $this->getObject()->hasProduitWithMultipleAcheteur()) {
$this->setWidget('autorisation_acheteur', new sfWidgetFormInputCheckbox());
$this->setVali... |
Read installation requirements from dedicated file
Removes duplication. | import codecs
from setuptools import setup
def read_lines_from_file(filename):
with codecs.open(filename, encoding='utf-8') as f:
return [line.rstrip('\n') for line in f]
long_description = read_lines_from_file('README.rst')
requirements = read_lines_from_file('requirements.txt')
setup(
name='Wei... | import codecs
from setuptools import setup
def read_lines_from_file(filename):
with codecs.open(filename, encoding='utf-8') as f:
return [line.rstrip('\n') for line in f]
long_description = read_lines_from_file('README.rst')
setup(
name='Weitersager',
version='0.2-dev',
description='A pro... |
Fix broken reference in documentation | """This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.D... | """This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.D... |
Change import method so components show up | var RouteHandler = require( 'react-router' ).RouteHandler,
classNames = require('classnames'),
{ connect } = require('react-redux'),
{ routeActions } = require('react-router-redux'),
{ compose } = require( 'redux' ),
HTML5Backend = require('react-dnd-html5-backend'),
DragDropContext = require('... | var RouteHandler = require( 'react-router' ).RouteHandler,
Header = require( './header' ),
Modal = require( './modal' ),
classNames = require('classnames'),
{ connect } = require('react-redux'),
{ routeActions } = require('react-router-redux'),
{ compose } = require( 'redux' ),
... |
Make English the fallback language in i18next.
Fixes: #1580 | // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/local... | // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/local... |
Update migration history to include trackchanges migrations | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('assessment', '0004_edited_content_migration'),
]
operations = [
migrations.CreateModel(
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('assessment', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='StaffW... |
[FIX] stock_request_ux: Fix a problem with the allocations
For this change https://github.com/OCA/stock-logistics-warehouse/commit/4464be475999c8ada492c56a1c30ca2b0eaa264e
If you confirm with a rute with 3 steps and create 3 pickings them has related with the request by allocation, and the qty_done, qty_In_progress a... | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, fields
class StockMove(models.Model):
_in... | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import models, fields
class StockMove(models.Model):
_in... |
Fix issue where first selection in detail pane after refresh would not be possible |
define([
'rangy',
'rangy-text'
], function(
rangy,
rangyText
) {
if (!rangy.initialized) rangy.init();
return {
expandRangeByWords: function(range, numberWords, splitBeforeAfterOutput) {
var e = rangy.createRange();
e.setStart(range.startContainer, range.start... |
define([
'rangy',
'rangy-text'
], function(
rangy,
rangyText
) {
return {
expandRangeByWords: function(range, numberWords, splitBeforeAfterOutput) {
if (!rangy.initialized) rangy.init();
var e = rangy.createRange();
e.setStart(range.startContainer, rang... |
Make a single template for markdown editor | 'use strict';
angular
.module('flashcardModule.directives')
.directive('markdownEditor', function() {
var converter = new Showdown.converter();
return {
restrict: 'E',
scope: {
text: '=text'
},
template: '<div ng-hide="isEditMode"... | 'use strict';
angular
.module('flashcardModule.directives')
.directive('markdownEditor', function() {
var converter = new Showdown.converter();
var previewTemplate = '<div ng-hide="isEditMode" ng-dblclick="toEditMode()" class="preview"></div>';
var editorTemplate = '<textarea ng-show="i... |
Enable strict validation of `package.json`. | 'use strict';
module.exports = function(grunt) {
// Configuration.
grunt.initConfig({
jscs: {
options: {
config: '.jscsrc'
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jshint: {
options: {
... | 'use strict';
module.exports = function(grunt) {
// Configuration.
grunt.initConfig({
jscs: {
options: {
config: '.jscsrc'
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jshint: {
options: {
... |
Improve code by avoiding flow through exception handling | import json
import jsonschema
from jsonschema import validate
with open("schemata/g6-scs-schema.json") as json_file1:
G6_SCS_SCHEMA = json.load(json_file1)
with open("schemata/g6-saas-schema.json") as json_file2:
G6_SAAS_SCHEMA = json.load(json_file2)
with open("schemata/g6-iaas-schema.json") as json_file3:
... | import json
import jsonschema
from flask import current_app
from jsonschema import validate
with open("schemata/g6-scs-schema.json") as json_file1:
G6_SCS_SCHEMA = json.load(json_file1)
with open("schemata/g6-saas-schema.json") as json_file2:
G6_SAAS_SCHEMA = json.load(json_file2)
with open("schemata/g6-iaas... |
Add 4 and 8 hours update intervals again | 'use strict';
angular.module('Reader.optionsPage', ['Reader.services', 'Reader.directives']);
function OptionsCtrl($scope, options) {
$scope.syncEnabled = options.isSyncEnabled;
$scope.options = options.get();
$scope.$watch('options', function(newValue, oldValue) {
options.set($scope.op... | 'use strict';
angular.module('Reader.optionsPage', ['Reader.services', 'Reader.directives']);
function OptionsCtrl($scope, options) {
$scope.syncEnabled = options.isSyncEnabled;
$scope.options = options.get();
$scope.$watch('options', function(newValue, oldValue) {
options.set($scope.op... |
i18next: Add i18next: to the local storage cache prefix.
This just makes it easier to see what these local storage entries are
related to. | // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/local... | // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/local... |
Make Ace save the user's code on failures | $(document).ready(function() {
configureDataTables();
configureCodeBox();
});
function configureDataTables(){
$('#problem-table').dataTable( {
"iDisplayLength": 25,
"aaSorting": [[ 3, "desc" ]],
"aoColumns": [
null,
null,
null,
null
... | $(document).ready(function() {
configureDataTables();
configureCodeBox();
});
function configureDataTables(){
$('#problem-table').dataTable( {
"iDisplayLength": 25,
"aaSorting": [[ 3, "desc" ]],
"aoColumns": [
null,
null,
null,
null
... |
Make the app externally visible | import wol
import json
from flask import request
from app_factory import create_app
app = create_app(__name__)
@app.route('/help', methods=['GET'])
def help():
return json.dumps({'help message': wol.help_message().strip()})
@app.route('/ports', methods=['GET'])
def get_wol_ports():
return json.dumps({"port... | import wol
import json
from flask import request
from app_factory import create_app
app = create_app(__name__)
@app.route('/help', methods=['GET'])
def help():
return json.dumps({'help message': wol.help_message().strip()})
@app.route('/ports', methods=['GET'])
def get_wol_ports():
return json.dumps({"port... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.