Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add annoy dependency for Trimap | from setuptools import setup, find_packages
setup(name='rnaseq-lib',
version='1.0a27',
description='Library of convenience functions related to current research',
url='http://github.com/jvivian/rnaseq-lib',
author='John Vivian',
author_email='jtvivian@gmail.com',
license='MIT',
... | from setuptools import setup, find_packages
setup(name='rnaseq-lib',
version='1.0a27',
description='Library of convenience functions related to current research',
url='http://github.com/jvivian/rnaseq-lib',
author='John Vivian',
author_email='jtvivian@gmail.com',
license='MIT',
... |
Fix rosdistro requirements that were broken | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='ros_get',
package_dir={'': 'src'}, # tell distutils packages are under src
packages=find_packages('src'), # include all packages under src
install_requires=[
'argcomplete',
'catkin_pkg',
'catkin_too... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='ros_get',
package_dir={'': 'src'}, # tell distutils packages are under src
packages=find_packages('src'), # include all packages under src
install_requires=[
'argcomplete',
'catkin_pkg',
'catkin_too... |
Fix repo URL after rename | from distutils.core import setup
setup(
name='firebase-token-generator',
version='1.2',
author='Greg Soltis',
author_email='greg@firebase.com',
py_modules=['firebase_token_generator'],
license='LICENSE',
url='https://github.com/firebase/PyFirebaseTokenGenerator',
description='A utility ... | from distutils.core import setup
setup(
name='firebase-token-generator',
version='1.2',
author='Greg Soltis',
author_email='greg@firebase.com',
py_modules=['firebase_token_generator'],
license='LICENSE',
url='https://github.com/firebase/firebase-token-generator-python',
description='A u... |
Bump up version to 0.3 | # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
setup(
name = 'djiki',
version = '0.2',
description = 'Django Wiki Application',
url = 'https://github.com/emesik/djiki/',
long_description = open('README.rst').read(),
author = 'Michał Sałaban',
author_email = 'michal... | # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
setup(
name = 'djiki',
version = '0.3',
description = 'Django Wiki Application',
url = 'https://github.com/emesik/djiki/',
long_description = open('README.rst').read(),
author = 'Michał Sałaban',
author_email = 'michal... |
Use importlib from Python instead from Django | # -*- coding: utf-8 -*-
from axes.models import AccessAttempt
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.importlib import import_module
DEFAULT_ACTION = 'axes_login_actions.actions.email.notify'
ACTIONS = getattr(settings, 'A... | # -*- coding: utf-8 -*-
from axes.models import AccessAttempt
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from importlib import import_module
DEFAULT_ACTION = 'axes_login_actions.actions.email.notify'
ACTIONS = getattr(settings, 'AXES_LOGIN_ACT... |
Add compatibility with Python 3.3. | import pynmea2
from tempfile import TemporaryFile
def test_stream():
data = "$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D\n"
sr = pynmea2.NMEAStreamReader()
assert len(sr.next('')) == 0
assert len(sr.next(data)) == 1
assert len(sr.next(data)) == 1
sr =... | from __future__ import print_function
import pynmea2
from tempfile import TemporaryFile
def test_stream():
data = "$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D\n"
sr = pynmea2.NMEAStreamReader()
assert len(sr.next('')) == 0
assert len(sr.next(data)) == 1
ass... |
Fix user selection for speaker add | from django.contrib import admin
from markedit.admin import MarkEditAdmin
from symposion.speakers.models import Speaker
class SpeakerAdmin(MarkEditAdmin):
list_display = ["name", "email", "created", "twitter_username"]
search_fields = ["name", "twitter_username"]
class MarkEdit:
fields = ['biog... | from django.contrib import admin
from markedit.admin import MarkEditAdmin
from symposion.speakers.models import Speaker
class SpeakerAdmin(MarkEditAdmin):
list_display = ["name", "email", "created", "twitter_username"]
raw_id_fields = ["user"]
search_fields = ["name", "twitter_username"]
class Mark... |
Revert "Added files via upload" | from math import cos,sqrt
import numpy as np
from scipy.optimize import fsolve
def func(p, *data):
x,y = p
i,j,r = data
return ((x+r)*(i-x)+(j-y)*y,(x+r)**2+y**2-r**2)
data = (-7,10,5)
x,y = fsolve(func, [1,1], args=data)
print x,y
d = sqrt((data[0]-x)**2+(data[1]-y)**2)
print d
#make a change | from math import cos,sqrt
import numpy as np
from scipy.optimize import fsolve
def func(p, *data):
x,y = p
i,j,r = data
return ((x+r)*(i-x)+(j-y)*y,(x+r)**2+y**2-r**2)
data = (-7,10,5)
x,y = fsolve(func, [1,1], args=data)
print x,y
d = sqrt((data[0]-x)**2+(data[1]-y)**2)
print d
|
Switch to websocket-client for python3 | from setuptools import setup
import sys
VERSION = "0.2.0"
if sys.version_info >= (3,):
requirements = ["websocket-client-py3"]
else:
requirements = ["websocket-client"]
setup(
name="pusherclient",
version=VERSION,
description="Pusher websocket client for python",
author="Erik Kulyk",
auth... | from setuptools import setup
import sys
VERSION = "0.2.0"
requirements = ["websocket-client"]
setup(
name="pusherclient",
version=VERSION,
description="Pusher websocket client for python",
author="Erik Kulyk",
author_email="e.kulyk@gmail.com",
license="",
url="",
install_requires=requ... |
Add requests as an installation requirement. | from setuptools import setup
setup(name='django-forge',
version=__import__('forge').__version__,
author='Justin Bronn',
author_email='jbronn@gmail.com',
description='A Django implementation of the Puppet Forge web API.',
url='https://github.com/jbronn/django-forge',
download_url='h... | from setuptools import setup
setup(name='django-forge',
version=__import__('forge').__version__,
author='Justin Bronn',
author_email='jbronn@gmail.com',
description='A Django implementation of the Puppet Forge web API.',
url='https://github.com/jbronn/django-forge',
download_url='h... |
Add help_text for time_from and time_until | from django.db import models
from django.core.urlresolvers import reverse
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugFi... | from django.db import models
from django.core.urlresolvers import reverse
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugFi... |
Fix annoying issue with view scrolling | import sublime
import sublime_plugin
class MoveByLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, forward=True, extend=False, number_of_lines=1):
for _ in range(number_of_lines):
self.view.run_command('move', {"by": "lines", "forward": forward, "extend": extend})
| import sublime
import sublime_plugin
class MoveByLinesCommand(sublime_plugin.TextCommand):
def is_selection_in_sight(self):
sel = self.view.sel()[0]
visible_region = self.view.visible_region()
in_sight = visible_region.intersects(sel) or visible_region.contains(sel)
return in_sigh... |
Add Event ordering by datetime | from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
class... | from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
class... |
Fix missing call to display.setup() |
import infrastructure
import display
import traceables
import matrix
import graph
# ==========================================================================
# Setup and register extension
def setup(app):
# Perform import within this function to avoid an import circle.
from sphinxcontrib impor... |
import infrastructure
import display
import traceables
import matrix
import graph
# ==========================================================================
# Setup and register extension
def setup(app):
# Perform import within this function to avoid an import circle.
from sphinxcontrib impor... |
Add debug logging to elm-format | import subprocess
import re
import sublime, sublime_plugin
class ElmFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = "elm-format {} --yes".format(self.view.file_name())
p = subprocess.Popen(command, shell=True)
class ElmFormatOnSave(sublime_plugin.EventListener):
def on_pre_save(self,... | from __future__ import print_function
import subprocess
import re
import sublime, sublime_plugin
class ElmFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = "elm-format {} --yes".format(self.view.file_name())
p = subprocess.Popen(command, stdout=subprocess.PIPE, sterr=subprocess.PIPE, she... |
Remove redundant space on new line | import os, sys
# Production specific settings
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['*']
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Database
# https://docs.djangoproject.com/en/1.11/re... | import os, sys
# Production specific settings
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['*']
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Database
# https://docs.djangoproject.com/en/1.11/re... |
Apply black formatting to migration | # Generated by Django 3.0.8 on 2020-07-12 17:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('places', '0010_auto_20200712_0505'),
]
operations = [
migrations.AlterModelOptions(
name='category',
options={'ordering': ['... | # Generated by Django 3.0.8 on 2020-07-12 17:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("places", "0010_auto_20200712_0505"),
]
operations = [
migrations.AlterModelOptions(
name="category",
options={"ordering": ["... |
Fix get_storage cache to hold separate entries for each experiment key | from copy import deepcopy
from simpleflake import simpleflake
from lab_assistant import conf, utils
__all__ = [
'get_storage',
'store',
'retrieve',
'retrieve_all',
'clear',
]
def get_storage(path=None, name='Experiment', **opts):
if not path:
path = conf.storage['path']
_op... | from copy import deepcopy
from collections import defaultdict
from simpleflake import simpleflake
from lab_assistant import conf, utils
__all__ = [
'get_storage',
'store',
'retrieve',
'retrieve_all',
'clear',
]
def get_storage(path=None, name='Experiment', **opts):
if not path:
pat... |
Add a hack for appending "IF NOT EXISTS" clause to "CREATE INDEX" | __all__ = [
'ensure_only_one_row',
'insert_or_ignore',
]
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), valu... | __all__ = [
'add_if_not_exists_clause',
'ensure_only_one_row',
'insert_or_ignore',
]
from garage import asserts
from sqlalchemy.schema import CreateIndex
def add_if_not_exists_clause(index, engine):
# `sqlalchemy.Index.create()` does not take `checkfirst` for reasons
# that I am unaware of, and ... |
Update regex to include filename capture group. | import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
... | import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
... |
Add unauthorize to service template | from flask import Blueprint, render_template, flash
from flask_login import login_required, current_user
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
flash('Only blue teams can access servi... | from flask import Blueprint, render_template, url_for, redirect
from flask_login import login_required, current_user
from scoring_engine.models.service import Service
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user... |
Remove TODO's converted to issues | from collections import Counter
from math import log2
from digestive import Sink
# TODO: stash intermediate histograms in multiple Counters?
# TODO: output as a spark
# TODO: output as plot
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter =... | from collections import Counter
from math import log2
from digestive import Sink
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
... |
Allow set scroll timeout param | from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, requ... | from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, requ... |
Make sure we close the socket | import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=Tru... | import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=Tru... |
Remove unused social auth keys | # Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials ... | # Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials ... |
Create initial counts outside the test class | import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
class CachedCountTechCase(TestCase):
def setUp(self):
initial_counts = (
{
'count_type': 'constituency',
'name':... | import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
def create_initial_counts(extra=()):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
... |
Check for error if use_3D and non-interactive | import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
ass... | import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
ass... |
Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text | from bot.action.util.textformat import FormattedText
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedText().bold("Usage").newline()
if type(args) is list:
text.concat(FormattedText().newline().join((cls.... | from bot.action.util.textformat import FormattedText, FormattedTextFactory
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
te... |
Fix out of bounds symbol generation | from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origi... | from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origi... |
Add tests for the Field class. | # -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import Field, ValidationError, Integer, Unicode
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
sel... | # -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import (
ValidationError, Field, FieldDescriptor, Integer, Unicode, ForeignKey,
ForeignKeyDescriptor)
class TestBaseField(TestCase):
def test_validate(self):
f = Fie... |
Fix TypeError: _set_bank_data() takes at least 7 arguments (7 given) | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... |
Switch luci-py tests to use gcloud SDK. | # Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = ... | # Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = ... |
Set location of source code to version tag. |
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/master.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import s... |
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/v0.1.0.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import s... |
Fix memebership table creation migration | """Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_tab... | """Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_tab... |
Update solution to be consistent |
def my_init(shape, dtype=None):
array = np.zeros(shape=(5,5,3,3))
array[2,2] = np.eye(3)
return array
inp = Input((None, None, 3), dtype="float32")
x = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="same", kernel_initializer=my_init)(inp)
conv_strides_same = Model(inputs=inp, output... | def my_init(shape=(5, 5, 3, 3), dtype=None):
array = np.zeros(shape=shape)
array[2, 2] = np.eye(3)
return array
conv_strides_same = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="same", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
conv_strides_va... |
Add test forecast.io API call | import juliet_module
from pygame import Rect
from time import time
from os import getcwd
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _... | import juliet_module
from pygame import Rect
from time import time
import forecastio
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
__forecast = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
... |
Add important todo for fixing prod | import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
... | import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
# TODO: It doesn't look like getenv is returning anything on prod
# Find an alternative or fi... |
Reduce path to shortest possible from current dir. | #
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "c... | #
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.relpath(os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)))
return os.path.normpath(os.path.join(os.path.dirnam... |
Fix silly prefix change on this branch so that it won't affect master again | # coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ":"
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
... | # coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ","
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
... |
Use an actually random transcript; update stats immediately | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random t... | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Cre... |
Add another empty line between imports and def. | import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
... | import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
... |
Use new util function for getting current people | from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.peopl... | from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from tot.utils import get_current_people
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import Per... |
Implement validation to the username field. | from django import forms
from django.core import validators
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
username = forms.CharField(label='username',
max_length=30,
required=True,) #validators=[self.isValidU... | from django import forms
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
def isValidUserName(username):
try:
User.objects.get(username=username)
except User.DoesNotExist:
return
raise ValidationError('The usern... |
Change ":" in titles to "-" for better SEO | import re
from unicodedata import normalize
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
"""Generates an slightly worse ASCII-only slug."""
result = []
for word in _punct_re.split(text.lower()):
word ... | import re
from unicodedata import normalize
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')
# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
"""Generates an slightly worse ASCII-only slug."""
result = []
for word in _punct_re.split(text.lower()):
word... |
Add a new passing test for invalid week numbers. | import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d ... | import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d ... |
Add dtype of iteration variable | import cgen
from sympy import Symbol
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: Optional, boolean flag... | import cgen
import numpy as np
from sympy import Symbol
__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']
class Dimension(Symbol):
"""Index object that represents a problem dimension and thus
defines a potential iteration space.
:param size: Optional, size of the array dimension.
:param buffered: O... |
Use YAML params instead of XML params | # -*- coding: utf-8 -*-
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be chan... | # -*- coding: utf-8 -*-
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be chan... |
Add missing import for new disk module | # Keep imports sorted alphabetically
import fabtools.arch
import fabtools.cron
import fabtools.deb
import fabtools.files
import fabtools.git
import fabtools.group
import fabtools.mysql
import fabtools.network
import fabtools.nginx
import fabtools.nodejs
import fabtools.openvz
import fabtools.pkg
import fabtools.postgre... | # Keep imports sorted alphabetically
import fabtools.arch
import fabtools.cron
import fabtools.deb
import fabtools.disk
import fabtools.files
import fabtools.git
import fabtools.group
import fabtools.mysql
import fabtools.network
import fabtools.nginx
import fabtools.nodejs
import fabtools.openvz
import fabtools.pkg
im... |
Fix broken requirements file references | import pytest
import os
import shutil
from subprocess import call
from cookiecutter.main import cookiecutter
playbook_setup_commands = ['pip install -r requirements.txt']
playbook_setup_success = 0
playbook_test_command = "molecule test"
playbook_test_success = 0
@pytest.mark.parametrize('role_name', ['tree'])
def ... | import pytest
import os
import shutil
from subprocess import call
from cookiecutter.main import cookiecutter
playbook_setup_commands = ['pip install -r https://raw.githubusercontent.com/nephelaiio/ansible-role-requirements/master/requirements.txt']
playbook_setup_success = 0
playbook_test_command = "molecule test"
pl... |
Add tests for cube and isis encoders. | # -*- coding: utf-8 -*-
import os
import glob
import pvl
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data/')
PDS_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data', 'pds3')
def test_dump():
files = glob.glob(os.path.join(PDS_DATA_DIR, "*.lbl"))
for infile in files:
label = pvl.load(i... | # -*- coding: utf-8 -*-
import os
import glob
import pvl
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data/')
PDS_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data', 'pds3')
def test_dump():
files = glob.glob(os.path.join(PDS_DATA_DIR, "*.lbl"))
for infile in files:
label = pvl.load(i... |
Correct path in South triple definition. | from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
... | from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
... |
Fix provider_location column add for PSQL | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... |
Remove missing import (since b62968cd2666) | """Used by pkg_resources to interpret PEP 345 environment markers."""
from _markerlib.markers import default_environment, compile, interpret, as_function
| """Used by pkg_resources to interpret PEP 345 environment markers."""
from _markerlib.markers import default_environment, compile, interpret
|
Add missing `__str__` to `Repository` model | from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.db import models
@python_2_unicode_compatible
class Repository(models.Model):
"""
Repository
Represents github repository. Name, descr... | from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.db import models
@python_2_unicode_compatible
class Repository(models.Model):
"""
Repository
Represents github repository. Name, descr... |
Fix tests broken by new log configuration option | from __future__ import absolute_import, division, print_function
import pytest
from screen19.screen import Screen19
def test_screen19_command_line_help_does_not_crash():
Screen19().run([])
def test_screen19(dials_data, tmpdir):
data_dir = dials_data("x4wide").strpath
with tmpdir.as_cwd():
Scree... | from __future__ import absolute_import, division, print_function
import pytest
from screen19.screen import Screen19
def test_screen19_command_line_help_does_not_crash():
Screen19().run([])
def test_screen19(dials_data, tmpdir):
data_dir = dials_data("x4wide").strpath
with tmpdir.as_cwd():
Scree... |
Solve 1000 digit fib number | '''
Problem 025
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What... | '''
Problem 025
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What... |
Fix the index dumper code | """This is a script to dump all the corpora on S3 into an index file."""
import boto3
res = s3.list_objects(Bucket='world-modelers', Prefix='indra_models')
s3 = boto3.session.Session(profile_name='wm').client('s3')
corpora = []
for entry in res['Content']:
if entry['Key'].endswith('/statements.json'):
co... | """This is a script to dump all the corpora on S3 into an index file."""
import boto3
if __name__ == '__main__':
s3 = boto3.session.Session(profile_name='wm').client('s3')
res = s3.list_objects(Bucket='world-modelers', Prefix='indra_models')
corpora = []
for entry in res['Content']:
if entry... |
Make `refresh` return self for chaining actions |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... |
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.cli... |
Use or operator in python to tidy up completion building. | import vim, syncrequest, types
class Completion:
def get_completions(self, column, partialWord):
parameters = {}
parameters['column'] = vim.eval(column)
parameters['wordToComplete'] = vim.eval(partialWord)
parameters['WantDocumentationForEveryCompletionResult'] = \
bool(... | import vim, syncrequest, types
class Completion:
def get_completions(self, column, partialWord):
parameters = {}
parameters['column'] = vim.eval(column)
parameters['wordToComplete'] = vim.eval(partialWord)
parameters['WantDocumentationForEveryCompletionResult'] = \
bool(... |
Fix buggy patched QuerySet methods | # This file is part of e-Giełda.
# Copyright (C) 2014 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... | # This file is part of e-Giełda.
# Copyright (C) 2014 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... |
Add a hack for fixing failing tests | import tempfile
import unittest
import os
from server import app
from server.models import db
class BaseTestCase(unittest.TestCase):
def setUp(self):
self.db_fd, self.test_db_path = tempfile.mkstemp('.db')
test_db_uri = 'sqlite:///{}'.format(self.test_db_path)
app.config['SQLALCHEMY_DATAB... | import tempfile
import unittest
import os
from server import app
from server.models import db
class BaseTestCase(unittest.TestCase):
def setUp(self):
self.db_fd, self.test_db_path = tempfile.mkstemp('.db')
# test_db_uri = 'sqlite:///{}'.format(self.test_db_path)
# app.config['SQLALCHEMY_D... |
Add ``remove`` flag to DecoratorScope | from dodo_commands.framework.singleton import Dodo
# Resp: add the current command_name
# to the list of commands decorated by decorator_name.
class DecoratorScope:
def __init__(self, decorator_name):
self.decorators = Dodo.get_config('/ROOT').setdefault(
'decorators', {}).setdefault(decorator... | from dodo_commands.framework.singleton import Dodo
# Resp: add the current command_name
# to the list of commands decorated by decorator_name.
class DecoratorScope:
def __init__(self, decorator_name, remove=False):
self.decorators = Dodo.get_config('/ROOT').setdefault(
'decorators', {}).setdef... |
Add doc comment to nwod lint tests | import npc
import pytest
import os
from tests.util import fixture_dir
def test_has_virtue():
char_file = fixture_dir('linter', 'nwod', 'Has Virtue.nwod')
with open(char_file, 'r') as char_file:
problems = npc.linters.nwod.lint_vice_virtue(char_file.read())
assert 'Missing virtue' not in problem... | """Tests the helpers for linting generic nwod characters"""
import npc
import pytest
import os
from tests.util import fixture_dir
def test_has_virtue():
char_file = fixture_dir('linter', 'nwod', 'Has Virtue.nwod')
with open(char_file, 'r') as char_file:
problems = npc.linters.nwod.lint_vice_virtue(cha... |
Send methods need to return the result | class AbstractObject(object):
def __init__(self):
pass
def send(self, frame, selector_string, arguments, universe):
# Turn the selector string into a selector
selector = universe.symbol_for(selector_string)
invokable = self.get_class(universe).lookup_invokable(selec... | class AbstractObject(object):
def __init__(self):
pass
def send(self, frame, selector_string, arguments, universe):
# Turn the selector string into a selector
selector = universe.symbol_for(selector_string)
invokable = self.get_class(universe).lookup_invokable(selec... |
Make Station.lines into a property | class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
... | class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
... |
Use generic path for ALS on iio device0. | # todo: chargedness of battery
import time
from datetime import datetime
import numpy as np
try:
from whereami.predict import Predicter
p = Predicter()
except ImportError:
p = None
from brightml.battery import get_battery_feature
from brightml.xdisplay import Display
d = Display()
DATE_FORMAT = '%Y-%m-... | # todo: chargedness of battery
import time
from datetime import datetime
import numpy as np
try:
from whereami.predict import Predicter
p = Predicter()
except ImportError:
p = None
from brightml.battery import get_battery_feature
from brightml.xdisplay import Display
d = Display()
DATE_FORMAT = '%Y-%m-... |
Change Challenges model block column to type Integer | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from downstream_node.startup import db
class Files(db.Model):
__tablename__ = 'files'
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
name = db.Column(db.String(512), unique=True)
class Challenges(db.Model):
__tablename__ = 'challenge... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from downstream_node.startup import db
class Files(db.Model):
__tablename__ = 'files'
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
name = db.Column(db.String(512), unique=True)
class Challenges(db.Model):
__tablename__ = 'challenge... |
Send email to Blink gardeners when tree closes. | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import gatekeeper
from master import master_utils
# This is the list of the builder categories and the corresponding critical
# steps. If on... | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import gatekeeper
from master import master_utils
# This is the list of the builder categories and the corresponding critical
# steps. If on... |
Add missing max_length on temporary thumbnail_url migration | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("wagtailembeds", "0007_populate_hash"),
]
operations = [
migrations.AlterField(
model_name="embed",
name="hash",
field=models.CharField(db_index=True, max... | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("wagtailembeds", "0007_populate_hash"),
]
operations = [
migrations.AlterField(
model_name="embed",
name="hash",
field=models.CharField(db_index=True, max... |
Tag v0.5.11 and update copyright year | __title__ = 'kaptan'
__package_name__ = 'kaptan'
__version__ = '0.5.10'
__description__ = 'Configuration manager'
__email__ = 'mail@emreyilmaz.me'
__url__ = 'https://github.com/emre/kaptan'
__author__ = 'Emre Yilmaz'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013-2015 Emre Yilmaz'
| __title__ = 'kaptan'
__package_name__ = 'kaptan'
__version__ = '0.5.11'
__description__ = 'Configuration manager'
__email__ = 'mail@emreyilmaz.me'
__url__ = 'https://github.com/emre/kaptan'
__author__ = 'Emre Yilmaz'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013-2018 Emre Yilmaz'
|
Move to fix column names. | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Seattle_Real_Time_Fire_911_Calls.csv")
| """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
data_columns = ["Date_Text", "Da... |
Delete unnecessary vars attr of Proj | """proj.py: aospy.Proj class for organizing work in single project."""
import time
from .utils import dict_name_keys
class Proj(object):
"""Project parameters: models, regions, directories, etc."""
def __init__(self, name, vars={}, models={}, default_models={}, regions={},
direc_out='', nc_d... | """proj.py: aospy.Proj class for organizing work in single project."""
import time
from .utils import dict_name_keys
class Proj(object):
"""Project parameters: models, regions, directories, etc."""
def __init__(self, name, vars={}, models={}, default_models={}, regions={},
direc_out='', nc_d... |
Revert "Support adding an /etc/host entry for the data proxy, if asked." | # Monkey patches BigQuery client creation to use proxy.
# Import torch before anything else. This is a hacky workaround to an error on dlopen
# reporting a limit on static TLS, tracked in https://github.com/pytorch/pytorch/issues/2575
import torch
import os
_HOST_FILE = "/etc/hosts"
kaggle_proxy_token = os.getenv("K... | # Monkey patches BigQuery client creation to use proxy.
# Import torch before anything else. This is a hacky workaround to an error on dlopen
# reporting a limit on static TLS, tracked in https://github.com/pytorch/pytorch/issues/2575
import torch
import os
kaggle_proxy_token = os.getenv("KAGGLE_DATA_PROXY_TOKEN")
if... |
Make docket export work (done last week, but not committed for some reason). | #!/usr/bin/env python
import sys
import os
import csv
import time
from datetime import datetime
from collections import namedtuple
from pymongo import Connection
pid = os.getpid()
DOCKETS_QUERY = {'scraped': True}
DOCKET_FIELDS = ['docket_id', 'title', 'agency', 'year']
if __name__ == '__main__':
# set up opt... | #!/usr/bin/env python
import sys
import os
import csv
import time
from datetime import datetime
from collections import namedtuple
from pymongo import Connection
pid = os.getpid()
DOCKETS_QUERY = {'scraped': True}
DOCKET_FIELDS = ['docket_id', 'title', 'agency', 'year']
def filter_for_postgres(v):
if v is None... |
Introduce "preview" suffix in the version number |
import os
import sys
from distutils.command.build import build
from setuptools import setup, Command
version_info = {
'name': 'ovirt-engine-sdk-python',
'version': '3.6.0.0',
'description': 'A SDK interface to oVirt Virtualization',
'author': 'Michael Pasternak',
'author_email': 'mpastern@redhat... |
import os
import sys
from distutils.command.build import build
from setuptools import setup, Command
version_info = {
'name': 'ovirt-engine-sdk-python',
'version': '3.6.0.0preview7',
'description': 'A SDK interface to oVirt Virtualization',
'author': 'Michael Pasternak',
'author_email': 'mpaster... |
Add six to test requirements. | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='pygcvs',
version=__import__('pygcvs').__version__,
description='A Python library for reading variable star data from GCVS.',
long_description=read... | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='pygcvs',
version=__import__('pygcvs').__version__,
description='A Python library for reading variable star data from GCVS.',
long_description=read... |
Make jmespath dependency version more lenient. | from setuptools import setup
setup(
name='eliot-tree',
version='15.0.0',
description='Render Eliot logs as an ASCII tree',
author='Jonathan Jacobs',
url='https://github.com/jonathanj/eliottree',
platforms='any',
license='MIT',
py_modules=['eliot_tree'],
entry_points={
# Thes... | from setuptools import setup
setup(
name='eliot-tree',
version='15.0.0',
description='Render Eliot logs as an ASCII tree',
author='Jonathan Jacobs',
url='https://github.com/jonathanj/eliottree',
platforms='any',
license='MIT',
py_modules=['eliot_tree'],
entry_points={
# Thes... |
Include correct documentation URL in error message | import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl ou... | import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl ou... |
Use Properties interface to get Manager properties. | """
Manager interface.
"""
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def... | """
Manager interface.
"""
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
se... |
Add a functional test for mouse grab. |
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class StdoutReportingController(object):
# XXX Make an interface for the controller and verify this fake.
def __ini... |
from pygame import K_q
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class QuittableController(object):
# XXX Make an interface for the controller and verify these... |
Use the example to verify tiled image updates are working | #!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc... | #!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc... |
Add the 401 Unauthorized when no username is detected, thus no user is logged in. This is the most basic form of permissions, where any user can log in and do anything. | from django.shortcuts import render
from django.core import serializers
from inventory.models import Item
from decimal import Decimal
import json
from django.utils import simplejson
# Create your views here.
from django.http import HttpResponse
from inventory.models import Item
def index(request):
if request.meth... | from django.shortcuts import render
from django.core import serializers
from inventory.models import Item
from decimal import Decimal
import json
from django.utils import simplejson
# Create your views here.
from django.http import HttpResponse
from inventory.models import Item
def index(request):
if request.meth... |
Add github + pypi to metadata | __title__ = 'django-docutils'
__package_name__ = 'django_docutils'
__description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.'
__version__ = '0.4.0'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013-2015 Tony Narlock'
| __title__ = 'django-docutils'
__package_name__ = 'django_docutils'
__description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.'
__version__ = '0.4.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/tony/django-docutils'
__pypi__ = 'https://pypi.org/project/django-docutils/'
__email_... |
Use modification, not creation times to determine relative newness. | #
# lib.py: utility functions for the Motebopok handlers
#
"""This file takes the difficulties out of working with directories,
and it also reduces clutter in at least one program."""
import os
def newer(file1, file2):
file1_creation = os.stat(file1).st_mtime
file2_creation = os.stat(file2).st_mtime
retur... | #
# lib.py: utility functions for the Motebopok handlers
#
"""This file takes the difficulties out of working with directories,
and it also reduces clutter in at least one program."""
import os
def newer(file1, file2):
file1_modification = os.stat(file1).st_mtime
file2_modification = os.stat(file2).st_mtime
... |
Add a note concerning FEINCMS_USE_PAGE_ADMIN | # ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
from __future__ import absolute_import
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyCon... | # ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
from __future__ import absolute_import
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyCon... |
Fix wrong module name in error message | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtOpenGLWidgets cla... | # -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtOpenGLWidgets cla... |
Correct __str__ & __repr__ implementations | from django.db import models
from django.conf import settings
class Gender(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
__repr__ = __str__
class UserToPronoun(models.Model):
email_hash = models.CharField(max_length=32)
user = models.ForeignK... | from django.db import models
from django.conf import settings
class Gender(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
__repr__ = lambda self: '<{}>'.format(self.__str__())
class UserToPronoun(models.Model):
email_hash = models.CharField(max_le... |
Remove former methods as models have been merged | # © 2015 Laetitia Gangloff, Acsone SA/NV (http://www.acsone.eu)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AccountInvoice(models.Model):
_inherit = "account.move"
account_wallet_type_id = fields.Many2one(
comodel_name='account.wal... | # © 2015 Laetitia Gangloff, Acsone SA/NV (http://www.acsone.eu)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
account_wallet_type_id = fields.Many2one(
comodel_name='account.wallet... |
Use attr access vs key | import yaml
from builder import utils
def bind_subparser(subparsers):
parser_destroy = subparsers.add_parser('destroy')
parser_destroy.set_defaults(func=destroy)
return parser_destroy
def destroy(args, cloud, tracker):
"""Destroy a previously built environment."""
created_servers = set()
al... | import yaml
from builder import utils
def bind_subparser(subparsers):
parser_destroy = subparsers.add_parser('destroy')
parser_destroy.set_defaults(func=destroy)
return parser_destroy
def destroy(args, cloud, tracker):
"""Destroy a previously built environment."""
created_servers = set()
al... |
Check variable for None value before null string when filtering tail numbers | # Load the on-time parquet file
on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
# The first step is easily expressed as SQL: get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql(
"SELECT DISTINCT Carrier, TailN... | # Load the on-time parquet file
on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
# The first step is easily expressed as SQL: get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql(
"SELECT DISTINCT Carrier, TailN... |
Move some code from serve view to build_asset function | import mimetypes
import posixpath
import urllib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.contrib.staticfiles.views import serve as staticfiles_serve
from django.http import HttpResponse
from .asset_attributes import AssetAttributes
from .assets import Asset,... | import mimetypes
import posixpath
import urllib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.contrib.staticfiles.views import serve as staticfiles_serve
from django.http import HttpResponse
from .asset_attributes import AssetAttributes
from .assets import Asset,... |
Make example use random color scheme | """
This is a very basic usage example of the JSONCodeEdit.
The interface is minimalist, it will open a test file. You can open other
documents by pressing Ctrl+O
"""
import logging
import os
import sys
from pyqode.qt import QtWidgets
from pyqode.json.widgets import JSONCodeEdit
class Window(QtWidgets.QMainWindow):
... | """
This is a very basic usage example of the JSONCodeEdit.
The interface is minimalist, it will open a test file. You can open other
documents by pressing Ctrl+O
"""
import logging
import os
import random
import sys
from pyqode.qt import QtWidgets
from pyqode.core import api, modes
from pyqode.json.widgets import JSO... |
Modify the version numbering guideline. | """The top-level Quantitative Imaging Pipeline module."""
__version__ = '4.5.3'
"""
The one-based major.minor.patch version.
The version numbering scheme loosely follows http://semver.org/.
The major version is incremented when there is an incompatible
public API change. The minor version is incremented when there
is ... | """The top-level Quantitative Imaging Pipeline module."""
__version__ = '4.5.3'
"""
The one-based major.minor.patch version.
The version numbering scheme loosely follows http://semver.org/.
The major version is incremented when a significant feature
set is introduced. The minor version is incremented when there
is a f... |
Use a saner test filename, to work on Windows. | #! /usr/bin/env python
"""Test script for the dumbdbm module
Original by Roger E. Masse
"""
# XXX This test is a disgrace. It doesn't test that it works.
import dumbdbm as dbm
from dumbdbm import error
from test_support import verbose
filename = '/tmp/delete_me'
d = dbm.open(filename, 'c')
d['a'] = 'b'
d['12345... | #! /usr/bin/env python
"""Test script for the dumbdbm module
Original by Roger E. Masse
"""
# XXX This test is a disgrace. It doesn't test that it works.
import dumbdbm as dbm
from dumbdbm import error
from test_support import verbose, TESTFN as filename
d = dbm.open(filename, 'c')
d['a'] = 'b'
d['12345678910'] ... |
Fix issue where idx test uses wrong bytes object | from .. import idx
import os
def test__count_dimensions():
yield check__count_dimensions, 9, 0
yield check__count_dimensions, [1, 2], 1
yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2
yield check__count_dimensions, [[[1,2], [2]]], 3
def check__count_dimensions(lst, i):
assert idx._count_dime... | from .. import idx
import os
def test__count_dimensions():
yield check__count_dimensions, 9, 0
yield check__count_dimensions, [1, 2], 1
yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2
yield check__count_dimensions, [[[1,2], [2]]], 3
def check__count_dimensions(lst, i):
assert idx._count_dime... |
Change url to get stable version number | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from urllib2 import Request, urlopen
from distutils.version import LooseVersion
BRANCH = 'stable'
REPO = 'git@github.com:roramirez/qpanel.git'
URL_STABLE_VERSION = 'https://raw.githubusercontent.com/roramirez/qpan... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from urllib2 import Request, urlopen
from distutils.version import LooseVersion
BRANCH = 'stable'
REPO = 'git@github.com:roramirez/qpanel.git'
URL_STABLE_VERSION = 'https://rodrigoramirez.com/qpanel/version/' + BR... |
Switch to main method in examples | #!/usr/bin/env python
'''
A simple script using sparqllib and rdflib to retrieve a JSON representation
of some information about Barack Obama from dbpedia.
'''
from sparqllib import Query
from rdflib import BNode, Literal
from rdflib.namespace import FOAF
from pprint import pprint
if __name__ == "__main__":
# co... | #!/usr/bin/env python
'''
A simple script using sparqllib and rdflib to retrieve a JSON representation
of some information about Barack Obama from dbpedia.
'''
from sparqllib import Query
from rdflib import BNode, Literal
from rdflib.namespace import FOAF
from pprint import pprint
def main():
# construct the que... |
Update the next version to 4.4.0 | # Author: Prabhu Ramachandran, Gael Varoquaux
# Copyright (c) 2004-2014, Enthought, Inc.
# License: BSD Style.
""" A tool for easy and interactive visualization of data.
Part of the Mayavi project of the Enthought Tool Suite.
"""
__version__ = '5.0.0'
__requires__ = [
'apptools',
'traits',
'traitsui',... | # Author: Prabhu Ramachandran, Gael Varoquaux
# Copyright (c) 2004-2014, Enthought, Inc.
# License: BSD Style.
""" A tool for easy and interactive visualization of data.
Part of the Mayavi project of the Enthought Tool Suite.
"""
__version__ = '4.4.0'
__requires__ = [
'apptools',
'traits',
'traitsui',... |
Remove weird matplot lib defaults thing that did nothing | import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[... | import matplotlib.pyplot as plt
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[(user, streak.get(... |
Make sure the user does not prepend plugin_name with pytest | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import re
import sys
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('pre_gen_project')
PLUGIN_REGEX = r'^[_a-zA-Z][_a-zA-Z0-9]+$'
plugin_name = '{{cookiecutter.plugin_name}}'
if not re.match(PLUGIN_REGEX, plugin_name):
logger.err... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import re
import sys
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('pre_gen_project')
PLUGIN_REGEX = r'^(?!pytest)[_a-zA-Z][_a-zA-Z0-9]+$'
plugin_name = '{{cookiecutter.plugin_name}}'
if not re.match(PLUGIN_REGEX, plugin_name):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.