text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use of @component for buttons in form | @section('js')
<script src="{{ asset('components/ckeditor/ckeditor.js') }}"></script>
@endsection
@component('core::admin._buttons-form', ['model' => $model])
@endcomponent
{!! BootForm::hidden('id') !!}
@include('core::admin._image-fieldset', ['field' => 'image'])
@include('core::form._title-and-slug')
{!! Tra... | @section('js')
<script src="{{ asset('components/ckeditor/ckeditor.js') }}"></script>
@endsection
@include('core::admin._buttons-form')
{!! BootForm::hidden('id') !!}
@include('core::admin._image-fieldset', ['field' => 'image'])
@include('core::form._title-and-slug')
{!! TranslatableBootForm::hidden('status')->... |
Check if world is remote so event isn't fired for single player entity tick | package com.matt.forgehax.mods.services;
import static com.matt.forgehax.Helper.getLocalPlayer;
import static com.matt.forgehax.Helper.getWorld;
import com.matt.forgehax.events.LocalPlayerUpdateEvent;
import com.matt.forgehax.util.mod.ServiceMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecr... | package com.matt.forgehax.mods.services;
import com.matt.forgehax.events.LocalPlayerUpdateEvent;
import com.matt.forgehax.util.mod.ServiceMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingEvent;
import net.min... |
Remove whitespace from top of file
Remove the unnecessary space at the top of the file before
the first code declaration. | var valid = function(el) {
// jquery the selector
var $el = $(el);
// narrow selection to only these validations
var $els = $el.find('[data-valid-required], [data-valid-pattern]');
// storage array to return
var arr = [];
// check for errors
var getError = function(element) {
// jquery the selector... |
var valid = function(el) {
// jquery the selector
var $el = $(el);
// narrow selection to only these validations
var $els = $el.find('[data-valid-required], [data-valid-pattern]');
// storage array to return
var arr = [];
// check for errors
var getError = function(element) {
// jquery the selecto... |
Make URL a string because of iOS build problems. | /****************************************************************************
* Copyright (C) 2019 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH (info@ecsec.de)
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General... | /****************************************************************************
* Copyright (C) 2019 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH (info@ecsec.de)
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General... |
Check that logging config file path is set. | package io.github.oliviercailloux.javase_maven_jul_hib_h2.launch;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import io.github.oliviercailloux.javase_maven_jul... | package io.github.oliviercailloux.javase_maven_jul_hib_h2.launch;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import io.github.oliviercailloux.javase_maven_jul... |
Refactor and add flow types | // @flow
import { times, uniq, compose, length } from 'ramda';
import { getRandomNumber, generatePassword } from '../../src/helpers/password';
const createArrayOfRandomNumbers = (min: number, max: number, count: number): Function =>
times((): number => getRandomNumber(min, max), count);
const countUniqueValuesInA... | import { getRandomNumber, generatePassword } from '../../src/helpers/password';
const R = require('ramda');
// Get rid of this and refactor
const repeat = (fn, arg1, arg2, count) => {
const arr = [];
for (let i = 0; i < count; i += 1) {
arr.push(fn(arg1, arg2));
}
return arr;
};
test('Generates a rando... |
Correct signature for updateConversationLoader params | import { GraphQLString, GraphQLNonNull } from "graphql"
import { mutationWithClientMutationId } from "graphql-relay"
import Conversation from "schema/me/conversation"
export default mutationWithClientMutationId({
name: "UpdateConversationMutation",
description: "Update a conversation.",
inputFields: {
conver... | import { GraphQLString, GraphQLNonNull } from "graphql"
import { mutationWithClientMutationId } from "graphql-relay"
import Conversation from "schema/me/conversation"
export default mutationWithClientMutationId({
name: "UpdateConversationMutation",
description: "Update a conversation.",
inputFields: {
conver... |
Change failure to an alert message. | $(document).ready( function () {
$(".upvote").click( function(event) {
var responseId = $(this).data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: responseId },
dataType: 'JSON'
}).done( function (voteCount) {
if (voteCount ... | $(document).ready( function () {
$(".upvote").click( function(event) {
var responseId = $(this).data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: responseId },
dataType: 'JSON'
}).done( function (voteCount) {
if (voteCount ... |
Update AudioChannel.playSong to use noteToFreq | var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
var args = args ? args : {};
this.frequency = args.freq ? args.freq : 220;
this.wave = args.wave ? args.wav... | var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
if(args) {
this.frequency = args.freq ? args.freq : 220;
this.wave = args.wave ? args.wave : "triangle";... |
Update blogroll and social links. | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'IPython development team and Enthought, Inc.'
SITENAME = u'DistArray'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Chicago'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'IPython development team and Enthought, Inc.'
SITENAME = u'DistArray'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Chicago'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_... |
Add missing @EnableDiscoveryClient in standalone server sample | /*
* Copyright © 2017 the original authors (http://cereebro.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required... | /*
* Copyright © 2017 the original authors (http://cereebro.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required... |
Remove limit for search field | from django import forms
from django.db.models import get_model
from django.utils.translation import ugettext as _
StoreAddress = get_model('stores', 'StoreAddress')
class StoreSearchForm(forms.Form):
STATE_CHOICES = (
(_('VIC'), _('Victoria')),
(_('NSW'), _('New South Wales')),
(_('SA')... | from django import forms
from django.db.models import get_model
from django.utils.translation import ugettext as _
StoreAddress = get_model('stores', 'StoreAddress')
class StoreSearchForm(forms.Form):
STATE_CHOICES = (
(_('VIC'), _('Victoria')),
(_('NSW'), _('New South Wales')),
(_('SA')... |
Fix NullPointerException when output base is null | package org.icij.extract.core;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.FileSystems;
import java.nio.charset.Charset;
import java.util.logging.Logger;
import org.apache.tika.parser.ParsingReader;
import org.apache.tika.exception.TikaException;
/**
* Extract
*
* @author Matthew... | package org.icij.extract.core;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.FileSystems;
import java.nio.charset.Charset;
import java.util.logging.Logger;
import org.apache.tika.parser.ParsingReader;
import org.apache.tika.exception.TikaException;
/**
* Extract
*
* @author Matthew... |
Convert LocalDateTime expected output to ISO-8601, since there's no timezone in LocalDateTime | /*
* ******************************************************************************
* Copyright 2016-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the Licens... | /*
* ******************************************************************************
* Copyright 2016-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the Licens... |
Change package name from 's3' to 'ucldc_iiif'. | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "ucldc-iiif",
version = "0.0.1",
description... | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "ucldc-iiif",
version = "0.0.1",
description... |
Fix for wrong application home path | package configurations
import (
"os"
"os/user"
"path"
)
var applicationName = "banksaurus"
// IsDev returns if in dev environment or not
func IsDev() bool {
if os.Getenv("GO_BANK_CLI_DEV") == "true" {
return true
}
return false
}
// DatabasePath returns the path nad name for the database
// taking into acco... | package configurations
import (
"os"
"os/user"
"path"
)
var applicationName = "banksaurus"
// IsDev returns if in dev environment or not
func IsDev() bool {
if os.Getenv("GO_BANK_CLI_DEV") == "true" {
return true
}
return false
}
// DatabasePath returns the path nad name for the database
// taking into acco... |
Create generic packr function to get schema | package validate
import (
"fmt"
"log"
"os"
"path"
"github.com/gobuffalo/packr"
"github.com/xeipuuv/gojsonschema"
)
// ValidateJSON is used to check for validity
func ValidateJSON(doc string) bool {
file := path.Join("file:///", GetPath(), "/", doc)
s := GetSchema()
schemaLoader := gojsonschema.NewStringLoa... | package validate
import (
"fmt"
"log"
"os"
"path"
"github.com/gobuffalo/packr"
"github.com/xeipuuv/gojsonschema"
)
// ValidateJSON is used to check for validity
func ValidateJSON(doc string) bool {
file := path.Join("file:///", GetPath(), "/", doc)
box := packr.NewBox("../../../")
s, err := box.MustString(... |
Use the correct name for the ListBuckets operation | var inspect = require('eyes').inspector();
var awssum = require('awssum');
var amazon = awssum.load('amazon/amazon');
var S3 = awssum.load('amazon/s3').S3;
var env = process.env;
var accessKeyId = process.env.ACCESS_KEY_ID;
var secretAccessKey = process.env.SECRET_ACCESS_KEY;
var awsAccountId = process.env.AWS_ACCOUNT... | var inspect = require('eyes').inspector();
var awssum = require('awssum');
var amazon = awssum.load('amazon/amazon');
var S3 = awssum.load('amazon/s3').S3;
var env = process.env;
var accessKeyId = process.env.ACCESS_KEY_ID;
var secretAccessKey = process.env.SECRET_ACCESS_KEY;
var awsAccountId = process.env.AWS_ACCOUNT... |
Add list order action boxoffice endpoint | <?php
require '../vendor/autoload.php';
$config = json_decode(file_get_contents("config/config.json"), true);
$config['root'] = __DIR__;
$app = new \Slim\App([ 'settings' => $config ]);
require '../dependencies.php';
// Routes
// =============================================================
$app->get('/events', Act... | <?php
require '../vendor/autoload.php';
$config = json_decode(file_get_contents("config/config.json"), true);
$config['root'] = __DIR__;
$app = new \Slim\App([ 'settings' => $config ]);
require '../dependencies.php';
// Routes
// =============================================================
$app->get('/events', Act... |
Use arrow function for this | const gulp = require('gulp')
const babel = require('gulp-babel')
const cache = require('gulp-cached')
const ext = require('gulp-ext')
const check = require('gulp-if')
const path = require('path')
const srcPath = 'src/**/*'
const condition = file => file.path.indexOf('/bin') > -1
gulp.task('transpile', function () {
... | const gulp = require('gulp')
const babel = require('gulp-babel')
const cache = require('gulp-cached')
const ext = require('gulp-ext')
const check = require('gulp-if')
const path = require('path')
const srcPath = 'src/**/*'
const condition = function (file) {
return file.path.indexOf('/bin') > -1
}
gulp.task('trans... |
Add instruction for stopping dev server | <?php
namespace Spark\Core;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\ProcessBuilder;
class DevelopmentServer
{
protected $documentRoot;
protected $router;
function __construct($documentRoot, $router)
{
$this->documentRoot = $documentRoot;
$this... | <?php
namespace Spark\Core;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\ProcessBuilder;
class DevelopmentServer
{
protected $documentRoot;
protected $router;
function __construct($documentRoot, $router)
{
$this->documentRoot = $documentRoot;
$this... |
Update feed-page-size given new feeds | var app = require('connect')();
var createRepostGuard = require('./src/repost-guard');
var fs = require('fs');
var log = require('./src/util').log;
var path = require('path');
// Keeping this forever in memory for now.
createRepostGuard.shared = createRepostGuard({
directory: path.join(__dirname, 'tmp'),
lineLimit... | var app = require('connect')();
var createRepostGuard = require('./src/repost-guard');
var fs = require('fs');
var log = require('./src/util').log;
var path = require('path');
// Keeping this forever in memory for now.
createRepostGuard.shared = createRepostGuard({
directory: path.join(__dirname, 'tmp'),
lineLimit... |
Add new properties, to be sandboxed | let origBot, origGuild;
// A dummy message object so ESLint doesn't complain
class Message {}
class Client {
constructor(bot, guild) {
origBot = bot;
origGuild = guild;
// TODO: sandboxed user
// this.user = bot.user
// TODO: sandboxed guild
// this.currentGuild = gui... | let origBot, origGuild;
// A dummy message object so ESLint doesn't complain
class Message {}
class Client {
constructor(bot, guild) {
origBot = bot;
origGuild = guild;
}
get guilds() {
return origBot.guilds.size
}
get users() {
return origBot.users.size
}
... |
Use metaclasses to register node types. | import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
_nodeTypes = {}
class _NodeTypeRegistrar(type):
def __init__(self, name, bases, dict):
type.__init__(self, name, bases, dict)
_nodeTypes[self.nodeType] = self
class NodeType(object):
__metaclass__ = _NodeType... | import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
class NodeType(object):
nodeType = 'UNKNOWN'
def __init__(self):
pass
def freeze(self):
return (self.nodeType, self.__dict__)
@classmethod
def thaw(class_, d):
return class_(**d)
class Cli... |
Split create database and create user into to individual commands | # -*- coding: utf-8 -*-
from fabric.api import run
def _generate_password():
import string
from random import sample
chars = string.letters + string.digits
return ''.join(sample(chars, 8))
def create_mysql_instance(mysql_user, mysql_password, instance_code):
user = instance_code
password = _... | # -*- coding: utf-8 -*-
from fabric.api import task, run
def _generate_password():
import string
from random import sample
chars = string.letters + string.digits
return ''.join(sample(chars, 8))
def create_mysql_instance(mysql_user, mysql_password, instance_code):
user = instance_code
passwo... |
Fix wart in event bus context | # -*- coding: utf-8 -*-
'''
A simple test engine, not intended for real use but as an example
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
import salt.utils.event
import salt.utils.json
log = logging.getLogger(__name__)
def even... | # -*- coding: utf-8 -*-
'''
A simple test engine, not intended for real use but as an example
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
import salt.utils.event
import salt.utils.json
log = logging.getLogger(__name__)
def even... |
[ENH] payments: Add a new action to add mulitple items to a cart (used in custom code only so far)
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@52748 b456876b-0849-0410-b77d-98878d47e9d5 | <?php
// (c) Copyright 2002-2014 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: Controller.php 46965 2013-08-02 19:05:59Z jonnybradley... | <?php
// (c) Copyright 2002-2014 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: Controller.php 46965 2013-08-02 19:05:59Z jonnybradley... |
Fix tests for udata/datagouvfr backend | import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps... | import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps... |
Fix static generator causing only one output at a time | <?php
namespace JLSalinas\RWGen;
trait GeneratorAggregateHack
{
protected $generator = null;
public function send($value)
{
if ($this->generator === null) {
if ($value === null) {
return;
}
$this->generator = $this->getGenerator();
}
... | <?php
namespace JLSalinas\RWGen;
trait GeneratorAggregateHack
{
public function send($value)
{
static $generator = null;
if ($generator === null) {
if ($value === null) {
return;
}
$generator = $this->getGenerator();
}
... |
Add debug information when server starts | // Package main initializes a web server.
package main
import (
"fmt"
"net/http"
_ "net/http/pprof" // import for side effects
"os"
log "github.com/Sirupsen/logrus"
"github.com/hack4impact/transcribe4all/config"
"github.com/hack4impact/transcribe4all/web"
)
func init() {
log.SetOutput(os.Stderr)
if config.C... | // Package main initializes a web server.
package main
import (
"net/http"
_ "net/http/pprof" // import for side effects
"os"
log "github.com/Sirupsen/logrus"
"github.com/hack4impact/transcribe4all/config"
"github.com/hack4impact/transcribe4all/web"
)
func init() {
log.SetOutput(os.Stderr)
if config.Config.D... |
Remove unnecessary modifiers to follow the convention
Change-Id: Ie8ff539252df6ed9df5ff827d639166a78fbf18d | /*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... | /*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... |
Solve problem to detect linked list cycle
https://www.hackerrank.com/challenges/ctci-linked-list-cycle | # https://www.hackerrank.com/challenges/ctci-linked-list-cycle
# Python 3
"""
Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.
A Node is defined as:
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
... | # https://www.hackerrank.com/challenges/ctci-linked-list-cycle
# Python 3
"""
Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.
A Node is defined as:
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
... |
Add javadocs with info on encoding | package com.ft.membership.crypto.signature;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;
public class Encoder {
private static final Base64.Encoder BASE_64_ENCODER = Base64.getUrlEncoder().withoutPadding();
private static final Base64.Decoder BASE_64_DECODER =... | package com.ft.membership.crypto.signature;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;
public class Encoder {
private static final Base64.Encoder BASE_64_ENCODER = Base64.getUrlEncoder().withoutPadding();
private static final Base64.Decoder BASE_64_DECODER =... |
Fix the bug of "Spelling error of a word"
The word "occured" should be spelled as "occurred".
So it is changed.
Change-Id: Ice5212dc8565edb0c5b5c55f979b27440eeeb9aa
Closes-Bug: #1505043 | # Copyright (c) 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | # Copyright (c) 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
Add files to the exported names. | """Read resources contained within a package."""
import sys
__all__ = [
'Package',
'Resource',
'ResourceReader',
'contents',
'files',
'is_resource',
'open_binary',
'open_text',
'path',
'read_binary',
'read_text',
]
if sys.version_info >= (3,):
from importlib_reso... | """Read resources contained within a package."""
import sys
__all__ = [
'Package',
'Resource',
'ResourceReader',
'contents',
'is_resource',
'open_binary',
'open_text',
'path',
'read_binary',
'read_text',
]
if sys.version_info >= (3,):
from importlib_resources._py3 im... |
Call the previous commit version 0.1.
And tag it as v0.1. Master is now 0.1.0.99, slated to become 0.1.1 when we feel
like labeling the next thing as a release. | from distutils.core import setup
__version__ = '0.1.0.99'
setup_args = {
'name': 'hera_librarian',
'author': 'HERA Team',
'license': 'BSD',
'packages': ['hera_librarian'],
'scripts': [
'scripts/add_librarian_file_event.py',
'scripts/add_obs_librarian.py',
'scripts/launch_li... | from distutils.core import setup
__version__ = '0.1'
setup_args = {
'name': 'hera_librarian',
'author': 'HERA Team',
'license': 'BSD',
'packages': ['hera_librarian'],
'scripts': [
'scripts/add_librarian_file_event.py',
'scripts/add_obs_librarian.py',
'scripts/launch_librari... |
Update py2app script for Qt 5.11 | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'icon... | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'icon... |
Remove requests and pyzmq from package dependencies
These will now have to be installed separately by the user depending on the
transport protocol required. | """setup.py"""
#pylint:disable=line-too-long
from codecs import open as codecs_open
try:
from setuptools import setup
except ImportError:
from distutils.core import setup #pylint:disable=import-error,no-name-in-module
with codecs_open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with codecs_open(... | """setup.py"""
#pylint:disable=line-too-long
from codecs import open as codecs_open
try:
from setuptools import setup
except ImportError:
from distutils.core import setup #pylint:disable=import-error,no-name-in-module
with codecs_open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with codecs_open(... |
Add missing global & var declarations | /* globals JSLang, CurrentPage */
$(document).ready(function () {
$(".delete.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Delete_Title"]});
$(".search.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Show_Users_Title"]});
$(".users.tipTitle").tipTip({delay: 0, ma... | /* globals JSLang */
$(document).ready(function () {
$(".delete.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Delete_Title"]});
$(".search.tipTitle").tipTip({delay: 0, maxWidth: "200px", content: JSLang["CMD_Show_Users_Title"]});
$(".users.tipTitle").tipTip({delay: 0, maxWidth: "200p... |
[rllib] Fix bad sample count assert | import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_siz... | import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_siz... |
Add the first cut at a function to get the x and y intercepts of a hough line.
(Needs much testing and fixing!) | /*! This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
// Pixel Manipulation Functions.
(function () {
window.getColor = function (data, x, y, width) {
... | /*! This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
// Pixel Manipulation Functions.
(function () {
window.getColor = function (data, x, y, width) {
... |
TST: Use itemgetter instead of lambda | from operator import itemgetter
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'... | import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['proper... |
Update GroupAttribute deduplication code to handle multi-value attributes. | "use strict";
import React from "react";
import SearchActions from "../actions/SearchActions.js";
function _dedupArray(arr, t, result) {
arr.forEach(function(item) {
if (Array.isArray(item)) {
_dedupArray(item, t, result);
return;
}
if (t.hasOwnProperty(item)) {
return;
}
t[i... | "use strict";
import React from "react";
import SearchActions from "../actions/SearchActions.js";
function dedupArray(arr) {
var t = {};
var result = [];
arr.forEach(function(item) {
if (t.hasOwnProperty(item)) {
return;
}
t[item] = true;
result.push(item);
});
return result;
}
funct... |
Remove vertical padding from nav button style | /**
* @flow
* A collection of common styles for navbar buttons
*/
import {StyleSheet, Platform} from 'react-native'
import * as c from '../colors'
export const commonStyles = StyleSheet.create({
button: {
flexDirection: 'row',
alignItems: 'center',
...Platform.select({
ios: {
paddingHorizontal: 18,
... | /**
* @flow
* A collection of common styles for navbar buttons
*/
import {StyleSheet, Platform} from 'react-native'
import * as c from '../colors'
export const commonStyles = StyleSheet.create({
button: {
flexDirection: 'row',
alignItems: 'center',
...Platform.select({
ios: {
paddingVertical: 11,
... |
Use opts to improve readability. | 'use strict';
const process = require('process');
const puppeteer = require('puppeteer');
const debug = require('./debug');
let opts = {
args: []
};
if (debug.LOAD_IMAGES == true) {
opts.args.push('--blink-settings=imagesEnabled=false');
}
puppeteer.launch(opts).then(async browser => {
let url = process... | 'use strict';
const process = require('process');
const puppeteer = require('puppeteer');
const debug = require('./debug');
puppeteer.launch({
args: [debug.LOAD_IMAGES == true ? '--blink-settings=imagesEnabled=false': '']
}).then(async browser => {
let url = process.argv[2];
let selector = process.argv[3]... |
Modify solution to fit the exercise specifications more closely | /*
Suppose you have a lot of files in a directory that contain words
Exercisei_j, where i and j are digits. Write a program that pads a 0 before
i if i is a single digit and 0 before j if j is a single digit. For example,
the word Exercise2_1 in a file will be replaced by Exercise02_01. Use the
following comm... | /*
Suppose you have a lot of files in a directory that contain words
Exercisei_j, where i and j are digits. Write a program that pads a 0 before
i if i is a single digit and 0 before j if j is a single digit. For example,
the word Exercise2_1 in a file will be replaced by Exercise02_01. Use the
following comm... |
Fix bug where amount for stripe is not correctly converted | from decimal import Decimal
# FIXME: The amount should be dynamically calculated by payment's currency.
# For example, amount will wrong for JPY since JPY does not support cents
def get_amount_for_stripe(amount, currency):
"""Get appropriate amount for stripe.
Stripe is using currency's smallest unit such as... | from decimal import Decimal
# FIXME: The amount should be dynamically calculated by payment's currency.
# For example, amount will wrong for JPY since JPY does not support cents
def get_amount_for_stripe(amount, currency):
"""Get appropriate amount for stripe.
Stripe is using currency's smallest unit such as... |
Switch to just icons for home and sign out in dashboard nav | <nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu">
<span class="sr-only">{{ Lang::get('cachet.dashboard.... | <nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu">
<span class="sr-only">{{ Lang::get('cachet.dashboard.... |
Raise read-only filesystem when the user wants to chmod in /history. | import os
from errno import EROFS
from fuse import FuseOSError
from gitfs import FuseMethodNotImplemented
from .view import View
class ReadOnlyView(View):
def getxattr(self, path, fh):
raise FuseMethodNotImplemented
def open(self, path, flags):
return 0
def create(self, path, fh):
... | import os
from errno import EROFS
from fuse import FuseOSError
from gitfs import FuseMethodNotImplemented
from .view import View
class ReadOnlyView(View):
def getxattr(self, path, fh):
raise FuseMethodNotImplemented
def open(self, path, flags):
return 0
def create(self, path, fh):
... |
Add installation requirements for developers | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.1.2dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oe... | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.1.2dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oe... |
tests.backends: Test using DatabaseBackend instead of RedisBackend, as the latter requires the redis module to be installed. | import unittest2 as unittest
from celery import backends
from celery.backends.amqp import AMQPBackend
from celery.backends.database import DatabaseBackend
class TestBackends(unittest.TestCase):
def test_get_backend_aliases(self):
expects = [("amqp", AMQPBackend),
("database", Database... | import unittest2 as unittest
from celery import backends
from celery.backends.amqp import AMQPBackend
from celery.backends.pyredis import RedisBackend
class TestBackends(unittest.TestCase):
def test_get_backend_aliases(self):
expects = [("amqp", AMQPBackend),
("redis", RedisBackend)]
... |
Add more return types after fixing a typo in my script | <?php
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* Class BaseUser.
*/
class BaseUser
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $username;... | <?php
namespace Symfony\Bridge\Doctrine\Tests\Fixtures;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* Class BaseUser.
*/
class BaseUser
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $username;... |
Mark empty object as static | package com.alexstyl.specialdates.events.namedays.calendar.resource;
import com.alexstyl.specialdates.events.namedays.NamedayLocale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
class NamedayJSONResourceProvider {
private static final JSONArray EMPTY = new JSONArray();
... | package com.alexstyl.specialdates.events.namedays.calendar.resource;
import com.alexstyl.specialdates.events.namedays.NamedayLocale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
class NamedayJSONResourceProvider {
private final NamedayJSONResourceLoader loader;
priva... |
Remove php old version check | <?php
/*
$Id$
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
*/
if (STORE_PAGE_PARSE_TIME == 'true') {
$time_start = explode(' ', PAGE_PARSE_START_TIME);
$time_end = explode(' ', microtime());
... | <?php
/*
$Id$
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
*/
if (STORE_PAGE_PARSE_TIME == 'true') {
$time_start = explode(' ', PAGE_PARSE_START_TIME);
$time_end = explode(' ', microtime());
... |
Fix GraphConvTensorGraph to GraphConvModel in tox21 | """
Script that trains graph-conv models on Tox21 dataset.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_to... | """
Script that trains graph-conv models on Tox21 dataset.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_to... |
Remove redundant ast.fix_missing_locations call. Moved to transformer. | import ast
import sys
from data.logic import _grammar_transformer
from puzzle.problems import problem
class LogicProblem(problem.Problem):
@staticmethod
def score(lines):
if len(lines) <= 1:
return 0
program = '\n'.join(lines)
try:
parsed = ast.parse(program)
if isinstance(parsed, a... | import ast
import sys
from data.logic import _grammar_transformer
from puzzle.problems import problem
class LogicProblem(problem.Problem):
@staticmethod
def score(lines):
if len(lines) <= 1:
return 0
program = '\n'.join(lines)
try:
parsed = ast.parse(program)
if isinstance(parsed, a... |
Add a familiar warn to quickly access console.log | var round = function(num)
{
return (num + 0.5) | 0
}
var floor = function(num)
{
return num | 0
}
var ceil = function(num)
{
return (num | 0) == num ? num | 0 : (num + 1) | 0
}
var abs = Math.abs
var sqrt = Math.sqrt
var log = function(num)
{
var result = Math.log(num)
return result
}
var signed_log = func... | var round = function(num)
{
return (num + 0.5) | 0
}
var floor = function(num)
{
return num | 0
}
var ceil = function(num)
{
return (num | 0) == num ? num | 0 : (num + 1) | 0
}
var abs = Math.abs
var sqrt = Math.sqrt
var log = function(num)
{
var result = Math.log(num)
return result
}
var signed_log = func... |
Add privateroom table to db | const Sequelize = require('sequelize');
const sequelize = new Sequelize('tbd', 'root', '12345');
const users = sequelize.define('user', {
userName: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
facebookId: {
type: Sequelize.STRING
},
token: {
type: Sequelize.STRING
... | const Sequelize = require('sequelize');
const sequelize = new Sequelize('tbd', 'root', '12345');
const users = sequelize.define('user', {
userName: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
facebookId: {
type: Sequelize.STRING
},
token: {
type: Sequelize.STRING
}... |
Move log message to else block, incorrectly report null when not null | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.notification.email',
name: 'EmailServiceDAO',
extends: 'foam.dao.ProxyDAO',
requires: [
'foam.nanos.notification.email.EmailMessage',
'foam.nanos... | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.notification.email',
name: 'EmailServiceDAO',
extends: 'foam.dao.ProxyDAO',
requires: [
'foam.nanos.notification.email.EmailMessage',
'foam.nanos... |
Remove spaces in computed properties | import fetch from 'isomorphic-fetch';
import url from 'url';
const baseUrlObj = {
protocol: 'https:',
host: 'api.github.com',
pathname: '/gists',
};
const baseUrlStr = url.format(baseUrlObj);
const FILENAME = 'playground.rs';
export function load(id) {
return fetch(`${baseUrlStr}/${id}`)
.then(response ... | import fetch from 'isomorphic-fetch';
import url from 'url';
const baseUrlObj = {
protocol: 'https:',
host: 'api.github.com',
pathname: '/gists',
};
const baseUrlStr = url.format(baseUrlObj);
const FILENAME = 'playground.rs';
export function load(id) {
return fetch(`${baseUrlStr}/${id}`)
.then(response ... |
[SPARK-32095][SQL] Update documentation to reflect usage of updated statistics
### What changes were proposed in this pull request?
Update documentation to reflect changes in https://github.com/apache/spark/commit/faf220aad9051c224a630e678c54098861f6b482
I've changed the documentation to reflect updated statistics ma... | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
Replace strings comparison with regexp | document.addEventListener('beforeload', onBeforeLoad, true);
var config = [
{
source: 'source.js',
reSource: 'reSource.js'
}
];
function onBeforeLoad(event) {
if (event.srcElement.tagName == 'SCRIPT') {
for(var i = 0; i < config.length; i++) {
var regexp = new RegExp(co... | document.addEventListener('beforeload', onBeforeLoad, true);
var config = [
{
source: 'source.js',
reSource: 'reSource.js'
}
];
function onBeforeLoad(event) {
if (event.srcElement.tagName == 'SCRIPT') {
console.error(event.url);
for(var i = 0; i < config.length; i++) {
... |
Set "PHP" word to uppercase! | <?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Admin / Cont... | <?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Admin / Cont... |
Fix end to end tests after password profile modifications | var assert = require("assert");
module.exports = {
"User set saved profile": function(browser) {
browser
.url(browser.launch_url)
.waitForElementVisible(".fa-sign-in")
.click(".fa-sign-in")
.setValue("#email", "test@lesspass.com")
.setValue("#passwordField", "test@lesspass.com")
... | var assert = require("assert");
module.exports = {
"User set saved profile": function(browser) {
browser
.url(browser.launch_url)
.waitForElementVisible(".fa-sign-in")
.click(".fa-sign-in")
.setValue("#email", "test@lesspass.com")
.setValue("#passwordField", "test@lesspass.com")
... |
Work on Recently-Used Database tab. | package org.reldb.dbrowser.ui.content.recent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.reldb.dbrowser.ui.DbTab;
... | package org.reldb.dbrowser.ui.content.recent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.reldb.dbrowser.ui.DbTab;
... |
Fix Stateless functional components + HOC | // @flow
import React, { Component } from 'react'
import { lifecycle } from 'recompose'
import type { Alert as AlertType } from '../types/application'
import type { clearAlert } from '../types/actions'
type Props = {
alert: AlertType,
clearAlert: clearAlert
}
const Alert = ({ alert, clearAlert }: Props) => {
i... | // @flow
import React, { Component } from 'react'
import type { Alert as AlertType } from '../types/application'
import type { clearAlert } from '../types/actions'
type Props = {
alert: AlertType,
clearAlert: clearAlert
}
export default class Alert extends Component {
props: Props
componentDidUpdate() {
... |
Add post modifier to version | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... |
Fix indent and don't decode input command. | import os
import shlex
import sys
from canaryd_packages import six
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug... | import os
import shlex
import sys
from canaryd_packages import six
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug... |
Fix Js error on tab refresh in element view | function bootstrap_tab_bookmark (selector) {
if (selector == undefined) {
selector = "";
}
var bookmark_switch = function () {
url = document.location.href.split('#');
if(url[1] != undefined) {
$(selector + '[href="#'+url[1]+'"]').tab('show');
}
}
/* Aut... | function bootstrap_tab_bookmark (selector) {
if (selector == undefined) {
selector = "";
}
var bookmark_switch = function () {
url = document.location.href.split('#');
if(url[1] != undefined) {
$(selector + '[href=#'+url[1]+']').tab('show');
}
}
/* Autom... |
Remove origin from meme model | from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(sel... | from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(sel... |
Fix problem with the proxy activator when using the blueprint bundle
git-svn-id: 212869a37fe990abe2323f86150f3c4d5a6279c2@1033177 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
Add 'large' size to the prop types | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class Bullet extends PureComponent {
render() {
const { className, color, size, borderColor, borderTint, ...others } = this.props;
const cl... | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class Bullet extends PureComponent {
render() {
const { className, color, size, borderColor, borderTint, ...others } = this.props;
const cl... |
Fix bug in AddObjects() RPC: new objects were not being counted. | package rpcd
import (
"encoding/gob"
"github.com/Symantec/Dominator/lib/srpc"
"github.com/Symantec/Dominator/proto/objectserver"
"io"
"runtime"
)
func (t *srpcType) AddObjects(conn *srpc.Conn) {
defer runtime.GC() // An opportune time to take out the garbage.
defer conn.Flush()
decoder := gob.NewDecoder(conn)... | package rpcd
import (
"encoding/gob"
"github.com/Symantec/Dominator/lib/srpc"
"github.com/Symantec/Dominator/proto/objectserver"
"io"
"runtime"
)
func (t *srpcType) AddObjects(conn *srpc.Conn) {
defer runtime.GC() // An opportune time to take out the garbage.
defer conn.Flush()
decoder := gob.NewDecoder(conn)... |
Set propper mimetype for image attachment | from email.mime.image import MIMEImage
from django.contrib.staticfiles import finders
from .base import EmailBase
class PlatformEmailMixin:
"""
Attaches the static file images/logo.png so it can be used in an html
email.
"""
def get_attachments(self):
attachments = super().get_attachments... | from email.mime.image import MIMEImage
from django.contrib.staticfiles import finders
from .base import EmailBase
class PlatformEmailMixin:
"""
Attaches the static file images/logo.png so it can be used in an html
email.
"""
def get_attachments(self):
attachments = super().get_attachments... |
Make sure to specify the length of the map before copy to avoid new allocations | // Copyright 2017 The Serulian Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package compilerutil
// ImmutableMap defines an immutable map struct, where Set-ing a new key returns a new ImmutableMap.
type ImmutableMap interface {
... | // Copyright 2017 The Serulian Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package compilerutil
// ImmutableMap defines an immutable map struct, where Set-ing a new key returns a new ImmutableMap.
type ImmutableMap interface {
... |
Reduce the test wait time to 20s
Signed-off-by: Julien Viet <5c682c2d1ec4073e277f9ba9f4bdf07e5794dabe@julienviet.com> | package io.vertx.ext.web.client;
import static io.vertx.core.Future.failedFuture;
import static io.vertx.core.Future.succeededFuture;
import static io.vertx.core.http.HttpHeaders.AUTHORIZATION;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.junit.Test;
import io.vertx.core.Futu... | package io.vertx.ext.web.client;
import static io.vertx.core.Future.failedFuture;
import static io.vertx.core.Future.succeededFuture;
import static io.vertx.core.http.HttpHeaders.AUTHORIZATION;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.junit.Test;
import io.vertx.core.Futu... |
Modify comparator to ensure `namespace` packages are given priority | 'use strict';
// FUNCTIONS //
/**
* Returns a comparison result. If `-1`, `a` comes before `b`. If `1`, `b` comes before `a`. If `0`, the order stays the same.
*
* @private
* @param {string} a - first string
* @param {string} b - second string
* @returns {boolean} comparison result
*/
function comparator( a, b ) {
i... | 'use strict';
// FUNCTIONS //
/**
* Returns a comparison result. If `-1`, `a` comes before `b`. If `1`, `b` comes before `a`. If `0`, the order stays the same.
*
* @private
* @param {string} a - first string
* @param {string} b - second string
* @returns {boolean} comparison result
*/
function comparator( a, b ) {
i... |
Add MultiScreenService to Default platforms | package com.connectsdk;
import java.util.HashMap;
public class DefaultPlatform {
public DefaultPlatform() {
}
public static HashMap<String, String> getDeviceServiceMap() {
HashMap<String, String> devicesList = new HashMap<String, String>();
devicesList.put("com.connectsdk.service.WebOSTVService", "com.... | package com.connectsdk;
import java.util.HashMap;
public class DefaultPlatform {
public DefaultPlatform() {
}
public static HashMap<String, String> getDeviceServiceMap() {
HashMap<String, String> devicesList = new HashMap<String, String>();
devicesList.put("com.connectsdk.service.WebOSTVService", "com.... |
Tweak ECDC scraper to strip whitespace | #!/usr/bin/env python
import requests
import lxml.html
import pandas as pd
import sys
URL = "http://ecdc.europa.eu/en/healthtopics/zika_virus_infection/zika-outbreak/Pages/Zika-countries-with-transmission.aspx"
columns_old = [
"country",
"affected_past_nine_months",
"affected_past_two_months"
]
columns_n... | #!/usr/bin/env python
import requests
import lxml.html
import pandas as pd
import sys
URL = "http://ecdc.europa.eu/en/healthtopics/zika_virus_infection/zika-outbreak/Pages/Zika-countries-with-transmission.aspx"
columns_old = [
"country",
"affected_past_nine_months",
"affected_past_two_months"
]
columns_n... |
Change version to 1.0.0 to match organizational versioning scheme. | #! /usr/bin/env python
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "django-premis-event-servi... | #! /usr/bin/env python
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "django-premis-event-servi... |
Upgrade to latest Symfony2 conventions | <?php
namespace Bundle\MarkdownBundle\DependencyInjection;
use Symfony\Components\DependencyInjection\Loader\LoaderExtension;
use Symfony\Components\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Components\DependencyInjection\BuilderConfiguration;
class MarkdownExtension extends LoaderExtension
{
public... | <?php
namespace Bundle\MarkdownBundle\DependencyInjection;
use Symfony\Components\DependencyInjection\Loader\LoaderExtension;
use Symfony\Components\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Components\DependencyInjection\BuilderConfiguration;
class MarkdownExtension extends LoaderExtension
{
public... |
Add more tests to the Hamming function. | package tests
import (
"fmt"
"testing"
"github.com/xrash/smetrics"
)
func TestHamming(t *testing.T) {
cases := []hammingcase{
{"a", "a", 0},
{"a", "b", 1},
{"AAAA", "AABB", 2},
{"BAAA", "AAAA", 1},
{"BAAA", "CCCC", 4},
{"karolin", "kathrin", 3},
{"karolin", "kerstin", 3},
{"1011101", "1001001", 2}... | package tests
import (
"fmt"
"testing"
"github.com/xrash/smetrics"
)
func TestHamming(t *testing.T) {
cases := []hammingcase{
{"a", "a", 0},
{"a", "b", 1},
{"AAAA", "AABB", 2},
{"BAAA", "AAAA", 1},
{"BAAA", "CCCC", 4},
}
for _, c := range cases {
r, err := smetrics.Hamming(c.a, c.b)
if err != nil... |
Remove separate execute mif command. | from sim import Sim
from mesh import Mesh
from exchange import Exchange
from demag import Demag
from zeeman import Zeeman
# Mesh specification.
lx = ly = lz = 50e-9 # x, y, and z dimensions (m)
dx = dy = dz = 5e-9 # x, y, and z cell dimensions (m)
Ms = 8e5 # saturation magnetisation (A/m)
A = 1e-11 # exchange ene... | from sim import Sim
from mesh import Mesh
from exchange import Exchange
from demag import Demag
from zeeman import Zeeman
# Mesh specification.
lx = ly = lz = 50e-9 # x, y, and z dimensions (m)
dx = dy = dz = 5e-9 # x, y, and z cell dimensions (m)
Ms = 8e5 # saturation magnetisation (A/m)
A = 1e-11 # exchange ene... |
Add bootstrap-js and bootstrap-fonts tasks | var gulp = require('gulp');
var less = require('gulp-less');
var cleanCSS = require('gulp-clean-css');
var sourcemaps = require('gulp-sourcemaps');
// The default Gulp.js task
gulp.task('default', ['bootstrap-fonts', 'bootstrap-js', 'less', 'watch']);
// Rebuild CSS from LESS
gulp.task('less', function () {
retur... | var gulp = require('gulp');
var less = require('gulp-less');
var cleanCSS = require('gulp-clean-css');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('default', ['less', 'watch']);
gulp.task('less', function () {
return gulp.src('assets/less/**/style.less')
.pipe(sourcemaps.init())
.pipe... |
Add offloader helper method for multiple | /*
* Copyright 2016 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or a... | /*
* Copyright 2016 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or a... |
Extend component class with React.Component in one more file from examples | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Connector } from 'redux/react';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/TodoActions';
export default class TodoApp extends Comp... | import React from 'react';
import { bindActionCreators } from 'redux';
import { Connector } from 'redux/react';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/TodoActions';
export default class TodoApp {
render() {
return (... |
fix:docs: Fix sitemap generator to use doc.id instead of doc.name
doc.id should be used instead of doc.name, otherwise links are wrongly
generated | exports.SiteMap = SiteMap;
/**
* @see http://www.sitemaps.org/protocol.php
*
* @param docs
* @returns {SiteMap}
*/
function SiteMap(docs){
this.render = function(){
var map = [];
map.push('<?xml version="1.0" encoding="UTF-8"?>');
map.push('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"... | exports.SiteMap = SiteMap;
/**
* @see http://www.sitemaps.org/protocol.php
*
* @param docs
* @returns {SiteMap}
*/
function SiteMap(docs){
this.render = function(){
var map = [];
map.push('<?xml version="1.0" encoding="UTF-8"?>');
map.push('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"... |
Add a user getter on UD | <?php
/**
* @license MIT
* @copyright 2014-2017 Tim Gunter
*/
namespace Kaecyra\ChatBot\Bot\Command;
use Kaecyra\ChatBot\Bot\DestinationInterface;
use Kaecyra\ChatBot\Bot\UserInterface;
/**
* User Destination
*
* @author Tim Gunter <tim@vanillaforums.com>
* @package chatbot
*/
class UserDestination {
/*... | <?php
/**
* @license MIT
* @copyright 2014-2017 Tim Gunter
*/
namespace Kaecyra\ChatBot\Bot\Command;
use Kaecyra\ChatBot\Bot\DestinationInterface;
use Kaecyra\ChatBot\Bot\UserInterface;
/**
* User Destination
*
* @author Tim Gunter <tim@vanillaforums.com>
* @package chatbot
*/
class UserDestination {
/*... |
Fix parent synonym for Location model | # -*- coding: utf-8 -*-
from . import db, BaseScopedNameMixin
from flask import url_for
from .board import Board
__all__ = ['Location']
class Location(BaseScopedNameMixin, db.Model):
"""
A location where jobs are listed, using geonameid for primary key. Scoped to a board
"""
__tablename__ = 'locatio... | # -*- coding: utf-8 -*-
from . import db, BaseScopedNameMixin
from flask import url_for
from .board import Board
__all__ = ['Location']
class Location(BaseScopedNameMixin, db.Model):
"""
A location where jobs are listed, using geonameid for primary key. Scoped to a board
"""
__tablename__ = 'locatio... |
Fix test on Java 10
git-svn-id: c1447309447e562cc43d70ade9fe6c70ff9b4cec@1830541 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
Fix address prefixes, add dogecoin/litecoin BIP32 versions | // https://en.bitcoin.it/wiki/List_of_address_prefixes
// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
module.exports = {
bitcoin: {
bip32: {
pub: 0x0488b21e,
priv: 0x0488ade4
},
pubKeyHash: 0x00,
scriptHash: 0x05,
wif: 0x80
},
dogecoin: {
... | // https://en.bitcoin.it/wiki/List_of_address_prefixes
module.exports = {
bitcoin: {
bip32: {
pub: 0x0488b21e,
priv: 0x0488ade4
},
pubKeyHash: 0x00,
scriptHash: 0x05,
wif: 0x80
},
dogecoin: {
pubKeyHash: 0x30,
scriptHash: 0x20,
wif: 0x9e
},
litecoin: {
scriptHas... |
Make it DRYer for people | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args... | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args... |
Allow MySQL versions > 5 (like MariaDB) | <?php
function dbconnect() {
global $hostname,$database,$dbuser,$dbpass,$db;
$db = mysql_connect($hostname,$dbuser,$dbpass) or die("Database error");
mysql_select_db($database, $db);
mysql_set_charset('utf8mb4',$db);
mysql_query("set sql_mode='ALLOW_INVALID_DATES'");
}
function... | <?php
function dbconnect() {
global $hostname,$database,$dbuser,$dbpass,$db;
$db = mysql_connect($hostname,$dbuser,$dbpass) or die("Database error");
mysql_select_db($database, $db);
mysql_set_charset('utf8mb4',$db);
mysql_query("set sql_mode='ALLOW_INVALID_DATES'");
}
function... |
Change the default to be geofencing with high accuracy at 30 sec intervals | package edu.berkeley.eecs.emission.cordova.tracker.location;
import android.content.Context;
import android.location.Location;
import com.google.android.gms.location.LocationRequest;
import edu.berkeley.eecs.emission.cordova.tracker.Constants;
/**
* Created by shankari on 10/20/15.
*
* TODO: Change this to read ... | package edu.berkeley.eecs.emission.cordova.tracker.location;
import android.content.Context;
import android.location.Location;
import com.google.android.gms.location.LocationRequest;
import edu.berkeley.eecs.emission.cordova.tracker.Constants;
/**
* Created by shankari on 10/20/15.
*
* TODO: Change this to read ... |
Add setFreq/setColor methods for FlashingBox | from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush
class FlashingBox(QOpenGLWidget):
def __init__(self, parent, freq=1, color=Qt.black):
super(FlashingBox, self).__init__(parent)
self.freq = freq
self.brushes = [QBrush(Qt.black), QBrush(color)]
... | from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush
class FlashingBox(QOpenGLWidget):
def __init__(self, parent, freq, color):
super(FlashingBox, self).__init__(parent)
self.freq = freq
self.brushes = [QBrush(Qt.black), QBrush(color)]
self.i... |
Fix bug affecting relative genome paths in sessions | /*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
*... | /*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
*... |
Update fb js to v2.12 | // https://dev.twitter.com/web/javascript/loading
window.twttr = (function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insert... | // https://dev.twitter.com/web/javascript/loading
window.twttr = (function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insert... |
Remove transition labels on converting PN to STG. | package org.workcraft.plugins.stg.tools;
import java.util.Map;
import org.workcraft.dom.math.MathNode;
import org.workcraft.dom.visual.VisualComponent;
import org.workcraft.gui.graph.tools.DefaultModelConverter;
import org.workcraft.plugins.petri.Place;
import org.workcraft.plugins.petri.Transition;
import org.workcr... | package org.workcraft.plugins.stg.tools;
import java.util.Map;
import org.workcraft.dom.math.MathNode;
import org.workcraft.gui.graph.tools.DefaultModelConverter;
import org.workcraft.plugins.petri.Place;
import org.workcraft.plugins.petri.Transition;
import org.workcraft.plugins.petri.VisualPetriNet;
import org.work... |
Remove redundant company create step | const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
const { set, get, assign } = require('lodash')
defineSupportCode(({ When }) => {
const Company = client.page.Company()
When(/^the Account management details are updated$/, async function () {
await Company
... | const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
const { set, get, assign } = require('lodash')
defineSupportCode(({ Given, When }) => {
const Company = client.page.Company()
Given(/^a company is created$/, async function () {
await client
.url(this.url... |
Add support for flake8 3.0 | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import flake8
if flake8.__version_info__ < (3,):
from flake8.engine import get_style_guide
else:
from flake8.api.legacy import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.pat... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
from flake8.engine import get_style_guide
cur_dir = os.path.dirname(__file__)
config_file = os.path.join(cur_dir, '..', 'tox.ini')
def run():
"""
Runs flake8 lint
:return:
A bool - if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.