text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add slug variable to pass in the URL | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostLis... | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostLis... |
Fix the spawning bug with autogenerated levels | package uk.co.alynn.games.ld30;
import java.util.List;
import uk.co.alynn.games.ld30.world.Planet;
import uk.co.alynn.games.ld30.world.Adversary;
public class SuperimposedWave extends Wave {
private final Wave m_left;
private final Wave m_right;
public SuperimposedWave(Wave left, Wave right) {
... | package uk.co.alynn.games.ld30;
import java.util.List;
import uk.co.alynn.games.ld30.world.Planet;
import uk.co.alynn.games.ld30.world.Adversary;
public class SuperimposedWave extends Wave {
private final Wave m_left;
private final Wave m_right;
public SuperimposedWave(Wave left, Wave right) {
... |
Add a Python 3 classifier recommended by community | #
# This is the regobj setuptools script.
# Originally developed by Ryan Kelly, 2009.
#
# This script is placed in the public domain.
#
from distutils.core import setup
# If we did a straight `import regobj` here we wouldn't be able
# to build on non-win32 machines.
regobj = {}
try:
execfile("regobj.py",rego... | #
# This is the regobj setuptools script.
# Originally developed by Ryan Kelly, 2009.
#
# This script is placed in the public domain.
#
from distutils.core import setup
# If we did a straight `import regobj` here we wouldn't be able
# to build on non-win32 machines.
regobj = {}
try:
execfile("regobj.py",rego... |
Fix composer for inplace in dev mode | <?php
require_once __DIR__ . '/deployer/recipe/yii2-app-advanced.php';
require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/in-place.php';
if (!file_exists (__DIR__ . '/deployer/stage/servers.yml')) {
die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" bef... | <?php
require_once __DIR__ . '/deployer/recipe/yii2-app-advanced.php';
require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/in-place.php';
if (!file_exists (__DIR__ . '/deployer/stage/servers.yml')) {
die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" bef... |
Update implicit default for view layout | /**
* getImplicitDefaults()
*
* Get a dictionary of implicit defaults this hook would like to merge
* into `sails.config` when Sails is loaded.
*
* @param {Dictionary} existingConfig
* Existing configuration which has already been loaded
* e.g. the Sails app path, and any config overrides (prog... | /**
* getImplicitDefaults()
*
* Get a dictionary of implicit defaults this hook would like to merge
* into `sails.config` when Sails is loaded.
*
* @param {Dictionary} existingConfig
* Existing configuration which has already been loaded
* e.g. the Sails app path, and any config overrides (prog... |
Use errors.New() instead of fmt.Errorf() where appropriate. | package armoredcrypt
import (
"fmt"
"encoding/base64"
"strings"
"errors"
)
const (
_MAGIC_PREFIX = "saltybox"
_V1_MAGIC = "saltybox1:"
)
func Wrap(body []byte) string {
encoded := base64.RawURLEncoding.EncodeToString(body)
return fmt.Sprintf("%s%s", _V1_MAGIC, encoded)
}
func Unwrap(varmoredBody string) ([... | package armoredcrypt
import (
"fmt"
"encoding/base64"
"strings"
)
const (
_MAGIC_PREFIX = "saltybox"
_V1_MAGIC = "saltybox1:"
)
func Wrap(body []byte) string {
encoded := base64.RawURLEncoding.EncodeToString(body)
return fmt.Sprintf("%s%s", _V1_MAGIC, encoded)
}
func Unwrap(varmoredBody string) ([]byte, err... |
:bug: Use defaultColors if config not provided
References #9 | 'use strict';
const foregroundColor = '#A1B0B8';
const borderColor = '#252525';
const oceanicColors = require('./colorschemes/oceanic.js');
const defaultColors = require('./colorschemes/regular.js');
const getColorScheme = cfg => {
if (cfg.materialshell) {
switch (cfg.materialshell.theme) {
case 'oceanic': retu... | 'use strict';
const foregroundColor = '#A1B0B8';
const borderColor = '#252525';
const oceanicColors = require('./colorschemes/oceanic.js');
const defaultColors = require('./colorschemes/regular.js');
const getColorScheme = cfg => {
if (cfg.materialshell) {
switch (cfg.materialshell.theme) {
case 'oceanic': retu... |
Add failing test for skin tones
As per issue #3. | var tape = require('tape')
var emojiStrip = require('..')
var emoji
tape('strip emoji', function (t) {
emoji = 'thumbs-up👍 for staying strong💪 without emoji please🙏'
t.equal(emojiStrip(emoji), 'thumbs-up for staying strong without emoji please')
emoji = 'dealing with emoji😡 makes me feel like poop💩'
t.e... | var tape = require('tape')
var emojiStrip = require('..')
var emoji
tape('strip emoji', function (t) {
emoji = 'thumbs-up👍 for staying strong💪 without emoji please🙏'
t.equal(emojiStrip(emoji), 'thumbs-up for staying strong without emoji please')
emoji = 'dealing with emoji😡 makes me feel like poop💩'
t.e... |
Add a die function to quickly throw errors | 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... |
Remove author tags from javadoc | /*
* 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")... | /*
* 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")... |
Allow --renovate-fork Cli flag for onboarding.
Fixes https://github.com/renovateapp/renovate/issues/1371. | const { detectPackageFiles } = require('../../../../manager');
const { createOnboardingBranch } = require('./create');
const { rebaseOnboardingBranch } = require('./rebase');
const { isOnboarded, onboardingPrExists } = require('./check');
async function checkOnboardingBranch(config) {
logger.debug('checkOnboarding()... | const { detectPackageFiles } = require('../../../../manager');
const { createOnboardingBranch } = require('./create');
const { rebaseOnboardingBranch } = require('./rebase');
const { isOnboarded, onboardingPrExists } = require('./check');
async function checkOnboardingBranch(config) {
logger.debug('checkOnboarding()... |
Swap the palindome spec for subset sum | "use strict";
var Sentient = require("../../lib/sentient");
describe("Exercise 4", function () {
var machineCode = Sentient.compile({
instructions: [
// Add your instructions here.
]
});
it("can solve the subset sum problem", function () {
var result = Sentient.run(machineCode, {
number... | "use strict";
var Sentient = require("../../lib/sentient");
describe("Exercise 4", function () {
var machineCode = Sentient.compile({
instructions: [
// Add your instructions here.
]
});
it("can find an array that is a palindrome of 3 numbers", function () {
var result = Sentient.run(machineC... |
Use same syntax for all assets | var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Larave... | var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Larave... |
Fix bug on fudge wrapper | import fudge
import inspect
class MethodNotAvailableInMockedObjectException(Exception):
pass
def getMock(class_to_mock):
return FudgeWrapper(class_to_mock)
class FudgeWrapper(fudge.Fake):
def __init__(self, class_to_mock):
self._class_to_mock = class_to_mock
self._declared_calls = {}
... | import fudge
import inspect
class MethodNotAvailableInMockedObjectException(Exception):
pass
def getMock(class_to_mock):
return FudgeWrapper(class_to_mock)
class FudgeWrapper(fudge.Fake):
def __init__(self, class_to_mock):
self._class_to_mock = class_to_mock
self._declared_calls = {}
... |
Add metrics to monitor Redis connections | package com.bendb.dropwizard.redis;
import com.bendb.dropwizard.redis.jersey.JedisPoolBinder;
import com.codahale.metrics.Gauge;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import redis.clients.jedis.JedisPool;... | package com.bendb.dropwizard.redis;
import com.bendb.dropwizard.redis.jersey.JedisPoolBinder;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import redis.clients.jedis.JedisPool;
public abstract class JedisBundle... |
Make use of get_pkg_data_filename for icon | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Defines constants used in `astropy.vo.samp`."""
import os
from ...utils.data import get_pkg_data_filename
__all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR',
'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_INSTANCE',
... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Defines constants used in `astropy.vo.samp`."""
import os
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
__all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR',
'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_IN... |
Add documentation for public class and method | package com.janosgyerik.tools.util;
import java.util.Arrays;
/**
* Utility class to work with matrices
*/
public class MatrixUtils {
private MatrixUtils() {
// utility class, forbidden constructor
}
/**
* Format matrix as String, by joining Arrays.toString of each row
* @param matrix... | package com.janosgyerik.tools.util;
import java.util.Arrays;
public class MatrixUtils {
private MatrixUtils() {
// utility class, forbidden constructor
}
public static String toString(int[][] matrix) {
StringBuilder builder = new StringBuilder();
builder.append("[");
if (... |
Update the profile alignment example. | from alignment.sequence import Sequence
from alignment.vocabulary import Vocabulary
from alignment.sequencealigner import SimpleScoring, GlobalSequenceAligner
from alignment.profile import Profile
from alignment.profilealigner import SoftScoring, GlobalProfileAligner
# Create sequences to be aligned.
a = Sequence('wh... | # Create sequences to be aligned.
from alignment.sequence import Sequence
a = Sequence("what a beautiful day".split())
b = Sequence("what a disappointingly bad day".split())
print "Sequence A:", a
print "Sequence B:", b
print
# Create a vocabulary and encode the sequences.
from alignment.vocabulary import Vocabulary
v... |
Fix string interpolation for displaying time periods
The interpolation was done in a way that actually subtracted two strings from each other instead of putting the literal '-' between them. | import dayjs from './dayjs.js'
import { i18n } from '@/plugins/i18n' // this imports i18-plugin from "frontend" or from "print", depending on where the helper is used
function dateShort(dateTimeString) {
return dayjs.utc(dateTimeString).format(i18n.tc('global.datetime.dateShort'))
}
function dateLong(dateTimeString... | import dayjs from './dayjs.js'
import { i18n } from '@/plugins/i18n' // this imports i18-plugin from "frontend" or from "print", depending on where the helper is used
function dateShort(dateTimeString) {
return dayjs.utc(dateTimeString).format(i18n.tc('global.datetime.dateShort'))
}
function dateLong(dateTimeString... |
Add Trove classifiers for 2.x and 3.x | from distutils.core import setup
def main():
setup(
name = 'logging_levels',
packages=['logging_levels'],
package_dir = {'logging_levels':'logging_levels'},
version = open('VERSION.txt').read().strip(),
author='Mike Thornton',
author_email='six8@devdetails.com',
... | from distutils.core import setup
def main():
setup(
name = 'logging_levels',
packages=['logging_levels'],
package_dir = {'logging_levels':'logging_levels'},
version = open('VERSION.txt').read().strip(),
author='Mike Thornton',
author_email='six8@devdetails.com',
... |
Revert "Remove explicit link to homepage view in i3p_base"
This reverts commit 3d4327f6d9d71c6b396b0655de81373210417aba. | #-- encoding: utf-8 --
from django.conf.urls.defaults import patterns, url
from haystack.views import search_view_factory
import views
import ajax
urlpatterns = patterns('',
url(r'^$', views.homepage, name='i4p-index'),
url(r'^homepage/ajax/slider/bestof/$', ajax.slider_bestof, name='i4p-homepage-ajax-slider... | #-- encoding: utf-8 --
from django.conf.urls.defaults import patterns, url
from haystack.views import search_view_factory
import views
import ajax
urlpatterns = patterns('',
#url(r'^$', views.homepage, name='i4p-index'),
url(r'^homepage/ajax/slider/bestof/$', ajax.slider_bestof, name='i4p-homepage-ajax-slide... |
Check for FailureData is an error ocurr
Signed-off-by: Andres Garcia <a32ab6d0ea593a061705598410d773d0d3e9ce01@gmail.com> | <?php
namespace Omnipay\Paysimple\Message;
class Response implements \Omnipay\Common\Message\ResponseInterface
{
public function __construct($request, $response)
{
$this->request = $request;
$this->response = $response;
}
public function getRequest()
{
$this->request;
}
public function isSuccessful()
... | <?php
namespace Omnipay\Paysimple\Message;
class Response implements \Omnipay\Common\Message\ResponseInterface
{
public function __construct($request, $response)
{
$this->request = $request;
$this->response = $response;
}
public function getRequest()
{
$this->request;
}
public function isSuccessful()
... |
Add update_tcbs.sql to the mix | """bug 958558 migration for update_product_version() and friends
Revision ID: 2c48009040da
Revises: 48e9a4366530
Create Date: 2014-01-13 12:54:13.988864
"""
# revision identifiers, used by Alembic.
revision = '2c48009040da'
down_revision = '4cacd567770f'
from alembic import op
from socorro.lib import citexttype, js... | """bug 958558 migration for update_product_version() and friends
Revision ID: 2c48009040da
Revises: 48e9a4366530
Create Date: 2014-01-13 12:54:13.988864
"""
# revision identifiers, used by Alembic.
revision = '2c48009040da'
down_revision = '4cacd567770f'
from alembic import op
from socorro.lib import citexttype, js... |
Remove after column for SQL lite compatibility | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterUserTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
if (Schema::hasTable('users')) {
if (!Schema::hasColumn('users', 'username')) {
... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterUserTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
if (Schema::hasTable('users')) {
if (!Schema::hasColumn('users', 'username')) {
... |
[MIG] Change the version of module. | # -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation ZIP Codes',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '9.0.1.0.0',
'depends': [
... | # -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation ZIP Codes',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '8.0.1.0.1',
'depends': [
... |
Use init shortcut in embed config |
var path = require('path');
var express = require('express');
var xAdmin = require('express-admin');
var dpath = path.resolve(__dirname, '../', process.argv[2], process.argv[3]);
var args = {
dpath: dpath,
config: require(path.join(dpath, 'config.json')),
settings: require(path.join(dpath, 'settings.jso... |
var path = require('path');
var express = require('express');
var expressAdmin = require('/home/mighty/node/modules/express-admin');
var dpath = path.resolve(__dirname, '../', process.argv[2], process.argv[3]);
var expressAdminArgs = {
dpath: dpath,
config: require(path.join(dpath, 'config.json')),
sett... |
chore(styleguide): Add a note to the copy to clipboard example on styleguide | /*doc
---
title: Copy To Clipboard
name: copy_to_clipboard_react
categories:
- react_components_copy-to-clipboard
- react_all
---
<code class="pam">
<i class="fa fa-download" alt="Install the Component"></i>
npm install pui-react-copy-to-clipboard --save
</code>
Require the subcomponents:
```
var CopyTo... | /*doc
---
title: Copy To Clipboard
name: copy_to_clipboard_react
categories:
- react_components_copy-to-clipboard
- react_all
---
<code class="pam">
<i class="fa fa-download" alt="Install the Component"></i>
npm install pui-react-copy-to-clipboard --save
</code>
Require the subcomponents:
```
var CopyTo... |
Unravel index for argmin of array | import doseresponse as dr
import numpy as np
import itertools as it
import os
import argparse
import sys
parser = argparse.ArgumentParser()
requiredNamed = parser.add_argument_group('required arguments')
requiredNamed.add_argument("--data-file", type=str, help="csv file from which to read in data, in same format as p... | import doseresponse as dr
import numpy as np
import itertools as it
import os
import argparse
import sys
parser = argparse.ArgumentParser()
requiredNamed = parser.add_argument_group('required arguments')
requiredNamed.add_argument("--data-file", type=str, help="csv file from which to read in data, in same format as p... |
Save runlog as output is added. | from django.db import models
from .bugwarriorconfig import BugwarriorConfig
class BugwarriorConfigRunLog(models.Model):
config = models.ForeignKey(
BugwarriorConfig,
related_name='run_logs',
)
success = models.BooleanField(default=False)
output = models.TextField()
stack_trace = m... | from django.db import models
from .bugwarriorconfig import BugwarriorConfig
class BugwarriorConfigRunLog(models.Model):
config = models.ForeignKey(
BugwarriorConfig,
related_name='run_logs',
)
success = models.BooleanField(default=False)
output = models.TextField()
stack_trace = m... |
Print the Jedi version when REPL completion is used
This also makes debugging easier, because people see which completion
they're actually using. | """
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on l... | """
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on l... |
Add autoincrement for jump in the future | class BytecodeBase:
autoincrement = True # For jump
def __init__(self):
# Eventually might want to add subclassed bytecodes here
# Though __subclasses__ works quite well
pass
def execute(self, machine):
pass
class Push(BytecodeBase):
def __init__(self, data):
... | class BytecodeBase:
def __init__(self):
# Eventually might want to add subclassed bytecodes here
# Though __subclasses__ works quite well
pass
def execute(self, machine):
pass
class Push(BytecodeBase):
def __init__(self, data):
self.data = data
def execute(sel... |
Change webhook priority to allow store owners to use the event before us | <?php
/**
* Created by PhpStorm.
* User: Zooma
* Date: 21/09/15
* Time: 15:58
*/
class Channel_Engine_Order_Complete {
private $client;
/**
* Constructor
*/
public function __construct($client) {
$this->client = $client;
add_action('woocommerce_order_status_completed', a... | <?php
/**
* Created by PhpStorm.
* User: Zooma
* Date: 21/09/15
* Time: 15:58
*/
class Channel_Engine_Order_Complete {
private $client;
/**
* Constructor
*/
public function __construct($client) {
$this->client = $client;
add_action('woocommerce_order_status_completed', a... |
Rename paths variable to fnames. | import os
class FileIterator(object):
"""
This FileIterator iterates over the paths contained in one or more directories.
"""
def __init__(self, *paths):
"""
@param paths: the file or directory paths.
"""
self._paths = paths
def __iter__(self):
return se... | import os
class FileIterator(object):
"""
This FileIterator iterates over the paths contained in one or more directories.
"""
def __init__(self, *paths):
"""
@param paths: the file or directory paths.
"""
self._paths = paths
def __iter__(self):
return se... |
Fix tests for menu toggling | import { expect } from 'chai'
import helpers from './helpers'
import store from '../../src/store'
import {
TOGGLE_SIDEBAR,
TOGGLE_USER_MENU
} from '../../src/store/mutation-types'
describe('main', () => {
beforeEach(helpers.reset)
afterEach(helpers.reset)
describe('actions', () => {
it('toggleSidebar... | import { expect } from 'chai'
import store from '../../src/store'
import {
TOGGLE_SIDEBAR,
TOGGLE_USER_MENU
} from '../../src/store/mutation-types'
describe('main', () => {
describe('actions', () => {
it('toggleSidebar', () => {
store._actions.toggleSidebar[0]({
commit: store.commit,
... |
Throw meaningful exception if properties file could not be found | import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.xml.bind.JAXBException;
import org.junit.Before;
import org.junit.Test;
import uk.bl.odin.orcid.client.OrcidAccessToken;
import uk.bl.odin.orcid.client.OrcidOAuthClient;
import uk.bl.odin.orcid.client.constants.OrcidAut... | import java.io.IOException;
import java.util.Properties;
import javax.xml.bind.JAXBException;
import org.junit.Before;
import org.junit.Test;
import uk.bl.odin.orcid.client.OrcidAccessToken;
import uk.bl.odin.orcid.client.OrcidOAuthClient;
import uk.bl.odin.orcid.client.constants.OrcidAuthScope;
import static org.ju... |
Make streamable artist updates as they happen, rather than commiting at the end of all artists | #!/usr/bin/env python
import psycopg2 as ordbms
import urllib, urllib2
import xml.etree.cElementTree as ElementTree
class SetArtistStreamable:
def __init__(self):
self.conn = ordbms.connect ("dbname='librefm'")
self.cursor = self.conn.cursor()
def updateAll(self):
"""Sets artists streamable ... | #!/usr/bin/env python
import psycopg2 as ordbms
import urllib, urllib2
import xml.etree.cElementTree as ElementTree
class SetArtistStreamable:
def __init__(self):
self.conn = ordbms.connect ("dbname='librefm'")
self.cursor = self.conn.cursor()
def updateAll(self):
"""Sets artists streamable ... |
tests: Fix test running when Django isn't available. | # -*- coding: utf-8 -*-
# Copyright (c) 2012-2013 Raphaël Barrois
try:
from django.db import models
django_loaded = True
except ImportError:
django_loaded = False
if django_loaded:
from semantic_version import django_fields as semver_fields
class VersionModel(models.Model):
version = se... | # -*- coding: utf-8 -*-
# Copyright (c) 2012-2013 Raphaël Barrois
from django.db import models
from semantic_version import django_fields as semver_fields
class VersionModel(models.Model):
version = semver_fields.VersionField(verbose_name='my version')
spec = semver_fields.SpecField(verbose_name='my spec')
... |
Use built-in Flask server when debugging - websockets won't work. | #!/usr/bin/env python
from flask import Flask
import views
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
met... | #!/usr/bin/env python
from gevent.pywsgi import WSGIServer
from flask import Flask
import views
from handler import PatchedWebSocketHandler
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add... |
Implement __getattr__ to reduce code | class SpaceAge(object):
YEARS = {"on_earth": 1,
"on_mercury": 0.2408467,
"on_venus": 0.61519726,
"on_mars": 1.8808158,
"on_jupiter": 11.862615,
"on_saturn": 29.447498,
"on_uranus": 84.016846,
"on_neptune": 164.79132}
def... | class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def on_earth(self):
return round(self.years, 2)
def on_mercury(self):
return round(self.years/0.2408467, 2)
def on_venus(self):
... |
Reset list view after showing panel
Signed-off-by: Max Brunsfeld <78036c9b69b887700d5846f26a788d53b201ffbb@gmail.com> | 'use babel';
import LineEndingListView from './line-ending-list-view';
let lineEndingTile = null;
export function activate() {
}
export function consumeStatusBar(statusBar) {
lineEndingTile = document.createElement('a');
lineEndingTile.className = "line-ending-tile";
atom.workspace.observeActivePaneItem((ite... | 'use babel';
import LineEndingListView from './line-ending-list-view';
let lineEndingTile = null;
export function activate() {
atom.workspace.observeActivePaneItem((item) => {
let ending = getLineEnding(item);
if (lineEndingTile) lineEndingTile.textContent = ending;
});
}
export function consumeStatusBa... |
Upgrade tangled 0.1a7 => 0.1a9 | from setuptools import setup
setup(
name='tangled.sqlalchemy',
version='0.1a4.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='W... | from setuptools import setup
setup(
name='tangled.sqlalchemy',
version='0.1a4.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='W... |
Add query params to demo | import Ember from 'ember';
import burgerMenu from 'ember-burger-menu';
const {
inject,
computed
} = Ember;
export default Ember.Controller.extend({
queryParams: [
'animation',
'itemAnimation',
'position',
'translucentOverlay',
'dismissOnClick',
'dismissOnEsc'
],
application: inject.... | import Ember from 'ember';
import burgerMenu from 'ember-burger-menu';
const {
inject,
computed
} = Ember;
export default Ember.Controller.extend({
application: inject.controller(),
burgerMenu,
translucentOverlay: computed.alias('application.translucentOverlay'),
dismissOnClick: computed.alias('applicati... |
Reset version number for maintenance branch. | """Spherical harmonic vector wind analysis."""
# Copyright (c) 2012-2013 Andrew Dawson
#
# 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 ... | """Spherical harmonic vector wind analysis."""
# Copyright (c) 2012-2013 Andrew Dawson
#
# 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 ... |
Add debugging to find issue. | import traceback
from flask import render_template, redirect, jsonify, session
from flask_login import login_user
from app.main import main
from app.main.dao import users_dao, verify_codes_dao
from app.main.forms import TwoFactorForm
@main.route("/two-factor", methods=['GET'])
def render_two_factor():
return re... | from flask import render_template, redirect, jsonify, session
from flask_login import login_user
from app.main import main
from app.main.dao import users_dao, verify_codes_dao
from app.main.forms import TwoFactorForm
@main.route("/two-factor", methods=['GET'])
def render_two_factor():
return render_template('vie... |
Fix the ASAN build by xfailing test_decimal when ASAN_OPTIONS is set.
Adding decimal columns crashes an ASAN built impalad. This change skips the test.
Change-Id: Ic94055a3f0d00f89354177de18bc27d2f4cecec2
Reviewed-on: http://gerrit.ent.cloudera.com:8080/2532
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485... | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
... | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted tests for decimal type.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestDecimalQueries(ImpalaTestSuite):
BATCH_SIZES = [0, 1]
... |
Increase timeout in crash/worker test for travis |
'use strict';
var path = require('path');
var expect = require('thehelp-test').expect;
var supertest = require('supertest');
var util = require('./util');
describe('top-level crash in worker', function() {
var agent, child;
before(function(done) {
agent = supertest.agent('http://localhost:3000');
chil... |
'use strict';
var path = require('path');
var expect = require('thehelp-test').expect;
var supertest = require('supertest');
var util = require('./util');
describe('top-level crash in worker', function() {
var agent, child;
before(function(done) {
agent = supertest.agent('http://localhost:3000');
chil... |
Use evt.coordinate instead of evt.getCoordinate() | goog.require('ol.Map');
goog.require('ol.RendererHint');
goog.require('ol.View2D');
goog.require('ol.layer.Tile');
goog.require('ol.source.TileWMS');
var wmsSource = new ol.source.TileWMS({
url: 'http://demo.opengeo.org/geoserver/wms',
params: {'LAYERS': 'ne:ne'}
});
var wmsLayer = new ol.layer.Tile({
source: ... | goog.require('ol.Map');
goog.require('ol.RendererHint');
goog.require('ol.View2D');
goog.require('ol.layer.Tile');
goog.require('ol.source.TileWMS');
var wmsSource = new ol.source.TileWMS({
url: 'http://demo.opengeo.org/geoserver/wms',
params: {'LAYERS': 'ne:ne'}
});
var wmsLayer = new ol.layer.Tile({
source: ... |
Use practicalmeteor:chai and not spacejamio:chai | Package.describe({
name: "practicalmeteor:google-translate",
summary: "Server side synchronous google translate.",
git: "https://github.com/practicalmeteor/meteor-google-translate.git",
version: '0.9.0-rc0'
});
Npm.depends({'googleapis': '1.0.21'});
Package.onUse(function (api) {
api.versionsFrom('0.9.3');
... | Package.describe({
name: "practicalmeteor:google-translate",
summary: "Server side synchronous google translate.",
git: "https://github.com/practicalmeteor/meteor-google-translate.git",
version: '0.9.0-rc0'
});
Npm.depends({'googleapis': '1.0.21'});
Package.onUse(function (api) {
api.versionsFrom('0.9.3');
... |
Use relative url for loading documentation.json. | var Documentation = require('./model/Documentation');
var Component = require('../ui/Component');
var DocumentationReader = require('./DocumentationReader');
var $$ = Component.$$;
var $ = require('../util/jquery');
var _ = require('../util/helpers');
var importDocumentation = require('./model/importDocumentation');
v... | var Documentation = require('./model/Documentation');
var Component = require('../ui/Component');
var DocumentationReader = require('./DocumentationReader');
var $$ = Component.$$;
var $ = require('../util/jquery');
var _ = require('../util/helpers');
var importDocumentation = require('./model/importDocumentation');
v... |
Allow setting a flag for writable / non writable folders | package retrobox.utils;
import java.io.File;
import xtvapps.core.Utils;
public class MountPoint {
File dir;
String description;
String filesystem = "unknown";
boolean isWritable = false;
public MountPoint(String path) {
this.dir = new File(path);
}
public MountPoint(File dir) {
this.dir = dir;
}
pu... | package retrobox.utils;
import java.io.File;
import xtvapps.core.Utils;
public class MountPoint {
File dir;
String description;
String filesystem = "unknown";
public MountPoint(String path) {
this.dir = new File(path);
}
public MountPoint(File dir) {
this.dir = dir;
}
public MountPoint() {
}
publ... |
Increase integration cli test memory
Signed-off-by: Euan <82ce0a5f500076a0414f27984d8e19adc458729b@amazon.com> | // +build !windows
package main
import (
"github.com/docker/docker/pkg/integration/checker"
"github.com/go-check/check"
)
func (s *DockerSuite) TestInspectOomKilledTrue(c *check.C) {
testRequires(c, DaemonIsLinux, memoryLimitSupport)
name := "testoomkilled"
_, exitCode, _ := dockerCmdWithError("run", "--name",... | // +build !windows
package main
import (
"github.com/docker/docker/pkg/integration/checker"
"github.com/go-check/check"
)
func (s *DockerSuite) TestInspectOomKilledTrue(c *check.C) {
testRequires(c, DaemonIsLinux, memoryLimitSupport)
name := "testoomkilled"
_, exitCode, _ := dockerCmdWithError("run", "--name",... |
Add API versioning for House endpoints. | 'use strict'
var passport = require('passport')
module.exports = function(app) {
var house = require('../controllers/houseController')
var versioning = require('../config/versioning')
app.route(versioning.url + '/houses')
.get(house.list_all_houses)
.post(passport.authenticate('jwt', {
session:... | 'use strict'
var passport = require('passport')
module.exports = function(app) {
var house = require('../controllers/houseController')
app.route('/houses')
.get(house.list_all_houses)
.post(passport.authenticate('jwt', {
session: false
}),
function(req, res) {
var token = getT... |
Change popup content to user input values | /**
@module ember-flexberry-gis
*/
import Ember from 'ember';
import BaseMapCommand from './base';
/**
Go to map-command.
Moves map to a given geographic point.
@class GoToMapCommand
@extends BaseMapCommand
*/
export default BaseMapCommand.extend({
/**
Executes map-command.
@method execute
*/
... | /**
@module ember-flexberry-gis
*/
import Ember from 'ember';
import BaseMapCommand from './base';
/**
Go to map-command.
Moves map to a given geographic point.
@class GoToMapCommand
@extends BaseMapCommand
*/
export default BaseMapCommand.extend({
/**
Executes map-command.
@method execute
*/
... |
Fix dependencies for Django 1.7
Older versions of django-mptt will generate warnings | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='blanc-basic-pages',
version='0.2.1',
description='Blanc Basic Pages for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/blanc-basic-pages',
maintainer='Alex Tomkins',
maintai... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='blanc-basic-pages',
version='0.2.1',
description='Blanc Basic Pages for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/blanc-basic-pages',
maintainer='Alex Tomkins',
maintai... |
Update script to store the basename instead of the complete path | #!/usr/bin/env python
import click
import os
import codecs
import json
import pandas as pd
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_file', nargs=1, type=click.Path())
def nerstats(input_files, output_file):
output_dir = os.path.dirname(output_... | #!/usr/bin/env python
import click
import os
import codecs
import json
import pandas as pd
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_file', nargs=1, type=click.Path())
def nerstats(input_files, output_file):
output_dir = os.path.dirname(output_... |
Move ID & HASH & CARD in CardDetail classes
from Controller to Model |
// ----------------------------------------------------------------
// CardDetail Class
// ----------------------------------------------------------------
// Model
class CardDetailModel extends CommonModel {
constructor({
name
} = {}) {
super({
name: name
});
this.NAME = 'Card Detail ... |
// ----------------------------------------------------------------
// CardDetail Class
// ----------------------------------------------------------------
// Model
class CardDetailModel extends CommonModel {
constructor({
name
} = {}) {
super({
name: name
});
this.NAME = 'Card Detail ... |
Use clone method for Stripes objects | import React from 'react';
import Route from 'react-router-dom/Route';
import { connectFor } from '@folio/stripes-connect';
import { modules } from 'stripes-loader'; // eslint-disable-line
import AddContext from './AddContext';
if (!Array.isArray(modules.app) && modules.length < 0) {
throw new Error('At least one mo... | import React from 'react';
import Route from 'react-router-dom/Route';
import { connectFor } from '@folio/stripes-connect';
import { modules } from 'stripes-loader'; // eslint-disable-line
import AddContext from './AddContext';
if (!Array.isArray(modules.app) && modules.length < 0) {
throw new Error('At least one mo... |
Add check for valid location | <?php
namespace PoGoPHP\Location;
use GuzzleHttp\Exception\GuzzleException;
use PoGoPHP\Http\HttpClientAwareInterface;
use PoGoPHP\Http\HttpClientAwareTrait;
class LocationSearcher implements HttpClientAwareInterface
{
use HttpClientAwareTrait;
public static $maps_url = 'https://maps.google.com/maps/api/geo... | <?php
namespace PoGoPHP\Location;
use GuzzleHttp\Exception\GuzzleException;
use PoGoPHP\Http\HttpClientAwareInterface;
use PoGoPHP\Http\HttpClientAwareTrait;
class LocationSearcher implements HttpClientAwareInterface
{
use HttpClientAwareTrait;
public static $maps_url = 'https://maps.google.com/maps/api/geo... |
Remove a needless static reference
The static method has been imported, no need to explicitly name the
class. | package io.dropwizard.logging;
import ch.qos.logback.classic.pattern.RootCauseFirstThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;
import java.util.regex.Pattern;
import static io.dropwizard.logging.PrefixedThrowableProxyConverter.*;
/**
* A {@link RootCauseFirstThrowableProxyConverter}... | package io.dropwizard.logging;
import ch.qos.logback.classic.pattern.RootCauseFirstThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;
import java.util.regex.Pattern;
import static io.dropwizard.logging.PrefixedThrowableProxyConverter.*;
/**
* A {@link RootCauseFirstThrowableProxyConverter}... |
Replace custom author tags with @author Apache Software Foundation.
git-svn-id: 774b6be6af7f353471b728afb213ebe1be89b277@130378 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* 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... | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* 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... |
Make provider-carousel test account for whitespace | import {moduleForComponent, test} from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import Ember from 'ember';
moduleForComponent('provider-carousel', 'Integration | Component | provider carousel', {
integration: true
});
test('it renders', function (assert) {
// Set any properties with this.s... | import {moduleForComponent, skip} from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import Ember from 'ember';
moduleForComponent('provider-carousel', 'Integration | Component | provider carousel', {
integration: true
});
skip('it renders', function (assert) {
// Set any properties with this.s... |
Fix the test; solution found by Christian Heimes. Thanks! | #! -*- coding: koi8-r -*-
# This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
"".encode("utf-8"),
b'\xd0\x9f\xd0\xb8\x... | #! -*- coding: koi8-r -*-
# This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
"".encode("utf-8"),
'\xd0\x9f\xd0\xb8\xd... |
Initialize osprofiler in WSGI application
This patch adds missing initialization of OSProfiler
when Cinder API is running as WSGI application.
Change-Id: Ifaffa2d58eeadf5d47fafbdde5538d26bcd346a6 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... |
Add pointerLock() custom element support.
Increase readability. | import THREE from 'three';
export default function pointerLock( controls, element = document.body ) {
const hasPointerLock = (
'pointerLockElement' in document ||
'mozPointerLockElement' in document ||
'webkitPointerLockElement' in document
);
if ( !hasPointerLock ) {
return;
}
const dispat... | import THREE from 'three';
export default function pointerLock( controls ) {
const hasPointerLock = 'pointerLockElement' in document ||
'mozPointerLockElement' in document ||
'webkitPointerLockElement' in document;
if ( !hasPointerLock ) {
return;
}
const element = document.body;
const dispatch... |
Enforce compatibility of the `undefined` and `default` setting for navbar color scheme. This makes the demo work for the default, but the inverse still doesn't work because of different scheme names. | import { computed } from '@ember/object';
import Navbar from 'ember-bootstrap/components/base/bs-navbar';
export default Navbar.extend({
classNameBindings: ['breakpointClass', 'backgroundClass'],
type: computed('appliedType', {
get() {
return this.get('appliedType');
},
set(key, value) { // esl... | import { computed } from '@ember/object';
import Navbar from 'ember-bootstrap/components/base/bs-navbar';
export default Navbar.extend({
classNameBindings: ['breakpointClass', 'backgroundClass'],
type: 'light',
/**
* Defines the responsive toggle breakpoint size. Options are the standard
* two character ... |
Update to use Laravel Console Menu version 3.x | <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Components\Menu;
use LaravelZ... | <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Components\Menu;
use LaravelZ... |
Add arguments validations:
1. Enable excluding secondaryBroadcstingUrl.
2. Validate https playback url was provided before setting its value. | <?php
require_once(dirname(__FILE__).'/../bootstrap.php');
if ($argc < 4)
die ("Required parameters not received. Run script in the following format: php setPartnerBroadcastingUrls.php {partnerId} {parimary broadcast URL} {HTTP playback URL} [{secondary broadcast URL}] [{HTTPS playback URL}]");
$partnerId = $argv[1]... | <?php
require_once(dirname(__FILE__).'/../bootstrap.php');
if ($argc < 4)
die ("Required parameters not received. Run script in the following format: php setPartnerBroadcastingUrls.php {partnerId} {parimary broadcast URL} {HTTP playback URL} [{secondary broadcast URL}] [{HTTPS playback URL}]");
$partnerId = $argv[1]... |
Add home link in docs. [ci skip] | <?php
// cleanup requested file path
$filePath = isset($_GET['f']) ? $_GET['f'] : 'lodash';
$filePath = preg_replace('#(\.*[\/])+#', '', $filePath);
$filePath .= preg_match('/\.[a-z]+$/', $filePath) ? '' : '.js';
// output filename
if (isset($_GET['o'])) {
$outputName = $_GET['o'];
} else if (isset(... | <?php
// cleanup requested file path
$filePath = isset($_GET['f']) ? $_GET['f'] : 'lodash';
$filePath = preg_replace('#(\.*[\/])+#', '', $filePath);
$filePath .= preg_match('/\.[a-z]+$/', $filePath) ? '' : '.js';
// output filename
if (isset($_GET['o'])) {
$outputName = $_GET['o'];
} else if (isset(... |
Exit with nonzero when qq strings are missing
Change-Id: Ife0f114dbe48faa445397aa7a94f74de2309d117 | #!/usr/bin/env python
import os
import sys
import xml.etree.ElementTree as ET
RES_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/src/main/res"))
EN_STRINGS = os.path.join(RES_FOLDER, "values/strings.xml")
QQ_STRINGS = os.path.join(RES_FOLDER, "values-qq/strings.xml")
# Get ElementTree contai... | #!/usr/bin/env python
import os
import xml.etree.ElementTree as ET
RES_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/src/main/res"))
EN_STRINGS = os.path.join(RES_FOLDER, "values/strings.xml")
QQ_STRINGS = os.path.join(RES_FOLDER, "values-qq/strings.xml")
# Get ElementTree containing all me... |
refactor: Move program option object into its own function | "use strict";
var program = require('commander');
var path = require('path');
var appDir = path.resolve(__dirname, '..', 'app');
var newCommand = require('./commands/new')(appDir);
var pkg = require(path.resolve(__dirname, '..', 'package.json'));
module.exports = function() {
setProgramBaseSettings();
setNe... | "use strict";
var program = require('commander');
var path = require('path');
var appDir = path.resolve(__dirname, '..', 'app');
var newCommand = require('./commands/new')(appDir);
var pkg = require(path.resolve(__dirname, '..', 'package.json'));
module.exports = function() {
setProgramBaseSettings();
setNe... |
Raise allowed difference for RandomForest | import numpy as np
from nose.tools import assert_true
from sklearn.ensemble import RandomForestClassifier
from splearn.ensemble import SparkRandomForestClassifier
from splearn.utils.testing import SplearnTestCase
from splearn.utils.validation import check_rdd_dtype
class TestSparkRandomForest(SplearnTestCase):
d... | import numpy as np
from nose.tools import assert_true
from sklearn.ensemble import RandomForestClassifier
from splearn.ensemble import SparkRandomForestClassifier
from splearn.utils.testing import SplearnTestCase
from splearn.utils.validation import check_rdd_dtype
class TestSparkRandomForest(SplearnTestCase):
d... |
Set max threads for MKL. | import logging, gensim, bz2
import mkl
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
mkl.set_num_threads(8)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2... | import logging, gensim, bz2
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2word = gensim.corpora.Dictionary.l... |
Add links to idvidual inventory scenes | import React from 'react'
import InventoryContainer from '../containers/InventoryContainer'
import ShadowBox from '../Components/ShadowBox'
import FlexDiv from '../Components/FlexDiv'
const InventoryBox = ShadowBox.extend`
width:100%;
margin:10px;
`
const InventoryDiv = FlexDiv.extend`
width:50%;
margin-top: ... | import React from 'react'
import InventoryContainer from '../containers/InventoryContainer'
import ShadowBox from '../Components/ShadowBox'
import FlexDiv from '../Components/FlexDiv'
const InventoryBox = ShadowBox.extend`
width:100%;
margin:10px;
`
const InventoryDiv = FlexDiv.extend`
width:50%;
margin-top: ... |
Add / Fouc out (on link clic) | console.log('main.js');
// Load Css async w LoadCSS & +1 polyfill / https://www.npmjs.com/package/fg-loadcss?notice=MIvGLZ2qXNAEF8AM1kvyFWL8p-1MwaU7UpJd8jcG
var stylesheet = loadCSS( "styles/main.css" );
onloadCSS( stylesheet, function() {
console.log( "LoadCSS > Stylesheet has loaded. Yay !" );
// + No Fouc ... | console.log('main.js');
// Load Css async w LoadCSS & +1 polyfill / https://www.npmjs.com/package/fg-loadcss?notice=MIvGLZ2qXNAEF8AM1kvyFWL8p-1MwaU7UpJd8jcG
var stylesheet = loadCSS( "styles/main.css" );
onloadCSS( stylesheet, function() {
console.log( "LoadCSS > Stylesheet has loaded. Yay !" );
$('.no-fouc')... |
Use SyncEmailMixin for account mails | import re
from allauth.account.adapter import DefaultAccountAdapter
from django.conf import settings
from adhocracy4.emails.mixins import SyncEmailMixin
from apps.contrib.emails import Email
from apps.users import USERNAME_INVALID_MESSAGE
from apps.users import USERNAME_REGEX
class UserAccountEmail(Email, SyncEmail... | import re
from allauth.account.adapter import DefaultAccountAdapter
from django.conf import settings
from apps.contrib.emails import Email
from apps.users import USERNAME_INVALID_MESSAGE
from apps.users import USERNAME_REGEX
class UserAccountEmail(Email):
def get_receivers(self):
return [self.object]
... |
Fix super with this call, was missing the status code | package org.iotbricks.core.binding.proton;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton.message.Message;
import or... | package org.iotbricks.core.binding.proton;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton.message.Message;
import or... |
Add checks for null and streaming files | var es = require('event-stream');
var stylus = require('stylus');
var gutil = require('gulp-util');
var path = require('path');
module.exports = function (options) {
var opts = options ? options : {};
var paths = opts.paths || [];
function stylusstream (file, cb) {
// file is on object passed in by gulp
... | var es = require('event-stream');
var stylus = require('stylus');
var gutil = require('gulp-util');
var path = require('path');
module.exports = function (options) {
var opts = options ? options : {};
var paths = opts.paths || [];
function stylusstream (file, cb) {
// file is on object passed in by gulp
... |
Allow at least 5 descriptors if detection goes wrong | 'use strict';
var toUint = require('es5-ext/lib/Number/to-uint')
, count = 0, limit = Infinity, callbacks = [];
exports.open = function () {
++count;
};
exports.close = function () {
if ((--count < limit) && callbacks.length) {
do {
callbacks.shift()();
} while ((count < limit) && callbacks.length);
}
};... | 'use strict';
var toUint = require('es5-ext/lib/Number/to-uint')
, count = 0, limit = Infinity, callbacks = [];
exports.open = function () {
++count;
};
exports.close = function () {
if ((--count < limit) && callbacks.length) {
do {
callbacks.shift()();
} while ((count < limit) && callbacks.length);
}
};... |
Add period at end of plug-in description
All other plug-in descriptions have that too. So for consistency.
Contributes to issue CURA-1190. | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeWriter
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "GCode Writer"),
"author"... | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeWriter
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "GCode Writer"),
"author"... |
Use a decorator to wrap the actual checks | import os
import uuid
import time
import json
from flask import Flask
app = Flask(__name__)
app.debug = True
def check(endpoint):
def actual_decorator(func):
def actual_check():
start_time = time.time()
try:
ret = func()
except:
# FIXME... | import os
import uuid
import time
import json
from flask import Flask
app = Flask(__name__)
app.debug = True
def check(endpoint):
def actual_check(function):
start_time = time.time()
ret = function()
total_time = time.time() - start_time
return json.dumps({
'status': r... |
Simplify regex in url matching | from django.conf.urls import url
from modelview import views
from oeplatform import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^(?P<sheettype>[\w\d_]+)s/$', views.listsheets, {}, name='modellist'),
url(r'^overview/$', views.overview, {}),
url(r'^(?P<sheettype>[\w\d_]+)s/add/... | from django.conf.urls import url
from modelview import views
from oeplatform import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^(?P<sheettype>[\w\d_]+)s/$', views.listsheets, {}, name='modellist'),
url(r'^overview/$', views.overview, {}),
url(r'^(?P<sheettype>[\w\d_]+)s/add/... |
Use argparse helper to add default values |
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.ArgumentParser(
prog='alertad',
description='Alerta server (for development purposes only)',
formatter_class=argparse.ArgumentDefaul... |
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.ArgumentParser(
prog='alertad',
description='Alerta server (for development purposes only)'
)
parser.add_argument(
'-P',
... |
Remove unnecessary Object declaration in type parameter
Change-Id: I466a2d43e9f9d3effd3860761a97855110b71781 | /*
* 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... |
Allow specifying test.py flags in 'inv test' | from os import mkdir
from os.path import join
from shutil import rmtree, copytree
from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish
# Until we move to spec-based testing
@task
def test(ctx, coverage=False, flags=""):
if "--verbose" not i... | from os import mkdir
from os.path import join
from shutil import rmtree, copytree
from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish
# Until we move to spec-based testing
@task
def test(ctx, coverage=False):
runner = "python"
if cover... |
Switch to using dbSession in db.py instead of baseInterface.py
This is another file that should have been included in PR #272,
where we transitioned all existing non-Flask db access to a
db connection using the new contextmanager. Originally missed
this one because it *is* using a contextmanager, but it's using
one in... | import logging
import sys
from dataactcore.interfaces.db import databaseSession
from dataactbroker.fsrs import (
configValid, fetchAndReplaceBatch, GRANT, PROCUREMENT)
logger = logging.getLogger(__name__)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
with databaseSession() as sess:... | import logging
import sys
from dataactcore.models.baseInterface import databaseSession
from dataactbroker.fsrs import (
configValid, fetchAndReplaceBatch, GRANT, PROCUREMENT)
logger = logging.getLogger(__name__)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
with databaseSession() a... |
ZimForm: Fix mutliple anlage select in create
Now its possible to add multiple anlagen to a zim
when create/edit.
It still gives an error when a anlage which was
part of a zim is not selected (remove anlage from zim) | <?php
/**
* Zim form.
*
* @package openZIM
* @subpackage form
* @author Your name here
* @version SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class ZimForm extends BaseZimForm
{
public function configure()
{
$this->embedRelation('Anlagen');
$this->widgetSc... | <?php
/**
* Zim form.
*
* @package openZIM
* @subpackage form
* @author Your name here
* @version SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class ZimForm extends BaseZimForm
{
public function configure()
{
$this->embedRelation('Anlagen');
$this->widgetSc... |
Fix database for testing environment | from .base_settings import *
import os
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
SECRET_KEY = '$1B&VUf$OdUEfMJXd40qdakA36@%2NE_41Dz9tFs6l=z4v_3P-'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'puzzlehunt_db',
'HOST': '1... | from .base_settings import *
import os
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
SECRET_KEY = '$1B&VUf$OdUEfMJXd40qdakA36@%2NE_41Dz9tFs6l=z4v_3P-'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'puzzlehunt_db',
'HOST': '127.0.... |
Update readme location following rename. | #!/usr/bin/env python
# # coding: utf-8
from setuptools import setup, find_packages
long_description = open('README.rst').read()
setup(
name='captainhook',
description='A collection of git commit hooks',
version='0.8.3',
long_description=long_description,
author='Alex Couper',
author_email='inf... | #!/usr/bin/env python
# # coding: utf-8
from setuptools import setup, find_packages
long_description = open('README.md').read()
setup(
name='captainhook',
description='A collection of git commit hooks',
version='0.8.3',
long_description=long_description,
author='Alex Couper',
author_email='info... |
Add tests for the 404 and 500 error handlers. | from django.core.urlresolvers import reverse
from django.test import Client
from django.test.client import RequestFactory
from projects.models import Project
from innovate import urls
from innovate.views import handle404, handle500
def test_routes():
c = Client()
for pattern in urls.urlpatterns:
resp... | from django.core.urlresolvers import reverse
from django.test import Client
from projects.models import Project
from innovate import urls
def test_routes():
c = Client()
for pattern in urls.urlpatterns:
response = c.get(reverse(pattern.name))
assert response.status_code == 301
assert ... |
Refactor 'one day to counter' (was actually -1, not +1) | <footer class="main-footer">
<div class="pull-right">
@if (isset($selectedDominion) && ($selectedDominion->round->isActive()))
@php
$diff = $selectedDominion->round->start_date->subDays(1)->diff(Carbon\Carbon::now());
$roundDurationInDays = $selectedDominion->round->star... | <footer class="main-footer">
<div class="pull-right">
@if (isset($selectedDominion) && ($selectedDominion->round->isActive()))
@php
$diff = $selectedDominion->round->start_date->diff(Carbon\Carbon::now());
$plusoneday = $diff->days + 1;
$roundDurationInDays =... |
Fix package and method names in comments | // This is a "stub" file. It's a little start on your solution.
// It's not a complete solution though; you have to write some code.
// Package triangle should have a package comment that summarizes what it's about.
// https://golang.org/doc/effective_go.html#commentary
package triangle
// Notice KindFromSides() re... | // This is a "stub" file. It's a little start on your solution.
// It's not a complete solution though; you have to write some code.
// Package twofer should have a package comment that summarizes what it's about.
// https://golang.org/doc/effective_go.html#commentary
package triangle
// Notice KindFromSides() retu... |
Fix location of song info metadata | import { setMetadata } from './actions/metadata'
function _loadMetadata(store) {
const songRequire = require.context('../songs/', true, /(info|song|package)\.json$/)
const metaData = songRequire('./info.json')
metaData.songs = {}
songRequire.keys().forEach(name => {
const parts = name.split('/')
const ... | import { setMetadata } from './actions/metadata'
function _loadMetadata(store) {
const songRequire = require.context('../songs/', true, /(info|song|package)\.json$/)
const metaData = songRequire('./info.json')
metaData.songs = {}
songRequire.keys().forEach(name => {
const parts = name.split('/')
const ... |
Add support for hooking retryablehttp request logs | package azure
import (
"io/ioutil"
"log"
"github.com/hashicorp/go-retryablehttp"
"net/http"
)
type Client struct {
logger *log.Logger
BaseURL string
subscriptionID string
tokenRequester *tokenRequester
httpClient *retryablehttp.Client
}
func NewClient(creds *AzureResourceManagerCredentials) (*... | package azure
import (
"io/ioutil"
"log"
"github.com/hashicorp/go-retryablehttp"
)
type Client struct {
logger *log.Logger
BaseURL string
subscriptionID string
tokenRequester *tokenRequester
httpClient *retryablehttp.Client
}
func NewClient(creds *AzureResourceManagerCredentials) (*Client, erro... |
Change ember app prefix to 'share/' | """share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | """share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... |
Make sure you can not instantiate class | package org.realityforge.replicant.shared.transport;
public final class ReplicantContext
{
/**
* Key used to retrieve an opaque identifier for the session from the ReplicantContextHolder.
* Used to pass data from the servlet to the EJB.
*/
public static final String SESSION_ID_KEY = "SessionID";
/**
... | package org.realityforge.replicant.shared.transport;
public class ReplicantContext
{
/**
* Key used to retrieve an opaque identifier for the session from the ReplicantContextHolder.
* Used to pass data from the servlet to the EJB.
*/
public static final String SESSION_ID_KEY = "SessionID";
/**
* Key ... |
Add form (forgot at commit before) | <div class="single">
<div class="panel warp">
<?php echo formOpen('user/signin'); ?>
<h1>Sign In</h1>
<div>
<?php echo inputText('username', 'Username'); ?>
</div>
<div>
<?php echo inputPassword('password', 'Password'); ?>
</div>
<div>
... | <div class="single">
<div class="panel warp">
<h1>Sign In</h1>
<div>
<?php echo inputText('username', 'Username'); ?>
</div>
<div>
<?php echo inputPassword('password', 'Password'); ?>
</div>
<div>
<?php echo inputCheckbox('keep', 'R... |
Add a separate endpoint for posting postcode lookups to | from django.conf.urls import patterns, include, url
from django.contrib import admin
from candidates.views import (ConstituencyPostcodeFinderView,
ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView)
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', ConstituencyPostcodeFinderV... | from django.conf.urls import patterns, include, url
from django.contrib import admin
from candidates.views import (ConstituencyPostcodeFinderView,
ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView)
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', ConstituencyPostcodeFinderV... |
Modify carousel interval to 7500ms | var main = function() {
$(".btn-projects").click(function() {
$('html,body').animate({
scrollTop: $(".proj").offset().top
},
'slow');
});
$(".btn-about").click(function() {
$('html,body').animate({
scrollTop: $(".bio").offset().top
... | var main = function() {
$(".btn-projects").click(function() {
$('html,body').animate({
scrollTop: $(".proj").offset().top
},
'slow');
});
$(".btn-about").click(function() {
$('html,body').animate({
scrollTop: $(".bio").offset().top
... |
:muscle: Add code for Map() instead of Array() | // Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.
module.exports = function(landscape) {
let actions = new Map();
let tickCount = 0;
let thingToDo = [];
return {
"tick": () =>... | // Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.
module.exports = function(landscape) {
let thingToDo = [];
return {
"tick": () => new Promise(function(resolve, reject) {
t... |
Test with even smaller files | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.envir... | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.envir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.