Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Modify function that calculate the expected signature
import logging import hashlib import json from django.http import HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from app.models import SocialNetworkApp logger = logging.getLogger(__name__) def _get_facebook_app(): apps = SocialNetworkApp.objects.all() for app in ap...
import logging import hashlib import hmac import json from django.http import HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from app.models import SocialNetworkApp logger = logging.getLogger(__name__) def _get_facebook_app(): apps = SocialNetworkApp.objects.all() f...
Use ResponseError instead of NoScriptError to be compatible with earlier versions of the redis client
import hashlib from redis.exceptions import NoScriptError class LuaScript(object): def __init__(self, redis, template, cache): self.redis = redis self.template = template self.cache = cache self.script = self._render_template(template) def _render_template(self, template): ...
import hashlib from redis.exceptions import ResponseError class LuaScript(object): def __init__(self, redis, template, cache): self.redis = redis self.template = template self.cache = cache self.script = self._render_template(template) def _render_template(self, template): ...
Fix for assertIs method not being present in Python 2.6.
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message self.assertIs(type(time),...
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is date...
Fix test data in an env test on skeleton generation
import binascii import datetime import <error descr="No module named nonexistent">nonexistent</error> print(binascii) print(datetime) print(nonexistent)
import binascii import datetime import <error descr="No module named 'nonexistent'">nonexistent</error> print(binascii) print(datetime) print(nonexistent)
Remove logging to stdout when performing tests
# -*- encoding: utf-8 -*- # # Copyright 2015 Red Hat, 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 ...
# -*- encoding: utf-8 -*- # # Copyright 2015 Red Hat, 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 ...
Define __all__ to suppress lint warnings.
from __future__ import absolute_import import logging logger = logging.getLogger('keyring') from .core import (set_keyring, get_keyring, set_password, get_password, delete_password) from .getpassbackend import get_password as get_pass_get_password try: import pkg_resources __version__ = pk...
from __future__ import absolute_import import logging logger = logging.getLogger('keyring') from .core import (set_keyring, get_keyring, set_password, get_password, delete_password) from .getpassbackend import get_password as get_pass_get_password try: import pkg_resources __version__ = pk...
Change cookie name for mobile setting
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True SESSION_COOKIE_NAME = 'bookworm_mobile'
Add docstring on every entity
# -*- coding: utf-8 -*- # This file defines the entities needed by our legislation. from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parent...
# -*- coding: utf-8 -*- # This file defines the entities needed by our legislation. from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parent...
Use the webserver module, which means the script is now cross-platform. Hooray, Python\!
#!/usr/bin/env python import sys import re import subprocess import urlparse import platform from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class OpenRemoteHandler(BaseHTTPRequestHandler): def do_GET(self): url = '' try: request_url = urlparse.urlsplit(self.path) ...
#!/usr/bin/env python import re import webbrowser import urlparse import platform from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class OpenRemoteHandler(BaseHTTPRequestHandler): def do_GET(self): url = '' try: request_url = urlparse.urlsplit(self.path) if re....
Fix test for async Block
# -*- coding: utf-8 -*- import pytest import logging from bitshares.aio.block import Block log = logging.getLogger("grapheneapi") log.setLevel(logging.DEBUG) @pytest.mark.asyncio async def test_aio_block(bitshares): block = await Block(333, blockchain_instance=bitshares) assert block["witness"] == "1.6.6" ...
# -*- coding: utf-8 -*- import asyncio import pytest import logging from bitshares.aio.block import Block log = logging.getLogger("grapheneapi") log.setLevel(logging.DEBUG) @pytest.mark.asyncio async def test_aio_block(bitshares): # Wait for block await asyncio.sleep(1) block = await Block(1, blockchain...
Fix documentation checks by adjusting intersphinx mapping
from crate.theme.rtd.conf.python import * if "sphinx.ext.intersphinx" not in extensions: extensions += ["sphinx.ext.intersphinx"] if "intersphinx_mapping" not in globals(): intersphinx_mapping = {} intersphinx_mapping.update({ 'reference': ('https://crate.io/docs/crate/reference/', None), 'sa': ('...
from crate.theme.rtd.conf.python import * if "sphinx.ext.intersphinx" not in extensions: extensions += ["sphinx.ext.intersphinx"] if "intersphinx_mapping" not in globals(): intersphinx_mapping = {} intersphinx_mapping.update({ 'reference': ('https://crate.io/docs/crate/reference/en/latest/', None), ...
Use new temp file directory.
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django.conf import settings import os import uuid from boto.s3.key import Key from boto.s3.connection import S3Connection from osgeo import gdal def ensure_band_count(key_string...
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django.conf import settings import os import uuid from boto.s3.key import Key from boto.s3.connection import S3Connection from osgeo import gdal def ensure_band_count(key_string...
Fix int float setting issue.
import os from django.core.management import BaseCommand from django.conf import settings def dump_attrs(obj_instance): for attr in dir(obj_instance): if attr != attr.upper(): continue yield attr, getattr(obj_instance, attr) class Command(BaseCommand): args = '' help = 'Crea...
import os from django.core.management import BaseCommand from django.conf import settings def dump_attrs(obj_instance): for attr in dir(obj_instance): if attr != attr.upper(): continue yield attr, getattr(obj_instance, attr) class Command(BaseCommand): args = '' help = 'Crea...
Update Structure composite to use the new abc
from dimod.core.sampler import Sampler from dimod.core.composite import Composite from dimod.core.structured import Structured from dimod.decorators import bqm_structured class StructureComposite(Sampler, Composite, Structured): """Creates a structured composed sampler from an unstructured sampler. todo ...
from dimod.core.sampler import Sampler from dimod.core.composite import Composite from dimod.core.structured import Structured from dimod.decorators import bqm_structured class StructureComposite(Sampler, Composite, Structured): """Creates a structured composed sampler from an unstructured sampler. """ # ...
Remove xfail from working test
# trivial_example.py # # Copyright 2014 BitVault. # # Reproduces the tests in trivial_example.rb from __future__ import print_function import pytest from random import randint from patchboard.tests.fixtures import (trivial_net_pb, trivial_net_resources, ...
# trivial_example.py # # Copyright 2014 BitVault. # # Reproduces the tests in trivial_example.rb from __future__ import print_function import pytest from random import randint from patchboard.tests.fixtures import (trivial_net_pb, trivial_net_resources, ...
Remove reference to scrobbler extension
import unittest from mopidy_scrobbler import Extension, frontend as frontend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[{{ cookiecutter.ext_name }}]', config) self.assertIn('...
import unittest from mopidy_{{ cookiecutter.ext_name }} import Extension, frontend as frontend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[{{ cookiecutter.ext_name }}]', config) ...
Adjust in a BC way to introduce TestCase
from datetime import datetime from django.core.files import File from django.conf import settings from armstrong.dev.tests.utils import ArmstrongTestCase from armstrong.dev.tests.utils.backports import * from armstrong.dev.tests.utils.concrete import * from armstrong.dev.tests.utils.users import * from ..models impor...
from datetime import datetime from django.core.files import File from django.conf import settings from armstrong.dev.tests.utils import ArmstrongTestCase from armstrong.dev.tests.utils.backports import * from armstrong.dev.tests.utils.concrete import * from armstrong.dev.tests.utils.users import * from ..models impor...
Fix to new page layout
import requests from bs4 import BeautifulSoup def nouda( url , out ): r = requests.get( url ) r.encoding = 'UTF-8' soup = BeautifulSoup( r.text ) teksti = soup.find_all( class_ ='Teksti' ) for string in teksti[0].stripped_strings: out.write( string.encode('utf8') + ' ' ) if __name__ == '__main__': ...
import requests from bs4 import BeautifulSoup def nouda( url , out ): r = requests.get( url ) r.encoding = 'UTF-8' soup = BeautifulSoup( r.text ) teksti = soup.find_all( class_ ='post-meta' ) for string in teksti[0].stripped_strings: out.write( string.encode('utf8') + ' ' ) if __name__ == '__main__'...
Fix markdown plugin so it's run only when needed
import markdown def markdownify_content(context): for article in context["articles"]: article["content"] = markdown.markdown(article["content"]) return context def inject_middlewares(middlewares): middlewares.add("markdownify_content", markdownify_content) return middlewares
import markdown import helpers logger = helpers.get_logger(__name__) def markdownify_content(context): if context["is_called_from_cli"]: arg_parser = context["arg_parser"] args = arg_parser.parse_args() if args.action == "generate": for article in context["articles"]: ...
Clear relatives if no family history
from radar.validation.groups import CohortGroupValidationMixin from radar.validation.core import Field, Validation from radar.validation.meta import MetaValidationMixin from radar.validation.patients import PatientValidationMixin from radar.validation.validators import required, none_if_blank, optional, max_length, in_...
from radar.validation.groups import CohortGroupValidationMixin from radar.validation.core import Field, Validation from radar.validation.meta import MetaValidationMixin from radar.validation.patients import PatientValidationMixin from radar.validation.validators import required, none_if_blank, optional, max_length, in_...
Fix bug in VectorName, caused by new Command arguments
# -*- coding: utf-8 -*- """ pylatex.numpy ~~~~~~~~~~~~~ This module implements the classes that deals with numpy objects. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ import numpy as np from pylatex.base_classes import BaseLaTeXClass from pylatex.package...
# -*- coding: utf-8 -*- """ pylatex.numpy ~~~~~~~~~~~~~ This module implements the classes that deals with numpy objects. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ import numpy as np from pylatex.base_classes import BaseLaTeXClass from pylatex.package...
Tweak comment text for clarity
import urllib import urlparse def add_query_params(url, params): """ Inject additional query parameters into an existing URL. If existing parameters already exist with the same name, they will be overwritten. Return the modified URL as a string. """ # If any of the additional parameters h...
import urllib import urlparse def add_query_params(url, params): """ Inject additional query parameters into an existing URL. If parameters already exist with the same name, they will be overwritten. Return the modified URL as a string. """ # If any of the additional parameters have empty valu...
Add some bogus tests to try and get this info.
from datetime import date import calendar print(calendar.__dir__()) print(calendar.__dict__) def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
from datetime import date import calendar def test_foo(): assert(calendar.__dir__() == "") def test_dummy(): assert(calendar.__dict__ == "") def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_busine...
Add very basic logic to figure out supported cipher suites.
import click CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]) @click.command(context_settings=CONTEXT_SETTINGS) @click.argument("host", type=click.STRING) @click.argument("port", type=click.INT) @click.option("--verify-cert", is_flag=True) def cli(host, port, verify_cert): """ A command line tool...
import socket import click from construct import UBInt16 from tlsenum.parse_hello import ( ClientHello, Extensions, HandshakeFailure, ServerHello ) from tlsenum.mappings import CipherSuites, ECCurves, ECPointFormat CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]) def send_client_hello(host, port, d...
Implement rollover correctly and a lot more concisely
def n_to_i(num, n): """ Translate num, ranging from -(n-1)/2 through (n-1)/2 into an index i from 0 to n-1 If num > (n-1)/2, map it into the interval This is necessary to translate from a physical Fourier mode number to an index in an array. """ cutoff = (n-1)/2 if num > cutoff...
def n_to_i(num, n): """ Translate num, ranging from -(n-1)/2 through (n-1)/2 into an index i from 0 to n-1 If num > (n-1)/2, map it into the interval This is necessary to translate from a physical Fourier mode number to an index in an array. """ cutoff = (n-1)/2 return (num+cut...
Remove relation to user model in order to keep things simpler
from django.db import models from django.contrib.auth.models import User ABODE_TYPES = ( ('SH', 'Small house'), ('H', 'House'), ('SB', 'Small building'), ('B', 'Building') ) GENDERS = ( ('M', 'Male'), ('F', 'Female') ) class World(models.Model): god = models.ForeignKey(User, related_na...
from django.db import models ABODE_TYPES = ( ('SH', 'Small house'), ('H', 'House'), ('SB', 'Small building'), ('B', 'Building') ) GENDERS = ( ('M', 'Male'), ('F', 'Female') ) class World(models.Model): name = models.CharField(max_length=30) description = models.TextField() class...
Make UglifyJSFilter docstring more consistent with other filters
"""Minify Javascript using `UglifyJS <https://github.com/mishoo/UglifyJS/>`_. UglifyJS is an external tool written for NodeJS; this filter assumes that the ``uglifyjs`` executable is in the path. Otherwise, you may define a ``UGLIFYJS_BIN`` setting. Additional options may be passed to ``uglifyjs`` by setting ``UGLIFYJ...
import subprocess from webassets.exceptions import FilterError from webassets.filter import Filter __all__ = ('UglifyJSFilter',) class UglifyJSFilter(Filter): """ Minify Javascript using `UglifyJS <https://github.com/mishoo/UglifyJS/>`_. UglifyJS is an external tool written for NodeJS; this filter assu...
Fix IndexError: pop from empty list
from bleach.linkifier import Linker from markdown.postprocessors import Postprocessor from markdown.extensions import Extension class LinkifyExtension(Extension): def __init__(self, **kwargs): self.config = { 'linker_options': [{}, 'Options for bleach.linkifier.Linker'], } su...
from bleach.linkifier import Linker from markdown.postprocessors import Postprocessor from markdown.extensions import Extension class LinkifyExtension(Extension): def __init__(self, **kwargs): self.config = { 'linker_options': [{}, 'Options for bleach.linkifier.Linker'], } su...
Revert "commiting failing dummytest to test CI-setup"
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # © 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Skarphed. # # Skarphed is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as ...
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # © 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Skarphed. # # Skarphed is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as ...
Fix bad initial count in slug creation helper
from django.db import IntegrityError from django.template.defaultfilters import slugify def save_obj_with_slug(obj, attribute='title', **kwargs): obj.slug = slugify(getattr(obj, attribute)) return save_obj_unique(obj, 'slug', **kwargs) def save_obj_unique(obj, attr, count=0, postfix_format='-{count}'): ...
from django.db import IntegrityError from django.template.defaultfilters import slugify def save_obj_with_slug(obj, attribute='title', **kwargs): obj.slug = slugify(getattr(obj, attribute)) return save_obj_unique(obj, 'slug', **kwargs) def save_obj_unique(obj, attr, count=0, postfix_format='-{count}'): ...
Fix link previous to TOC and Fix priority
from markdown.extensions import Extension from markdown_i18n.parser import I18NTreeProcessor class I18NExtension(Extension): def __init__(self, **kwargs): self.config = { 'i18n_lang': ['en_US', 'Locale'], 'i18n_dir': ['', 'Path to get the translations and'] } self....
from markdown.extensions import Extension from markdown_i18n.parser import I18NTreeProcessor class I18NExtension(Extension): def __init__(self, **kwargs): self.config = { 'i18n_lang': ['en_US', 'Locale'], 'i18n_dir': ['', 'Path to get the translations and'] } self....
Add tests for sending messages to "user" projects
from nose.tools import * from lamson.testing import * import os from lamson import server relay = relay(port=8823) client = RouterConversation("queuetester@localhost", "requests_tests") confirm_format = "testing-confirm-[0-9]+@" noreply_format = "testing-noreply@" host = "localhost" def test_react_for_existing_proje...
from nose.tools import * from lamson.testing import * import os from lamson import server relay = relay(port=8823) client = RouterConversation("queuetester@localhost", "requests_tests") confirm_format = "testing-confirm-[0-9]+@" noreply_format = "testing-noreply@" host = "localhost" def test_react_for_existing_proje...
Update IP address of kafka consumer
#!/usr/bin/env python import threading, logging, time from kafka import KafkaConsumer class Consumer(threading.Thread): daemon = True def run(self): #consumer = KafkaConsumer(bootstrap_servers='10.100.198.220:9092', consumer = KafkaConsumer(bootstrap_servers='10.0.2.15:9092', ...
#!/usr/bin/env python import threading, logging, time from kafka import KafkaConsumer class Consumer(threading.Thread): daemon = True def run(self): consumer = KafkaConsumer(bootstrap_servers='10.100.198.220:9092', #consumer = KafkaConsumer(bootstrap_servers='10.0.2.15:9092', ...
Fix bad indentation in processor
from datapackage_pipelines.wrapper import process def process_row(row, row_index, spec, resource_index, parameters, stats): for f in spec['schema']['fields']: if 'factor' in f: factor = { '1m': 1000000 }[f['factor']] v = row[f...
from datapackage_pipelines.wrapper import process def process_row(row, row_index, spec, resource_index, parameters, stats): for f in spec['schema']['fields']: if 'factor' in f: factor = { '1m': 1000000 }[f['factor']] v = r...
Clean __main__ + header boiler plate
#!/usr/bin/env python # Xtriage.py # Copyright (C) 2017 Diamond Light Source, Richard Gildea # # This code is distributed under the BSD license, a copy of which is # included in the root directory of this package. from __future__ import absolute_import, division, print_function from xia2.Driver.DriverFactory im...
#!/usr/bin/env python from __future__ import absolute_import, division, print_function from xia2.Driver.DriverFactory import DriverFactory def Xtriage(DriverType=None): """A factory for the Xtriage wrappers.""" DriverInstance = DriverFactory.Driver("simple") class XtriageWrapper(DriverInstance.__clas...
Add util to convert between short and long postId formats
from datetime import datetime def strptime(string, fmt='%Y-%m-%dT%H:%M:%S.%f'): return datetime.strptime(string, fmt) # From http://stackoverflow.com/a/14620633 # CAUTION: it causes memory leak in < 2.7.3 and < 3.2.3 class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__in...
from datetime import datetime def strptime(string, fmt='%Y-%m-%dT%H:%M:%S.%f'): return datetime.strptime(string, fmt) # From http://stackoverflow.com/a/14620633 # CAUTION: it causes memory leak in < 2.7.3 and < 3.2.3 class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__in...
Fix iteritems isn't a method name in Py3
# coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: ...
# coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: ...
Use the C Loader/Dumper when available
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(yaml.loader.Loader): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_...
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(getattr(yaml, 'CSafeLoader', yaml.SafeLoader)): pass OrderedLoader.add_constructor( yaml.resolver.Ba...
Fix TemplateTag issue with filters
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if key_name in d: return d[key_name] return '' @register...
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if d is not None: if key_name in ...
Move testing code into "if __name__ == '__main__'" so it's not run on import.
import errno import hotshot import hotshot.stats import os import sys import test.pystone if sys.argv[1:]: logfile = sys.argv[1] else: import tempfile logf = tempfile.NamedTemporaryFile() logfile = logf.name p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() ...
import errno import hotshot import hotshot.stats import os import sys import test.pystone def main(logfile): p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOO...
Load the backend with get_cache
import time from django.test import TestCase from infinite_memcached.cache import MemcachedCache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = MemcachedCache( server="127.0.0.1:11211", params={}, ) self.assertEqual(0, mc._get_memcache_timeou...
import time from django.test import TestCase from django.core.cache import get_cache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = get_cache('infinite_memcached.cache.MemcachedCache', LOCATION='127.0.0.1:11211') self.assertEqual(0, mc._get_memcache_...
Remove NA values from export.
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] ...
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] ...
Change test to use a user model with name not id for pk
import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): my_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Remove coverage on replay; development is suspended.
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description o...
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description o...
Make permissions declaration DRY (NC-1282)
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole, ProjectGroupRole, ProjectRole PERMISSION_LOGICS = ( ('saltstack.SaltStackService', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission...
from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('saltstack.SaltStackService', structure_perms.service_permission_logic), ('saltstack.SaltStackServiceProjectLink', structure_perms.service_project_link_permission_logic), ) property_permission_logic = structure_perms.property...
Replace currency full name with currency code.
import moneyed FFXOS_ACTIVITY_NAME = 'Submit FirefoxOS device price' def get_currency_choices(): return sorted(((currency, data.name) for currency, data in moneyed.CURRENCIES.items()))
import moneyed FFXOS_ACTIVITY_NAME = 'Submit FirefoxOS device price' def get_currency_choices(): return sorted(((currency, data.code) for currency, data in moneyed.CURRENCIES.items()))
Fix create action for key value pair
from st2actions.runners.pythonrunner import Action from st2client.client import Client from st2client.models.datastore import KeyValuePair class KVPAction(Action): def run(self, key, action, st2host='localhost', value=""): st2_endpoints = { 'action': "http://%s:9101" % st2host, 'r...
from st2actions.runners.pythonrunner import Action from st2client.client import Client from st2client.models.datastore import KeyValuePair class KVPAction(Action): def run(self, key, action, st2host='localhost', value=""): st2_endpoints = { 'action': "http://%s:9101" % st2host, 'r...
Remove generate error page from admin site
from jingo import register from olympia.amo.urlresolvers import reverse @register.function def admin_site_links(): return { 'addons': [ ('Search for add-ons by name or id', reverse('zadmin.addon-search')), ('Featured add-ons', reverse('zadmin.features')), ...
from jingo import register from olympia.amo.urlresolvers import reverse @register.function def admin_site_links(): return { 'addons': [ ('Search for add-ons by name or id', reverse('zadmin.addon-search')), ('Featured add-ons', reverse('zadmin.features')), ...
Add more informative error message for yank options assertion test.
#!/usr/local/bin/env python """ Test various utility functions. """ #============================================================================================= # GLOBAL IMPORTS #============================================================================================= from yank.utils import YankOptions #====...
#!/usr/local/bin/env python """ Test various utility functions. """ #============================================================================================= # GLOBAL IMPORTS #============================================================================================= from yank.utils import YankOptions #====...
Fix missing message in ValidationError
from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username...
from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username...
Use -dev tag for in-dev versions
""" Convert docs to Dash.app's docset format. """ from __future__ import absolute_import, division, print_function __author__ = 'Hynek Schlawack' __version__ = '2.0.0' __license__ = 'MIT'
""" Convert docs to Dash.app's docset format. """ from __future__ import absolute_import, division, print_function __author__ = 'Hynek Schlawack' __version__ = '2.0.0-dev' __license__ = 'MIT'
Revert "remove dog and cat commands( see random.cat/help.html for some background on this)"
import logging import re from ..tools import Cog from ..tools import get_guild_config log = logging.getLogger(__name__) ayygen = re.compile('[aA][yY][Yy][yY]*') class Fun(Cog): """contains the on message for ayy""" async def on_message(self, message): if self.bot.location == 'laptop' or message.guil...
import logging import re from ..tools import Cog from ..tools import get_guild_config log = logging.getLogger(__name__) ayygen = re.compile('[aA][yY][Yy][yY]*') class Fun(Cog): @commands.command() async def cat(self, ctx): cat = await get_json(self.bot.session, 'http://random.cat/meow') ret ...
Add a function to identify the boundary of a preclipped cell
import numpy as np import scipy as sp def cell_boundary_mask(image): """ Identifies the clipping boundary of a cell image. Returns this as a mask, where True corresponds to "inside the cell". This is done by finding a mask that is True where image != 0 (as the clipped area will be perfectly zero). Imperfections...
Use sqlalchemy BigInteger instead of mysql BIGINT
from sqlalchemy import Column, Integer, String, Text, ForeignKey from sqlalchemy.dialects.mysql import BIGINT from sqlalchemy.orm import relationship from bookmarks.database import Base class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) username = Column(String(50), unique=Tru...
from sqlalchemy import Column, Integer, BigInteger, String, Text, ForeignKey from sqlalchemy.orm import relationship from bookmarks.database import Base class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) username = Column(String(50), unique=True, nullable=False) name = Col...
Test case when there's no riemann config
from pytest import fixture from oshino.config import Config, RiemannConfig @fixture def base_config(): return Config({"riemann": {"host": "localhost", "port": 5555 }, "interval": 5 }) def test_base_config_get_ri...
from pytest import fixture from oshino.config import Config, RiemannConfig @fixture def base_config(): return Config({"riemann": {"host": "localhost", "port": 5555 }, "interval": 5 }) @fixture def incomplete_con...
Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-us...
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-us...
Change style of setting records_class default
from __future__ import unicode_literals __version__ = '1.5.1' def register( model, app=None, manager_name='history', records_class=None, **records_config): """ Create historical model for `model` and attach history manager to `model`. Keyword arguments: app -- App to install historic...
from __future__ import unicode_literals __version__ = '1.5.1' def register( model, app=None, manager_name='history', records_class=None, **records_config): """ Create historical model for `model` and attach history manager to `model`. Keyword arguments: app -- App to install historic...
Add box.text namespace. Also switch to oss@box.com for email addr.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='genty', version='0.0.1', description='Allows you to run a test with multiple data sets', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='genty', version='0.0.1', description='Allows you to run a test with multiple data sets', ...
Add explicit usage of backend
from .page import Page import six from bs4 import UnicodeDammit, BeautifulSoup # from lxml.etree import fromstring def parse(source): """Parse a HOCR stream into page elements. @param[in] source Either a file-like object or a filename of the HOCR text. """ # Corece the source into content. ...
from .page import Page import six from bs4 import UnicodeDammit, BeautifulSoup # from lxml.etree import fromstring def parse(source): """Parse a HOCR stream into page elements. @param[in] source Either a file-like object or a filename of the HOCR text. """ # Corece the source into content. ...
Fix an actual schema validation error in one of the tests
import pytest import python_jsonschema_objects as pjo @pytest.fixture def test_class(): schema = { 'title': 'Example', 'properties': { "claimed_by": { "id": "claimed", "type": ["string", "integer", "null"], "description": "Robots Only. ...
import pytest import python_jsonschema_objects as pjo @pytest.fixture def test_class(): schema = { 'title': 'Example', 'properties': { "claimed_by": { "id": "claimed", "type": ["string", "integer", "null"], "description": "Robots Only. ...
Fix problem with finding sample name from fastqc_screen output
import sys import os header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] with open(fi) as screen_results: results = {} for line in screen_results: fields = line.strip()....
import sys import os header = ['Sample', 'Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] if sample[-7:] == '_screen': sample = sample[:-7] with open(fi) as screen_results: results = {...
Return self in Pipeline add_after and add_before
class Pipeline(object): """Defines a pipeline for transforming sequence data.""" def __init__(self, convert_token=None): if convert_token is not None: self.convert_token = convert_token else: self.convert_token = lambda x: x self.pipes = [self] def __call__(...
class Pipeline(object): """Defines a pipeline for transforming sequence data.""" def __init__(self, convert_token=None): if convert_token is not None: self.convert_token = convert_token else: self.convert_token = lambda x: x self.pipes = [self] def __call__(...
Set title to 'Assignment' in student dashboard
from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from devilry.addons.dashboard.dashboardplugin_registry import registry, \ DashboardItem import dashboardviews def simpleview(request, *args): return mark_safe(u"""S...
from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from devilry.addons.dashboard.dashboardplugin_registry import registry, \ DashboardItem import dashboardviews registry.register_important(DashboardItem( title ...
Use IRC server on localhost by default
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab import importlib from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'irc.freenode.net', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], ...
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab import importlib from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_...
Add logging filter for checking that the app is actually deployed
import logging import traceback from hashlib import sha256 from datetime import datetime, timedelta # Adapted http://djangosnippets.org/snippets/2242/ by user s29 (October 25, 2010) class _RateLimitFilter(object): last_error = datetime.min def filter(self, record): from django.conf import settings ...
import logging import traceback from hashlib import sha256 from datetime import datetime, timedelta # Adapted http://djangosnippets.org/snippets/2242/ by user s29 (October 25, 2010) class _RateLimitFilter(object): last_error = datetime.min def filter(self, record): from django.conf import settings ...
Move NumPy dependency to optional rastertoolz dependency
import os.path from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages # read README as the long description readme = 'README' if os.path.exists('README') else 'README.md' with open(readme, 'r') as f: long_description = f.read() setup( name='spandex', version='0....
import os.path from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages # read README as the long description readme = 'README' if os.path.exists('README') else 'README.md' with open(readme, 'r') as f: long_description = f.read() setup( name='spandex', version='0....
Decrease the bound on cffi
#!/usr/bin/env python from setuptools import setup setup(name='Robot Daemon', version='1.0', description='Daemon for vision code for Source Bots', author='SourceBots', author_email='', packages=['robotd'], setup_requires=["cffi>=1.0.0"], ffi_modules=["robotd/vision/apriltag/...
#!/usr/bin/env python from setuptools import setup setup(name='Robot Daemon', version='1.0', description='Daemon for vision code for Source Bots', author='SourceBots', author_email='', packages=['robotd'], setup_requires=["cffi>=0.8.6"], ffi_modules=["robotd/vision/apriltag/...
Fix packaging of data files
from setuptools import setup, find_packages setup( name="openslides-gui", version="1.0.0dev1", description="GUI frontend for openslides", long_description="", # TODO url='http://openslides.org', author='OpenSlides-Team, see AUTHORS', author_email='support@openslides.org', license='MIT',...
from setuptools import setup, find_packages setup( name="openslides-gui", version="1.0.0dev1", description="GUI frontend for openslides", long_description="", # TODO url='http://openslides.org', author='OpenSlides-Team, see AUTHORS', author_email='support@openslides.org', license='MIT',...
Bump version number for future release.
from setuptools import setup, find_packages setup ( name = 'hypnotoad', version = '0.1.1', author = 'Jon Bringhurst', author_email = 'jonb@lanl.gov', url = 'https://www.git.lanl.gov/rm/hypnotoad', license = 'LICENSE.txt', ...
from setuptools import setup, find_packages setup ( name = 'hypnotoad', version = '0.1.2', author = 'Jon Bringhurst', author_email = 'jonb@lanl.gov', url = 'https://www.git.lanl.gov/rm/hypnotoad', license = 'LICENSE.txt', ...
Revert "Try less than 2.0."
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='mdot', version='0.1', packages=['mdot'], include_packa...
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='mdot', version='0.1', packages=['mdot'], include_packa...
Use better syntax for unpacking tuples
#!/usr/bin/python3 import sys, os import nltk if len(sys.argv) < 2: print("Please supply a filename.") sys.exit(1) filename = sys.argv[1] with open(filename, 'r') as f: data = f.read() # Break the input down into sentences, then into words, and position tag # those words. raw_sentences = nltk.sent_toke...
#!/usr/bin/python3 import sys, os import nltk if len(sys.argv) < 2: print("Please supply a filename.") sys.exit(1) filename = sys.argv[1] with open(filename, 'r') as f: data = f.read() # Break the input down into sentences, then into words, and position tag # those words. raw_sentences = nltk.sent_toke...
Set praise list as home
"""pronto_praise URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Cl...
"""pronto_praise URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Cl...
Implement function to upload and rotate a file with an existing timestamp
from dcu.active_memory.rotate import rotate from dcu.active_memory.rotate import splitext from dcu.active_memory.upload import multipart_upload import os.path import reimport logging logger = logging.getLogger(__name__) def upload_rotate(file_path, s3_bucket, s3_key_prefix, aws_key=None, aws_secret=None): ''' ...
Use one of the real data files in test
import pytest import parse_vcf as pv def test_openfile(): assert pv.openfile('test_parse_vcf.py')[0] == True
import pytest import parse_vcf as pv def test_openfile(): # The real input file is called: 001.vcfmod assert pv.openfile('001.vcfmod')[0] == True
Add stacklevel=2 to make calling code clear
"""For backward compatibility, expose main functions from ``setuptools.config.setupcfg`` """ import warnings from functools import wraps from textwrap import dedent from typing import Callable, TypeVar, cast from .._deprecation_warning import SetuptoolsDeprecationWarning from . import setupcfg Fn = TypeVar("Fn", boun...
"""For backward compatibility, expose main functions from ``setuptools.config.setupcfg`` """ import warnings from functools import wraps from textwrap import dedent from typing import Callable, TypeVar, cast from .._deprecation_warning import SetuptoolsDeprecationWarning from . import setupcfg Fn = TypeVar("Fn", boun...
Change test to show WebOb filters consume completely before resulting in a body
# Test various types of WebOb middleware import sys from fireside import WSGIFilter from webob.dec import wsgify from servlet_support import * # FIXME be explicit from javax.servlet import FilterChain @wsgify.middleware def all_caps(req, app): resp = req.get_response(app) resp.body = resp.body.upper() ...
# Test various types of WebOb middleware import sys from fireside import WSGIFilter from webob.dec import wsgify from servlet_support import * # FIXME be explicit from javax.servlet import FilterChain @wsgify.middleware def all_caps(req, app): resp = req.get_response(app) resp.body = resp.body.upper() ...
Fix version to include 3 digits.
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. """ Tweepy Twitter API library """ __version__ = '3.1' __author__ = 'Joshua Roesslein' __license__ = 'MIT' from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error ...
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. """ Tweepy Twitter API library """ __version__ = '3.1.0' __author__ = 'Joshua Roesslein' __license__ = 'MIT' from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.erro...
Fix slices for Python 3
def merge(a, b): if len(a) * len(b) == 0: return a + b v = (a[0] < b[0] and a or b).pop(0) return [v] + merge(a, b) def mergesort(list): if len(list) < 2: return list m = len(list) / 2 return merge(mergesort(list[:m]), mergesort(list[m:]))
def merge(a, b): if len(a) * len(b) == 0: return a + b v = (a[0] < b[0] and a or b).pop(0) return [v] + merge(a, b) def mergesort(list): if len(list) < 2: return list m = len(list) / 2 return merge(mergesort(list[:int(m)]), mergesort(list[int(m):]))
Remove helper functions from sharepa init
from sharepa.search import ShareSearch, basic_search # noqa from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa from sharepa.helpers import source_agg, source_counts
from sharepa.search import ShareSearch, basic_search # noqa from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
Fix py script to package all .pdb files now that its moved to tools.
import os import os.path import sys import zipfile ''' Seeks for *.pdb files from current directory and all child directories. All found pdb files are copied to 'pdb-files.zip' file with their relative file paths. ''' fileList = [] rootdir = os.curdir zip_file_name = "pdb-files.zip" if os.path.isfile(zip_file_name):...
import os import os.path import sys import zipfile ''' Seeks for *.pdb files from current directory and all child directories. All found pdb files are copied to 'pdb-files.zip' file with their relative file paths. ''' fileList = [] rootdir = os.getcwd()[0:-6] # strip the /tools from the end zip_file_name = "Tundra-pd...
Add cryptography test for EC
# see https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa.html from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import hashes from cryptography.exceptions import InvalidSignature private_key = ec.generate_private_key(curve=ec.SECP384R1()) # $ PublicKeyGenera...
# see https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa.html from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import hashes from cryptography.exceptions import InvalidSignature private_key = ec.generate_private_key(curve=ec.SECP384R1()) # $ PublicKeyGenera...
Allow raw snippets without trailing slash
from django.conf.urls.defaults import url, patterns urlpatterns = patterns('dpaste.views', url(r'^$', 'snippet_new', name='snippet_new'), url(r'^diff/$', 'snippet_diff', name='snippet_diff'), url(r'^history/$', 'snippet_history', name='snippet_history'), url(r'^delete/$', 'snippet_delete', name='snippe...
from django.conf.urls.defaults import url, patterns urlpatterns = patterns('dpaste.views', url(r'^$', 'snippet_new', name='snippet_new'), url(r'^diff/$', 'snippet_diff', name='snippet_diff'), url(r'^history/$', 'snippet_history', name='snippet_history'), url(r'^delete/$', 'snippet_delete', name='snippe...
Add lastest updates to script
#!/usr/bin/python # -*- coding: UTF-8 -*- from __future__ import division import feedparser, os from BeautifulSoup import BeautifulSoup import nltk, re, pprint from nltk import word_tokenize # from urllib2 import Request as request import urllib2 def ie_preprocess(document): sentences = nltk.sent_tokenize(document) ...
#!/usr/bin/python # -*- coding: UTF-8 -*- from __future__ import division import feedparser, os from BeautifulSoup import BeautifulSoup import nltk, re, pprint from nltk import word_tokenize # from urllib2 import Request as request import urllib2 def ie_preprocess(document): sentences = nltk.sent_tokenize(document) ...
Improve script task to allow multiline
import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'sc...
import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'sc...
Add Register resource to handle user registration and save user data to the database
from flask_restful import Resource class AccountsManager(Resource): """docstring for AccountsManager.""" def get(self): return {"route": "login"} def post(self): return {"route": "register"}
from flask import jsonify, make_response from flask_restful import Resource, reqparse from app.models import User from app.db_instance import save from validator import validate class AccountsManager(Resource): """docstring for AccountsManager.""" def __init__(self): self.parser = reqparse.RequestPars...
Revert to having static version numbers again.
"""distutils The main package for the Python Module Distribution Utilities. Normally used from a setup script as from distutils.core import setup setup (...) """ # This module should be kept compatible with Python 2.1. __revision__ = "$Id$" import sys __version__ = "%d.%d.%d" % sys.version_info[:3] del sys...
"""distutils The main package for the Python Module Distribution Utilities. Normally used from a setup script as from distutils.core import setup setup (...) """ # This module should be kept compatible with Python 2.1. __revision__ = "$Id$" # Distutils version # # Please coordinate with Marc-Andre Lemburg ...
Add source trail logic to FontmakeError and partly TTFAError
class FontmakeError(Exception): """Base class for all fontmake exceptions.""" pass class TTFAError(FontmakeError): def __init__(self, exitcode): self.exitcode = exitcode def __str__(self): return "ttfautohint command failed: error " + str(self.exitcode)
import os class FontmakeError(Exception): """Base class for all fontmake exceptions. This exception is intended to be chained to the original exception. The main purpose is to provide a source file trail that points to where the explosion came from. """ def __init__(self, msg, source_file): ...
Test for writing and removing server info files
"""Test NotebookApp""" #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #-----------------------------...
"""Test NotebookApp""" #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #-----------------------------...
Add IndexResource to example module.
def install_module(app): """Installs this localmodule.""" install_module
class IndexResource(object): def on_get(self, req, res): res.body = 'Hello. This is app.' def install_module(app): """Installs this localmodule.""" app.api.add_route('/', IndexResource())
Change port for breakpad to available port.
# Copyright 2014 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. """ActiveMaster definition.""" from config_bootstrap import Master class Breakpad(Master.Master3): project_name = 'Breakpad' project_url = ('https://co...
# Copyright 2014 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. """ActiveMaster definition.""" from config_bootstrap import Master class Breakpad(Master.Master3): project_name = 'Breakpad' project_url = ('https://co...
Fix Bunny crawler crash on non-date image names
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Bunny' language = 'en' url = 'http://bunny-comic.com/' start_date = '2004-08-22' history_capable_days = 14 schedule = 'Mo,Tu,We,Th,Fr' time_zone = -8 ri...
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Bunny' language = 'en' url = 'http://bunny-comic.com/' start_date = '2004-08-22' history_capable_days = 14 schedule = 'Mo,Tu,We,Th,Fr' time_zone = -8 ri...
Allow images in EXTRACTs, etc.
from regparser.tree.depth import markers as mtypes from regparser.tree.struct import Node from regparser.tree.xml_parser import ( paragraph_processor, simple_hierarchy_processor, us_code) class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor): """Paragraph Processor which does not try to derive ...
from regparser.tree.depth import markers as mtypes from regparser.tree.struct import Node from regparser.tree.xml_parser import ( paragraph_processor, simple_hierarchy_processor, us_code) class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor): """Paragraph Processor which does not try to derive ...
Fix ConnectedSWFObject: restrict attributes set by constructor
# -*- coding:utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. import boto.swf from . import settings SETTINGS = settings.get() class ConnectedSWFObject(object): """Authenticated object interface Provides the instance attribu...
# -*- coding:utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. import boto.swf from . import settings SETTINGS = settings.get() class ConnectedSWFObject(object): """Authenticated object interface Provides the instance attribu...
Add 10 days only in the leap day case too.
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
Replace true/false from JSON to python False/True
#!/usr/bin/python import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../third-party/jsonschema") import jsonschema import jsonschema.exceptions def main(argv): if len(argv) < 3: print "Usage: " print "\t" + os.path.basename(__file__) + " <json file> <schema file...
#!/usr/bin/python import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../third-party/jsonschema") import jsonschema import jsonschema.exceptions def main(argv): if len(argv) < 3: print "Usage: " print "\t" + os.path.basename(__file__) + " <json file> <schema file...
Fix the test case for block cache.
import angr import logging l = logging.getLogger("angr.tests") import os test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) def test_block_cache(): p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translation_cache=True) b = p.factory.blo...
import angr import logging l = logging.getLogger("angr.tests") import os test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) def test_block_cache(): p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translation_cache=True) b = p.factory.blo...
Use the python MBox class rather than parsing the mailbox manually
#!/usr/bin/env python """ Simple Python module to parse a Thunderbird mail file and scan each email message with ClamAV in order to detect suspect messages. """ import pyclamav import os import re import email import argparse import sys import tempfile mail_split_re = re.compile(r'\s(?=From -)') def pr...
#!/usr/bin/env python """ Simple Python module to parse a Thunderbird mail file and scan each email message with ClamAV in order to detect suspect messages. """ import pyclamav import os import email import argparse import sys import tempfile import mailbox def print_message(parsed, signature=None): ...
Remove atomic transaction from command to reduce memory usage
import logging from django.core.management.base import BaseCommand from django.db import transaction from document.models import Document from document.models import Submitter logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): self.do() @transacti...
import logging from django.core.management.base import BaseCommand from django.db import transaction from document.models import Document from document.models import Submitter logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): self.do() # @transac...
Remove arg create because it will use closest_photodb.
''' This file is the WSGI entrypoint for remote / production use. If you are using Gunicorn, for example: gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-" ''' import werkzeug.middleware.proxy_fix import backend backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.w...
''' This file is the WSGI entrypoint for remote / production use. If you are using Gunicorn, for example: gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-" ''' import werkzeug.middleware.proxy_fix import backend backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.w...
Switch to a test schedule based on the environment
from apscheduler.schedulers.blocking import BlockingScheduler import logging import warner import archiver import announcer import flagger import os logging.basicConfig() sched = BlockingScheduler() @sched.scheduled_job("cron", hour=4) #@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing def destalina...
from apscheduler.schedulers.blocking import BlockingScheduler import logging import warner import archiver import announcer import flagger import os # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: s...