Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Test multiple values of N and N_prime | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
from builtins import * # NOQA
standard_library.install_aliases() # NOQA
import chainer.functions as F
import chainer.links as L
imp... | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
from builtins import * # NOQA
standard_library.install_aliases() # NOQA
import chainer.functions as F
import chainer.links as L
from... |
Fix import for python 3 | import pyOmicron
import STS
__all__=["pyOmicron","STS"]
__version__ = 0.1
| import pyOmicron
try:
import STS
except:
import pyOmicron.STS
__all__=["pyOmicron","STS"]
__version__ = 0.1
|
Add test for already registered user | import shutil
import pytest
import hug
from overtime_calculator.src import api
from overtime_calculator.src.auth import get_user_folder
def test_register():
user_name = 'test1'
response = hug.test.post(
api,
'/register',
{'username': user_name, 'password': user_name},
)
asser... | import shutil
import pytest
import hug
from overtime_calculator.src import api
from overtime_calculator.src.auth import get_user_folder
EXISTING_USER = 'test1'
UNREGISTERED_USER = 'test2'
def test_registration_of_new_user():
response = hug.test.post(
api,
'/register',
{'username': EXIST... |
Remove '?_popup' from toolbar urls | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
@toolbar_pool.register
class BlogToolbar(CMSToolbar):
def... | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
@toolbar_pool.register
class BlogToolbar(CMSToolbar):
def... |
Set frame only when using 2D | from poliastro.bodies import (
Earth,
Jupiter,
Mars,
Mercury,
Neptune,
Saturn,
Uranus,
Venus,
)
from poliastro.plotting.core import OrbitPlotter2D, OrbitPlotter3D
from poliastro.twobody import Orbit
def plot_solar_system(outer=True, epoch=None, use_3d=False):
"""
Plots the whol... | from typing import Union
from poliastro.bodies import (
Earth,
Jupiter,
Mars,
Mercury,
Neptune,
Saturn,
Uranus,
Venus,
)
from poliastro.plotting.core import OrbitPlotter2D, OrbitPlotter3D
from poliastro.twobody import Orbit
def plot_solar_system(outer=True, epoch=None, use_3d=False):
... |
Fix error messages in get_fans | import typing as tp # NOQA
from chainer import types # NOQA
from chainer import utils
class Initializer(object):
"""Initializes array.
It initializes the given array.
Attributes:
dtype: Data type specifier. It is for type check in ``__call__``
function.
"""
def __init__(... | import typing as tp # NOQA
from chainer import types # NOQA
from chainer import utils
class Initializer(object):
"""Initializes array.
It initializes the given array.
Attributes:
dtype: Data type specifier. It is for type check in ``__call__``
function.
"""
def __init__(... |
Add error handling to reduce dependency on pypi | import xmlrpclib
from socket import gaierror
VERSION_OK = "0.5.13"
try:
pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
VERSION_OK = pypi.package_releases('ricecooker')[0]
except gaierror:
pass
VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date."
VERSION_SOFT_WARNING = "0.5.6"
VERSION_SOFT_W... | import xmlrpclib
from socket import gaierror, error
VERSION_OK = "0.6.0"
try:
pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
VERSION_OK = pypi.package_releases('ricecooker')[0]
except (gaierror, error):
pass
VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date."
VERSION_SOFT_WARNING = "0.5.6"... |
Fix test_email_url() after changes to email templating for sharing emails | import urlparse
from django.test import TestCase, override_settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
mock_request = Mock()
... | import urlparse
from django.test import TestCase, override_settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
mock_request = Mock()
... |
Allow Questions to be copied | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
admin.site.register(Question, ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
def copy_question(modeladmin, request, queryset):
for orig in queryset:
q = Question(question_text="Ko... |
Add newline at end of file. | from unittest import TestCase
import eduid_IdP_html
__author__ = 'ft'
class TestLoad_settings(TestCase):
def test_load_settings(self):
settings = eduid_IdP_html.load_settings()
self.assertTrue(settings['gettext_domain'] is not None) | from unittest import TestCase
import eduid_IdP_html
__author__ = 'ft'
class TestLoad_settings(TestCase):
def test_load_settings(self):
settings = eduid_IdP_html.load_settings()
self.assertTrue(settings['gettext_domain'] is not None)
|
Use page_unpublished signal in frontend cache invalidator | from django.db import models
from django.db.models.signals import post_delete
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.signals import page_published
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def page_published_signal_handler(instance, **kwargs):
pur... | from django.db import models
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.signals import page_published, page_unpublished
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def page_published_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
... |
Allow running jobsteps to be deallocated | from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(sel... | from __future__ import absolute_import, division, unicode_literals
from changes.api.base import APIView
from changes.constants import Status
from changes.config import db
from changes.jobs.sync_job_step import sync_job_step
from changes.models import JobStep
class JobStepDeallocateAPIView(APIView):
def post(sel... |
Rename ResCountry class to CompassionCountry | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <emmanuel.mathier@gmail.com>
#
# The licence is in the fi... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <emmanuel.mathier@gmail.com>
#
# The licence is in the fi... |
Add a ruler to column 72 | # encoding: utf-8
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
... | # encoding: utf-8
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
... |
Fix the syntax for NickServ logins | from module_interface import Module, ModuleType
from message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickSer... | from pyheufybot.module_interface import Module, ModuleType
from pyheufybot.message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attemp... |
Remove now asks for site file to be deleted | #deletes wahji content
import os, shutil, platform
def rem(loc):
os.chdir(loc)
print "deleting content"
"""delete them folder and its contents"""
shutil.rmtree("themes")
"""delete .wahji file"""
os.remove(".wahji")
"""delete 4040.html file"""
os.remove("404.html")
"""delete content folder"""
shutil.... | #deletes wahji content
import os, shutil, platform
def rem(loc):
os.chdir(loc)
site = raw_input("Input site folder: ")
print "Are you sure you want to delete", site, "Y/N: "
confirm = raw_input()
if confirm == "Y" or confirm == "y":
"""delete site folder"""
shutil.rmtree(site)
print "Deleting site"
... |
Add totally untested pools ;) | import abc
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class MapTask(object):
def __init__(self, args, task):
self.args = args
self.task = task
self.pool = Pool(cpu_count())
def iter_input(self, i... | from multiprocessing import Pool as ProcessPool
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class PoolAPI(object):
def map(self, *args,... |
Correct the geographic field name | # -*- coding: utf-8 -*-
""" ``SQLAlchemy`` model definition for the watercourses."""
from geoalchemy import GeometryColumn, GeometryDDL, LineString
from sqlalchemy import Column, Unicode, Integer
from anuket.models import Base
class Watercourse(Base):
""" Table for the watercourses - LINESTRINGS - Lambert93."""
... | # -*- coding: utf-8 -*-
""" ``SQLAlchemy`` model definition for the watercourses."""
from geoalchemy import GeometryColumn, GeometryDDL, LineString
from sqlalchemy import Column, Unicode, Integer
from anuket.models import Base
class Watercourse(Base):
""" Table for the watercourses - LINESTRINGS - Lambert93."""
... |
Handle 5 as a factor | def raindrops(number):
if is_three_a_factor(number):
return "Pling"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
| def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
return number % 5 == 0
|
UPDATE init; add utf-8 encoding | ########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | # -*- coding: utf-8 -*-
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/license... |
Add url to access the index view. | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'purepython.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
from fb.views import index
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', index),
url(r'^admin/', include(admin.site.urls)),
)
|
Add event key to upcoming match notification | import calendar
import datetime
from consts.notification_type import NotificationType
from notifications.base_notification import BaseNotification
class UpcomingMatchNotification(BaseNotification):
def __init__(self, match, event):
self.match = match
self.event = event
self._event_feed =... | import calendar
import datetime
from consts.notification_type import NotificationType
from notifications.base_notification import BaseNotification
class UpcomingMatchNotification(BaseNotification):
def __init__(self, match, event):
self.match = match
self.event = event
self._event_feed =... |
Migrate old passwords without "set_unusable_password" | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database does... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
... |
Maintain top 10k order when writing into file | import csv
import time
import requests
import lxml.html
top10k = {}
for page_index in range(1, 201):
print('Requesting page {}'.format(page_index))
url = 'https://osu.ppy.sh/p/pp/'
payload = {
'm': 0, # osu! standard gamemode
'o': 1, # descending order
'page': page_index,
}
... | import csv
import time
import collections
import requests
import lxml.html
top10k = collections.OrderedDict()
for page_index in range(1, 201):
print('Requesting page {}'.format(page_index))
url = 'https://osu.ppy.sh/p/pp/'
payload = {
'm': 0, # osu! standard gamemode
'o': 1, # descendin... |
Add a method to print a message on the sense hat | class HatManager(object):
def __init__(self, sense):
self.sense = sense
self._pressure = self.sense.get_pressure()
self._temperature = self.sense.get_temperature()
self._humidity = self.sense.get_humidity()
def refresh_state(self):
self._pressure = self.sense.get_press... | class HatManager(object):
def __init__(self, sense):
self.sense = sense
self._pressure = self.sense.get_pressure()
self._temperature = self.sense.get_temperature()
self._humidity = self.sense.get_humidity()
def refresh_state(self):
self._pressure = self.sense.get_press... |
Fix incorrect import after refactor of dariah_static_data models. | from dariah_static_data.models import VCC
from dariah_static_data.management.commands._private_helper import Command as SuperCommand
class Command(SuperCommand):
filename = 'tadirah_vcc.csv'
fieldnames = ['uri', 'name', 'description']
mapping = [('name', 'name', 1), ('uri', 'uri', 1), ('description', 'des... | from dariah_static_data.models import TADIRAHVCC
from dariah_static_data.management.commands._private_helper import Command as SuperCommand
class Command(SuperCommand):
filename = 'tadirah_vcc.csv'
fieldnames = ['uri', 'name', 'description']
mapping = [('name', 'name', 1), ('uri', 'uri', 1), ('description... |
Add Trip and Step ModelForms | from django.contrib.auth.forms import AuthenticationForm
from django import forms
from django.core.validators import MinLengthValidator
from .models import PoolingUser
from users.forms import UserCreationForm
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.EmailInput(attrs={'placehold... | from django.contrib.auth.forms import AuthenticationForm
from django import forms
from django.core.validators import MinLengthValidator
from .models import PoolingUser, Trip, Step
from users.forms import UserCreationForm
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.EmailInput(attrs... |
Test generic creator of jobs. | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa 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... | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa 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... |
Use pyramid.paster instad of paste.deploy | import os
import logging
from paste.deploy import loadapp
from paste.script.util.logging_config import fileConfig
log = logging.getLogger(__name__)
def get_pylons_app(global_conf):
pyramid_config = os.path.realpath(global_conf['__file__'])
dir_, conf = os.path.split(pyramid_config)
config_file = os.path.... | import os
import logging
import pyramid.paster
from paste.script.util.logging_config import fileConfig
log = logging.getLogger(__name__)
def get_pylons_app(global_conf):
pyramid_config = os.path.realpath(global_conf['__file__'])
dir_, conf = os.path.split(pyramid_config)
config_file = os.path.join(dir_, ... |
Fix “python -m skyfield” following ∆T array rename | # -*- coding: utf-8 -*-
import pkg_resources
import skyfield
from skyfield.api import load
from skyfield.functions import load_bundled_npy
def main():
print('Skyfield version: {0}'.format(skyfield.__version__))
print('jplephem version: {0}'.format(version_of('jplephem')))
print('sgp4 version: {0}'.format(... | # -*- coding: utf-8 -*-
import pkg_resources
import numpy as np
import skyfield
from skyfield.api import load
from skyfield.functions import load_bundled_npy
def main():
print('Skyfield version: {0}'.format(skyfield.__version__))
print('jplephem version: {0}'.format(version_of('jplephem')))
print('sgp4 ve... |
Add the function back for now | from uuid import uuid4
class MessageBus:
"""A class that is used behind the scenes to coordinate events and timings of
animations.
"""
def __init__(self):
self.subs = {}
def new_id(self):
"""Use this to get a name to use for your events."""
return str(uuid4())
def re... | import inspect
from uuid import uuid4
def get_parameters(f):
return list(inspect.signature(f).parameters.keys())
class MessageBus:
"""A class that is used behind the scenes to coordinate events and timings of
animations.
"""
def __init__(self):
self.subs = {}
def new_id(self):
... |
Fix import issue due to name changes | """ module SimPEG.EM.NSEM.Utils
Collection of utilities that are usefull for the NSEM problem
NOTE: These utilities are not well test, use with care
"""
from __future__ import absolute_import
from .MT1Dsolutions import get1DEfields # Add the names of the functions
from .MT1Danalytic import getEHfields, getImpedanc... | """ module SimPEG.EM.NSEM.Utils
Collection of utilities that are usefull for the NSEM problem
NOTE: These utilities are not well test, use with care
"""
from __future__ import absolute_import
from .MT1Dsolutions import get1DEfields # Add the names of the functions
from .MT1Danalytic import getEHfields, getImpedanc... |
Fix name of command sent by send_dialogue action. | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class SendDialogueAction(ConversationAction):
action_name = 'send_dialogue'
action_display_name = 'Send Dialogue'
needs_confirmation = True
needs_group = True
needs_running = True
def chec... | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class SendDialogueAction(ConversationAction):
action_name = 'send_dialogue'
action_display_name = 'Send Dialogue'
needs_confirmation = True
needs_group = True
needs_running = True
def chec... |
Rename olfactory stimulus file and internal array. | """
Create odorant stimuli in hd5 format
"""
"""
Create the gexf configuration based on E. Hallem's cell paper on 2006
"""
import numpy as np
import h5py
osn_num = 1375;
f = h5py.File("al.hdf5","w")
dt = 1e-4 # time step
Ot = 2000 # number of data point during reset period
Rt = 1000 # number of data point during o... | """
Create odorant stimuli in hd5 format
"""
"""
Create the gexf configuration based on E. Hallem's cell paper on 2006
"""
import numpy as np
import h5py
osn_num = 1375;
f = h5py.File("olfactory_stimulus.h5","w")
dt = 1e-4 # time step
Ot = 2000 # number of data point during reset period
Rt = 1000 # number of data ... |
Change version number for release | from setuptools import setup
setup(
name='mdf_forge',
version='0.5.0',
packages=['mdf_forge'],
description='Materials Data Facility python package',
long_description="Forge is the Materials Data Facility Python package to interface and leverage the MDF Data Discovery service. Forge allows users to ... | from setuptools import setup
setup(
name='mdf_forge',
version='0.4.1',
packages=['mdf_forge'],
description='Materials Data Facility python package',
long_description="Forge is the Materials Data Facility Python package to interface and leverage the MDF Data Discovery service. Forge allows users to ... |
Check for the name of the submodule we'd like to ignore in a more general way. | import importlib
import pkgutil
ignore_packages = set(['test'])
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
... | import importlib
import pkgutil
ignore_packages = set(['test'])
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
... |
Add PageBegin to pkg exports | #copyright ReportLab Inc. 2000
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/platypus/__init__.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/platypus/__init__.py,v 1.12 2000/11/29 17:28:50 rgbecker Exp $
__version__=''' $Id: __init__.py,v 1.12 2000/11/29... | #copyright ReportLab Inc. 2000
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/platypus/__init__.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/platypus/__init__.py,v 1.13 2002/03/15 09:03:37 rgbecker Exp $
__version__=''' $Id: __init__.py,v 1.13 2002/03/15... |
Fix copypaste error in card definitions | from ..utils import *
##
# Minions
class OG_151:
"Tentacle of N'Zoth"
deathrattle = Hit(ALL_MINIONS, 1)
| from ..utils import *
##
# Minions
|
Store more data about a mod in the registry | import modinfo
class Mod():
"""The Mod class
This is supposed to act like a superclass for mods.
Execution order is as follows:
mod_load -> mod_complete
"""
def mod_info(self):
"""Get the mod info
Returns:
A tuple with the name, version, and author
"""
... | import modinfo
import sys
class Mod():
"""The Mod class
This is supposed to act like a superclass for mods.
Execution order is as follows:
mod_load -> mod_complete
"""
def mod_info(self):
"""Get the mod info
Returns:
A tuple with the name, version, and author
... |
Add forward/reverse mapping of checkerstati | #!/usr/bin/python3
from checker.local import LocalChecker as BaseChecker
#from checker.contest import ContestChecker as BaseChecker
OK = 0
TIMEOUT = 1
NOTWORKING = 2
NOTFOUND = 3
| #!/usr/bin/python3
from checker.local import LocalChecker as BaseChecker
#from checker.contest import ContestChecker as BaseChecker
OK = 0
TIMEOUT = 1
NOTWORKING = 2
NOTFOUND = 3
_mapping = ["OK", "TIMEOUT", "NOTWORKING", "NOTFOUND"]
def string_to_result(strresult):
return _mapping.index(strresult)
def result_... |
Remove unneeded import from testing. | from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from netaddr import AddrFormatError, EUI, mac_unix_expanded
import pprint
class ASNField(models.BigIntegerField):
description = "32-bit ASN field"
default_val... | from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from netaddr import AddrFormatError, EUI, mac_unix_expanded
class ASNField(models.BigIntegerField):
description = "32-bit ASN field"
default_validators = [
... |
Add is_active() method to the Baro class | from datetime import datetime
import utils
class Baro:
"""This class contains info about the Void Trader and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation'... | from datetime import datetime
import utils
class Baro:
"""This class contains info about the Void Trader and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation'... |
Revert string -> integer change for statsd port | """
bux_grader_framework
~~~~~~~~~~~~~~~~~~~~
A framework for bootstraping of external graders for your edX course.
:copyright: 2014 Boston University
:license: GNU Affero General Public License
"""
__version__ = '0.4.3'
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False... | """
bux_grader_framework
~~~~~~~~~~~~~~~~~~~~
A framework for bootstraping of external graders for your edX course.
:copyright: 2014 Boston University
:license: GNU Affero General Public License
"""
__version__ = '0.4.3'
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False... |
Add simple helper properties to Problem. | from src.data import meta
class Problem(object):
def __init__(self, name, lines):
self.name = name
self.lines = lines
self._solutions = None
self._constraints = []
def constrain(self, fn):
self._constraints.append(fn)
# Invalidate solutions.
self._solutions = None
def solutions(sel... | from src.data import meta
class Problem(object):
def __init__(self, name, lines):
self.name = name
self.lines = lines
self._solutions = None
self._constraints = []
@property
def kind(self):
return str(type(self)).strip("'<>").split('.').pop()
@property
def solution(self):
return se... |
Convert gcode now houses all files. | import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import s3g
#input_file = '../doc/gcode_samples/skeinforge_single_extrusion_snake.gcode'
#input_file = '../doc/gcode_samples/skeinforge_dual_extrusion_hilbert_cube.gcode'
input_file = '../doc/gcode_samples/miracle_grue_single_extrusion.gc... | import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import s3g
#input_file = '../doc/gcode_samples/skeinforge_single_extrusion_snake.gcode'
input_file = '../doc/gcode_samples/skeinforge_dual_extrusion_hilbert_cube.gcode'
#input_file = '../doc/gcode_samples/miracle_grue_single_extrusion.gc... |
Make code a little cleaner | from extraction.core import ExtractionRunner
from extraction.runnables import Extractor, RunnableError, Filter, ExtractorResult
import os
import sys
import grobid
import pdfbox
import filters
if __name__ == '__main__':
runner = ExtractionRunner()
runner.add_runnable(pdfbox.PDFBoxPlainTextExtractor)
runner.ad... | from extraction.core import ExtractionRunner
from extraction.runnables import Extractor, RunnableError, Filter, ExtractorResult
import os
import sys
import grobid
import pdfbox
import filters
def get_extraction_runner():
runner = ExtractionRunner()
runner.add_runnable(grobid.GrobidPlainTextExtractor)
# OR
... |
Bump version 0.21.0rc5 --> 0.21.0rc6 | import logging
__version__ = "0.21.0rc5"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
| import logging
__version__ = "0.21.0rc6"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
Set default Django middleware in test settings | import os
from django.urls import (
include,
path,
)
BASE_DIR = os.path.dirname(__file__)
STATIC_URL = "/static/"
INSTALLED_APPS = (
'gcloudc',
'djangae',
'djangae.commands', # Takes care of emulator setup
'djangae.tasks',
)
DATABASES = {
'default': {
'ENGINE': 'gcloudc.db.backe... | import os
from django.urls import (
include,
path,
)
BASE_DIR = os.path.dirname(__file__)
STATIC_URL = "/static/"
# Default Django middleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMid... |
Make test independent of whatever else is in the database. Also, use a different way of calling subprocess.Popen so that we can use quotes and dollars without having to do difficult cross-architectural escaping. | import os, sys
try:
import sybprocess
except ImportError:
# user private copy for old Python versions
import MonetDBtesting.subprocess26 as subprocess
def client(cmd, input = None):
clt = subprocess.Popen(cmd,
shell = True,
stdin = subprocess.PIPE,
... | import os, sys
try:
import sybprocess
except ImportError:
# user private copy for old Python versions
import MonetDBtesting.subprocess26 as subprocess
def client(cmd, input = None):
clt = subprocess.Popen(cmd,
stdin = subprocess.PIPE,
stdout = subpr... |
Fix configuration of email default sender | from flask_mail import Message
from zou.app import mail, app
def send_email(subject, body, recipient_email, html=None):
"""
Send an email with given subject and body to given recipient.
"""
if html is None:
html = body
with app.app_context():
message = Message(
sender=... | from flask_mail import Message
from zou.app import mail, app
def send_email(subject, body, recipient_email, html=None):
"""
Send an email with given subject and body to given recipient.
"""
if html is None:
html = body
with app.app_context():
mail_default_sender = app.config["MAIL... |
Fix reference to acq table file in script | #!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from mica.stats import update_acq_stats
update_acq_stats.main()
import os
table_file = mica.stats.acq_stats.table_file
file_stat = os.stat(table_file)
if file_stat.st_size > 50e6:
print("""
Warning: {tfile} is larger than 50MB a... | #!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
from mica.stats import update_acq_stats
import mica.stats.acq_stats
update_acq_stats.main()
table_file = mica.stats.acq_stats.TABLE_FILE
file_stat = os.stat(table_file)
if file_stat.st_size > 50e6:
print("""
Warning: {... |
Move newline handling to a function. | from __future__ import print_function
import sys
import os
import fcntl
import termios
import argparse
class RootRequired(Exception):
"""Our standard exception."""
pass
def send(data, tty):
"""Send each char of data to tty."""
if(os.getuid() != 0):
raise RootRequired('Only root can send in... | #!/usr/bin/env python
from __future__ import print_function
import sys
import os
import fcntl
import termios
import argparse
class RootRequired(Exception):
"""Our standard exception."""
pass
def send(data, tty):
if len(data):
# Handle trailing newline
if data[-1][-1] != '\n':
... |
Check variable before accessing it | # coding=utf-8
import os
from unittest import main
from _jb_runner_tools import jb_start_tests, jb_doc_args
from teamcity import unittestpy
if __name__ == '__main__':
path, targets, additional_args = jb_start_tests()
args = ["python -m unittest"]
if path:
discovery_args = ["discover", "-s"]
... | # coding=utf-8
import os
from unittest import main
from _jb_runner_tools import jb_start_tests, jb_doc_args
from teamcity import unittestpy
if __name__ == '__main__':
path, targets, additional_args = jb_start_tests()
args = ["python -m unittest"]
if path:
discovery_args = ["discover", "-s"]
... |
Update package version to v1.1.0 | from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='django-cra-helper',
version='1.0.2',
description='The missing... | from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='django-cra-helper',
version='1.1.0',
description='The missing... |
Add project dependencies to install | #!/usr/bin/env python
#coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
from aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__
from setuptools import setup
setup(
name = __title__,
author = __authors__,
author_emai... | #!/usr/bin/env python
#coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
from aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__
from setuptools import setup
setup(
name = __title__,
author = __authors__,
author_emai... |
Update Django requirement to latest LTS | from setuptools import setup, find_packages
setup(
name='django-lightweight-queue',
url="https://chris-lamb.co.uk/projects/django-lightweight-queue",
version='2.0.1',
description="Lightweight & modular queue and cron system for Django",
author="Chris Lamb",
author_email='chris@chris-lamb.co.u... | from setuptools import setup, find_packages
setup(
name='django-lightweight-queue',
url="https://chris-lamb.co.uk/projects/django-lightweight-queue",
version='2.0.1',
description="Lightweight & modular queue and cron system for Django",
author="Chris Lamb",
author_email='chris@chris-lamb.co.u... |
Bump version number in preparation for next release. | #!/usr/bin/env python
"""Django/PostgreSQL implementation of the Meteor DDP service."""
import os.path
from setuptools import setup, find_packages
setup(
name='django-ddp',
version='0.2.0',
description=__doc__,
long_description=open('README.rst').read(),
author='Tyson Clugg',
author_email='tyso... | #!/usr/bin/env python
"""Django/PostgreSQL implementation of the Meteor DDP service."""
import os.path
from setuptools import setup, find_packages
setup(
name='django-ddp',
version='0.2.1',
description=__doc__,
long_description=open('README.rst').read(),
author='Tyson Clugg',
author_email='tyso... |
Update barcode resource to new resource specification | """Module for generating Barcode Checksum Poster resource."""
from PIL import Image
from utils.retrieve_query_parameter import retrieve_query_parameter
def resource_image(request, resource):
"""Create a image for Barcode Checksum Poster resource.
Args:
request: HTTP request object (QueryDict).
... | """Module for generating Barcode Checksum Poster resource."""
from PIL import Image
from utils.retrieve_query_parameter import retrieve_query_parameter
def resource(request, resource):
"""Create a image for Barcode Checksum Poster resource.
Args:
request: HTTP request object (QueryDict).
res... |
Implement parser method for optional offset | # -*- coding: utf-8 -*-
import arrow
from jinja2 import nodes
from jinja2.ext import Extension
class TimeExtension(Extension):
tags = set(['now'])
def __init__(self, environment):
super(TimeExtension, self).__init__(environment)
# add the defaults to the environment
environment.ext... | # -*- coding: utf-8 -*-
import arrow
from jinja2 import nodes
from jinja2.ext import Extension
class TimeExtension(Extension):
tags = set(['now'])
def __init__(self, environment):
super(TimeExtension, self).__init__(environment)
# add the defaults to the environment
environment.ext... |
Add test for recursive agg | from __future__ import print_function
import cooler.contrib.higlass as cch
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_fil... | from __future__ import print_function
import cooler.contrib.higlass as cch
import cooler.contrib.recursive_agg_onefile as ra
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000... |
Use parse() method to instantiate Requirement | #!/usr/bin/env python
import json
from pip.req import parse_requirements
from pip.download import PipSession
from pip._vendor import pkg_resources
from pip._vendor.six import print_
requirements = [pkg_resources.Requirement(str(req.req)) for req
in parse_requirements('requirements.txt', session=PipSes... | #!/usr/bin/env python
import json
from pip.req import parse_requirements
from pip.download import PipSession
from pip._vendor import pkg_resources
from pip._vendor.six import print_
requirements = [pkg_resources.Requirement.parse(str(req.req)) for req
in parse_requirements('requirements.txt', session=... |
Fix mis-naming from pylint cleanup | # -*- coding: utf-8 -*-
'''
Module for running arbitrary tests with a __virtual__ function
'''
from __future__ import absolute_import
def __virtual__():
return False
def test():
return True
| # -*- coding: utf-8 -*-
'''
Module for running arbitrary tests with a __virtual__ function
'''
from __future__ import absolute_import
def __virtual__():
return False
def ping():
return True
|
Remove release title from the GitHub release notes body | """
Generates the release notes for the latest release, in Markdown.
Convert CHANGELOG.rst to Markdown, and extracts just the latest release.
Writes to ``scripts/latest-release-notes.md``, which can be
used with https://github.com/softprops/action-gh-release.
"""
from pathlib import Path
import pypandoc
this_dir = ... | """
Generates the release notes for the latest release, in Markdown.
Convert CHANGELOG.rst to Markdown, and extracts just the latest release.
Writes to ``scripts/latest-release-notes.md``, which can be
used with https://github.com/softprops/action-gh-release.
"""
from pathlib import Path
import pypandoc
this_dir = ... |
Use %APPDATA% for data on Windows. | import os
__author__ = 'jakub'
CONFIG_DIR = os.path.expanduser('~/.httpie')
| import os
from requests.compat import is_windows
__author__ = 'jakub'
CONFIG_DIR = (os.path.expanduser('~/.httpie') if not is_windows else
os.path.expandvars(r'%APPDATA%\\httpie'))
|
Add app run on main | from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/_add_numbers')
def add_numbers():
''' Because numbers must be added server side '''
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
@app.route('/')... | from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/_add_numbers')
def add_numbers():
''' Because numbers must be added server side '''
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
@app.route('/')... |
Integrate integer test function into instantiation | """Creates the station class"""
#import ask_user from ask_user
#import int_check from int_check
#import reasonable_check from reasonable_check
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total... | """Creates the station class"""
#import request_integer_in_range from request_integer_in_range
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
request_integer_in_range : requests an integer in a range
"""
def __... |
Add name_en field due to 'not null' constraint on the Category table | import os
from app import create_app, db
from app.models import User, Category
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
#pyli... | import os
from app import create_app, db
from app.models import User, Category
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
#pyli... |
Add some info about tweepy | from streamsx.topology.topology import *
import streamsx.topology.context
import sys
import tweets
#
# Continually stream tweets that contain
# the terms passed on the command line.
#
# python3 app.py Food GlutenFree
#
def main():
terms = sys.argv[1:]
topo = Topology("TweetsUsingTweepy")
# Event based source st... | from streamsx.topology.topology import *
import streamsx.topology.context
import sys
import tweets
#
# Continually stream tweets that contain
# the terms passed on the command line.
#
# python3 app.py Food GlutenFree
#
#
# Requires tweepy to be installed
#
# pip3 install tweepy
#
# http://www.tweepy.org/
#
# You must ... |
Remove extraneous quote in asserter dockstring | from pprint import pformat
def assert_calls_equal(expected, actual):
"""
Check whether the given mock object (or mock method) calls are equal and
return a nicely formatted message.
"""
if not expected == actual:
raise_calls_differ_error(expected, actual)
def raise_calls_differ_error(expe... | from pprint import pformat
def assert_calls_equal(expected, actual):
"""
Check whether the given mock object (or mock method) calls are equal and
return a nicely formatted message.
"""
if not expected == actual:
raise_calls_differ_error(expected, actual)
def raise_calls_differ_error(expe... |
Increment patch version to 0.7.2 | """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.1'
| """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.2'
|
Make cloud check evaluate greater than or equals | from pyowm.owm import OWM
from datetime import datetime, timedelta
class WeatherManager:
def __init__(self, key, lat, lon):
owm = OWM(key)
self.mgr = owm.weather_manager()
self.lat = lat
self.lon = lon
self.last_updated = None
def load_data(self):
self.data = se... | from pyowm.owm import OWM
from datetime import datetime, timedelta
class WeatherManager:
def __init__(self, key, lat, lon):
owm = OWM(key)
self.mgr = owm.weather_manager()
self.lat = lat
self.lon = lon
self.last_updated = None
def load_data(self):
self.data = se... |
Change to 3 spaces in front of toctree elements | import shutil
import os
import re
work = os.getcwd()
found = []
regex = re.compile(r'pydarkstar\.(.*)\.rst')
for root, dirs, files in os.walk(work):
for f in files:
m = regex.match(f)
if m:
found.append((root, f))
for root, f in found:
path = os.path.join(root, f)
with open(pat... | import shutil
import os
import re
work = os.getcwd()
found = []
regex = re.compile(r'pydarkstar\.(.*)\.rst')
for root, dirs, files in os.walk(work):
for f in files:
m = regex.match(f)
if m:
found.append((root, f))
for root, f in found:
path = os.path.join(root, f)
with open(pat... |
Clarify meaning of --all option for packages command | # Copyright 2017-2020 TensorHub, Inc.
#
# 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 writ... | # Copyright 2017-2020 TensorHub, Inc.
#
# 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 writ... |
Include templates and static at the installing process too | from setuptools import setup
setup(
name='django-setmagic',
version='0.2',
author='Evandro Myller',
author_email='emyller@7ws.co',
description='Magically editable settings for winged pony lovers',
url='https://github.com/7ws/django-setmagic',
install_requires=[
'django >= 1.5',
... | from setuptools import setup
setup(
name='django-setmagic',
version='0.2.1',
author='Evandro Myller',
author_email='emyller@7ws.co',
description='Magically editable settings for winged pony lovers',
url='https://github.com/7ws/django-setmagic',
install_requires=[
'django >= 1.5',
... |
Use pytest_(un)configure to setup cache_directory | collect_ignore = ["setup.py"]
| import tempfile
import shutil
import jedi
collect_ignore = ["setup.py"]
# The following hooks (pytest_configure, pytest_unconfigure) are used
# to modify `jedi.settings.cache_directory` because `clean_jedi_cache`
# has no effect during doctests. Without these hooks, doctests uses
# user's cache (e.g., ~/.cache/je... |
Allow empty conversations to be serialized | def user(model):
if not model.is_authenticated():
return {}
return {
'id': model.id,
'display_name': model.display_name,
'first_name': model.first_name,
'last_name': model.last_name,
}
def category(model):
return {
'id': model.id,
'name': model.... | def user(model):
if not model.is_authenticated():
return {}
return {
'id': model.id,
'display_name': model.display_name,
'first_name': model.first_name,
'last_name': model.last_name,
}
def category(model):
return {
'id': model.id,
'name': model.... |
Support passing html attributes into MenuItem | from __future__ import unicode_literals
from six import text_type
from django.utils.text import slugify
from django.utils.html import format_html
class MenuItem(object):
def __init__(self, label, url, name=None, classnames='', order=1000):
self.label = label
self.url = url
self.classname... | from __future__ import unicode_literals
from six import text_type
try:
# renamed util -> utils in Django 1.7; try the new name first
from django.forms.utils import flatatt
except ImportError:
from django.forms.util import flatatt
from django.utils.text import slugify
from django.utils.html import format_... |
Add check to print_layer_shapes to fail explicitely on model used connected to other models. | from __future__ import print_function
import numpy as np
import theano
def print_layer_shapes(model, input_shape):
"""
Utility function that prints the shape of the output at each layer.
Arguments:
model: An instance of models.Model
input_shape: The shape of the input you will provide to ... | from __future__ import print_function
import numpy as np
import theano
def print_layer_shapes(model, input_shape):
"""
Utility function that prints the shape of the output at each layer.
Arguments:
model: An instance of models.Model
input_shape: The shape of the input you will provide to ... |
Add Error class as base for error codes | from collections import namedtuple
class Error(namedtuple('Error', ['file', 'line_number', 'code', 'message'])):
"""Error class creates error codes to be shown to the user."""
def __repr__(self):
"""Override namedtuple's __repr__ so that error codes are readable."""
return '{}:{}: {} {}' .for... | |
Change to rpio and add clean | import configparser
import time
import RPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
self.send_in... | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
self.sen... |
Add argument option for --interactive. | #!/usr/bin/env python
import sys
import argparse
from akaudit.audit import Auditer
def main(argv = sys.argv, log = sys.stderr):
parser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l', '--log', default='info... | #!/usr/bin/env python
import sys
import argparse
from akaudit.audit import Auditer
def main(argv = sys.argv, log = sys.stderr):
parser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l', '--log', default='info... |
Add base directory capability to empy engine. | #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import em
from . import Engine
class EmpyEngine(Engine):
"""Empy templating engine."""
handle = 'empy'
def __init__(self, template, **kwargs):
"""Initialize empy template."""
super(... | #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import os.path
import em
from . import Engine
class SubsystemWrapper(em.Subsystem):
"""Wrap EmPy's Subsystem class.
Allows to open files relative to a base directory.
"""
def __init__(self, bas... |
Add utilities for computing metrics | def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
if al > ah:
raise ValueError("Interval A bounds are inverted")
if bl > bh:
raise ValueError("Interval B bounds are inverted")
return ah >= bl and bh >= al
| from __future__ import division
import scipy
import scipy.stats
def overlapping(interval_a, interval_b):
al, ah = interval_a
bl, bh = interval_b
if al > ah:
raise ValueError("Interval A bounds are inverted")
if bl > bh:
raise ValueError("Interval B bounds are inverted")
return a... |
Test suite should pass even if example dependencies are not present | import glob
from libmproxy import utils, script
from libmproxy.proxy import config
import tservers
def test_load_scripts():
example_dir = utils.Data("libmproxy").path("../examples")
scripts = glob.glob("%s/*.py" % example_dir)
tmaster = tservers.TestMaster(config.ProxyConfig())
for f in scripts:
... | import glob
from libmproxy import utils, script
from libmproxy.proxy import config
import tservers
def test_load_scripts():
example_dir = utils.Data("libmproxy").path("../examples")
scripts = glob.glob("%s/*.py" % example_dir)
tmaster = tservers.TestMaster(config.ProxyConfig())
for f in scripts:
... |
Add a get prepared date method | from django.db import models
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
| from django.db import models
def get_prepared_date(cls):
return cls.prepared_date or cls.parent.prepared_date
def register(cls, admin_cls):
cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
cls.add_to_class('get_prepared_date', get_prepared_date)
|
Add missing names to module namespace. | from .Averager import Averager
from .Config import Config
from .RateTicker import RateTicker
from .Ring import Ring
from .SortedList import SortedList
from .String import string2time, time2string
from .Timer import Timer
from .UserInput import user_input
| from .Averager import Averager
from .Config import Config
from .RateTicker import RateTicker
from .Ring import Ring
from .SortedList import SortedList
from .String import string2time, time2string, time2levels, time2dir, time2fname
from .Timer import Timer
from .UserInput import user_input
|
Add link states to polymer_states | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/. | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Link states
UP, DOWN = (0, 1), (0, -1)
LEFT, RIGHT = (-1, 0), (1, 0)
SLACK = (0, 0) |
Resolve config from envvar relative to cwd | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from logging import getLogger
import os
import pwm
db = SQLAlchemy()
_logger = getLogger('pwm_server')
class PWMApp(Flask):
def bootstrap(self):
""" Initialize database tables for both pwm_server and pwm. """
from .models import ... | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from logging import getLogger
import os
import pwm
db = SQLAlchemy()
_logger = getLogger('pwm_server')
class PWMApp(Flask):
def bootstrap(self):
""" Initialize database tables for both pwm_server and pwm. """
from .models import ... |
Allow to import subclasses of layers | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from importlib import import_module
import pkgutil
import sys
import inspect
from . import layers
def import_recursive(package, clsmembers):
"""
Takes a package... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from importlib import import_module
import pkgutil
import sys
from . import layers
def import_recursive(package):
"""
Takes a package and imports all modules un... |
Remove hook that snuck in | from groundstation import logger
log = logger.getLogger(__name__)
def handle_describeobjects(self):
if not self.payload:
log.info("station %s sent empty DESCRIVEOBJECTS payload - new database?" % (str(self.origin)))
return
for obj in self.payload.split(chr(0)):
if obj not in self.stati... | from groundstation import logger
log = logger.getLogger(__name__)
def handle_describeobjects(self):
if not self.payload:
log.info("station %s sent empty DESCRIVEOBJECTS payload - new database?" % (str(self.origin)))
return
for obj in self.payload.split(chr(0)):
if obj not in self.stati... |
Use PEP 440 compatible local version identifier | """Remote control Samsung televisions via TCP/IP connection"""
from .remote import Remote
__title__ = "samsungctl"
__version__ = "0.6.0-git"
__url__ = "https://github.com/Ape/samsungctl"
__author__ = "Lauri Niskanen"
__author_email__ = "ape@ape3000.com"
__license__ = "MIT"
| """Remote control Samsung televisions via TCP/IP connection"""
from .remote import Remote
__title__ = "samsungctl"
__version__ = "0.6.0+1"
__url__ = "https://github.com/Ape/samsungctl"
__author__ = "Lauri Niskanen"
__author_email__ = "ape@ape3000.com"
__license__ = "MIT"
|
Fix documentation of fft sub-package to eliminate references to refft. | """\
Core FFT routines
==================
Standard FFTs
fft
ifft
fft2
ifft2
fftn
ifftn
Real FFTs
refft
irefft
refft2
irefft2
refftn
irefftn
Hermite FFTs
hfft
ihfft
"""
depends = ['core']
| """\
Core FFT routines
==================
Standard FFTs
fft
ifft
fft2
ifft2
fftn
ifftn
Real FFTs
rfft
irfft
rfft2
irfft2
rfftn
irfftn
Hermite FFTs
hfft
ihfft
"""
depends = ['core']
|
Allow for representative view display with sample configuration | DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
| DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
TWILIO_NUMBERS = ['']
|
Fix trying to display result in case of not 2D vectors | from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vect... | from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vect... |
Add other planets age function | # File: space_age.py
# Purpose: Write a program that, given an age in seconds, calculates
# how old someone is in terms of a given planet's solar years.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Saturday 17 September 2016, 06:09 PM
class SpaceAge(object):
"""docstrin... | # File: space_age.py
# Purpose: Write a program that, given an age in seconds, calculates
# how old someone is in terms of a given planet's solar years.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Saturday 17 September 2016, 06:09 PM
class SpaceAge(object):
"""docstrin... |
Add a couple more Flag tests. | import unittest
from construct import Flag
class TestFlag(unittest.TestCase):
def test_parse(self):
flag = Flag("flag")
self.assertTrue(flag.parse("\x01"))
def test_parse_flipped(self):
flag = Flag("flag", truth=0, falsehood=1)
self.assertFalse(flag.parse("\x01"))
def te... | import unittest
from construct import Flag
class TestFlag(unittest.TestCase):
def test_parse(self):
flag = Flag("flag")
self.assertTrue(flag.parse("\x01"))
def test_parse_flipped(self):
flag = Flag("flag", truth=0, falsehood=1)
self.assertFalse(flag.parse("\x01"))
def te... |
Tweak formatting of argparse section to minimize lines extending past 80 chars. | #!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status ... | #!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status ... |
Add skeleton for secondary structure and write pdb module | # import porter_paleale
def predict_secondary_structure(sequence):
"""
Predict the secondary structure of a given sequence
:param sequence: Amino acid sequence
:return: Secondary structure prediction as a string
H = helix
E = Strand
C =r coil
"""
# return porter_palea... | |
Use django reverse function to obtain url instead of hard-coding | from django.views import View
from django.views.generic import TemplateView
from django.contrib import auth
from django.contrib import messages
from django import http
class LoginView(TemplateView):
template_name = "admin/login.html"
def post(self, request):
username = request.POST['username']
... | from django.views import View
from django.views.generic import TemplateView
from django.contrib import auth
from django.contrib import messages
from django import http
from django.urls import reverse
class LoginView(TemplateView):
template_name = "admin/login.html"
def post(self, request):
username =... |
Add game loop to prototype | from board import Board, BoardCanvas
b = Board(19, 19)
c = BoardCanvas(b)
| #!/usr/bin/env python
import platform
import subprocess
import sys
from copy import deepcopy
from board import Board, BoardCanvas
def clear():
subprocess.check_call('cls' if platform.system() == 'Windows' else 'clear', shell=True)
class _Getch:
"""
Gets a single character from standard input. Does no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.